meandeviation.com > learn php > robust add it up

robust add it up - checking fields and more php

The basic 'add it up' script did not check that the values it was given were numbers. This process is called 'validating'. The 'robust add it up' script does this and in the processes introduces a number of other PHP features:

As normal there are two files, a web form and a PHP script:

Try going to the form and entering two numbers and then pressing the "add it up!" button. Try it with proper numbers and then 'illegal' values - try adding "fred" to 17.

Notice that the resulting page looks very different if the fields are numbers (it shows the sum) from if there is a problem (and explanatory error message).

looking at the robust add it up script

Download the files to your machine as normal. The robust-add-it-up.html file is identical to add-it-up.html except for the <form> 'action' attribute:

<form method="GET" action="do-robust-add-it-up.php">
...

So, we'll move staright to the PHP in do-robust-add-it-up.php.

Right at the beginning is a <?php ...?> tag. It starts by getting $first and $second from the $_GET array which you have seen before:

<?php
$first = $_GET['first'];
$second = $_GET['second'];{
...

There is then a comment:

// note: this script uses the function is_numeric is ideally shopuld tun under PHP 4 or greater
// however it has a 'fix' so that it works to some extent with PHP 3 also

If the characters '//' appear on a line, then everything after that is ignored. Typically it is something added to help someone to read the code later, but is ignored by PHP and does NOT appear on the web page.

This is then followed by something new, the definition of a function "is_number":

function is_number($x)
{
...
}
}....

This is basically some PHP script that checks somehting is a valid number - which we obviousy need to validate the input fields. For the moment we will skip the details of this and look at the next lines:

  if ( is_number($first) && is_number($second) ) {
$is_ok = true;
$title = "I can add up!";
$answer = $first + $second;
} else {
$is_ok = false;
$title = "bad numbers to add up";
}

The "&&" means logical and, so the condition reads "if $first is a number and $second is a number".

Notice the way a function like "is_number" is used with the thing it is being applied to in brackets following it. This follows the conventions in mathematics such as log(n) or sin(a).

The "if" statement we have seen so far had a single statement following them. This is more complicated and needs several statements and these are enclosed in curly braces "{ .... }". Also this "if" statement has something to do if the condition is not true (the "else" part).

So, if the two fields are numbers than the new variables $isd_ok is set to true, the $title variable is set to be "I can add up!" and the $answer variable is et tot he sum of $first and $second.

If one or other field is not a number then the 'else' part is executed and instead $is_ok is set to false and $title is set to "bad numbers to add up".

After this we get the actual HTML for the resulting page.

The $title variable is used to set the page title and the first heading:

<<html>
<head>
<title><?php echo $title; ?></title>
</head>
...
<h2><?php echo $title; ?></h2> ....

Sometimes when the page varies just a little we can use variables like this to produce variants for different circimstances.

After this however the page varies a lot depending on whether the fields are numbers are not. The $is_ok variable is used to decide which part to show:

<?php
if ( $is_ok ) :
?>
<table> .... </table> <?php
else : // the following ....
?> <p>Sorry, I can't add up ... </p>
<?php
endif;
?> ...

This is a 'long' form of if-else. The colon at the end of "if ( $is_ok ) :" means that PHP looks ahead to the (optional) "else:" and "endif;" rather than expecting a single statement to follow or a set of statements in "{...}". In addition there can be ordinary HTML on each 'branch' of the if.

In this case the if branch has the same HTNl as we saw in do-add-it-up.php constructing the table showing the sum.

The else branch consists of a simple error message.

After the "if (...): ... else: ... endif;" there is just some more HTML to finish the page.

other ways of doing it

There are usually lots of ways of doing the same thing.

Look at:

The first of these is identical to do-robust-add-it-up.php except that each branch of the 'if-else-endif' contains the HTML for a whole web page. Because of this the variable $title is not needed.

When you make a script like this that produces pages with two or more differenty kinds you may decide either way of doing thimngs. It depends on how much of the page is similar whether you choose to have the php script formatted as two complete pages or one page with 'variants' within it.

The second of these alternatives uses the original condition to choose between the two pages rather than creating the 'boolean' (the computing word for a true/false value) variable $is_ok.

As a general pattern I prefer to have pages which are closer to either the original or the first of these two - do all the complicated conditions and calculations in some PHP script at the top of the page and then have a relatively simple bit generating the page itself. However, probably the last is the most common form to see. I find it is too 'mixed' up for me - but I guess it is a matter of taste.

A more radical variation can be found in 'factored add it up', which breaks the script up further and is a better pattern for more complex interactive web applications.

finally - the bit in the function!

OK now to look inside that function at the top ...

 

function is_number($x)
{
$ver = phpversion();
$x = trim($x);
if ( $ver[0] == "4" ) {
return is_numeric($x);
} else {
return $x == "0" || ( $x+1 != 1 ) ;
}
}

This code doesn't do anything but defines the function "is_number" to be used later (in the 'if' condition). When it is used the code is executed with the relevant value for $x (in this case $first then $second).

The code first of all uses a built-in PHP function 'phpversion()' to find which version of PHP is running and put it in a variable $ver. This is because PHP version 4 has a built-in function 'is_numeric' that we can use but PHP 3 didn't have it.

After getting the version it removes any leading or trailing white space (spaces, tabs etc.) from the 'parameter' $x (a parameter is the things that is passed to the function to work on). To do this it uses the PHP supplied fundtion 'trim'.

Note that the statement "$x = trim($x);" is not like a piece of mathemetics declaring two things are equal. Instead it means "make the new value of $x be the result of applying 'trim' to the old value of $x".

The condition for the 'if' is looking at the first character of the version (In PHP $vrr[0] is the first character from $ver, $ver[1] is the second etc. - yes this sounds wierd but some computer languages do this starting 'arrays' at zero). It looks at the fiorst character only because the version can be someting like "4.1.7".

If the first character of the version is "4" it simply returns the result of the built-in finmction "is_numeric".

If it is an older version it does some slightly wierd checks. The second part of this is using the fact that if $x starts woith something that is not a number it will be treatyed as zero when PHP adds it to 1. This is a good example of what in compting is called a 'hack' - a bit of code that works ... but well only just. There are better, but more complex ways of doing this too.

 


http://www.meandeviation.com/tutorials/learnphp/about-robust-add-it-up.html Alan Dix © 2002