Jump to content

Help uploading files in PHP


TheBrandon

Recommended Posts

Hello everyone,

 

I'm writing a script that allows a user to upload multiple attachments to an email from PHP. So far, everything seems to be working except the multiple attachments part. If I upload one file, it works. If I upload 2, it's messing up the file names so the files don't exist.

 

So if I upload a.jpg, it works. If I upload a.jpg and b.jpg, b.jpg gets named a b.jpg. Can someone help me understand why this is happening and how to fix it?

 

I'm almost certain its happening on my while loop around lune 72, but the more I look at the syntax the more it looks okay to me.

 

I had it appending the path to the file names (so a.jpg become uploads/a.jpg) so I commented that out in hopes that was causing the error but it didn't fix it.

 

Below is the full script.

 

<?php
/*******************************************
/*		contact_us_process.php
/*		Author: Brandon Pence (brandonpence@gmail.com)
/*				 
/*		Desc:	This page process and checks the submitted form.
/*		
/*				variable		meaning
/*				--------		-------
/*				$FieldCheck		Instance of the FieldCheck class.
/*
/******************************************/

//start session
session_start();

//include files
require ("./inc/include.inc.php");

//include Field Check Class
include("classes/FieldCheck.php");

//instantiate fieldcheck class
$FieldCheck = new FieldCheck;

extract($_POST);

/*****DEBUG*********/
echo '<h1>POST ARRAY:</h1>';
print_r($_POST);
echo '<hr/>';

echo '<h1>DATAFILE:</h1>';
print_r($datafile);

echo 'foreach: <hr/>';

echo '<h1>FILES ARRAY:</h1>';
print_r($_FILES);
echo '<hr/>';

echo 'File name test: '.$_FILES['uploadedfile']['name']['0'].'<br/>';
echo 'File name test: '.$_FILES['uploadedfile']['name']['1'].'<br/>';
echo 'File name test: '.$_FILES['uploadedfile']['name']['2'].'<br/>';
/********************/

//foreach($datafile as $key=>$value){
//echo 'Datafile: '.$datafile.' || Key: '.$key.' || Value: '.$value.'<br/>';
//$value = $id.'/'.$value;
//echo 'Datafile: '.$datafile.' || Key: '.$key.' || Value: '.$value.'<br/>';
//}


if(file_exists("uploads/$id")){
echo 'Folder Exists!';
}else{
echo 'Folder does not exist. Create folder.';

//create directory
mkdir("uploads/$id",0777,true);
}

//path we want the files stored in
$target_path = "uploads/$id/";

//begin counter
$i = 0;

$files = array();
    		
//begin loop
while($i < 3){

//make sure each array key has valid data
if(!is_null($_FILES['uploadedfile']['name'][$i])){

	//append path to filenames in array
	//$target_path = $target_path . basename($_FILES['uploadedfile']['name'][$i]); 

	//upload files
	if(move_uploaded_file($_FILES['uploadedfile']['name'][$i], $target_path)) {
    		echo "The file ".  basename($_FILES['uploadedfile']['name'][$i]). " has been uploaded";
    		
    		$files[$i] = 'uploads/'.$id.'/'.$_FILES['uploadedfile']['name'][$i];
    	}
    
    //if file upload failed
   	}else{
    	echo "There was an error uploading the file, please try again!";
}

$i++;

}

//validate input
if (!$FieldCheck->checkName($your_name)){ $errors['your_name'] = "Your name is not valid.";}
if (!$FieldCheck->isEmpty($your_date)){ $errors['your_date'] = "Your date is not valid.";}
if (!$FieldCheck->isEmpty($your_message)){ $errors['your_message'] = "Your message is not valid.";}

foreach($_POST as $key=>$value){

$fields[$key] = $value;

}

//print_r($_POST);

//check for error messages
if (isset($errors)) {
$_SESSION['errors'] = $errors;
$_SESSION['fields'] = $fields;
$_SESSION['error_msg'] = "Errors found!  Please review your entries.";
$url = "./testimonials.php?action=errors";
header ("Location: $url");
exit;
}else{


echo '$files ARRAY:';
print_r($files);

// email fields: to, from, subject, and so on
$to = "a@c.om";
$from = "a@b.com"; 
$subject ="Testing Script"; 
$message = "My message";
$headers = "From: $from";

// boundary 
$semi_rand = md5(time()); 
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 

// headers for attachment 
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; 

// multipart boundary 
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n"; 
$message .= "--{$mime_boundary}\n";

// preparing attachments
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" . 
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" . 
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}

// send

$ok = @mail($to, $subject, $message, $headers); 
if ($ok) { 
echo "<p>mail sent to $to!</p>"; 
} else { 
echo "<p>mail could not be sent!</p>"; 
} 

echo 'EMAIL SENT!';

}

?>

 

Link to comment
Share on other sites

Got it. It was this part:

//path we want the files stored in
$target_path = "uploads/$id/";

//begin counter
$i = 0;

$files = array();
    		
//begin loop
while($i < 3){

//make sure each array key has valid data
if(!is_null($_FILES['uploadedfile']['name'][$i])){

	//append path to filenames in array
	$target_path = $target_path . basename( $_FILES['uploadedfile']['name'][$i]); 

	//upload files
	if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'][$i], $target_path)) {
    		echo "The file ".  basename( $_FILES['uploadedfile']['name'][$i]). " has been uploaded";
    		
    		$files[$i] = 'uploads/'.$id.'/'.$_FILES['uploadedfile']['name'][$i];
    	}
    
    //if file upload failed
   	}else{
    	echo "There was an error uploading the file, please try again!";
}

$i++;

}

 

The $target_path variable was being overwritten on the first execution of the loop so any subsequent files were breaking.

 

Changing it to this fixed it:

//path we want the files stored in
$target_path = "uploads/$id/";

//begin counter
$i = 0;

$files = array();
    		
//begin loop
while($i < 3){

//make sure each array key has valid data
if(!is_null($_FILES['uploadedfile']['name'][$i])){

	//append path to filenames in array
	$target_path_link = $target_path . basename( $_FILES['uploadedfile']['name'][$i]); 

	//upload files
	if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'][$i], $target_path_link)) {
    		echo "The file ".  basename( $_FILES['uploadedfile']['name'][$i]). " has been uploaded";
    		
    		$files[$i] = 'uploads/'.$id.'/'.$_FILES['uploadedfile']['name'][$i];
    	}
    
    //if file upload failed
   	}else{
    	echo "There was an error uploading the file, please try again!";
}

$i++;

}

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.