July 7, 2008
Beginners' Corner, PHP
No Comments
This is the first "Beginners' Corner" article, designed to help new PHP programmers in their quest to become veteran PHP programmers. In this initial installment we'll look at a few things which are best avoided, but for various reasons often become habits of new PHP users who do not yet know better. Many of these may become habits simply because there are so many bad examples out there to learn from, often because they are dated and PHP has moved on in a manner which obsoletes them.
<?php Tags
The first bad habit to avoid is using <? instead of <?php or <?= instead of <?php echo. While saving those few keystrokes is a temptation to all of us lazy programmers, it is a potential problem should you need to run the script on a site where the short_open_tag option is disabled. One likely reason to have it disabled is in order to avoid confusion with <?xml tags in XML documents, and as XML is much more prevalent now than it was when PHP was created, you are more likely to find such configurations in use; so just get in the habit of typing those three extra characters and saving yourself a lot of aggravation in the future.
Read the rest...
June 29, 2008
Beginners' Corner, Debugging
3 Comments
[2008/07/15: Added this to the "Beginners' Corner" category]
A common problem I see new PHP users running into is having a script output absolutely nothing: the dreaded "blank page" syndrome. This is normally due to a syntax error of some sort generating a fatal parse error. As this error is generated before any of the script is actually executed, none of the file's output ever gets sent to the browser. If the current PHP environment on the server has display_errors turned off, then not even the error message generated by the parser gets displayed. Additionally, since no PHP commands actually get executed when there is a parse error, turning on display_errors within that script via the ini_set() function will make no difference.
The two usual approaches to debugging such problems are to either search the PHP or web server error logs to look for relevant error messages, or else to turn on display_errors, either globally in the php.ini file or at the directory level via a .htaccess file, assuming you are running under Apache and the necessary Apache settings are in effect to allow this. (A third alternative is to use an editor that has PHP syntax checking built in, such as PHPDesigner.)
If for some reason none of those approaches is practical for your situation, a simple way to have any parse errors be displayed is to create a tiny wrapper script that includes the offending file:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL | E_STRICT);
include 'path/to/flawed/file.php';
?>
All you have to do is run this script in your browser, et voilà, your parse errors will now be displayed.