What are some best practices for handling PHP error messages in the context of file uploads?

When handling PHP error messages in the context of file uploads, it is important to properly validate and sanitize user input to prevent potential security vulnerabilities. Additionally, it is recommended to use error handling techniques such as try-catch blocks to gracefully handle any errors that may occur during the file upload process. Lastly, make sure to provide informative error messages to the user to assist them in resolving any issues.

try {
    // Validate file upload
    if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('File upload error: ' . $_FILES['file']['error']);
    }

    // Sanitize file name
    $filename = basename($_FILES['file']['name']);

    // Move uploaded file to desired directory
    move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $filename);

    echo 'File uploaded successfully!';
} catch (Exception $e) {
    echo 'An error occurred: ' . $e->getMessage();
}