What are the consequences of not properly validating and sanitizing user input in PHP scripts?

When user input is not properly validated and sanitized in PHP scripts, it leaves the application vulnerable to various security risks such as SQL injection, cross-site scripting (XSS), and other forms of attacks. To prevent these vulnerabilities, it is crucial to validate and sanitize user input before using it in the application.

// Example of validating and sanitizing user input in PHP
$username = $_POST['username'];

// Validate input
if (!preg_match("/^[a-zA-Z0-9]*$/", $username)) {
    echo "Invalid username format";
    exit;
}

// Sanitize input
$clean_username = filter_var($username, FILTER_SANITIZE_STRING);

// Now use $clean_username in your application