Zweistein2 Zweistein2 - 6 months ago 10
PHP Question

if statement unusual behavior

Heyho,

I have a little website and want to create a pdf out of it. For this I use dompdf and some basic php:

/**
* @Route ("/generatePDF/{php}", name="generatePDF")
*/
public function generatePDFAction($php)
{
$isPHP = $php;

if($isPHP == true)
{
$lang = "php";
}else
{
$lang = "js";
}

//open a link with $lang and get it's html (=> $html)

//Just for testing, normally it's a working websites html-code
$html = $isPHP;

$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('a4', 'landscape');
$dompdf->render();
$pdf = $dompdf->output();

//$isPHP = false;

if($isPHP == true)
{
file_put_contents("downloads/rulesphp.pdf", $pdf);
unset($dompdf);
return new Response($this -> redirect('/downloads/rulesphp.pdf'));
}else
{
file_put_contents("downloads/rulesjs.pdf", $pdf);
unset($dompdf);
return new Response($this -> redirect('/downloads/rulesjs.pdf'));
}
}


then call it:

<a class="btn btn-default" href="{{ path('generatePDF', {'php': 'true'}) }}">PDF aktualisieren</a>


or

<a class="btn btn-default" href="{{ path('generatePDF', {'php': 'false'}) }}">PDF aktualisieren</a>


whether I want the php or the js rules.

$isPHP
is a boolean I handover to the function. The first if-statement works like charm, it only breaks at the end...
$html is normally the websites html, I just set it to
$isPHP
for testing purpose (to see if
$isPHP
is
true/false
). Now the problem:

Whenever I run my code it creates and redirects me to a rulesphp.pdf, whether or not
$isPHP
is set to "true" or "false".

Sidenote: When I uncomment the "
//$isPHP = false
" - line it creates a "rulesjs.pdf", as expected, but if I comment it in again or delete it, it won't go back to it's old behavior (as if
$isPHP
is always
true
-> creating rulesphp.pdf, regardless of what
$isPHP
is set), it just keeps the "creating rulesjs.pdf /
$isPHP
is always
false
"-behavior.

Sidenote2:
$isPHP
is set correctly, so if it's true, then the pdfs content is true (because of
$html = $isPHP
), if it's false the pdfs content is false, too.

Answer

@Route ("/generatePDF/{php}", name="generatePDF")

Your routing pass you string parameters. So, if you call it by /generatePDF/true, /generatePDF/false urls - you receive strings.

Use:

$isPHP === 'true'

or $isPHP = $php === 'true'