PHP Function Reference

PHP move_uploaded_file() Function



The PHP move_uploaded_file() function moves an uploaded file to a new location. This function only works on files uploaded via PHP's HTTP POST upload mechanism. If the destination file already exists, it will be overwritten.

Syntax

move_uploaded_file(file, dest)

Parameters

file Required. Specify the filename of the uploaded file.
dest Required. Specify the destination of the moved file.

Return Value

Returns true on success. If file is not a valid upload file, then no action will occur, and returns false. If file is a valid upload file, but cannot be moved due to any reason, no action will occur, and returns false. Additionally, a warning will be issued.

Example: move_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 move this file to the specified location.

<?php
$file = 'test.txt';
$dest = '/temp/test.txt';

//moving if $file is uploaded via HTTP POST
if(move_uploaded_file($file, $dest)) {
  echo "$file is moved to $dest\n";
} else {
  echo "$file can not be moved to $dest\n";
}
?>

The output of the above code will be:

test.txt can not be moved to /temp/test.txt

Example: uploading multiple files

Consider one more example where multiple files are uploaded and moved to the specified location.

<?php
$upload_dir = '/temp';

foreach ($_FILES["fig"]["error"] as $key => $error) {
  if ($error == UPLOAD_ERR_OK) {
    $tmp_name = $_FILES["fig"]["tmp_name"][$key];
    
    $name = basename($_FILES["fig"]["name"][$key]);
    move_uploaded_file($tmp_name, "$upload_dir/$name");
  }
}
?>

❮ PHP Filesystem Reference