What are some best practices for handling user input in PHP forms without relying on JavaScript?

When handling user input in PHP forms without relying on JavaScript, it is important to validate and sanitize the input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. One way to do this is by using PHP functions like filter_var() to sanitize input and regular expressions to validate input.

// Example of validating and sanitizing user input in a PHP form
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = filter_var($_POST["username"], FILTER_SANITIZE_STRING);
    $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
    
    if (!preg_match("/^[a-zA-Z0-9]*$/", $username)) {
        $errors[] = "Username can only contain letters and numbers.";
    }
    
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format.";
    }
    
    // If there are no errors, proceed with form processing
    if (empty($errors)) {
        // Process the form data
    } else {
        // Display errors to the user
        foreach ($errors as $error) {
            echo $error . "<br>";
        }
    }
}