Link to home
Start Free TrialLog in
Avatar of sakvk
sakvk

asked on

PHP file upload

Hi,

I have a HTML form with user name , password and a file to upload.

then a php, i am not sure how to send the uploaded resume as an attachment. Attached is the code, please do let me know how to proceed.
test.html
<html>
<head></head>
<body>
<table border="0" align="center" width="100%" cellpadding="0" cellspacing="0">
<tbody>
<tr ><!-- Top Header -->
<form enctype="multipart/form-data" name="studentinfo" action="login" method="post" >
<table > 
  <tbody><tr><td  align="center"><span style="position:relative;font-family: verdana; padding-left: 30px; font-size:14px;"><h3>Upload your homework</h3> <sub>(<font color="#FF0000">*</font>) Indicates mandatory</sub> </td>
</tr>
<tr>
<td align=right nowrap><span class="wt1">First Name</span><span class="warn"><font color="#FF0000">*</font></span></td>
<td><input id="txt_firstname" name="txt_firstname" type="text" size="35" maxlength="60" /> </td>
</tr>
<tr>
<td align=right nowrap><span class="wt1">Last Name</span><span class="warn"><font color="#FF0000">*</font></span></td>
<td><input id="txt_lastname" name="txt_lastname" type="text" size="35" maxlength="60" /> </td>
</tr><tr>
<td align=right nowrap><span class="wt1">Email Address</span><span class="warn"><font color="#FF0000">*</font></span><br>&nbsp;</td>
<td><input id="txt_email" name="txt_email" type="text" size="35" maxlength="60" /></td>
</tr>
<tr>
<td><input name="submitdate" type="hidden" value="<?php date(); ?>" /></td>
</tr><tr>
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<td align=right nowrap><span class="wt1">Upload your resume  </span><br>&nbsp;(Upload your homework with the assignment number on it.)</td>
<td> <input type="file" id="txt_resume" name="txt_resume" size="35" maxlength="60"  value=""/></td>
</tr>
<tr><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr>
<tr><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td><td align=center><input type=submit class="button" value="Submit"></td></tr>
</tbody>
</table>
</form>
<br> <br><br>
</td>
</tr>
</table>
</body>
</html>
 
login.php
 
<?php
 
if(isset($_POST['txt_firstname']))
{
$firstname=$_POST['txt_firstname'];
$lastname=$_POST['txt_lastname'];
$email=$_POST['txt_email'];
if($firstname=''&&$lastname=''&&$email='')
{
echo "You should Enter the required fields";
}
else{
	$toaddress = "admin@xxx.com";
	$subject = "Your homework submission!";
	$message = "Dear ".$firstname.",<br><br>";
	$message = "Your details details,<br>First Name:" .$firstname."<br>";	
	$message = $message ."Email:" .$email."<br><br>";        
        $message = $message ."Regards,<br>ADMIN";
	$headers = "From: $email";
        $success = mail($toaddress,$subject,$message,$headers);
	if ($success)        
          {
          // Redirect to thank you page.
          Header("Location: thanks.php");
          }       
 
    }
 }
 
 
 
}
 
?>

Open in new window

Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

The uploaded files appear in the $_FILES superglobal array.  I will post a teaching-example script that shows you how to find and process these.
Read this code and the man pages, then post back here if you have any questions.  Best regards, ~Ray
<?php // RAY_upload_example.php
error_reporting(E_ALL);
 
// MANUAL REFERENCE PAGES
// http://docs.php.net/manual/en/features.file-upload.php
// http://docs.php.net/manual/en/features.file-upload.common-pitfalls.php
// http://docs.php.net/manual/en/function.move-uploaded-file.php
// http://docs.php.net/manual/en/function.getimagesize.php
 
// ESTABLISH THE NAME OF THE 'uploads' DIRECTORY
$uploads = 'uploads';
 
// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT
$max_file_size = '8192000';  // EIGHT MEGABYTE LIMIT ON UPLOADS
 
// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array('jpg', 'gif', 'png', 'txt');
 
// ESTABLISH THE NUMBER OF FILES WE CAN UPLOAD
$nf = 3;
 
 
 
// THIS IS A LIST OF THE POSSIBLE ERRORS THAT CAN BE REPORTED IN $_FILES[]["error"]
$errors	= array(
	0 => "Success!",
	1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
	2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
	3 => "The uploaded file was only partially uploaded",
	4 => "No file was uploaded",
	6 => "Missing a temporary folder",
	7 => "Cannot write file to disk"
);
 
 
 
// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST))
{
	?>
	<h2>Upload <?=$nf?> file(s)</h2>
 
	<!--
		SOME THINGS TO NOTE ABOUT THIS FORM...
		NOTE THE CHOICE OF ENCTYPE IN THE HTML FORM STATEMENT
		MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
		INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY
	-->
 
	<form name="UploadForm" enctype="multipart/form-data" action="<?=$_SERVER["REQUEST_URI"]?>" method="POST">
	<input type="hidden" name="p" value="1" />
	<input type="hidden" name="MAX_FILE_SIZE" value="<?=$max_file_size?>" />
	<p>
	Find the file(s) you want to upload and click the "Upload" button below.
	</p>
 
	<?php for ($n = 0; $n < $nf; $n++)
		{
			echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>\n";
		}
	?>
	<br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <b>overwrite</b> existing files.
	<input type="submit" name="_submit" value="Upload" />
	</form>
	<?php
	die();
}
 
 
 
