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.
6. Let the Database Do the Work Instead of Your Script

As stated above, PHP is used together with MySQL so often that the LAMP acronym is one of the most well-known combinations in Web design. Consequently, one of the best ways to write faster PHP scripts is to learn MySQL well enough that it works as much as possible instead of PHP. These two snippets of code illustrate the concept:


<?php //find all the books that Asimov wrote after 1980
$sql = "select YEAR, BOOK from MY_BOOKSHELF where AUTHOR LIKE 'Asimov' ; ";
  if ($sql_res = mysql_query("$sql")) {
    while ($r  = mysql_fetch_array($sql_res)) {
      if ($r[YEAR] > 1980) {// print the book title ;}
   }
?>

And,


<?php //find with MySql all the books that Asimov wrote after 1980
$sql = "select BOOK from MY_BOOKSHELF where AUTHOR LIKE 'Asimov'  AND YEAR > 1980;";
  if ($sql_res = mysql_query("$sql")) {
    while ($r = mysql_fetch_array($sql_res)) {
      // just print all the returned titles ;
}
?>

The second version will run much faster than the first, because database engines are designed to select as quickly as possible all and only the data matching any combination of criteria. They'll always be much faster than PHP is in this kind of task. Therefore, make sure that as much as possible of your selection logic is inside the SQL query, not in the PHP code that builds and uses it. Of course, this whole tip applies as is to any other database engine you would use with PHP.

7. Write Portable File Management Code

Line endings in text files are encoded differently on each family of operating systems. Binary files, such as images or compressed archives, are much worse, in the sense that even one corrupted character can make the whole file useless. Practically speaking, this means it is up to you to write code that will manage file contents in the same way on any platform you might use. This remains true even if you are sure that you and your Web server will always and only run GNU/Linux. Otherwise, you could find no error in your image or text processing code until you use it to upload a file from the Windows or Apple computer of a friend!

As far as PHP is concerned, the solution is to make proper use of the t (text mode translation) and b (binary) flags of the fopen() system call. The gory details are at www.php.net/function.fopen. Note that the page explicitly suggests: “for portability, it is also strongly recommended that you re-write code that uses or relies upon the t mode.”

8. Know String Processing Functions

Web pages still are mostly made of text, and the same is true for many databases. This is why optimizing text analysis and processing is one of the easiest ways to make all of your scripts run faster. Regular expressions are made to order for such jobs, but they look like hieroglyphics and may not even always be the optimal solution. PHP, although not going to the same extremes (uh, we mean power and flexibility of Perl), has more than one function working just like regular expressions, only much quicker. We refer to str_replace(), strcmp(), strtolower(), strtoupper(), strtr(), substr(), trim(), ucfirst() and several others. Take some time to study them in the manual, it will be well worth it.

9. Keep Layout and Programming Separate

A sure way to make the source of any Web site unreadable and difficult to update is to interlace large chunks of PHP and HTML code, even if each piece of PHP is used only once in the page, as in this example:


myfile.php>
<!-- lots of HTML code for static header, logo, menus...>
<?php lots of PHP code generating a list of the latest news ?>
<!-- lots of HTML code for the central part of the page...>
<?php lots of PHP code creating a per-user list of the
   most popular pages ?>
<!-- lots of HTML code for the user feedback form...>

Instead of making this error, encapsulate every piece of PHP code in one or more functions, then put them all in one separate file (without any HTML code), which will be loaded with the include_once command. The result will be much cleaner and easier to maintain:


myfile.php>
<?php include_once ("common_code.php"); ?>
<!-- lots of HTML code for the static page header, logo,
menus...>
<?php show_latest_news (); /* only one function call */ ?>
<!-- lots of HTML code for the central part of the page...>
<?php show_most_popular_pages (); /* only one function call */ ?>
<!-- lots of HTML code for the user feedback form...>

Anther big advantage of this approach is that, by simply including common_code.php as shown above, any page of your Web site will be able to use those same functions. Even more important, should any function be modified, the new version would be available immediately in all the pages.

______________________

Articles about Digital Rights and more at http://stop.zona-m.net CV, talks and bio at http://mfioretti.com

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState