PHP Error Handling and Debugging – Part 1

This article describes the process of testing PHP code.  Using the tips that I will explain can help to decrease the code/test cycle time.

The first thing that you must know in order to plan your code/test process is the environment in which your code will run.

If you have full control of the system, less configuration is required. In this case you can rely on the default settings, and simply need to know where the logs are kept by default. On a typical LAMP (apache) system you can find the log files in /var/log/httpd. Check the documentation for the operating system that you use as some operating systems use a different directory (i.e. one version of Ubuntu uses /var/log/apache2). By default error messages from php will be kept in this directory.

If you are developing on a server where you don’t have access to the default logs, you can configure where your log messages are sent by putting a php.ini file containing the directive

error_log: path_to_log

in the root of the domain.

With this information in mind, we can begin to find code errors.

There are two error types to look for:

  1. parse
  2. runtime

A parse error is the first thing to look for when testing new or modified code. This can be something like a missing semicolon or other grammatical mistake. If a parse error occurs, it will be sent to PHP’s error_log. A simple way to find this kind of error is to load the file directly in a browser (i.e. an AJAX script that would not normally run in a browser could be tested this way for parse errors). With a default PHP installation the parse error will shown on the screen.

Most errors that are encountered are runtime errors. There are two kinds of runtime errors:

  1. exception
  2. functional

The first kind of runtime error happens when a statement or function call that is grammatically correct encounters a unexpected circumstance such as an invalid parameter (i.e. fopen(file_that_doesnt_exist,’r’)). This kind of error can only be seen during an actual run of the code with valid inputs. Opening the file in the browser directly usually will not find it as the inputs will not be those that would typically be encountered. For example opening an AJAX script that relys on the _POST variable for its input will typically not run many of the branches because of the missing _POST variables. To find this error, run the script as it would typically be run and check the error log for errors.

A functional runtime error is when the code runs, doesn’t generate an error, but doesn’t produce the expected outputs. To find this error use one or more of the following techniques:

  • echo/printf
  • error_log
  • try/catch

The simplest way to find errors is by adding echo statements to the code. This method can be somewhat tedious and slower to use than others, but a few well placed echo statements that use print_r to show the value of key return data structures can sometimes quickly illuminate the source of the malfunctioning code. The problem with this method is that because it outputs directly to stdout (the web browser) it is only available if the script can be run in the web browser directly with typical inputs. Many times this is not possible (i.e. for AJAX or cron code).

A more general way of debugging is to use the error_log function instead of echo. With the error_log function you can direct the messages to a file of your choosing with

error_log($message,3,"path/filename")

or to the configured error_log mentioned earlier via

error_log($message)

A bonus when using the error_log() function is that you also get a timestamp for each error logged.

If a runtime error is expected, a try/catch statement should be placed to ignore it or otherwise handle it in a way that doesn’t cause the script to stop abruptly.  This way the script will continue to run and an error will be logged.  This is better because you will know at what section of code the error occurred.  If the blocking error had gone uncaught (in the case of AJAX responder script errors), the calling application might have received a malformed response (parse error).  A try/catch statement is only helpful when a blocking exception occurs, and will not help to debug functional runtime errors.  The structure of this type of code testing is as follows:

try {
 //your new code
 } catch(Exception $E) {
 error_log(E.getMessage());
 }

In this article we have discussed simple code/test cycle techniques for PHP.  Tune in next time for part 2 where we will review using a debugger such as XDebug.

Javascript Compression — Tools and Process

This article is a review of the tools and processes that I have tested and gives plusses and minuses of each.

Software Uncompressed Compressed Percent Comment
Closure Compiler 39K 16K 59% with ADVANCED_OPTIMIZATIONS
YUI Compressor 39K 22K 44%
perl-Javascript-Minifier 39K 25K 36%

 

perl-Javascript-Minifier
Since CPAN library’s Javascript-Minifier and CSS-Minifier are immediately available linux tools they are a good starting point. The Javascript-Minifier is simple to use. Here is a script that you can try to see how it works:

