is_uploaded_file
is_uploaded_file($filename)
Returns true when the file was uploaded by a form in the current request (the path from $_FILES["…"]["tmp_name"]). It protects against slipping in a path to another file on the server.
Parameters
- $filename – the temporary path from $_FILES["field"]["tmp_name"].
Examples
// an ordinary file does not pass
$file = sys_get_temp_dir() . "/garth-example.txt";
file_put_contents($file, "x");
var_dump(is_uploaded_file($file)); // bool(false)
unlink($file);
// error codes in $_FILES["…"]["error"]
echo UPLOAD_ERR_OK; // 0
echo UPLOAD_ERR_INI_SIZE; // 1
echo UPLOAD_ERR_NO_FILE; // 4
// checking a file uploaded from a form
// $f = $_FILES["photo"] ?? null;
// if ($f === null || $f["error"] !== UPLOAD_ERR_OK || !is_uploaded_file($f["tmp_name"])) { … error … }
// if ($f["size"] > 5 * 1024 * 1024) { … too large … }
Things to watch out for
- Always check $_FILES["…"]["error"] first. When a limit is exceeded (upload_max_filesize, post_max_size), the file does not arrive at all.
- When the form data exceed post_max_size, both $_FILES and $_POST are empty. The form then looks as if it was not sent.
- The name ($_FILES["…"]["name"]) and the type (["type"]) are sent by the browser and can be forged. Check the type by the content with finfo_file().
- For saving, use move_uploaded_file(), which does the check itself.
Related functions:
move_uploaded_file()
finfo_file()
getimagesize()