Solved

PHP file upload

Posted on 2009-05-19
11
421 Views
Last Modified: 2013-12-13
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

0
Comment
Question by:sakvk
  • 5
  • 3
  • 2
  • +1
11 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 24425867
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.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 24425887
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

0
 
LVL 40

Expert Comment

by:RQuadling
ID: 24425902
Also, the manual does give a good walkthrough...

http://docs.php.net/file_upload


0
 

Author Comment

by:sakvk
ID: 24426566
Hi,

I need the file to go as a mail attachment.
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 24426586
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).
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 108

Expert Comment

by:Ray Paseur
ID: 24426612
"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.
0
 

Author Comment

by:sakvk
ID: 24426623
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.
0
 

Author Comment

by:sakvk
ID: 24426632
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
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 24441174
Sure. Here is how to go about that.  Adapt the upload process shown in the teaching example I posted above to add a variable for the email address that you want to send to (such as $client_email in the snippet below).  Then look near line 165 where we produce a link to the file.  Here is the sort of thing you would need to do near there.

Best of luck with your project, ~Ray
// THIS IS LINE 165 FROM THE TEACHING EXAMPLE ABOVE

echo "<br/><a href=\"$my_file\">See the file $my_file</a>\n";
 

// PREPARE AN EXPLICIT URL FOR THIS FILE

$my_url = $_SERVER["HTTP_HOST"] . '/' . $my_file;
 

// SEND THE EMAIL WITH THE EXPLICIT URL OR ISSUE ERROR MESSAGE IF mail() COMMAND FAILS

$client_email = 'you@your.org';

if (!mail($client_email, 'LINK TO UPLOADED FILE', $my_url))

{

    echo "FAIL: mail() TO $client_email";

}

Open in new window

0
 
LVL 2

Expert Comment

by:musickmann
ID: 24586708
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

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 24586820
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
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now