Articles: Handling file uploads

Kristian Fiskerstrand's blog

In this article we'll describe how to allow a visitor to upload a file, and then check that the file is filetype we accept.
Added: 2003-07-15 21:14:14 - Modified: 2005-12-27 19:23:18 - Level: Beginner
Printer friendly version PDF File
Recommend this article to a friend.

Bookmark this on google Bookmark this on del.icio.us Submit this to digg Bookmark this at yahoo Bookmark this at reddit Bookmark this at furl Search technorati for links to this page Toggle more
1 2

Next page >>

PHP has made it trivial to upload files, but dispite this people seem to be having problems, therefore I decided to write a little article on the subject, and hopefully it will describe how simple it is to someone else, after all, everything is simple when you know it.

Since PHP 4.1, some super global values was introduced, among these were the $_FILES array. The usage is fairly simple, $_FILES['inputname'][], where the 2nd brackets contain diffrent choices, depending on the information we want to get, we are going to use tmp_name and name. The tmp_name is the temporary location of the file after it has been uploaded to the server. This is usually some temporary directory, eg /tmp on a Unix based file system. The name contain the name of the file, without a path. You also have a choice named type that contains the MIME type of the file. This can be used to control the file types we want to allow.

We submit the data to the PHP file using the POST method of a standard form, including a <input type="file" [...].

<?xml version="1.0" encoding="iso-8859-1" ?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Our file uploader</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="myfile1" />
<input type="file" name="myfile2" />
<input type="submit" value="Upload files" />
</form>
</body>
</html>

we name this file form.htm. This is the whole page needed, written as valid XHTML 1.0 Strict, as the form action tell, it send the data to the page upload.php. This is the script that perform the actual file uploading. You should also note that here is 2 files being submitted, this can be extended depending on the need and the configuration of the server. On the next page you will find the upload.php file.

1 2

Next page >>

Related articles:



[Sitemap]