How can PHP developers ensure the integrity and security of uploaded files when integrating them into a database for sorting and logging purposes?

To ensure the integrity and security of uploaded files in PHP, developers can implement file validation checks before storing them in a database. This includes checking file types, file sizes, and performing virus scans. Additionally, developers should store files outside of the web root directory to prevent direct access from the browser.

// Example code snippet for file validation before storing in a database
if(isset($_FILES['file'])) {
    $file = $_FILES['file'];
    
    // Check file type
    $allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
    if(!in_array($file['type'], $allowedTypes)) {
        die('Invalid file type.');
    }
    
    // Check file size
    if($file['size'] > 5242880) { // 5MB
        die('File size exceeds limit.');
    }
    
    // Perform virus scan (using ClamAV for example)
    exec('clamscan ' . $file['tmp_name'], $output, $return);
    if($return !== 0) {
        die('Virus detected.');
    }
    
    // Store file in a secure directory
    $uploadDir = '/path/to/secure/directory/';
    $uploadFile = $uploadDir . basename($file['name']);
    
    if(move_uploaded_file($file['tmp_name'], $uploadFile)) {
        // File uploaded successfully, now store file path in the database
        $filePath = $uploadFile;
        // Insert $filePath into the database
    } else {
        die('Failed to upload file.');
    }
}