What are some best practices for handling file uploads and processing in PHP to ensure data integrity and security?

When handling file uploads and processing in PHP, it is crucial to validate and sanitize user input to prevent security vulnerabilities such as file injection attacks. Additionally, it is important to set proper file permissions, limit file types and sizes, and store uploaded files in a secure location to ensure data integrity and prevent unauthorized access.

// Example PHP code snippet for handling file uploads securely

// Check if file was uploaded without errors
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    // Validate file type
    $allowed_types = ['image/jpeg', 'image/png'];
    if (in_array($_FILES['file']['type'], $allowed_types)) {
        // Move uploaded file to a secure location
        $upload_path = '/path/to/uploads/';
        move_uploaded_file($_FILES['file']['tmp_name'], $upload_path . $_FILES['file']['name']);
        echo 'File uploaded successfully.';
    } else {
        echo 'Invalid file type. Allowed types are JPEG and PNG.';
    }
} else {
    echo 'Error uploading file.';
}