What are some best practices for error handling and debugging in PHP scripts like the one for file upload?

Issue: When handling file uploads in PHP scripts, it is important to implement proper error handling and debugging to ensure the script runs smoothly and securely. Best practices include checking for errors in the upload process, handling file validation, and displaying informative error messages to users.

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

// Handle file validation
$allowed_extensions = array('jpg', 'jpeg', 'png');
$upload_extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

if (!in_array($upload_extension, $allowed_extensions)) {
    die('Invalid file extension. Please upload a JPG, JPEG, or PNG file.');
}

// Move uploaded file to destination directory
$upload_path = 'uploads/' . basename($_FILES['file']['name']);

if (!move_uploaded_file($_FILES['file']['tmp_name'], $upload_path)) {
    die('Error moving uploaded file to destination directory.');
}

echo 'File uploaded successfully!';
?>