#!/usr/bin/perl
 use JavaScript::Minifier qw(minify);
 my($iFile)=$ARGV[0];
 my($oFile)=$iFile;
 $oFile=~ s/[.]js//;
 $oFile="${oFile}_perl_min.js";
 open(INFILE, "$iFile") or die;
 open(OUTFILE, ">$oFile") or die;
 minify(input => *INFILE, outfile => *OUTFILE);
 close(INFILE);
 close(OUTFILE);

In my tests, it didn’t break my code, but did generate errors because of incorrectnesses in my code. I used the google chrome jslint plugin to find the errors. jslint only works on pure javascript, but strings are not parsed. Thus you can use php to initialize variables by putting the php code inside of quotes, and still check it with jslint.

 

YUI Compressor
The YUI Compressor is Yahoo’s library, and works better than perl-Javascript-Minifier. Here is an example command for using YUI Compressor:

java -jar yuicompressor-2.4.7.jar --type js -o filename_yui_min.js filename.js

A nice feature of the yuicompressor is that it can accept javascript strings from the command line. This makes it simple to script. It’s goal is to not break code, and in my tests this was observed to be true.

 

Closure Compiler
The google closure compiler is the most advanced of the ones that I tested. It has a simple mode that doesn’t break code and an option for ADVANCED_OPTIMIZATIONS that produces very compressed code. Here is an example command for using the closure compiler in simple mode:

java -jar compiler.jar --js filename.js --js_output_file filename_closure_min.js --externs externs.js

And similarly for advanced mode:

java -jar compiler.jar --compilation_level ADVANCED_OPTIMIZATIONS --js filename.js --js_output_file filename_closure_min.js --externs exterms.js

Similar to perl-Javascript-Minifier, closure compiler only works on pure javascript files. Because of the effectiveness of the optimizations that it does, it can break code. To effectively use it, you need to design your javascript with minification in mind. Typically you want to use your javascript as a library (i.e. as handers for events such as mouse clicks) to do this, you need to add a small amount of code that preserves the function names that will be available to external scripts. Similarly if you want to use external libraries in your library, you need to add extern declarations that will preserve the external symbols. There are less modifications required if you use the simple mode than for the advanced mode. I wanted to use advanced mode for some script that contains jQuery calls (including jQuery Mobile), but wasn’t able to find a way to preserve the jQuery and $ symbols. I tried using –externs with the externs file available as an addon from google svn, but this didn’t solve the problem. Therefore I recommend using simple mode for files containing jQuery and advanced mode for files that do not.

 

In summary of the tools reviewed google closure compiler is the most effective, perl-Javascript-Minifier is the least likely to break code, and yuicompressor is a compromise between these extremes. Additionally each of these tools can be run locally on your machine.

What modern business applications should offer users.

Modern business applications should offer users the following features…

While developing solutions for various projects that I’ve undertaken I’ve come up with a few ideas on the types of features that I’d like my applications to offer users.  While this list is far from complete I think it would be good to post it for comment.  Bear in mind that when I’m discussing modern business applications I’m discussing thin client web based applications using cloud architecture.

Modern business application features:

  • Remote connectivity to data and functionality.
  • Encapsulation of business logic.
  • Continuous contextual decision support.
  • User specific views of the data and logical processes
  • Security
  • Flexibility
  • Data Importing / Exporting capabilities

Remote connectivity to data and functionality: Traditional business applications ran on workstations and desktop computers.  Data was stored on the computer itself or on a server and was not accessible unless the user was sitting in front of the desktop computer itself or another computer connected to the server.  This in effect chained the user to his or her desktop device.  Modern business applications must utilize web technology and provide device independent services that allow the user to connect to the data and logic of the business through any device that they can be authenticated through that has internet connectivity.

