What are some best practices for handling file uploads securely and efficiently in PHP applications?

When handling file uploads in PHP applications, it is important to validate the file type, size, and content to prevent malicious uploads. Additionally, storing uploaded files outside of the web root directory and renaming them to prevent overwriting existing files can enhance security. Using server-side validation and sanitization techniques can help protect against common vulnerabilities like directory traversal attacks.

// Example PHP code snippet for handling file uploads securely
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $uploadDir = '/path/to/uploads/';
    $uploadFile = $uploadDir . basename($_FILES['file']['name']);
    
    // Validate file type and size
    $allowedTypes = ['image/jpeg', 'image/png'];
    $maxSize = 1048576; // 1MB
    if (in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size'] <= $maxSize) {
        move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile);
        echo 'File uploaded successfully.';
    } else {
        echo 'Invalid file type or size.';
    }
} else {
    echo 'Error uploading file.';
}