else // WE HAVE GOT SOMETHING IN $_POST
{
 
// THERE IS POST DATA - PROCESS IT
	echo "<h2>Results: File Upload</h2>\n";
 
// ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
//	echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>\n";
 
// ITERATE OVER THE CONTENTS OF $_FILES
	foreach ($_FILES as $my_uploaded_file)
	{
 
// SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
		$error_code	= $my_uploaded_file["error"];
		if ($error_code == 4) continue;
 
// SYNTHESIZE THE NEW FILE NAME
		$f_type	= trim(strtolower(end    (explode( '.', basename($my_uploaded_file['name'] )))));
		$f_name	= trim(strtolower(current(explode( '.', basename($my_uploaded_file['name'] )))));
		$my_new_file = getcwd() . '/' . $uploads . '/' . $f_name .'.'. $f_type;
		$my_file     = $uploads . '/' . $f_name .'.'. $f_type;
 
// OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
		if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");
 
// IF THERE ARE ERRORS
		if ($error_code != 0)
		{
			$error_message = $errors[$error_code];
			die("Sorry, Upload Error Code: $error_code: $error_message");
		}
 
// GET THE FILE SIZE
		$file_size	= number_format($my_uploaded_file["size"]);
 
// MOVE THE FILE INTO THE DIRECTORY
// IF THE FILE IS NEW
		if (!file_exists($my_new_file))
		{
			if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
			{
				$upload_success = 1;
			}
			else
			{
				$upload_success = -1;
			}
 
// IF THE FILE ALREADY EXISTS
		}
		else
		{
			echo "<br/><b><i>$my_file</i></b> already exists.\n";
 
// SHOULD WE OVERWRITE THE FILE? IF NOT
			if (empty($_POST["overwrite"]))
			{
				$upload_success = 0;
 
// IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
			}
			else
			{
				$now	= date('Y-m-d');
				$my_bak = $my_new_file . '.' . $now . '.bak';
				if (!copy($my_new_file, $my_bak))
				{
					echo "<br/><b>Attempted Backup Failed!</b>\n";
				}
				if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
				{
					$upload_success = 2;
				}
				else
				{
					$upload_success = -1;
				}
			}
		}
 
// REPORT OUR SUCCESS OR FAILURE
		if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; }
		if ($upload_success == 1) { echo "<br/><b><i>$my_file</i></b> has been saved.\n"; }
		if ($upload_success == 0) { echo "<br/><b>It was NOT overwritten.</b>\n"; }
		if ($upload_success < 0)  { echo "<br/><b>ERROR <i>$my_file</i> NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</b>\n"; }
		if ($upload_success > 0)
		{
			echo "$file_size bytes uploaded.\n";
			if (!chmod ($my_new_file, 0755))
			{
				echo "<br/>chmod(0755) FAILED: fileperms() = ";
				echo substr(sprintf('%o', fileperms($my_new_file)), -4);
			}
			echo "<br/><a href=\"$my_file\">See the file $my_file</a>\n";
		}
// END ITERATOR
	}
}
?>

Open in new window

Also, the manual does give a good walkthrough...

http://docs.php.net/file_upload


Avatar of sakvk
sakvk

ASKER

Hi,

I need the file to go as a mail attachment.
Do you mean you are going to upload a file and then generate an email with the uploaded file as an attachment?

If so, this is best performed in 2 steps.

The first is the upload and then email it.

As far as I know you cannot use the mailto: protocol for a file upload.

For mail sending, then I would recommend using a PHP class (phpmailer is probably the most common, though I use the htmlmimemail5 class from phpguru.org which has recently been renamed to RMail).
"I need the file to go as a mail attachment."

You can do that, or you can just upload the file and send a link.  If you send a link, the email will be much smaller (lighter) and you will have a copy of the file stored on the server.  That way if the attachment is stripped off or accidentally lost you will still have the file in a safe place.
Avatar of sakvk

ASKER

So to send a mail with the attachment,

I have to first upload the file and then send an email... ?  Can I not email it directly without uploading?

Please provide me more inputs.
Avatar of sakvk

ASKER

Hey Ray,

Thats a good idea...

To have the file on the server and then send link ... but how do i achieve that? please provide me some inputs
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I am using Ray's script and it works very well, thank you sooooo much!

I am trying to edit the script so that the upload is part of an online order form. I'm trying to figure out how to make it so that the script checks for an uploaded file, and if it is there process the file, but if there is no uploaded file, it continues on to processing the rest of the post variables into an email....

Forgive the butchering of your work Ray...but I am enjoying dissecting the script and learning a little more about php...

I tried to put your entire script in another IF statement that checks for whether there is an uploaded file and if yes continues with your script, and if no, moves on to the email building section of your script.
I tried adding this:
// THIS IS A LIST OF THE POSSIBLE ERRORS THAT CAN BE REPORTED IN $_FILES[]["error"]
$errors	= array(
	0 => "Success!",
	1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
	2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
	3 => "The uploaded file was only partially uploaded",
	4 => "No file was uploaded",
	6 => "Missing a temporary folder",
	7 => "Cannot write file to disk"
);
 
if (!$errors == 4){
 
 
 
And then moving the email building portion of the script outside your iterator loop at the end.
 
Am I even on the right track?

Open in new window

Yes, I think that is workable.  You could also test to see if the $_FILES variable was empty.  I would make both tests.  Best regards, ~Ray