Skip to content
PHP Logo

How can conditional statements be used to validate the form submission before processing the avatar upload?

To validate the form submission before processing the avatar upload, you can use conditional statements to check if the required form fields are filled out correctly. This can help prevent errors or malicious uploads before proceeding with the avatar upload process.

php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Check if the required form fields are filled out
    if (isset($_POST['username']) && isset($_FILES['avatar'])) {
        // Process the avatar upload
        // Move the uploaded file to a specific directory
        $targetDir = "uploads/";
        $targetFile = $targetDir . basename($_FILES["avatar"]["name"]);
        if (move_uploaded_file($_FILES["avatar"]["tmp_name"], $targetFile)) {
            echo "Avatar uploaded successfully.";
        } else {
            echo "Error uploading avatar.";
        }
    } else {
        echo "Please fill out all required fields.";
    }
}