header
 
     
 
pixel
pixel pixel

Upload files using a HTML form

This tutorial explains the basics of uploading images or files to your server using a HTML form and the PHP function copy. I haven't explained form validation or file checking - I'll go into further detail on that in future tutorials. To kick things off, you'll need a HTML form:

uploadform.htm
<html>
  <head>
    <title>HTML Form for uploading image to server</title>
  </head>
  <body>
    <form name="upload" method="post" action="uploadresults.php" enctype="multipart/form-data">
      <input type="file" name="Image"><br> 
      <input type="submit" value="Upload Image">
    </form>
  </body>
</html>

There are two things to note about the HTML code. Firstly, I've defined the attribute enctype="multipart/form-data" in the form tag. This encodes your form data differently to normal, allowing you to submit files. Secondly, I've used the input element with type = "file". The browser renders this as follows:

Note the 'Browse...' button. Clicking this opens a window allowing the user to browse their local computer and select a file (go on, try it). Once they've selected a file and clicked 'Open', the window closes and the file's local path appears in the form (eg - "C:\My Documents\button.gif"). Clicking 'Upload Image' (eg - the submit button) sends the form results, including the local file, to uploadresults.php for processing:

uploadresults.php
<?php
copy 
($_FILES['Image']['tmp_name'], $_FILES['Image']['name']) or die ('Could not upload');
?>

The uploaded image is stored on the server in a temporary location. You can reference it by using the global array $_FILES. There are several variables available:

  • $_FILES['file']['name']: name of the file
  • $_FILES['file']['type']: filetype of the uploaded file
  • $_FILES['file']['size']: size of the uploaded file (in bytes)
  • $_FILES['file']['tmp_name']: name for the temporary file stored on the server
  • $_FILES['file']['error']: an error code resulting from the file transfer
Once uploadresults.php has finished executing, the temporary file is deleted. You use the PHP functions copy or move_uploaded_file to store the file in a permanent location (in fact, our current webhost only allows move_uploaded_file). Copy and move_uploaded_file have two arguments - the first is the temporary location, the second is the final destination where you wish to save the file. In the example above, I saved the file in the same directory as uploadresults.php. If I wanted to save it in a subdirectory, I'd have used something like this:
<?php
copy 
($_FILES['Image']['tmp_name'], "images/".$_FILES['Image']['name']) or die ('Could not upload');
?>

IMPORTANT: be sure to turn on the write permissions of the directory where you're copying the files to or you may get a 'permission denied' or some similar error. Most FTP programs let you set the CHMOD for a directory - set it to 777 to give it write permissions.

So there you have it. There are checks you can perform on uploaded files to ensure they're the right size, filetype, etc. In fact, I'd strongly recommend you have some checks in place, particularly if your upload form is open to the public. For example, you can specify a maximum size of the uploaded file (which importantly kicks in before the file is uploaded). You can check the filetype to make sure it's a certain type. You can even resize images to create thumbnails on the fly. I'll cover all of these in future tutorials so stay tuned. :-)

Unhelpful Helpful Rating 3.9 (score out of 5, no. of ratings: 250)
Comments
Comment by Jyaif on 2005-11-01
this code is usefull

Comment by Allan on 2005-02-07
Nice Tutorial Thx,..... :)

Comment by Andre on 2005-02-10
Thank you very much this helped me a whole bunch. Can't believe I didn't figure this out on my own.

Comment by Cynthia on 2005-02-15
Finally someone that kept it simple! Other tutorials didn't work.

Comment by Dark Angel on 2005-02-21
.__. This didn't work because I always get errors.

Comment by Aircan on 2005-02-21
I'm getting this error: Warning: copy(uploads/bently_1.jpg): failed to open stream: Permission denied in /home/virtual/site189/fst/var/www/html/html_site/php/uploadresults.php on line 2 Could not upload Why?

Comment by gurk on 2005-02-23
worked fine for me. only forgot te set the atributes of the folders to write. mightbe helpfull to know. thanks

Comment by peter on 2005-02-24
100% perfect

Comment by Ressy on 2005-02-27
Good job on this tut. Does exactly what I wanted.

Comment by santhosh on 2005-02-27
Very useful

Comment by Amitesh on 2005-02-28
I tried this code but it is not working. File is not uploading. "); echo("Error is :: ".$_FILES['upfile']['error']); } @unlink($_FILES['upfile']['tmp_name']); ?> output of this code is :: Upload of Hlpstep3.gif to /home/toy/www/images/ failed!!!! Error is :: 0

Comment by Matt on 2005-03-03
The problem with your uploads is probably that your "root" access on the webserver doesn't have write access to that directory. Check/change your settings using chmod. (I'm going to use ftp once it gets up to the server so I don't have that security risk).

Comment by Rodney on 2005-03-03
This works perfectly! Simple solution!

Comment by Eskil on 2005-03-05
Great and Simple way to do this, thx for the tut :) How can I check that the file uploaded is an image (.gif or .jpg) Is there a simple way ?

Comment by shanmuga on 2005-03-09
nice one. thanks

Comment by MP on 2005-03-10
I get this: Warning: Unable to open '' for reading: No such file or directory in /nfs/cust/8/32/55/555238/web/karikatur/uploadresults.php on line 2 Could not upload

Comment by Ricardo on 2005-03-12
I don't get it... nothing happens...

Comment by Lukus on 2005-03-23
Worked great once I set the CHMOD to 777 for the file and used the right case for the file name.

Comment by Chandra Mohan Nayal on 2005-03-28
It was a good tip ! Thannks

Comment by mohd Javed on 2005-03-29
that code is not sufficient to post or Upload the Image,so please give me detail code in PHP. How to Upload the updated image direct server .

