What are some best practices for handling file uploads in PHP to ensure temporary storage is secure?

When handling file uploads in PHP, it is important to ensure that temporary storage is secure to prevent unauthorized access or execution of malicious files. One best practice is to store uploaded files in a directory outside of the web root to prevent direct access via the browser. Additionally, it is recommended to generate unique filenames for uploaded files to prevent overwriting existing files and potential security vulnerabilities.

// Set the upload directory outside of the web root
$uploadDir = '/var/www/uploads/';

// Generate a unique filename for the uploaded file
$filename = uniqid() . '_' . basename($_FILES['file']['name']);

// Move the uploaded file to the secure directory
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadDir . $filename)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Failed to upload file.';
}