How to check whether the user uploaded a file in PHP?
In PHP, you can use the $_FILES
superglobal array to check if a file has been uploaded. The $_FILES
array contains information about all files that have been uploaded in the current request.
You can check if a file has been uploaded by checking if the $_FILES
array is not empty and if the error code for the file is UPLOAD_ERR_OK
, which indicates that the file was uploaded successfully. Here's an example:
<?php
if (!empty($_FILES) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
// File was uploaded
} else {
// File was not uploaded
}
In this example, file
is the name of the file input field in the HTML form used to upload the file.
You may also want to check for other error codes like UPLOAD_ERR_NO_FILE
to check if the user did not upload any file or UPLOAD_ERR_INI_SIZE
if the file size exceeds the allowed limit.