0

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;
    }
}
?>
D4v3
  • 31
  • 11
  • if your code is error-free, verify permissions in both folder and file. Plus, if that doesn't resolve it, then your unknown HTML form may be at fault. Check for errors. – Funk Forty Niner Aug 02 '16 at 00:11
  • How do I do that? I'm currently developing on windows XP and can't see the option – D4v3 Aug 02 '16 at 00:13
  • consult http://php.net/manual/en/function.error-reporting.php to check for errors and apply that to your code, that's if you're accessing that file as `http://localhost/file.xxx` rather than `file:///file.xxx` and that a webserver and PHP are successfully installed. – Funk Forty Niner Aug 02 '16 at 00:14
  • I'm accessing the file from file:///file.xxx as I'm using a localhost server for development purposes, is that why my scripts aren't appearing to work? – D4v3 Aug 02 '16 at 00:22
  • that is exactly the reason. Those are two different animals altogether ;-) – Funk Forty Niner Aug 02 '16 at 00:42

0 Answers0