PHP: Hot Pages: Basic Code: Finding errors

  1. Custom functions
  2. Basic Code
  3. Line endings

There are two common ways of finding errors when a PHP web page doesn’t do what you expect.

First, look at the source. Often, the web page will partially display, and then stop at the offending line. You can use your browser’s “view source” menu item to look at the HTML that the PHP generated, and see where it stopped. Sometimes that’s all you need to find the error.

If the resulting page and source are completely blank, go to the command line of your server and type “php <filename>”, where <filename> is the name of the PHP file that isn’t working. For example:

php time.php

You’ll likely get an error back looking something like this:

Parse error: parse error in time.php on line 18

This means that PHP cannot find any way to understand something in line 18. Look at line 18, and see what it says. Chances are once you know which line the error is on, the error will be obvious.

Finally, if the page is sort of working but not quite, you can add some code to the top to tell the server to show you errors and warnings. By default, most production servers will not show PHP errors, because the errors can expose private information. But while you’re writing a PHP page, it’s very useful to be able to see those errors. Add these lines to the very top of your page:

<?php

ini_set('display_errors', true);

error_reporting(E_ALL);

?>

I usually put these on the top of any page I’m writing if the page contains more than a few lines of PHP code. I leave them there until I’m done testing the page, and then I remove them.

  1. Custom functions
  2. Basic Code
  3. Line endings