PHP is_uploaded_file() Function
The PHP is_uploaded_file() function checks whether a file was uploaded via HTTP POST.
This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working. For example - /etc/passwd. This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.
For proper working, this function needs an argument like $_FILES['userfile']['tmp_name'] - the name of the uploaded file on the client's machine $_FILES['userfile']['name'] does not work.
Syntax
is_uploaded_file(filename)
Parameters
filename |
Required. Specify the path to the file to check. |
Return Value
Returns true if the file was uploaded via HTTP POST, otherwise returns false.
Example: is_uploaded_file() example
Lets assume that we have a file called test.txt in the current working directory. The example below demonstrates on using this function to check whether this file is uploaded via HTTP POST or not.
<?php $file = 'test.txt'; //checking if $file is uploaded via HTTP POST if(is_uploaded_file($file)) { echo "The file $file is uploaded via HTTP POST.\n"; } else { echo "The file $file is not uploaded via HTTP POST.\n"; } ?>
The output of the above code will be:
The file test.txt is not uploaded via HTTP POST.
Example: displaying content of the file if uploaded via HTTP POST
Consider one more example where the content of the file is displayed to the user, if the file is uploaded via HTTP POST.
<?php //checking if the file is uploaded via HTTP POST if (is_uploaded_file($_FILES['userfile']['temp_test.txt'])) { echo "File ". $_FILES['userfile']['test.txt']. " is uploaded successfully.\n"; //displaying contents of the file echo "Displaying contents:\n"; readfile($_FILES['userfile']['test.txt']); } else { echo "File ". $_FILES['userfile']['test.txt'] . " is not uploaded successfully.\n"; } ?>
The output of the above code will be:
File test.txt is uploaded successfully. Displaying contents: This is a test file. It contains dummy content.
❮ PHP Filesystem Reference