How can error reporting and handling be optimized in PHP scripts to troubleshoot issues like file upload failures?

When troubleshooting file upload failures in PHP scripts, error reporting and handling can be optimized by enabling error reporting, checking for specific file upload errors, and providing informative error messages to the user.

// Enable error reporting for file uploads
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Check for file upload errors
if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    switch ($_FILES['file']['error']) {
        case UPLOAD_ERR_INI_SIZE:
            $errorMsg = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
            break;
        case UPLOAD_ERR_FORM_SIZE:
            $errorMsg = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
            break;
        case UPLOAD_ERR_PARTIAL:
            $errorMsg = 'The uploaded file was only partially uploaded';
            break;
        case UPLOAD_ERR_NO_FILE:
            $errorMsg = 'No file was uploaded';
            break;
        case UPLOAD_ERR_NO_TMP_DIR:
            $errorMsg = 'Missing a temporary folder';
            break;
        case UPLOAD_ERR_CANT_WRITE:
            $errorMsg = 'Failed to write file to disk';
            break;
        case UPLOAD_ERR_EXTENSION:
            $errorMsg = 'A PHP extension stopped the file upload';
            break;
        default:
            $errorMsg = 'Unknown upload error';
            break;
    }

    // Display error message to the user
    echo $errorMsg;
}