How to Use the PHP move_uploaded_file() Function



In this article, you will learn how to use the PHP move_uploaded_file() function.

PHP move_uploaded_file() Function

The move_uploaded_file() function in PHP is used to move an uploaded file from its temporary location to a new destination on the server.

bool move_uploaded_file ( string $filename , string $destination );
  • $filename: The path to the uploaded file on the server.
  • $destination: The path where the file should be moved to.
  if(isset($_FILES['uploaded_file'])) {
    $filename = $_FILES['uploaded_file']['tmp_name'];
    $destination = 'path/to/destination/' . $_FILES['uploaded_file']['name'];
    if(move_uploaded_file($filename, $destination)) {
      echo 'File successfully uploaded.';
    } else {
      echo 'There was an error uploading the file.';

Note that in order for the move_uploaded_file() function to work, the upload_tmp_dir configuration setting in php.ini must be set to a writable directory.

The move_uploaded_file() function should only be used with files that have been uploaded to the server via an HTTP POST request. The function checks whether the file is a valid uploaded file, and if so, it moves the file to the specified destination.

It is important to validate the uploaded file before calling the move_uploaded_file() function, as the function does not perform any validation itself. For example, you should check that the file is of the correct type, is within an acceptable size limit, and does not contain any malicious content. You can use the $_FILES array to retrieve information about the uploaded file, such as its name, type, size, and temporary location.

The function returns TRUE on success and FALSE on failure. In case of failure, you can use the error element of the $_FILES array to determine the error code, or check the value of $_FILES[‘uploaded_file’][‘error’] for a specific file.

When moving the uploaded file, it is a good practice to specify a unique file name to avoid overwriting existing files with the same name. You can generate a unique file name by appending a timestamp, a random number, or a hash of the original file name to the file name.

It’s also important to set the appropriate permissions on the destination directory to ensure that the file can be written to it. By default, newly created directories are usually readable and writable by the owner and readable by everyone else. You can use the chmod() function to set the permissions on the directory.