What are some best practices for error handling and reporting in PHP when dealing with file uploads?

When dealing with file uploads in PHP, it is important to implement proper error handling and reporting to ensure the security and reliability of your application. One best practice is to check for errors during the file upload process and provide meaningful error messages to the user if any issues occur. Additionally, logging errors to a file or database can help in troubleshooting and debugging any issues that may arise.

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