Why is it important to validate and sanitize input data in PHP forms before writing to a file?

It is important to validate and sanitize input data in PHP forms before writing to a file to prevent security vulnerabilities such as SQL injection, cross-site scripting (XSS), and other malicious attacks. By validating input data, you ensure that only expected and safe data is written to the file. Sanitizing input data helps to remove any potentially harmful characters or code that could compromise the security of your application.

// Validate and sanitize input data before writing to a file
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = htmlspecialchars($_POST["name"]);
    $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
    
    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Invalid email format";
    } else {
        // Write validated and sanitized data to a file
        $file = fopen("data.txt", "a");
        fwrite($file, "Name: $name, Email: $email\n");
        fclose($file);
        echo "Data written to file successfully";
    }
}