Top Ten Tips for Getting Started with PHP

Here are ten tips that will help you avoid some of the most common pitfalls when coding Web applications in PHP.
10. Check the Results of Function and System Calls

Last but not least, all PHP functions must return acceptable data to the code that called them. The tricky part of this apparently superfluous statement is the fact that the meaning of acceptable depends on the whole script, and it may be different at any time. Here is a very dumb, but effective example of what we mean:

function subtraction($A, $B) {
	$diff = $A - $B;
   $C = 1/subtraction(3, 3);      // ERROR! Division by Zero!
   $D = 1/(1 - subtraction(3,3);

Although calculating $C will make the script crash, calculating (with the same operands), $D will not. The point is that before doing anything with a variable, you should check that it has an acceptable value. In the example above, this would mean assigning the subtraction result to an auxiliary variable and proceeding with the division only if it is non-null.

It is even more important to check return values from system calls, that is, the built-in functions provided to allow interaction with external processes and files. Should you forget to check a return value, data could be thrown away without anyone noticing, as in this example:

$HANDLE = fopen("newuser.txt","w")); // open a file
fwrite($HANDLE, "New User Data");    // write to it

If fopen fails (because, for example, the disc is full or you had no permission to write) the New User Data is lost for good. Before writing, check that $HANDLE is not null:

if (!$HANDLE = fopen("newuser.txt","w")) { die "File access failed: newuser.txt"; }
fwrite($HANDLE, "New User Data");

Happy PHP coding!

Marco Fioretti is a hardware systems engineer interested in free software both as an EDA platform and, as the current leader of the RULE Project, as an efficient desktop. Marco lives with his family in Rome, Italy.


Articles about Digital Rights and more at CV, talks and bio at