What are some best practices for handling file uploads in PHP to prevent errors and improve security?

File uploads in PHP can be a security risk if not handled properly. To prevent errors and improve security, it is important to validate file types, check file sizes, and store uploaded files in a secure directory outside of the web root. Additionally, using functions like move_uploaded_file() and checking file permissions can help mitigate potential risks.

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

// Check file size
$maxSize = 1048576; // 1MB
if ($_FILES['file']['size'] > $maxSize) {
    die('File is too large.');
}

// Store uploaded file in a 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 'Error uploading file.';
}