Skip to content
PHP Logo

What are common pitfalls when using move_uploaded_file in PHP?

One common pitfall when using move_uploaded_file in PHP is not checking if the file was successfully uploaded before attempting to move it. This can lead to errors if the file was not uploaded properly. To solve this, always check the return value of move_uploaded_file to ensure the file was moved successfully.

php
// Check if file was uploaded successfully before moving it
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $uploadDir = 'uploads/';
    $uploadFile = $uploadDir . basename($_FILES['file']['name']);

    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
        echo "File was uploaded successfully.";
    } else {
        echo "Error moving file.";
    }
} else {
    echo "Error uploading file.";
}