What are the best practices for handling file uploads in PHP to avoid errors like Internal Server Error 500?

When handling file uploads in PHP, it is important to ensure that the server settings allow for large file uploads and that the PHP configuration settings are properly configured. To avoid Internal Server Error 500, make sure to check for errors during the file upload process and handle them gracefully. Additionally, sanitize file names to prevent any potential security risks.

<?php
// Check if there are any errors during file upload
if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    // Handle the error appropriately
    die('File upload failed with error code: ' . $_FILES['file']['error']);
}

// Sanitize the file name to prevent any security risks
$filename = preg_replace("/[^A-Za-z0-9.]/", '', $_FILES['file']['name']);

// Move the uploaded file to the desired directory
$uploadPath = 'uploads/' . $filename;
if (!move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath)) {
    die('Failed to move uploaded file');
}

echo 'File uploaded successfully';
?>