I have a form with some fields that I need to implement in a WordPress template. If I do it in vanilla PHP it works but when I put it in a WordPress template it doesn't work, can it be a problem with $_POST
?
<?php
/**
* Template Name: Telesales
*/
?>
<?php if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$DOFMonth = $_POST['DOFMonth'];
$DOFDay = $_POST['DOFDay'];
$DOFYear = $_POST['DOFYear'];
$Content = "Name,LastName,Birthday\n";
$Content .= "$firstName,$lastName,$DOFMonth-$DOFDay-$DOFYear\n";
$FileName = $firstName."-".date("d-m-y-h:i:s").".csv";
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $FileName . '"');
echo $Content;
exit();
} ?>
<form action="" method="post">
<label>First name</label>
<input type="text" name="firstName" placeholder="Rose" required="" value="">
<br>
<label>Last name</label>
<input type="text" name="lastName" placeholder="McDonnell" required="" value="">
<br>
<label>Date of Birth</label>
<select name="DOFMonth" required="">
<option value="null">Month</option>
<option value="January">January</option>
<option value="February">February</option>
</select>
<select name="DOFDay" required="">
<option value="null">Day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<select name="DOFYear" required="">
<option value="null">Year</option>
<option value="1920">1920</option>
</select>
<input type="submit" name="submit" value="Submit">
</form>
header
to send a CSV, because HTTP headers can only be sent once. You should be seeing this as a series of PHP warnings and PHP notices in your PHP error log$error
but this variable is never used anywhere, there is no error checking codeheader
calls! What I'm saying is that you can only send HTTP headers once, and the moment you send any type of output PHP will send the headers for you, and that's exactly what you've done here by closing your PHP tags, outputting 2 newlines, then opening them again. Those newlines are HTML content, so PHP tells the browser to expect HTML, sends the headers, and then starts sending HTML. This means when your code callsheader
to tell it to expect a Excel/CSV file it's too late! Headers have already been sent!header
, remove the useless closing PHP tag and opening PHP tag just after your comment, then go find your PHP error log so that if this happens again it becomes obvious rather than it being a surprise