Back to results for “File Upload Handling”
PHP › File Upload Handling

How do you move an uploaded file from its temporary location to a permanent storage location using move_uploaded_file?

Beginner

Answer

The move_uploaded_file function safely moves a file that was uploaded through an HTTP POST request from its temporary server location to a permanent destination you specify, and it specifically verifies that the file was genuinely uploaded through PHP's upload mechanism rather than being an arbitrary file path, providing an important security check compared to using a generic file move function for this specific purpose.
$destination = 'uploads/' . basename($_FILES['document']['name']);
if (move_uploaded_file($_FILES['document']['tmp_name'], $destination)) {
    echo 'Upload successful';
}
Real-world example A file upload handler moves a successfully validated upload from its temporary location into a permanent uploads folder using move_uploaded_file, taking advantage of its built in verification that the file genuinely came from a legitimate upload.

Common follow-ups: Why is move_uploaded_file preferred over a generic rename or copy function for this purpose?;What happens if move_uploaded_file fails, such as due to a permissions issue on the destination folder?