How to Upload files with PHP
Posted on May 23, 2008 by Marty
In this Tutorial im going to outline the process of how you can use a simple PHP script to upload files directly to your server, re-naming them and storing them in a chosen location, all from a very simple form which you can style and place anywhere on your webpages…
things to keep in mind for this script to function properly
you will require the following:
- Web hosting
- PHP 5 or above installed
- Write access to a directory on your web server
- some PHP knowledge ( to allow for your own customization)
- basic CSS & Colour values to style your form
Before we get to any code you’re going to need a HTML form, in order to pass information to the script, like the name of the file, size, file extension etc… but for this script we will only have to deal with the name of the file.
below is an html form with some basic CSS styles applied purly for aesthetic reasons of my own.
<div style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; color:#CC9900; margin:0 auto; width:400px;"> <form id="frmupload" name="frmupload" method="post" action="upload.php" enctype="multipart/form-data" style=" margin:0 auto; padding:10px; background-color:#FFFBCC; border:1px solid #E6DB55;"> <strong>Select File</strong> <input name="f1" type="file" size="30" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px; size:12px;" /> <input type="submit" name="button" id="button" value="GO!" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px; size:12px; color:#CC6600; background-color:#E6DB55" /> </form>
The HTML code above will produce a form which will resemble the form below, you can change the colour values & fonts to match your site style..

Paste the above code into a webpage on your site, upload and view your page in a browser, click on the browse button, locate an image to upload and click GO!, the form will be submitting to a page called upload.php (once we create it) but once this part is done then your half way there…
The Main part of the form is the upload field, this is named f1,(as in file1)
this form name will be posted (SENT) to the upload page were it will be used in the script.
The Uplaod script which is shown below can be copied to a new page on your server called upload.php, paste this code into it and upload it to your server, now ill take you through the code step by step to build a basic understanding of what is going on in the code…
PHP CODE
<?php
$target_path=""; $file_name = "";
$file_name = basename($_FILES['F1']['name']);
if($file_name! = "")
{
$target_path = "uploads/" . mktime() ."_";
$target_path = $target_path . $file_name;
move_uploaded_file($_FILES['F1']['tmp_name'], $target_path);
}else{
echo "<div style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; border:1px solid #E6DB55; background-color:#FFFBCC; color:#CC9900; margin:0 auto; width:400px; padding:10px; text-align:center;">
The file field was empty or no file selected.<br>
please go back and try again.</div>";
}
?>
from the code above, if you’ve dabbled with PHP you’ll most probably be familiar with the above code, if not thats ok because i’ll break it down and give you a better understanding of what happening, whats going were and how its getting there.
$target_path=""; $file_name="";
The First part of the code initialises the first two variables and assigns them with no value.
target_path: this will obviously be the target to where we want the file to be saved.
file_name: This is going to be the file name passed over from the form…
Once we arrive at the upload.php page the file name is read into the script by using the code
$file_name = basename($_FILES['F1']['name']);
This is were we tell the script file_name will take the value of the posted file name from the previous page, using the server call to $_FILES and referencing the form field name f1 (this by the way you can change to what you want, but just remember to change it in both the form and the script) the other value on the end of the code ['name'] represents the temporary name given to it.
Now that we have the basename of the file, a question is asked by using a IF statement.
if($file_name!="")
This question basicly asks “IF the file name, is NOT equal to nothing.” then we can run the rest of the script
so if the question is TRUE and the filename has a value of say “picture.jpg” we can continue further into the script and we assign the variable $target_path with the location of the folder in which the file will be stored, now this can be any folder on your website, just as long as there is write permissions set to allow the script to save the file and that the folder path is relative to were the script is located on your server,
“you may have to contact your host, Most FTP programs like FLASHFXP support sending commands which can change write access permissions (CHMOD)”
$target_path = "uploads/" . mktime() . "_"; $target_path = $target_path . $file_name;
The Target for our files will be located in a folder caled uploads funny enough..
If we take a closer look at the $target_path value we can see the “uploads/” folder name but also an addition to the filename ie “picture.jpg” using the . which joins the text together, so we can create a unique file name for this upload, with the mktime() function we can tell PHP to print a timestamp or any format we wish to create unique filenames, this is so that no file will be overwritten (unless 2 are posted at the very, very, very same time) but for this script the mktime() will produce somthing along these lines “1211499610″ which returns the Unix timestamp, this will be enough to produce the unique upload name we require, so now our $target_path value looks like this “uploads/1211499610″
following the mktime() function there is another addition to the $target_path value which is appended to the end of the mktime() value again using the . this time we add “_” this to break up our filename just so we can tell them apart when looking for them or linking to them, so now our $target_path value looks like this “uploads/1211499610_”
On the next line of code we again reference the $target_path variable and do a liitle joinging together,
$target_path = $target_path . $file_name;
on the end of this line we again use the . to join the $file_name value which is “picture.jpg” to the end of our target path so now the $target_path value looks like this “uploads/1211499610_picture.jpg”
Now were getting to the end of the script, the next line of code
move_uploaded_file($_FILES['F1']['tmp_name'], $target_path);
Using the move_upload_files() function with the argument sent as $_FILES['F1']['tmp_name'], $target_path this basicly tells the server to move the file, named f1, to its target path, which we specified above…
Now, remember the Question we asked above at the start of the script “IF the file name, is NOT equal to nothing.” then run the rest of the script, well the next line of code from the script is run only if the question is set to false, so that if the value of the filename is nothing then run this part of the code…
}else{
echo “<div style=â€font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; border:1px solid #E6DB55; background-color:#FFFBCC; color:#CC9900; margin:0 auto; width:400px; padding:10px; text-align:center;â€>
The file field was empty or no file selected.<br>
please go back and try again.</div>â€;
}
after the IF statement is run and the value is set to false the script will out put a message to the user telling them that the field is empty and ask them to return to the page they were, (again you can customise this to suit your needs), the code in the script will output similar to the image below.

