php file upload

Written by Gertjan on December 6th, 2007

In this tutorial i will teach you how you can upload files to your website using PHP. I will teach you the basics and show you how to manage witch files may be uploaded.

A very useful aspect of PHP is its ability to manage file uploads to your server. Allowing users to upload a file to your server can be a security risk, so please be careful when uploading files.
Before you can use PHP to manage your uploads, you must build an form that lets users select a file to upload.

Let’s start by creating the file upload form:

Files are uploaded from the browser using an input tag, with the type parameter set to “file”. This is supported by all browsers currently available on the market.

The important thing is to set the ENCTYPE attribute of the form to “multipart/form-data” and set the form’s action to the file upload page. The file upload page will handle the actual file uploading.
We can set a filesize limit by adding a hidden input element with the NAME attribute set to “MAX_FILE_SIZE” and the VALUE parameter to the max allowed filesize (in bytes).

file: uploadform.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 <form name="upload-form" id="upload-form" method="post" action="./upload.php" enctype="multipart/form-data"> 
  <input type="hidden" name="MAX_FILE_SIZE" value="30000"> 
  <fieldset> 
  <legend>File upload:</legend> 
  <dl> 
    <dt> 
      <label for="file">File:</label> 
    </dt> 
    <dd> 
      <input tabindex="1" accesskey="b" name="file" type="file" id="file" /> 
    </dd> 
  </dl> 
  <input tabindex="2" accesskey="l" type="submit" name="cmdupload" value="Upload" /> 
  </fieldset> 
</form>

After the user clicks the Upload button, the data will be posted to the server and the user will be redirected to upload.php. This PHP file is going to process the form data and validate the uploaded file.

NOTE: You will need to create a new directory in the directory where upload.php resides, called “upload”, as we are going to be saving files there.

Now let’s begin creating the upload script:

In PHP, uploaded files are accessed via the $_FILES array:

  • $_FILES["file"]["name"]: The original filename on the client’s machine.
  • $_FILES['file']['type']: The mime type of the file.
  • $_FILES['file']['size']: The size, in bytes, of the uploaded file.
  • $_FILES['file']['tmp_name']: The temporary filename of the file in which the uploaded file was stored on the server.

We start our script by setting the upload directory and the name of the log file.

Now we declare a filetype blacklist, this is an array that contains all filetypes that are NOT allowed in the filename.

Now we declare a list of filetypes that are allowed, again this is an array that contains all types that are allowed.

Then we check to see if the upload directory exits and if it’s writable.

Now we check to see if the user has pressed the upload button on the upload form. If he has not pressed the button the user will be redirected back to the upload form.

Then we check to see if $_FILES['file']['error'] reports an error.

Now it’s time to check if a item from the blacklist has been found in the filename. if not the script continues, if so the script will display an error and log the attempt to the log file.

Next we check if the filetype is allowed, if not the script exits and informs the user, again the attempt will be logged to the log file.

Now we check to see if there already is a file with the same name, if so the script exits and display’s an error.

Next is checking to see if a file has been uploaded with the name $_FILES['file']['tmp_name'].

The temporary copied files disappears when the script ends. To store the uploaded file we need to copy it to a different location:
The move_uploaded_file() function will move the temporary file to the desired location.

The file is now uploaded, now we log the uploader’s IP, the date and the time in an upload log.

The script is finished and displays a message saying that the file has been uploaded.

file: upload.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
 <?php
$uploaddir = "upload/"; //Upload directory: needs write premissions
$log = "uploadlog.txt"; // Upload LOG file
// what file types do you want to disallow?
$blacklist = array(".php", ".phtml", ".php3", ".php4", ".php5", ".exe", ".js",".html", ".htm", ".inc");
 // allowed filetypes       
$allowed_filetypes = array('.jpg','.gif','.bmp','.png'); 
 
if (!is_dir($uploaddir)) {
    die ("Upload directory does not exists.");
}
if (!is_writable($uploaddir)) {
    die ("Upload directory is not writable.");
}
 
