Take a moment to commit the following list to memory—it contains the variables that are automatically placed in the $_FILES superglobal after a successful file upload. The base of img1 comes from the name of the input field in the original form.
$_FILES[$img1][tmp_name]. The value refers to the temporary file on the web server.
$_FILES[img1][name]. The value is the actual name of the file that was uploaded. For example, if the name of the file was me.jpg, the value of $_FILES[img1][name] is me.jpg.
$_FILES[img1][size]. The size of the uploaded file in bytes.
$_FILES[img1][type]. The MIME type of the uploaded file, such as image/jpg.
| Note |
A MIME type indicates the type of the content being transmitted. For instance, the MIME type of a JPEG file is image/jpg, and the MIME type of a Microsoft Word document is application/msword. |
The goal of this script is to take the uploaded file, copy it to the document root of the web server, and return a confirmation to the user containing values for all the variables in the preceding list.
Open a new file in your text editor and start a PHP block:
<?
Create an if…else statement that checks for a value in $_FILES[img1]. if ($_FILES[img1] != "") {
If $_FILES[img1] is not empty, execute the copy function. Use @ before the function name to suppress warnings, and use the die() function to cause the script to end and a message to be displayed if the copy() function fails.
@copy($_FILES[img1][tmp_name],
"/usr/local/apache2/htdocs/".$_FILES[img1][name])
or die("Couldn't copy the file.");
| Note |
If the document root of your web server is not /usr/local/apache2/htdocs/, as shown in step 3, change the path to match your own system. For example, a Windows user might use /Program Files/Apache Group/Apache/htdocs/. |
Continue the else statement to handle the lack of a file for upload:
} else {
die("No input file specified");
Close the if…else statement, and then close your PHP block:
} ?>
Add this HTML:
<HTML> <HEAD> <TITLE>Successful File Upload</TITLE> </HEAD> <BODY> <H1>Success!</H1>
Mingle HTML and PHP, printing a line that displays values for the various elements of the uploaded file (name, size, and type):
<P>You sent: <? echo $_FILES[img1][name]; ?>, a <? echo $_FILES[img1][size]; ?> byte file with a mime type of <? echo $_FILES[img1][type]; ?>.</P>
Add some more HTML so that the document is valid:
</BODY> </HTML>
Save the file with the name do_upload.php.
The code should look something like the following figure.
In the next section, you finally get to upload a file!