Current Location: Home> Latest Articles> Comprehensive Guide to PHP move_uploaded_file() Function: Secure File Upload Handling

Comprehensive Guide to PHP move_uploaded_file() Function: Secure File Upload Handling

gitbox 2025-07-22

Introduction to move_uploaded_file() Function

In PHP, the move_uploaded_file() function is used to move an uploaded file from its temporary directory to a specified new location. It is commonly used for handling user-uploaded files such as images, documents, and more, providing effective management of uploaded file storage.

The function syntax is as follows:

<span class="fun">bool move_uploaded_file(string $filename, string $destination)</span>

Here, $filename is the temporary path of the uploaded file, and $destination is the target path. The function returns true if the move is successful, or false otherwise.

How to Use move_uploaded_file() to Move Uploaded Files

Ensure the Uploaded File Exists

Before calling move_uploaded_file(), verify that the uploaded file exists and there are no errors. You can check the file info using the $_FILES array.

$file_tmp = $_FILES['file']['tmp_name'];
if (!file_exists($file_tmp)) {
    echo "Uploaded file does not exist!";
    exit;
}

Check and Create Target Directory

Before moving the file, ensure the target directory exists. If it doesn't, create it using mkdir() and set appropriate permissions.

$destination = "uploads/";
if (!is_dir($destination)) {
    mkdir($destination, 0777, true);
}

Perform the File Move Operation

Once the uploaded file and target directory are confirmed, use move_uploaded_file() to move the file and check the result to determine success.

$filename = $_FILES['file']['name'];
$destination_path = $destination . $filename;
if (move_uploaded_file($file_tmp, $destination_path)) {
    echo "File moved successfully!";
} else {
    echo "File move failed!";
}

Important Notes

Set Directory Permissions

To ensure files can be saved successfully, the target directory must have read and write permissions. Use the chmod() function to adjust permissions if necessary.

<span class="fun">chmod($destination, 0777);</span>

This grants the directory read, write, and execute permissions, facilitating file management.

Prevent File Overwriting

If a file with the same name already exists in the target directory, move_uploaded_file() will overwrite it. It is recommended to check for existing files before moving the uploaded file.

$filename = $_FILES['file']['name'];
$destination_path = $destination . $filename;
if (file_exists($destination_path)) {
    echo "File already exists!";
    exit;
}

Conclusion

This article explains the usage of PHP's move_uploaded_file() function in detail, covering file existence checks, target directory management, permission settings, and file overwrite prevention. Mastering these aspects helps developers handle file uploads more securely and effectively.