In the context of PHP, what are some common mistakes to avoid when dealing with file uploads and file manipulation in scripts, as demonstrated in the code snippet shared in the forum thread?

Common mistakes to avoid when dealing with file uploads and file manipulation in PHP scripts include not checking for errors during the file upload process, not validating file types and sizes, and not sanitizing user input to prevent directory traversal attacks. To address these issues, always check for errors after uploading a file, validate file types and sizes before processing them, and sanitize user input to prevent security vulnerabilities.

// Check for errors during file upload
if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    die('File upload failed with error code: ' . $_FILES['file']['error']);
}

// Validate file type and size
$allowedTypes = ['image/jpeg', 'image/png'];
$maxSize = 5 * 1024 * 1024; // 5MB

if (!in_array($_FILES['file']['type'], $allowedTypes) || $_FILES['file']['size'] > $maxSize) {
    die('Invalid file type or size. Only JPEG and PNG files under 5MB are allowed.');
}

// Sanitize user input to prevent directory traversal attacks
$fileName = basename($_FILES['file']['name']);
$filePath = 'uploads/' . $fileName;

if (!move_uploaded_file($_FILES['file']['tmp_name'], $filePath)) {
    die('Failed to move uploaded file to destination directory.');
}

echo 'File uploaded successfully.';