How can PHP scripts be optimized to handle file uploads efficiently and securely?

To optimize PHP scripts for handling file uploads efficiently and securely, it is important to set appropriate file size limits, validate file types, and store uploaded files in a secure location on the server. Additionally, using functions like move_uploaded_file() to move files from the temporary directory to the desired location can help prevent security vulnerabilities.

// Set maximum file size limit
$maxFileSize = 5 * 1024 * 1024; // 5MB

// Validate file type
$allowedFileTypes = ['jpg', 'jpeg', 'png'];
$uploadedFileType = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array($uploadedFileType, $allowedFileTypes)) {
    die('Invalid file type. Only JPG, JPEG, and PNG files are allowed.');
}

// Move uploaded file to secure location
$uploadDirectory = 'uploads/';
$uploadedFilePath = $uploadDirectory . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadedFilePath)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Failed to upload file.';
}