Are there any best practices for handling file uploads securely in PHP?

When handling file uploads securely in PHP, it is important to validate the file type, size, and content to prevent malicious files from being uploaded. It is also recommended to store the uploaded files outside of the web root directory to prevent direct access. Additionally, consider renaming the uploaded files to prevent potential security risks.

<?php
// Ensure file is uploaded via POST method
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $file = $_FILES['file'];

    // Validate file type
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (!in_array($file['type'], $allowedTypes)) {
        die('Invalid file type.');
    }

    // Validate file size
    if ($file['size'] > 5000000) {
        die('File size is too large.');
    }

    // Store file outside web root directory
    $uploadDir = '/path/to/uploads/';
    $uploadFile = $uploadDir . basename($file['name']);

    if (move_uploaded_file($file['tmp_name'], $uploadFile)) {
        echo 'File uploaded successfully.';
    } else {
        echo 'Failed to upload file.';
    }
}
?>