What are the best practices for handling file uploads in PHP to ensure secure and efficient transfer of files?

When handling file uploads in PHP, it is important to validate the file type, size, and content to prevent security vulnerabilities such as malicious file uploads. Additionally, storing uploaded files outside of the web root directory can help prevent direct access to sensitive files. Using functions like move_uploaded_file() to transfer files securely and efficiently is recommended.

<?php
// Check if file is uploaded successfully
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    // Validate file type
    $allowedTypes = ['image/jpeg', 'image/png'];
    if (in_array($_FILES['file']['type'], $allowedTypes)) {
        // Validate file size
        if ($_FILES['file']['size'] <= 5000000) {
            // Move uploaded file to secure directory
            $uploadDir = '/path/to/secure/directory/';
            $uploadFile = $uploadDir . basename($_FILES['file']['name']);
            if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
                echo 'File uploaded successfully!';
            } else {
                echo 'Failed to upload file.';
            }
        } else {
            echo 'File size exceeds limit.';
        }
    } else {
        echo 'Invalid file type.';
    }
} else {
    echo 'Error uploading file.';
}
?>