What are some best practices for handling file uploads in PHP to prevent malicious file uploads?

When handling file uploads in PHP, it is crucial to implement security measures to prevent malicious file uploads. One common best practice is to restrict the file types that can be uploaded and validate the file extension. Additionally, it is recommended to store the uploaded files outside of the web root directory to prevent direct access. Another important measure is to generate unique filenames for the uploaded files to prevent overwriting existing files.

// Specify allowed file types
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];

// Validate file type
if (!in_array($_FILES['file']['type'], $allowedTypes)) {
    die('Invalid file type. Allowed types: jpg, png, gif');
}

// Store uploaded file outside of web root
$uploadDirectory = '/path/to/upload/directory/';
$fileName = uniqid() . '_' . $_FILES['file']['name'];
$uploadPath = $uploadDirectory . $fileName;

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