What are some best practices for optimizing file uploads in PHP for efficiency?

When optimizing file uploads in PHP for efficiency, it is important to set appropriate limits for file size, validate file types, and move uploaded files to a secure location on the server. Additionally, using asynchronous file uploads or chunked uploads can help improve performance when dealing with large files.

// Set maximum file size limit
ini_set('upload_max_filesize', '20M');

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

// Move uploaded file to secure location
$upload_dir = 'uploads/';
$upload_file = $upload_dir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_file)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Error uploading file.';
}