How can PHP developers optimize file upload processes to handle larger files efficiently and securely?

To optimize file upload processes for larger files in PHP, developers can increase the max upload size in php.ini, use chunked file uploads to handle large files efficiently, and validate file types and sizes to ensure security.

// Increase max upload size in php.ini
ini_set('upload_max_filesize', '20M');
ini_set('post_max_size', '20M');

// Handle chunked file uploads
$chunkSize = 1 * 1024 * 1024; // 1MB
$uploadDir = 'uploads/';
$fileName = $_POST['name'];
$chunkIndex = $_POST['chunkIndex'];
$totalChunks = $_POST['totalChunks'];

$chunkFile = $uploadDir . $fileName . '_' . $chunkIndex;
$in = fopen("php://input", "rb");
$out = fopen($chunkFile, $chunkIndex == 0 ? "wb" : "ab");

while ($chunk = fread($in, $chunkSize)) {
    fwrite($out, $chunk);
}

fclose($in);
fclose($out);

if ($chunkIndex == $totalChunks - 1) {
    // File upload complete, merge chunks if necessary
}

// Validate file types and sizes
$allowedTypes = ['image/jpeg', 'image/png'];
$allowedSize = 10 * 1024 * 1024; // 10MB

if (in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size'] <= $allowedSize) {
    // File is valid, proceed with upload
} else {
    // Invalid file type or size
}