PHP Upload File Using Forms
You can upload files on server using a HTML form and PHP. You can upload any kind of file like images, videos, ZIP files, Microsoft Office documents, PDFs, and other files.
The uploaded file can be saved in any folder on permanent basis. You can also implement some basic security check like file type and file size to ensure that users upload the correct file type and within the allowed limit.
1. HTML Form
For file uploading to work, the form's optional enctype attribute must be set to "multipart/form-data".
<form action="mypage.php" method="post" enctype="multipart/form-data">
<input name="myfile" type="file">
<input type="submit" name="submit" value="Upload">
</form>
2. $_FILES Array
After the form is submitted, information about the uploaded file can be accessed via PHP superglobal array $_FILES. For example, if the upload form contains a file select field with name="photo", you can obtain its details like the name, type, size, temporary name or any error occurred while attempting the upload the file.
$_FILES['photo']['name']: This variable specifies the original name of the file, including the extension. It doesn't include the file path. Therefore, if you browse to a file named vacation.png and upload it via the form, this variable will be assigned the value vacation.png.
$_FILES['photo']['type']: This variable specifies the MIME type of the file. Therefore, in the case of the vacation.png image file, this variable would be assigned the value image/png. If a PDF was uploaded, the value application/pdf would be assigned.
$_FILES['photo']['size']: This variable specifies the size, in bytes, of the file. For example, in the case of the vacation.png file, this variable could plausibly be assigned a value such as 5253, or roughly 5KB.
$_FILES['photo']['tmp_name']: This variable specifies the temporary name assigned to the file once it has been uploaded to the server. This is the name of the file assigned to it while stored in the temporary directory (specified by the PHP directive upload_tmp_dir).
$_FILES['photo']['error']: This array value offers important information pertinent to the outcome of the upload attempt.
PHP offers two functions specifically intended to aid in the file upload process, is_uploaded_file() and move_uploaded_file().
3. Determining Whether File Was Uploaded
The is_uploaded_file() function determines whether a file specified by the input parameter filename is uploaded using the POST method. If the answer is yes, the file is copied to the desired destination. Otherwise, an error message is displayed.
if (is_uploaded_file($_FILES['photo']['tmp_name']))
{
// copy file
}
else
{
// display error message
}
4. Moving an Uploaded File
After a file has been successfully uploaded, it is temporarily stored on the server. To use this file, or store it permanently, you need to move it from the temporary directory to a permanent location using the move_uploaded_file() function.
Although copy() works equally well, move_uploaded_file() offers one additional feature: it will check to ensure that the file denoted by the filename input parameter was in fact uploaded via PHP's HTTP POST upload mechanism. If the file has not been uploaded, the move will fail and a FALSE value will be returned. Because of this, you can forgo using is_uploaded_file() as a precursor condition to using move_uploaded_file().
// Check if file was uploaded without errors
if (isset($_FILES['photo']) && $_FILES['photo']['error'] == 0)
{
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (!array_key_exists($ext, $allowed))
{
die("Error: Please select a valid file format.");
}
// Verify file size - 5 MB maximum
$maxsize = 5 * 1024 * 1024;
if ($filesize > $maxsize)
{
die("Error: File size is larger than the allowed limit.");
}
// Verify MYME type of the file
if (in_array($filetype, $allowed))
{
// Check whether file exists before uploading it
if (file_exists("upload/" . $_FILES["photo"]["name"]))
{
echo $_FILES["photo"]["name"] . " is already exists.";
}
else
{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]);
echo "Your file was uploaded successfully.";
}
}
else
{
echo "Error: There was a problem uploading your file. Please try again.";
}
}
else
{
echo "Error: " . $_FILES["photo"]["error"];
}
The move_uploaded_file() function checks to ensure that the first argument contains a valid upload file, and if so, it moves it to the path and renames it to the file name specified by the second argument. The specified folder must already exist, and if the function succeeds in moving the file, it returns true.
5. Upload Error Messages
Sufficient information for determining the outcome (and in the case of an error, the reason for the error) is provided in $_FILES['userfile']['error'].
UPLOAD_ERR_OK: A value of 0 is returned if the upload is successful.
UPLOAD_ERR_INI_SIZE: A value of 1 is returned if there is an attempt to upload a file whose size exceeds the value specified by the upload_max_filesize directive.
UPLOAD_ERR_FORM_SIZE: A value of 2 is returned if there is an attempt to upload a file whose size exceeds the value of the max_file_size directive, which can be embedded into the HTML form.
UPLOAD_ERR_PARTIAL: A value of 3 is returned if a file is not completely uploaded. This might happen if a network error causes a disruption of the upload process.
UPLOAD_ERR_NO_FILE: A value of 4 is returned if the user submits the form without specifying a file for upload.
UPLOAD_ERR_NO_TMP_DIR: A value of 6 is returned if the temporary directory does not exist.
UPLOAD_ERR_CANT_WRITE: A value of 7 is returned if the file can’t be written to the disk.
UPLOAD_ERR_EXTENSION: A value of 8 is returned if an issue with PHP’s configuration caused the upload to fail.