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

One Response to “A Simple File Upload Script using PHP”

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

    Wakish

Leave a Reply