9.6. Processing Uploaded Files
Problem
You want to process a file uploaded by a user.
Solution
Use the $_FILES
array:
// from <input name="event" type="file"> if (is_uploaded_file($_FILES['event']['tmp_name'])) { readfile($_FILES['event']['tmp_name']); // print file on screen }
Discussion
Starting in PHP 4.1, all uploaded files appear in the
$_FILES
superglobal array. For each file, there are four pieces of
information:
-
name
The name assigned to the form input element
-
type
The MIME type of the file
-
size
The size of the file in bytes
-
tmp_name
The location in which the file is temporarily stored on the server.
If you’re using an earlier version of PHP, you need
to use $HTTP_POST_FILES
instead.
After you’ve selected a file from that array, use
is_uploaded_file( )
to confirm that the file
you’re about to process is a legitimate file
resulting from a user upload, then process it as you would other
files on the system. Always do this. If you blindly trust the
filename supplied by the user, someone can alter the request and add
names such as /etc/passwd to the list for
processing.
You can also move the file to a permanent location; use
move_uploaded_file( )
to safely transfer the file:
// move the file: move_uploaded_file() also does a check of the file's // legitimacy, so there's no need to also call is_uploaded_file() move_uploaded_file($_FILES['event']['tmp_name'], '/path/to/file.txt');
Note that the value stored in tmp_name
is the complete path to the file, not just the base name. ...
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.