What are potential pitfalls to avoid when modifying existing PHP scripts for file uploads and downloads?

One potential pitfall to avoid when modifying existing PHP scripts for file uploads and downloads is not properly sanitizing user input, which can lead to security vulnerabilities such as directory traversal attacks. To prevent this, always validate and sanitize user input before using it to determine file paths.

// Validate and sanitize user input for file uploads
$upload_dir = '/path/to/uploads/';
$allowed_extensions = ['jpg', 'png', 'pdf'];

if(isset($_FILES['file']) && $_FILES['file']['error'] == 0) {
    $file_extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
    
    if(in_array($file_extension, $allowed_extensions)) {
        $upload_path = $upload_dir . basename($_FILES['file']['name']);
        
        if(move_uploaded_file($_FILES['file']['tmp_name'], $upload_path)) {
            echo 'File uploaded successfully!';
        } else {
            echo 'Failed to upload file.';
        }
    } else {
        echo 'Invalid file extension.';
    }
} else {
    echo 'No file selected or error uploading file.';
}