I have a html form (method POST, linked to the following PHP script etc) and can't see why my script isn't working.
It's supposed to take the name and email from the form (mname, memail), validate them, and then save the values into 'mailinglist.csv'. I can't get it to work though.
Here is my script:
<?php
//variables set to empty
$mnameErr = $memailErr = "";
$mname = $memail = "";
//validate name
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["mname"])) {
$mnameErr = "Name is required";
} else {
$mname = test_input($_POST["mname"]);
//checks if name only contains letters and whitespaces
if (!preg_match("/^[a-zA-Z ]*$/",$mname)) {
$mnameErr = "Only letters and white space allowed";
}
}
//validate email
if (empty($_POST["memail"])) {
$memailErr = "Email is required";
} else {
$memail = test_input($_POST["memail"]);
//checks if email address is well-formed
if (!filter_var($memail, FILTER_VALIDATE_EMAIL)) {
$memailErr = "Invalid email format";
}
}
//validate data function
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
//saves details to mailinglist.csv
if($memailErr != "")
{
echo("There was an error.");
} else {
$fs = fopen("mailinglist.csv","a");
$txt = $mname.", ".$memail."\n";
fwrite($txt);
fclose($fs);
header("Location: thankyou.html");
}
exit;
}
}
?>