O'Reilly logo

Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition by Robin Nixon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

An Example Program

Let’s look at how a real-life PHP program integrates with an HTML form by creating the program convert.php, listed in Example 11-10. Type it in as shown and try it for yourself.

Example 11-10. A program to convert values between Fahrenheit and Celsius
<?php // convert.php
$f = $c = "";

if (isset($_POST['f'])) $f = sanitizeString($_POST['f']);
if (isset($_POST['c'])) $c = sanitizeString($_POST['c']);

if ($f != '')
{
    $c = intval((5 / 9) * ($f - 32));
    $out = "$f °f equals $c °c";
}
elseif($c != '')
{
    $f = intval((9 / 5) * $c + 32);
    $out = "$c °c equals $f °f";
}
else $out = "";

echo <<<_END
<html><head><title>Temperature Converter</title>
</head><body><pre>
Enter either Fahrenheit or Celsius and click on Convert

<b>$out</b>
<form method="post" action="convert.php">
Fahrenheit <input type="text" name="f" size="7" />
   Celsius <input type="text" name="c" size="7" />
           <input type="submit" value="Convert" />
</form></pre></body></html>
_END;

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

When you call up convert.php in a browser, the result should look something like the screen grab in Figure 11-8.

The temperature conversion program in action
Figure 11-8. The temperature conversion program in action

To break the program down, the first line initializes the variables $c and $f in case they do not get posted to the program. The next two lines ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required