What are some recommended methods for securely handling file uploads in PHP?

When handling file uploads in PHP, it is crucial to implement security measures to prevent malicious file uploads that can harm your server or compromise user data. Some recommended methods for securely handling file uploads in PHP include validating file types, restricting file sizes, storing files outside of the web root directory, and using unique file names to prevent overwriting existing files.

// Example of securely handling file uploads in PHP

// Specify allowed file types
$allowedFileTypes = array('jpg', 'jpeg', 'png', 'gif');

// Specify maximum file size in bytes
$maxFileSize = 1048576; // 1MB

// Specify upload directory outside of web root
$uploadDirectory = '/path/to/upload/directory/';

// Generate unique file name
$fileName = uniqid() . '_' . $_FILES['file']['name'];

// Move uploaded file to secure directory
if (in_array(pathinfo($fileName, PATHINFO_EXTENSION), $allowedFileTypes) && $_FILES['file']['size'] <= $maxFileSize) {
    move_uploaded_file($_FILES['file']['tmp_name'], $uploadDirectory . $fileName);
    echo 'File uploaded successfully.';
} else {
    echo 'Invalid file type or file size too large.';
}