Comment by Richard on 2005-03-30
great turorial, just one question. How do you post the original location where the image came from.

Comment by madeshwaran on 2005-03-30
This was realy helpfull for me. and i got the result

Comment by Kurisu on 2005-03-30
Are there similar scripts that allow only image files like JPG/GIF/BMP/whatever? I think this one allows all sorts o files to be uploaded.

Comment by Hunen Daabool on 2005-04-04
I cannot Copy 'tmp_name' File To any folder under web site after Uplodin fIles Help Me Abbout This Plaese And thanks.

Comment by Clems on 2005-04-05
Thank you to keep it simple!

Comment by haq on 2005-04-05
wheres the demonstration ,if you wwant some good rating plz come with demonstration next time

Comment by Bill the Blagger on 2005-04-09
All credit to you for making a stab at a topic which confuses the hell out of people. You've tackled it in a straightforward and no-nonsense way instead of attempting to provide an ultra complex bells and whistles app which would be doomed to failure. One tip for your readers: If the script is not doing as required, try changing the copy() function for a move_uploaded_file() function.

Comment by John A Cove on 2005-04-14
Excellent, thanks :)

Comment by Gilles on 2005-04-14
Doesn.t  work!!!!

Comment by Jason Trautwein on 2005-04-21
This has been very informative and an excellent start for simple quick information for file uploads.

Comment by Ayman Wahby on 2005-04-26
Thanks somehow, because I used this function "@copy" on my localhost (apache server) and it wored successfully. But when I upload my application on the host server, it didn't work... Can anyone tell me any comment ? (ayman_wahby@yahoo.com). Great thanks for your care.

Comment by joe on 2005-04-28
Remember that you need to set permissions on the folder you are copying to. Look into CHMOD. Sometimes your FTP program will allow you to adjust permissions. On some ISP you have to do this with shell access. This would require root access to your server. Also check into your user account control panel and snoop around and look for folder permissions. Set permissions on your folder to be writable. I user CHMOD 777

Comment by Drax on 2005-05-05
Very heplful. . . Thanks a lot

Comment by pavan on 2005-05-13
how to upload swf image for jpeg we have image/pjpeg & bmp we have image/bmp for swf we have image/??? or anything pls send we the answer to my email tvpk272@rediffmail.com

Comment by sweetbee on 2005-05-30
How to upload the file at desired location?

Comment by JD on 2005-06-14
Does the job and I can work the rest out by myself. After reading these messages, I'm amazed how many stupid are out there.

Comment by david on 2005-06-25
Thanks so much, I have tried several other examples and tutorials, this one worked straight away!

Comment by lithuania on 2005-07-06
u need to chmod the folder where the images go to 777(u can do it with any ftp program)then ur images vil go fine ;]

Comment by Carlosgoias on 2005-07-12
EXCELENTE!!!!

Comment by Rick on 2005-07-12
Thanks.. but now I want to email a form uploaded image.. how do I do that?

Comment by Chris Miller on 2005-07-13
What a great example. It worked perfectly the first time. I can take it from here. At last, an example that informs instead of showing off.

Comment by hetiland on 2005-07-15
thanks boys. Very special

Comment by Kelly on 2005-07-23
That's Sooooooo HOT!!

Comment by Ann Stewart on 2005-07-26
Hi, thanks but don't understand. I need to upload my e-book but probably did not input it properly. Would someone please explain this CHMOD and 777 to me? Also, I'm working with a sitebuilder and their server. They're picky.

Comment by RK on 2005-08-16
why all could not upload ??? all just show could not upload

Comment by sendil on 2005-08-19
Need Help ! I try to set Read and Write permission for the folder where the images are uploaded. After setting the permissions ( 777 ). It turns back to 000 again. Can somebody tell me what the problem is.

Comment by Raj on 2005-08-25
It would be highly useful if uploading could be done for say 100 images

Comment by Armorine on 2005-08-26
Infiltrate...do you see anything?

Comment by mitanshu on 2005-08-28
can i save the file in mysql database itself

Comment by Ian Weir on 2005-09-02
At last, something that keeps it simple without making it too complicated. I have tried out other tutorials, and they were all too complicated. Simplicity is beauty. Keep up the good work!

Comment by 4736 on 2005-09-14
could be more detail

Comment by some who codes php for a living on 2005-09-18
useless

Comment by smalltree on 2005-09-27
Whats with all the negative feedback? This tutorial gives the basics and works fine if you've got your permissions set OK. Perfect for impatient people like me. Oh and on the last comment.. if you code PHP for a living why are you reading this? You might be a bit more positve and maybe give another link to help people out or better still write a tutorial that isnt 'useless' as you put it.

Comment by Gourav on 2005-10-06
this code is useless

Comment by lisa on 2005-12-04
brilliant worked first go - thanks for providing me with the essentials only first - makes sense in comparison to other tutorials ive read

Comment by suraj on 2006-02-18
hey the tutorial was great and very simple.... great job

Comment by Kirill on 2006-04-10
Hi! And what became with others?

Comment by Li on 2006-05-05
Hi all! I want to establish the same guest book. Prompt as?

Comment by Jude on 2007-02-01
Very helpful - thanks!

Comment by James on 2009-11-12
Does what it says it is supposed to do - if you need more do some fucking research you lazy pieces of crap. To the author - thanks for the to tut.

Comment by taufik on 2008-01-14
it's too simple.. how if i want to create folder on server and i also upload a file on it? can you do that?

Comment by joel george on 2009-12-30
awsome code

Post a Comment
Name
Email
(optional)
Comment
RatingUnhelpful Helpful
Security Image* (this is just to prevent spam submissions)
Security Image