What are some key considerations for error handling and debugging in PHP scripts, especially when dealing with file uploads?

When dealing with file uploads in PHP scripts, it is important to implement proper error handling and debugging techniques to ensure the smooth functioning of the upload process. Some key considerations include checking for file upload errors, validating file types and sizes, setting appropriate file permissions, and logging errors for troubleshooting.

// Check for file upload errors
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. Allowed types: jpeg, png. Max size: 5MB');
}

// Set appropriate file permissions
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);

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

// Log errors for troubleshooting
error_log('File uploaded successfully: ' . $uploadFile);