persepolis persepolis - 3 months ago 17
PHP Question

Problem running PHP temperature converter

I've been trying to work a simple form-based temperature converter, but I'm currently getting a white screen, and I cannot see what is wrong with the code. In addition, any ideas / suggestions for best practice are most welcome!

<?php // convert.php

if (isset($_POST['temperature']))
$temp = sanitize_string($_POST['temperature']);

if (isset($_POST['scale']))
{
if ($_POST['scale'] == 'fah')
$conv = 'fah';
$output = intval((5 / 9) * ($temp - 32));
elseif ($_POST['scale'] == 'cel')
$conv = 'cel';
$output = intval((9 / 5) * ($temp + 32));
else
$output = '';
}
?>

<html>

<head>
<title>Temperature converter</title>
</head>

<body>
<?php
if (isset($_POST['submitted']) and isset($conv))
{
if ($conv == 'fah')
print("$temp degrees Fahrenheit is $output degrees Celcius");
elseif ($conv == 'cel')
print("$temp degrees Celcius is $output degrees Fahrenheit");
}
?>

<form method="post" action="convert.php">
<label>Temperature <input type="text" name="temperature"></label>
<label>Celcius <input type="radio" name="scale" value="cel"></label>
<label>Fahrenheit <input type="radio" name="scale" value="fah"></label>
<input type="hidden" name="submitted" value="yes">
<input type="submit">
</form>
</body>

</html>

<?php
print_r($_POST);

function sanitize_string($var)
{
$var = stripslashes($var);
$var = htmlentities($var);
$var = strip_tags($var);
return $var;
}
?>

Answer

You forgot to use curly braces on the inner if/elseif on line 11. It should look like the following:

if (isset($_POST['scale']))
{
    if ($_POST['scale'] == 'fah') {
        $conv = 'fah';
        $output = intval((5 / 9) * ($temp - 32));
    }
    elseif ($_POST['scale'] == 'cel') {
        $conv = 'cel';
        $output = intval((9 / 5) * ($temp + 32));
    }
    else
        $output = '';
}

Try to avoid the shorthand if-syntax where you can leave off the curly braces.