Well i hope you found that useful, and it helps with the development of your site or application.
Comments (15)










Very nice!
In your tutorial, you mistakenly wrote:
if($file_name!=“”)
This is incorrect. To check equality to something, you must utilize the == operator.
What you’ve said was “Can we NOT set “” to $file_name?” which doesn’t make much sense at all.
Oops, sorry, going for so long without sleep makes me dumb. =P
I didnt see the exclamation point in front.
Hehe. Honest mistake, right?
its all good.
after so long looking at code, i often do this.
You could just pop out of PHP to display your HTML code instead of using the echo function to display 10 lines of the stuff.
//blahblah
else {
?>
<?php
// the rest
maybe you should get some sleep then. lols
He wasn’t referring to the exclamation point operator, he was referring to the single equal sign in the if statement.
You *need* double equals signs (“==”) otherwise you are telling php what a variable is supposed to hold in a string, integer, etc… Unless you need boolean support, then you use three equals signs (“===”).
So you were right about the exclamation point, but you needed to equals signs so it says “If file name isn’t equal to nothing”.
An easier and faster way to go about doing it could also be this–
if(is_empty($file_name)){
doThis();
}
You can contact me if by the email address I used if you have any questions about what I’ve said. I’ve just woken up so I’m not sure how clear I’m being.
Matt
Select File:
its nice but the upload size limit is only 5 mb right?
Hi Jad,
this would really depend on your web host,
what you can do is create a new php page,
copy this code into you page
phpinfo();
open it in your browser and look for this “upload_max_filesize” without the Quotes and it will tell you..
Just a note, as far as I cant tell PHP 5 isn’t required to run this code, it ought to work on PHP 4.x too.
cool i like it :D
i will use it :D
I found your blog on google and read a few of your other posts. I just added you to my Google News Reader. Keep up the good work. Look forward to reading more from you in the future.
I am make a PHP submission form, when click submit button this error will come out
“Warning: move_uploaded_file(uploads/dd.pdf) [function.move-uploaded-file]: failed to open stream: Permission denied in /home/newton/domains/newton.co.in/public_html/uploader.php on line 12
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move ‘/tmp/phpNIPhXb’ to ‘uploads/dd.pdf’ in /home/newton/domains/newton.co.in/public_html/uploader.php on line 12
There was an error uploading the file, please try again!”
Please sort out this problem
thanks a lot… i m new to PHP.. struggling for last 2 days to learn uploading file.. ur was the only column that helped me out of more than 100 i visited… reason being the file name “F1″, should be same in form and $_FILES… u r the only one who has explained it completely… thanxs again..