Skip to content
PHP Logo

How can the global variable $_FILES be utilized to solve image upload issues in PHP?

When uploading images in PHP, issues may arise such as file size limitations or file type restrictions. To solve these issues, the global variable $_FILES can be utilized to access information about the uploaded file, such as its size and type. By checking this information and applying appropriate validations, we can ensure that only valid image files within the size limits are uploaded.

php
// Check if file was uploaded without errors
if ($_FILES['file']['error'] == UPLOAD_ERR_OK) {
    // Check file size
    if ($_FILES['file']['size'] < 5000000) { // 5MB limit
        // Check file type
        $allowed_types = array('image/jpeg', 'image/png', 'image/gif');
        if (in_array($_FILES['file']['type'], $allowed_types)) {
            // Move the uploaded file to desired directory
            move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
            echo 'File uploaded successfully.';
        } else {
            echo 'Invalid file type. Allowed types: JPEG, PNG, GIF.';
        }
    } else {
        echo 'File is too large. Maximum size allowed: 5MB.';
    }
} else {
    echo 'Error uploading file. Please try again.';
}