Skip to content
PHP Logo

How can PHP developers ensure proper data validation and error handling when dealing with file uploads in a web application?

When dealing with file uploads in a web application, PHP developers can ensure proper data validation and error handling by checking the file type, size, and ensuring secure file storage. They should also validate the uploaded file using PHP functions like `move_uploaded_file()` and handle any errors that may occur during the upload process.

php
<?php
// Check if file was uploaded without errors
if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
    $file_name = $_FILES['file']['name'];
    $file_size = $_FILES['file']['size'];
    $file_tmp = $_FILES['file']['tmp_name'];
    
    // Validate file type
    $file_type = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
    if($file_type != "jpg" && $file_type != "png" && $file_type != "jpeg" && $file_type != "gif"){
        echo "Only JPG, JPEG, PNG & GIF files are allowed.";
        exit();
    }
    
    // Validate file size
    if($file_size > 5000000){
        echo "File size must be less than 5MB.";
        exit();
    }
    
    // Move uploaded file to desired location
    if(move_uploaded_file($file_tmp, "uploads/" . $file_name)){
        echo "File uploaded successfully.";
    } else {
        echo "Error uploading file.";
    }
} else {
    echo "Error uploading file.";
}
?>