Encapsulation of business logic: Traditional business applications such as spreadsheets, word-processors, and email allowed for the transportation and transformation of data, but the use of business logic was largely left to the discretion of the user.  Modern business applications can be designed to encapsulate the steps that must be taken with information and resources to automate processes and insure execution of critical procedures required by users.  By profiling the procedures and steps required for critical processes in the business, developers can create software that encapsulates them and insures that the order of operations is followed, all steps required are taken, all resources required are employed, and follow through is complete.  Outcomes and ownership of inputs from each step can also be tracked to determine each users contribution to the success of the process.  Success ratios for processes can be increased as the mundane oversight of each detail is moved from managers to system applications with the general oversight of larger categories of processes taken on by tech empowered managers.

Continuous contextual decision support: Because of the connectivity offered by todays diverse array of computing devices, from smart phones, laptops, tablet PCs, to thin client enabled desktop PCs.  Users now have the ability to receive data and logic at any point of the business process.  Modern business applications must provide contextual decision support by offering relevant information to the user at the right time with suggestions for its proper use and allow for user feedback into the system.

User specific views of the data and logical processes: Modern business applications must offer users unique views of the data and logical processes that fits their context to the business.  For example a vendor that supplies a business would need access to statistics indicating demand for the particular commodity they offer.  Their view of the data and logic would be an on demand view or automated communication with forecasted consumption data generated by internal business processes that the vendor never sees.  User specific views of the data and logic offer modular controls to the business and protects its core competencies from probing by competition.

Security: Traditional business applications were prone to interruption by natural disasters and other disruptive events such as fires, floods, tornadoes etc.  Modern business applications can offer security to its users by storing data and logic in a cloud environment where information is distributed off site amongst computers in multiple data centers.  This offers a degree of security to the user and provides for a significant reduction in recovery time when the business is impacted by such an event.

Flexibility: Modern business applications created with web based technologies are more flexible than traditional business applications because of the ease in which updates can be rolled out to the user.  In traditional environments users had to undergo an application update procedure before receiving an updated version of a business application that contained the latest data and logic.  Web applications are updated remotely with no effort required by the end user making their innovation, iteration, and revision much more seamless and transparent to end users.

Data Importing / Exporting capabilities: Modern business applications should easily convert data with traditional applications such as spreadsheets and allow the user the comfort of converting data for use outside of the application.  Data transfer methods such as XML are a good standard for data export and can allow for data interchange between disparaging systems and applications.

Comments and discussion are welcome.

A simple ajax page update example using jquery

An ajax example using jquery

Ajax Loading Image

Download the latest version of jquery from jquery.com and load it into your server. Create an html file or php script and output the html detailed below:
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
“http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>

<script type=”text/javascript”>
function AjaxUpdate()
{
$(document).ready(function(){$(“#MyDiv”).load(“http://yourdomain.com/yourscript.php”)});
/* setTimeout(“RssFeeder()”,90000); */
}
</script>
<title>Quick Ajax with jquery Demo</title>
</head>
<body>
<script type=”text/javascript” src=”http://yourdomain.com/javascript/jquery-1.3.2.js”></script>
<div id=”MyDiv”>
<img src=”http://yourdomain.com/images/loading.gif” alt=”Loading content…” style=”display:block; margin-left:auto; margin-right:auto; vertical-align:middle;”/>
</div>
<!– Use this method for user event loading. –>
<button onclick=”AjaxUpdate();”>Update Page</button>

<script type=”text/javascript”>
// Use this for delayed loading
eval (‘setTimeout(“AjaxUpdate()”,30000)’);
</script>
</body>
</html>

Now if you’ll create a php script to send the information to page. The data you send to the page will go into the div id:Mydiv.

In this example when the user clicks the Update button the div contents will refresh. I’ve also included an example on the page that will update the div within 30 seconds of the page load. You can write javascript back to the page with the php script so you could cause it to load again if you wanted to.

Go to http://ajaxload.info to get loading graphics for your ajax powered web applications. It’s free.

Hope this helps.

– Joel