thomaSmith thomaSmith - 18 days ago 6
PHP Question

inserting form data into a pdf file

I am inserting form data into a pdf file using php, I am looping through the form data using a foreach loop, the problem is that the submit button value is also inserted into the pdf file, which I do not want this to happen. is it also possible to insert the labels for the form inputs into the pdf file. also, I have only used two input fields in the example but I have a lot more that's why I am using a loop.

form

<?php require 'pdf.php';?>
<form action="#" method="post">
<label for="fname">First Name:</label> <input type="text" name="fname" placeholder="First Name">
<label for="lname">Last Name</label> <input type="text" name="lname" placeholder="Last Name">
<input type="submit" value="Submit" name="submit">
</form>


pdf

<?php require('fpdf.php');?>
<?php
if(isset($_POST['submit'])) {


$pdf = new FPDF();
$pdf->AddPage();

foreach ($_POST as $key => $data) {

$pdf->SetFont('Arial','B',16);
$pdf->write(40,"$data");
$pdf->ln(10);


}
$pdf->Output();
}
?>

Answer

You're writing the entire $_POST variable to the file, it contains everything that has a name.

You should write selectively instead:

if(isset($_POST['submit'])){
  if(isset($_POST['fname']) && isset($_POST['lname'])){
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);

    $pdf->write(40,$_POST['fname'] . " " . $_POST['lname']);
    $pdf->ln(10);
  } else {
    echo 'did not supply all the data';
  }
}

Or to exclude a specific key:

foreach ($_POST as $key => $data) {
  if($key == 'submit'){
    continue;
  }

  $pdf->SetFont('Arial','B',16);
  $pdf->write(40,"$data");
  $pdf->ln(10);
}
Comments