Skip to content
PHP Logo

How can PHP scripts be optimized for handling file uploads to ensure compatibility with various browsers and prevent errors like incorrect file formats?

File uploads in PHP can be optimized by checking the file format and size before processing the upload. This can help prevent errors like incorrect file formats and ensure compatibility with various browsers. One way to achieve this is by using the `$_FILES` superglobal array to access information about the uploaded file, such as its MIME type and size.

php
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $allowedFormats = ['image/jpeg', 'image/png', 'image/gif'];
    $maxFileSize = 2 * 1024 * 1024; // 2MB

    if (in_array($_FILES['file']['type'], $allowedFormats) && $_FILES['file']['size'] <= $maxFileSize) {
        // Process the file upload
        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
        echo 'File uploaded successfully!';
    } else {
        echo 'Invalid file format or size. Please upload a file in JPEG, PNG, or GIF format and less than 2MB.';
    }
} else {
    echo 'Error uploading file. Please try again.';
}