Are there any best practices for securely saving files locally using PHP?

When saving files locally using PHP, it is important to follow best practices to ensure the security of the files and prevent unauthorized access. One common approach is to store files outside of the web root directory to prevent direct access via URL. Additionally, it is recommended to sanitize file names to prevent directory traversal attacks. Finally, consider implementing access control mechanisms to restrict who can upload and access files.

// Define the directory where files will be saved
$uploadDirectory = '/path/to/upload/directory/';

// Get the uploaded file name and sanitize it
$fileName = basename($_FILES['file']['name']);
$fileName = preg_replace("/[^a-zA-Z0-9._-]/", "", $fileName);

// Move the uploaded file to the designated directory
if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadDirectory . $fileName)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Error uploading file.';
}