Rauru.com

About

In Rauru.com I share my experiences and knowledge as a web developer. You'll also find many Internet-related stuff that I believe you'll find extraordinary ;)

Hi peeps,

Ever found yourself wondering how to create a File Upload System using PHP? Today is your lucky day! :P Follow me and I’ll show you how to implement a simple file upload script in your site using PHP.

What we need to get started:

  • A Web Server (like XAMPP) or Internet Host with Php capabilities.
  • Basic to semi-advanced Php knowledge.
  • Basic knowledge of HTML.
  • A text editor to create our little script (like notepad).
  • A folder in our server where to upload the files (eg. uploads)

The Form

The first thing we need is the form that will allow our visitors to select an upload their file to our site. Here’s a sample snippet (which you can also download for testing purposes :D):

Download form.zip
8
9
10
11
<form action="upload.php" method="post" enctype="multipart/form-data">
    <label>File:</label> <input type="file" name="file" /><br />
    <input type="submit" name="submit" value="Submit" />
</form>

Let’s take a closer, deeper look to this form. As you can see, it’s just like any form you might have previously seen in other places except that this time we’re adding a special attribute: ENCTYPE. With it, we are telling our visitor’s browser that this form handles files by setting multipart/form-data as it’s value.

Once the user clicks on the Submit button, the form will send all the data via POST to our script, upload.php, which will handle it and save it to our uploads folder (you didn’t forget to create it, did you?)

The Upload Script

Before we get started, there are a few things that we need to know in order to understand what this snippet do. Php has some predefined variables called Super Variables. These include $_GET, $_POST, $_COOKIE, $_SESSION, $_SERVER, $_ENV, $_FILES and $_REQUEST.

$_FILES is an array that will contain all the information of our uploaded file. The contens of $_FILES are saved as follows:

  • $_FILES['file']['name']: the original name of the file in the visitor’s computer.
  • $_FILES['file']['type']: the mime-type of our file (that is, the file type).
  • $_FILES['file']['size']: the size of the uploaded file (in bytes).
  • $_FILES['file']['temp_name']: The temporary filename of the file in which the uploaded file was stored on the server.
  • $_FILES['file']['error']: The error code associated with this upload.

Note that ‘file‘ is the name we set for our file input field in our upload form. It can be whatever you want! Here’s our script:

Download upload.zip
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
<?php
// Upload directory: remember to give it write permission!
$uploaddir = “upload/”;
// 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['submit']) {
 
    if (isset($_FILES['file'])) {
        if ($_FILES['file']['error'] != 0) {
            switch ($_FILES['file']['error']) {
                case 1:
                    print ‘The file is too big.’; // php installation max file size error
                    exit;
                    break;
                case 2:
                    print ‘The file is too big.’; // form max file size error - DEPRECATED
                    exit;
                    break;
                case 3:
                    print ‘Only part of the file was uploaded’.;
                    exit;
                    break;
                case 4:
                    print ‘No file was uploaded.’;
                    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 !”;
                    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)){
				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!”;
					} 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 too big.’; // php installation max file size error
							break;
						case 2:
							print ‘The file is too 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’;
							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 { // There’s a file with the same name
				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: form.html”);
}
?>

Now, what does our little script do?:

  1. Set our upload folder.
  2. Set a fyletype blacklist and a filetype whitelist.
  3. Check that our uploads directory exists and is writable.
  4. Now, we validate that our user clicked on the Submit button. If he didn’t then redirect him to the form.
  5. Check if our super variable $_FILES has found any error on our uploaded file.
  6. Validate our uploaded file against our file type blacklist to prevent people uploading things that we don’t want on our server.
  7. Check that the file doesn’t exist. If there’s another file with the same name we alert our visitor and abort the upload process. Otherwise we save the file in our uploads folder and let him know that the upload was succesful.

Hope that helps ;)

P. S.: oh, and if you liked my tutorial please don’t forget to Digg it! :D :D

13 Responses to “A Simple File Upload Script using PHP”

  1. It’s a nice one, definelty handy specially for php newbies..
    Keep going!
    - Wakish -

    Wakish

  2. i dont have a website yet.. but its someone who told me to upload something to his website.. so i found dis tutorial is didactic.. good for newbies
     

    rain

  3. Excelente! muchas gracias! :D

    jose

  4. @jose: De nada ;)

    Ikki

  5.  Do just need to upload the uploads folder, form.php and upload.php on to my site? Because in my browser when i click submit it has just a blank page… What did i do wrong?

    Karen

  6. @Karen: You need to create a “upload” folder on your server and give it writing permissions before using this script. Remember to change the path to its location in line 3!

    Give it a try and let me know if it worked, ok? ;)

    Ikki

  7. Gave ‘upload’ folder writing permissions 0774.  Changed the path to ‘public_html/orielchambers/upload’ (the path on my server). The browser sends my page to upload.php with blank page still.

    Karen

  8. @Karen: I think you’re setting the wrong path. Try this: put both scripts (the form and the uploaded script) in the folder “orielchambers” and set your $uploaddir variable to “upload/”.

    If it doesn’t work please let me know. I may give you a hand with your script if you allow me to do so.

    Ikki

  9. No sorry it doesnt work.
    Here’s my script:-

    <?php
    // Upload directory: remember to give it write permission!
    $uploaddir = “upload/”;
    // 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['submit']) {
     
        if (isset($_FILES['file'])) {
            if ($_FILES['file']['error'] != 0) {
                switch ($_FILES['file']['error']) {
                    case 1:
                        print ‘The file is too big.’; // php installation max file size error
                        exit;
                        break;
                    case 2:
                        print ‘The file is too big.’; // form max file size error - DEPRECATED
                        exit;
                        break;
                    case 3:
                        print ‘Only part of the file was uploaded’.;
                        exit;
                        break;
                    case 4:
                        print ‘No file was uploaded.’;
                        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 !”;
                        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)){
    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!”;
    } 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 too big.’; // php installation max file size error
    break;
    case 2:
    print ‘The file is too 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’;
    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 { // There’s a file with the same name
    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: form.html”);
    }
    ?>

    Karen

  10. Upload.php and form.html and the ‘uploads’ folder are all in orielchambers folder on public.html.

    Karen

  11. @Karen: I think I found your problem. See this line in your script:

    $blacklist = array(“.php”, “.phtml”, “.php3?, “.php4?, “.php5?, “.exe”, “.js”,“.html”, “.htm”, “.inc”);

    You’re missing some closing double-quotes in your blacklist array. It should be like this:

    $blacklist = array(“.php”, “.phtml”, “.php3?”, “.php4?”, “.php5?”, “.exe”, “.js”,“.html”, “.htm”, “.inc”);

    It should work now. You were getting a blank page because of a PHP error. You should enable PHP to display errors in your scripts in order to let you know when something goes wrong (but use it only on testing enviroments, never on production enviroments!).

    Let me know if it worked, ok?

    Ikki

  12. Corrected the line, and….. it still gives me a blank page. This one is weird!

    Karen

  13. @Karen: Strange. I didn’t find any further errors on your script. Try adding this line to your upload.php:

    error_reporting(E_ALL);

    This function will tell PHP to display any errors it might encounter while executing this script. Please copy the error message and post it here :)

    Ikki

Leave a Reply