An upload script permits users to upload a file from a client computer to the remote server. It contains two parts: the HTML form and the PHP code. The HTML code for an upload form field is:
The enctype attribute of the form tag indicates that the form should be able to handle multiple types of data, including files.
When an user click on the Submit button, the form data are sent to the PHP script specified in the action attribute ("script.php"). If you want form data to be sent to the same page, you can use action="".
In the PHP code, the uploaded file can be accessed using the $_FILES superglobal. This variable is an array with the fallowing elements:
$_FILES['file']['name'] - the original name of the uploaded file
$_FILES['file']['type'] - the type of the file
$_FILES['file']['size'] - the size in bytes of the uploaded file
$_FILES['file']['tmp_name'] - the location and name of the temporary copy of the file stored on the server
$_FILES['file']['error'] - the error code associated with any problem resulting from the file upload. A value of 0 indicates there is no error.
Assuming that is uploaded a JPEG image (image.jpg), this code will output:
Create an Upload Script with Restrictions on upload
The uploaded file is initially copied in a temporary directory, and disappears when the PHP script ends. The move_uploaded_file() function can transfer it from the temporary directory to anoter folder. Syntax:
- "temp_file" is the location and name of the temporary copy of the file, that is stored in $_FILES['field_name']['tmp_name'] - "destination" is the destination and name of the moved file.
You can add restrictions on what the user is allowed to upload, by checking the values of $_FILES array. For example, you can restrict the type or size of the uploaded file. In this script, the user may only upload .gif, .jpeg or .png files and the file size must be under 100 kb (see also the comments in script code)
- The move_uploaded_file() function will overwrite an existing file, with the same filename, without warning, so the script checks if the file already exists (with file_exists() ), if it does not, it copies the file to the directory specified in the $updir variable (here "uploads"). - The expresion: end(explode('.', strtolower($fname))) splits the name of the file by the "." delimiter and gets the last element (in lowercase), which is the file extension. - The if (in_array($ftype, $allowtype)) instruction returns TRUE if $ftype is found in the $allowtype array, otherwise, False. - If the file is successfully uploaded, returns a confirmation message with the name and the size of the file.