What are the best practices for handling file uploads in PHP to ensure the security and integrity of the uploaded files?

File uploads in PHP can pose security risks if not handled properly. To ensure the security and integrity of uploaded files, it is important to validate file types, limit file sizes, sanitize file names, and move uploaded files to a secure directory outside of the web root.

// Example PHP code snippet for handling file uploads securely

// Define allowed file types
$allowed_types = array('jpg', 'jpeg', 'png', 'gif');

// Validate file type
$file_extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array($file_extension, $allowed_types)) {
    die('Invalid file type.');
}

// Limit file size
$max_size = 5 * 1024 * 1024; // 5MB
if ($_FILES['file']['size'] > $max_size) {
    die('File is too large.');
}

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

// Move uploaded file to secure directory
$upload_dir = 'uploads/';
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}
$upload_path = $upload_dir . $clean_filename;
if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_path)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Error uploading file.';
}