PHP File Upload Script

PHP File Uploading Code

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

uploaded file by PHP code

The goal of this script is to take the uploaded file and 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 display if the copy() function fails.

@copy($_FILES[img1][tmp_name], "/usr/local/bin/apache_1.3.26/
htdocs/".$_FILES[img1][name]) or die("Couldn't copy the file.");

 Note  If the document root of your Web server is not /usr/local/bin/apache_1.3.26/htdocs/ as shown in step 3, change the path to match your own system. For example, a Windows user might use /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, then close your PHP block:


Add this HTML:

<TITLE>Successful File Upload</TITLE>

Mingle HTML and PHP, printing a line that displays values for the various elements of the uploaded file (name, size, 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:


Save the file with the name do_upload.php.