if ($_POST['cmdupload'])
{
 
$ip = trim($_SERVER['REMOTE_ADDR']); 
 
    if (isset($_FILES['file']))
    {
        if ($_FILES['file']['error'] != 0)
        {
            switch ($_FILES['file']['error'])
            {
                case 1:
                    print 'The file is to big.'; // php installation max file size error
					exit;
                    break;
                case 2:
                    print 'The file is to big.'; // form max file size error
					exit;
                    break;
                case 3:
                    print 'Only part of the file was uploaded';
					exit;
                    break;
                case 4:
                    print 'No file was uploaded</p>';
					exit;
                    break;
                case 6:
                    print "Missing a temporary folder.";
					exit;
                    break;
                case 7:
                    print "Failed to write file to disk";
					exit;
                    break;
                case 8:
                    print "File upload stopped by extension";
					exit;
                    break;
 
            }
        } else {
            foreach ($blacklist as $item)
            {
                if (preg_match("/$item\$/i", $_FILES['file']['name']))
                {
                    echo "Invalid filetype !";
                     	$date = date("m/d/Y"); 
    					$time = date("h:i:s A");                 
                		$fp = fopen($log,"ab"); 
                		fwrite($fp,"$ip | ".$_FILES['file']['name']." | $date | $time | INVALID TYPE"."\r\n"); 
                		fclose($fp);
                    unset($_FILES['file']['tmp_name']);
                    exit;
                }
            }
			// Get the extension from the filename.
            $ext = substr($_FILES['file']['name'], strpos($_FILES['file']['name'],'.'), strlen($_FILES['file']['name'])-1); 
   			// Check if the filetype is allowed, if not DIE and inform the user.
   			if(!in_array($ext,$allowed_filetypes)){
						$date = date("m/d/Y"); 
    					$time = date("h:i:s A");                     
                		$fp = fopen($log,"ab"); 
                		fwrite($fp,"$ip | ".$_FILES['file']['name']." | $date | $time | INVALID TYPE"."\r\n"); 
                		fclose($fp);
      					die('The file you attempted to upload is not allowed.');
			}
            if (!file_exists($uploaddir . $_FILES["file"]["name"]))
            {
                // Proceed with file upload
                if (is_uploaded_file($_FILES['file']['tmp_name']))
                {
                    //File was uploaded to the temp dir, continue upload process
                    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $_FILES['file']['name']))
                    {
                        // uploaded file was moved and renamed succesfuly. Display a message.
                        echo "Upload successful !";
                        // Now log the uploaders IP adress date and time
                        $date = date("m/d/Y"); 
    					$time = date("h:i:s A");                
                		$fp = fopen($log,"ab"); 
                		fwrite($fp,"$ip | ".$_FILES['file']['name']." | $date | $time | OK"."\r\n"); 
                		fclose($fp); 
                    } else {
                        echo "Error while uploading the file, Please contact the webmaster.";
                        unset($_FILES['file']['tmp_name']);
                    }
                } else {
                    //File was NOT uploaded to the temp dir
                    switch ($_FILES['file']['error'])
                    {
                        case 1:
                            print 'The file is to big.'; // php installation max file size error
                            break;
                        case 2:
                            print 'The file is to big.'; // form max file size error
                            break;
                        case 3:
                            print 'Only part of the file was uploaded';
                            break;
                        case 4:
                            print 'No file was uploaded</p>';
                            break;
                        case 6:
                            print "Missing a temporary folder.";
                            break;
                        case 7:
                            print "Failed to write file to disk";
                            break;
                        case 8:
                            print "File upload stopped by extension";
                            break;
 
                    }
 
                }
            } else {
                echo "Filename already exists, Please rename the file and retry.";
                unset($_FILES['file']['tmp_name']);
            }
        }
    } else {
        // user did not select a file to upload
        echo "Please select a file to upload.";       
    }
} else {
    // upload button was not pressed
    header("Location: uploadform.php");
}
?>

Tags: , , , ,

Related Posts:

