Skip to content
PHP Logo

What are the potential pitfalls when using the move_uploaded_file function in PHP for file uploads?

One potential pitfall when using the move_uploaded_file function in PHP for file uploads is not properly validating the file before moving it to the desired directory. This can lead to security vulnerabilities such as allowing malicious files to be uploaded and executed on the server. To mitigate this risk, it is important to validate the file type, size, and ensure that the file is not already present in the target directory before moving it.

php
// Example code snippet for validating file before moving it
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $file_name = $_FILES['file']['name'];
    $file_tmp = $_FILES['file']['tmp_name'];
    
    $target_dir = "uploads/";
    
    // Validate file type
    $allowed_extensions = ['jpg', 'jpeg', 'png', 'pdf'];
    $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
    
    if (!in_array($file_extension, $allowed_extensions)) {
        echo "Invalid file type. Allowed file types are: " . implode(', ', $allowed_extensions);
        exit;
    }
    
    // Validate file size
    if ($_FILES['file']['size'] > 5242880) { // 5MB
        echo "File size exceeds the limit of 5MB";
        exit;
    }
    
    // Check if file already exists in target directory
    if (file_exists($target_dir . $file_name)) {
        echo "File already exists";
        exit;
    }
    
    // Move the uploaded file to the target directory
    if (move_uploaded_file($file_tmp, $target_dir . $file_name)) {
        echo "File uploaded successfully";
    } else {
        echo "Error uploading file";
    }
} else {
    echo "Error uploading file: " . $_FILES['file']['error'];
}