Kamikaze_goldfish
Kamikaze_goldfish

Reputation: 861

Php save data to .csv and then redirect

Like the title says, I am trying to make a php script that saves the data to a csv then redirects them to another url on my site. All that is happening is when I hit the submit button I get an error on saying it cannot handle the request.

This is my form

<form action="submit.php" method="post">

    <h1 style="text-align: center;">Register</h1><br>

    <fieldset>
     <legend>Your registration info</legend>
     <label for="name">Name:</label>
     <input type="text" id="name" name="user_name" required="">

     <label for="mail">Email:</label>
     <input type="email" id="mail" name="user_email" required="">

     <label for="phone">Phone:</label>
     <input type="phone" id="phone" name="phone">

     <label for="guest">Guest or Spouse:</label>
     <input type="text" id="gsname" name="gsname">

     <label>Date Attending:</label>
     <input type="radio" id="tuesday" value="tuesday" name="date"><label 
for="tuesday" class="light">Tuesday, May #, 2018 10 AM - 11:30 AM</label> 
<br>
     <input type="radio" id="thursday" value="thursday" name="date"><label 
for="thursday" class="light">Thursday, May #, 2018 10 AM - 11:30 AM</label>
    </fieldset>


     <button type="submit" name="submit">Register Now</button>
    </form>

This is my php script.

if (isset($_POST['submit'])){
// Fetching variables of the form which travels in URL
$name = $_POST['user_name'];
$email = $_POST['user_email'];
$phone = $_POST['phone'];
$gsname = $_POST['gsname'];
$date = $POST['date'];
$open = fopen("formdata.csv", "a");
$csvData = $name. "," $email. "," $phone. "," $gsname. "," $date. "n";
fwrite($open,$csvData)
fclose($open)
#if($name !=''&& $email !=''&& $phone !=''&& $gsname
//  To redirect form on a particular page
header("Location:https://www.google.com/");
}
else (
header("Location:https://www.charter.com");
)

?>

Can anyone give me an idea where I am messing up? I know data validation is important, but if I am using it on the form itself, do I need to validate it here?

Upvotes: 0

Views: 509

Answers (1)

David Shack
David Shack

Reputation: 131

A few things that I would try:

  • Fix the typo $date = $_POST['date'];
  • Fix the string concatenation $name . "," . $email . "," . $phone . "," . $gsname . "," . $date . "\n";
  • Check to make sure your script is receiving the POST request. If not double check the path on the form action attribute.
  • Double check the directory in which you are attempting to create/write formdata.csv is writable. I would suggest using fputcsv() as well.

Although it's not mandatory, it's highly recommended that you do server-side validation. Never assume the data you are receiving is the way you want it.

Upvotes: 1

Related Questions