43 Responses to “php file upload”

  1. James Says:

    This is great, easy to understand code and good instructions. However, I have been at it for hours and can not get it to work. I read the instructions to a tee and no joy.

    After several attempts to get the directory folder correct, which I’m still not sure it is, it would just gives me a browser error. I caught that my file upload page was mispelled and corrected that, so now it does not appear to redirect to update.php. If it does, its so fast you can not see it run the upload page at all. So now it just “submits” and lands back on the upload page.

    I’m using WAMP server on my local machine with all the latest updates for PHP and MYSQL.

    Please tell me I’ve overlooked something simple…anyone?

  2. Andi Says:

    I don’t know why it does not work for you but it does seem to work for me.
    I’m using XAMPP by the way, but I don’t think that has any bearing on the subject. try printing every variable both global or local just to check what values are going in the conditions of the different statements. Thank you, I hope I contributed something. Although I can’t seem to make it work if an array is used rather than the switch case statement.

  3. Amardeep Says:

    Awesome Script…It works like a charm…Thank you for doing such a great job. I was looking for something like this for few days and am new to PHP…

    Great job…

  4. seenu Says:

    oh tats working great really a great job and thanx

  5. Iqbal Says:

    Hey

    That script worked right out of the box!!!
    Cool…Now if only somebody would write how to get over the 2MB limit for
    uploads….(in php.ini)…my server does not permit editing php.ini

    Iqbal

  6. Rommel Says:

    What should I do if there is an error: Upload directory is not writable.

  7. pawan Says:

    good

  8. Brandon Says:

    This is great! I’m rather new to PHP and have been messing around as of late, teaching myself new things. Your script was straight forward and very easy to read, and made the uploading extremely easy. Thank you!

  9. dan Says:

    Great script, any idea how I can tweak this script to define the files to be uploaded (specific path on local machines), so basically I would like to save the users the time to browse to the log files as I know where my application is storing these.
    How can I specify the path and file names instead of a browse button functionality?
    Any help is much appreciated!
    Thanks

    Dan

  10. Fawad ali Says:

    i have a form ….name … ADDNEWMULTIMEDIA.php

    Add New Multimedia

    <<Back

    Title: –
    <input name=”tbtitle” type=”text” class=”inputtext” id=”tbtitle” value=”" />

    File: –

    Description: –

     

    this form is posted to….. ADDNEWMULTIMEDIAACTION.php…
    <?php
    require_once(“../includes/allclasses.php”);
    if ((($_FILES["file"]["type"] == “image/gif”)
    || ($_FILES["file"]["type"] == “image/jpeg”)
    || ($_FILES["file"]["type"] == “image/pjpeg”))
    && ($_FILES["file"]["size"] 0)
    {
    echo “Return Code: ” . $_FILES["file"]["error"] . “”;
    }
    else
    {
    echo “Upload: ” . $_FILES["file"]["name"] . “”;
    echo “Type: ” . $_FILES["file"]["type"] . “”;
    echo “Size: ” . ($_FILES["file"]["size"] / 1024) . ” Kb”;
    echo “Temp file: ” . $_FILES["file"]["tmp_name"] . “”;

    if (file_exists(“upload/” . $_FILES["file"]["name"]))
    {
    echo $_FILES["file"]["name"] . ” already exists. “;
    }
    else
    {
    move_uploaded_file($_FILES["file"]["tmp_name"],
    “upload/” . $_FILES["file"]["name"]);
    echo “Stored in: ” . “upload/” . $_FILES["file"]["name"];
    }
    }
    }
    else
    {
    echo “Invalid file”;
    }

    $title = “”;
    $description = “”;
    $file = “”;
    $querystring = array();

    if(isset($_REQUEST['tbtitle']) && !empty($_REQUEST['tbtitle']))
    {
    $title = trim($_REQUEST['tbtitle']);
    $querystring[] = “tbtitle=”.urlencode($_REQUEST['tbtitle']);
    }

    if(isset($_REQUEST['tbdescription']) && !empty($_REQUEST['tbdescription']))
    {
    $description = trim($_REQUEST['tbdescription']);
    $querystring[] = “tbdescription=”.urlencode($_REQUEST['tbdescription']);
    }

    if(isset($_REQUEST['tbfile']) && !empty($_REQUEST['tbfile']))
    {
    $file = trim($_REQUEST['tbfile']);
    $querystring[] = “tbfile=”.urlencode($_REQUEST['tbfile']);
    }
    $qs = implode(“&”,$querystring);

    $nid = $objmultimedia->addnewmultimedia($title, $description, $file);

    if($nid>0)
    {
    header(“location:multimedia.php?msg=3″);
    exit;
    }
    else
    {
    header(“location:addnewmultimedia.php?msg=4&”.$qs);
    exit;
    }
    ?>

    but i can not save the selected(uploaded ) file to another location by move_uploaded_file()… i receive a warning message i.e
    1- Warning: Undefined index: error in C:\Inetpub\wwwroot\icna\admin\addnewmultimediaaction.php on line 8
    2-Warning: Unable to create ‘upload/navsep.jpg’: Permission denied in C:\Inetpub\wwwroot\icna\admin\addnewmultimediaaction.php on line 26

    Warning: Unable to move ‘C:\PHP\uploadtemp\php23.tmp’ to ‘upload/navsep.jpg’ in C:\Inetpub\wwwroot\icna\admin\addnewmultimediaaction.php on line 26
    Stored in: upload/navsep.jpg
    Warning: Cannot add header information – headers already sent by (output started at C:\Inetpub\wwwroot\icna\admin\addnewmultimediaaction.php:8) in C:\Inetpub\wwwroot\icna\admin\addnewmultimediaaction.php on line 64

    can antbody help me.????

  11. rafiq Says:

    Very good

  12. chetan Says:

    hi this is chetan, awesome script, it has helped me a lot…

    i want to ask you guys a question that, if a file is present already at the server then it file already exists rename and retry error, but i want that the script shold check if the filee exists then it should rename the new file being uploaded and then upload it over the server…
    so could you help me with that…

    any help will be greatly appreciated…

    thanks in the advance…

  13. PHP File Upload « 春、夏、秋、冬 Says:

    [...] PHP File Upload 16Apr08 1. PHP File Upload [...]

  14. diva Says:

    Its an awesome article.I was struggling with file upload on server it works like a charm.Although its not exactly what I am looking for yet it is really good article.Thankyou for helping newbies like me!!

  15. Runinord Says:

    Great script well done with good comments and easy to use as well as easy to modify :-)
    Good job.

  16. Puneet Says:

    It doesnt work……..!!!!

    my file name is “example-domain.com/uploader.php”

    When i select the file & press upload. It comes like this :( Please help me!!!!

    I get this error

    // Where the file is going to be placed $target_path = “uploads/”; /* Add the original filename to our target path. Result is “uploads/filename.extension” */ $target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

    my Hosting plan is Linux. Im puting this file in my “www” folder (where “index.html” file resides)

    If i am wrong then Can anyone tell me where should i paste/ add these files or Do i need to add something???

    Atleast reply me …… anyone????? HELP !!!!!!!!!! :(

  17. Ravi Kanojiya Says:

    hi, i have uploaded file in a folder but now i want to show in other page, how does it possible? pls help

  18. Amina Says:

    Can someone please explain what the 1st line is meant to be and should the php file reside where the index does?

  19. Carl Says:

    hi thx for the great script.

    it works like a charm.
    now all i need to find is a script like this to remove files.

    if u have any ideas plz let me know thx

  20. PatrickC Says:

    Question: Is there to be instantly redirected to the picture after it has been uploaded?

  21. PatrickC Says:

    Sorry, it was supposed to say this: Is there a way to be instantly redirected to the picture after it has been uploaded?

  22. Houssam Ballout Says:

    hello,
    Where is the tutorial for making files available for download?!
    Thanks

  23. Mr. Beginner Says:

    Thanks… it really helped me a lot! Structured it is!

  24. Santhosh Says:

    Awesome,Thank You for giving this code.

  25. yeak Says:

    for those don’t knw whether to create a folder .
    NOte -> wamp->www>new>folder. new is the place u store the index.html and upload.php and inside the new folder create a folder name folder

  26. dark vader Says:

    it works like a charm

  27. Denyse Orrego Says:

    A further issue is really that video gaming has become one of the all-time biggest forms of fun for people spanning various ages. Kids engage in video games, and adults do, too. The actual XBox 360 is amongst the favorite games systems for people who love to have hundreds of games available to them, and who like to play live with some others all over the world. Thank you for sharing your ideas.

  28. my egy Says:

    36. hi!,I like your writing very so much! proportion we be in contact extra approximately your post on AOL? I require a specialist in this space to resolve my problem. Maybe that is you! Looking ahead to look you.

  29. BBW Says:

    I genuinely enjoy looking at on this site, it holds fantastic blog posts.

  30. julyanne Says:

    You really make it appear so easy together with your presentation but I to find this topic to be actually one thing that I feel I might never understand. It seems too complicated and very vast for me. I’m taking a look forward to your subsequent put up, I¡¦ll attempt to get the hang of it!

  31. Anonymous Says:

    Awesome Blog. Me and my wife really like your arts ! Keep it up.

  32. world mafia madness Says:

    I haven¡¦t checked in here for a while since I thought it was getting boring, but the last several posts are good quality so I guess I will add you back to my everyday bloglist. You deserve it friend :)

  33. Webhosting Winterthur Says:

    I don?t even know how I finished up here, however I believed this publish was once great. I don’t recognize who you are however certainly you’re going to a well-known blogger in case you aren’t already ;) Cheers!

  34. Bill Lehew Says:

    Somebody essentially help to make seriously articles I would state. This is the very first time I frequented your website page and thus far? I surprised with the research you made to make this particular publish incredible. Wonderful job!

  35. albanian air Says:

    Thank you for your site post. Manley and I are saving to get a new book on this topic and your article has made people like us to save the money. Your notions really clarified all our issues. In fact, a lot more than what we had thought of ahead of the time we came across your excellent blog. My partner and i no longer have doubts and a troubled mind because you clearly attended to our needs in this article. Thanks

  36. Robin Lee Says:

    Personally i think quite happy to have discovered this page and looking forward to much more cool minutes reading here.

  37. Tandy Lundie Says:

    Pretty section of content. I simply stumbled upon your site and in accession capital to assert that I get actually loved account your weblog posts. Any way I’ll be subscribing to your augment and even I achievement you get entry to persistently rapidly.

  38. hair extensions Says:

    A movie I actually want to see? Astonishing!

  39. scary halloween masks Says:

    These vertebrates, as well as an infinity of other life forms — animal and vegetable, marine, terrestrial, and aërial — were the products of unguided evolution acting on life-cells made by the Old Ones, but escaping beyond their radius of attention. They had been suffered to develop unchecked because they had not come in conflict with the dominant beings. Bothersome forms, of course, were mechanically exterminated. It interested us to see in some of the very last and most decadent sculptures a shambling, primitive mammal, used sometimes for food and sometimes as an amusing buffoon by the land dwellers, whose vaguely simian and human foreshadowings were unmistakable. H.P. Lovecraft “At the Mountains of Madness”

  40. Johnny Says:

    What a great piece of text! No idea how you wrote this text..it’d take me days. Well worth it though, I’d suspect. Have you considered selling ads on your website?

  41. full version software download Says:

    Good web site! I truly love how it is easy on my eyes and the data are well written. I am wondering how I could be notified when a new post has been made. I’ve subscribed to your RSS feed which must do the trick! Have a great day! “A crime which is the crime of many none avenge.” by Lucan.

  42. Chiropractor Phoenix Says:

    I simply couldn’t go away your site prior to suggesting that I extremely loved the usual info a person supply to your visitors? Is going to be again continuously to inspect new posts.

  43. fiverr Says:

    I feel this is among the such a lot important info for me. And i am satisfied reading your article. However want to statement on few general things, The website taste is perfect, the articles is in point of fact great : D. Good process, cheers

Leave a Reply