What are some best practices for securely handling file uploads in PHP scripts?

When handling file uploads in PHP scripts, it is crucial to validate and sanitize the file before saving it to the server. This includes checking the file type, size, and ensuring it does not contain any malicious code. Additionally, it is recommended to store uploaded files outside the web root directory to prevent direct access.

// Validate file type
$allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array($extension, $allowedTypes)) {
    die('Invalid file type. Allowed types: jpg, jpeg, png, gif');
}

// Validate file size
$maxSize = 5 * 1024 * 1024; // 5MB
if ($_FILES['file']['size'] > $maxSize) {
    die('File size exceeds the limit of 5MB');
}

// Sanitize file name
$fileName = preg_replace("/[^A-Za-z0-9.]/", '', $_FILES['file']['name']);

// Move file to secure directory
$uploadDir = '/path/to/secure/directory/';
if (!move_uploaded_file($_FILES['file']['tmp_name'], $uploadDir . $fileName)) {
    die('Failed to upload file');
}