November 4, 2012

How to Fix the Typical "My PHP Script Does Not Work" Problem

A PHP script that "does not work" because of an error will emit error messages such as "use of undefined variable", "an error in MySQL query", "permission denied", "parse error", etc. If you do not see an error when you should, it could mean that PHP is configured to suppress errors; a common practice in production environments. Developers who use AMP stacks unknowingly have PHP setup this way, and when they run into "does not work" problems and see no errors, they start asking silly questions.

The environment in which you develop code must be setup differently. Here is what you need to do in order to make PHP more verbose about errors.

display_errors = On

The most common reason for not seeing an error is that that the display_errors » setting is off. Set its value to on so that the PHP displays the errors as part of the output.

error_reporting = E_ALL | E_STRICT

The error_reporting » setting determines the type of errors that are displayed and logged by PHP. Examples include fatal errors, warnings and notices. I set this to E_ALL | E_STRICT but you can settle for less.

log_errors = On, error_log = ...

PHP can write errors to files. Set log_errors » to on so that PHP can write errors to the location specified in the error_log » setting.

The error_log setting could be empty, in which case errors are sent to the SAPI error logger; the eventual destination depends on the webserver (e.g. on Apache, the errors end up in the Apache error log). I set this to C:\php-errors.txt and create a shortcut to this file on my desktop.

Miscellaneous Tips

1. Never assume that your query will always succeed

Most novice programmers do not code to check if the query failed. A query that looks OK could still fail for many reasons, for example, because of a constraint violation. That is why you should always check the status of your query.If you are using mysql_query you could do something like this:

$result = mysql_query("INSERT INTO users (...) VALUES (...)");
if ($result === FALSE) {
    // handle the error, or just...
mail($email, $subject, $message, $headers);

2. View page source often

Sometimes an error is there but you can't see it:

Page with no visible error

View page source, and there you have it:

View page source to reveal the error