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;
  	return($diff);
}
   $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:


<?php
$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:


<?php
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 http://stop.zona-m.net CV, talks and bio at http://mfioretti.com

Free Dummies Books
Continuous Engineering

Learn:

  • What continuous engineering is
  • How to continuously improve complex product designs
  • How to anticipate and respond to markets and clients
  • How to get the most out of your engineering resources

Get your free book now

Sponsored by IBM

Free Dummies Books
Service Virtualization

Learn to:

  • Define service virtualization
  • Select the most beneficial services to virtualize
  • Improve your traditional approach to testing
  • Deliver higher-quality software faster

Get your free book now

Sponsored by IBM