Processing the Form Data (PHP Code)
When the file was uploaded, PHP created a temporary copy of the file, and built the superglobal $_FILES array containing information about the file. For each file, there are five pieces of data. We had named our upload field 'uploaded_file', so the following data would exist:
$_FILES["uploaded_file"]["name"] the original name of the file uploaded from the user's machine
$_FILES["uploaded_file"]["type"] the MIME type of the uploaded file (if the browser provided the type)
$_FILES["uploaded_file"]["size"] the size of the uploaded file in bytes
$_FILES["uploaded_file"]["tmp_name"] the location in which the file is temporarily stored on the server
$_FILES["uploaded_file"]["error"] an error code resulting from the file upload
The example below accepts an uploaded file and saves it in the upload directory. It allows to upload only JPEG images under 350Kb. The code, itself, is rather clear, but we will give a little explanation. Have a look at the example and save this PHP code as upload.php.
<?php
//Сheck that we have a file
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) {
//Check if the file is JPEG image and it's size is less than 350Kb
$filename = basename($_FILES['uploaded_file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") &&
($_FILES["uploaded_file"]["size"] < 350000)) {
//Determine the path to which we want to save this file
$newname = dirname(__FILE__).'/upload/'.$filename;
//Check if the file with the same name is already exists on the server
if (!file_exists($newname)) {
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) {
echo "It's done! The file has been saved as: ".$newname;
} else {
echo "Error: A problem occurred during file upload!";
}
} else {
echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists";
}
} else {
echo "Error: Only .jpg images under 350Kb are accepted for upload";
}
} else {
echo "Error: No file uploaded";
}
?>
Before you do anything with the uploaded file you need to determine whether a file was really uploaded. After that we check if the uploaded file is JPEG image and its size is less than 350Kb. Next we determine the path to which we want to save this file and check whether there is already a file with such name on the server. When all checks are passed we copy the file to a permanent location using the move_upload_file() function. This function also confirms that the file you're about to process is a legitimate file resulting from a user upload. If the file is uploaded successfully then the corresponding message will appear.