Are there best practices for handling file uploads in PHP to ensure data integrity and security?

When handling file uploads in PHP, it is important to implement best practices to ensure data integrity and security. This includes validating file types, checking file sizes, and storing files in a secure location on the server. Additionally, it is recommended to rename uploaded files to prevent overwriting existing files and to sanitize file names to prevent directory traversal attacks.

// Example code snippet for handling file uploads in PHP

// Check if file was uploaded without errors
if ($_FILES['file']['error'] == UPLOAD_ERR_OK) {
    
    // Validate file type
    $allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
    if (!in_array($_FILES['file']['type'], $allowedTypes)) {
        die('Invalid file type. Allowed types are: jpeg, png, pdf');
    }
    
    // Check file size
    if ($_FILES['file']['size'] > 5242880) { // 5MB
        die('File size is too large. Max allowed size is 5MB');
    }
    
    // Sanitize file name
    $fileName = preg_replace("/[^A-Za-z0-9.]/", '', $_FILES['file']['name']);
    
    // Move uploaded file to secure location
    $uploadDir = 'uploads/';
    $uploadPath = $uploadDir . $fileName;
    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath)) {
        echo 'File uploaded successfully';
    } else {
        die('Failed to upload file');
    }
} else {
    die('Error uploading file');
}