How can beginners in PHP improve their file upload scripts by directly accessing $_FILES?

Beginners in PHP can improve their file upload scripts by directly accessing $_FILES by properly validating and sanitizing the uploaded file data. This includes checking for errors, file size limits, file type restrictions, and ensuring the file is actually uploaded before processing it. By directly accessing $_FILES, beginners can handle file uploads securely and efficiently.

// Check if file was uploaded without errors
if(isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
    // Validate file size
    if($_FILES['file']['size'] > 5000000) {
        echo "File is too large";
    } else {
        // Validate file type
        $allowedTypes = ['image/jpeg', 'image/png'];
        if(in_array($_FILES['file']['type'], $allowedTypes)) {
            // Process the uploaded file
            $uploadPath = 'uploads/' . basename($_FILES['file']['name']);
            move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath);
            echo "File uploaded successfully";
        } else {
            echo "Invalid file type";
        }
    }
} else {
    echo "Error uploading file";
}