move_uploaded_file
move_uploaded_file($from, $to)
Moves a file uploaded by a form from the temporary folder to its destination. Returns true. For a file that did not come from a form it returns false and moves nothing.
Parameters
- $from – the temporary path from $_FILES["field"]["tmp_name"].
- $to – the target path including the file name. It overwrites an existing file.
Examples
// it does not move a file that did not come from a form
$file = sys_get_temp_dir() . "/garth-example.txt";
file_put_contents($file, "x");
var_dump(move_uploaded_file($file, sys_get_temp_dir() . "/garth-target.txt")); // bool(false)
var_dump(file_exists($file)); // bool(true)
unlink($file);
// a safe name: random, the extension by the detected type
$extensions = array("image/jpeg" => "jpg", "image/png" => "png", "image/webp" => "webp");
// the type detected with finfo_file() from the uploaded file
$type = "image/png";
$name = bin2hex(random_bytes(8)) . "." . $extensions[$type];
var_dump(preg_match('/^[0-9a-f]{16}\.png$/', $name)); // int(1)
// saving from a form
// if (move_uploaded_file($_FILES["photo"]["tmp_name"], __DIR__ . "/uploads/" . $name)) { … }
Things to watch out for
- Never use the original file name as the target. A file “image.php” would be saved and could be run. Create the name yourself and derive the extension from the type detected by the content.
- The folder with uploaded files should not run PHP. On Apache this is ensured by .htaccess turning PHP off, or by storing files outside the site folder.
- The target folder must exist and PHP must be allowed to write to it. An existing file with the same name is overwritten.
- PHP deletes the temporary file at the end of the request. When you do not move it, it disappears.
Related functions:
is_uploaded_file()
finfo_file()
random_bytes()
getimagesize()