How can PHP scripts ensure secure access to directories for file uploads without compromising system integrity?

When allowing file uploads in PHP scripts, it is crucial to ensure that the uploaded files are stored in a secure directory to prevent unauthorized access. To achieve this, the PHP script should validate the file type, sanitize the file name, and move the uploaded file to a designated directory outside the web root. By storing the files outside the web root, you prevent direct access to the files via a URL, thus enhancing the security of the system.

<?php
// Define the directory where uploaded files will be stored
$uploadDirectory = '/path/to/secure/directory/';

// Validate file type, sanitize file name, and move the uploaded file to the secure directory
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $fileName = basename($_FILES['file']['name']);
    $fileType = $_FILES['file']['type'];
    
    // Add additional validation for file type if needed
    
    $uploadPath = $uploadDirectory . $fileName;
    
    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath)) {
        echo 'File uploaded successfully.';
    } else {
        echo 'Error uploading file.';
    }
} else {
    echo 'Error uploading file.';
}
?>