Why Is My Page Blank?: How To Write PHP Scripts
Why Is My Page Blank?: How To Write PHP Scripts
37
Strict: This type of error message warns you about using techniques that are not considered
good practice.
Notice: This advises you about relatively minor issues, such as the use of a nondeclared
variable. Although this type of error wont stop your page from displaying (and you can turn
off the display of notices), you should always try to eliminate them. Any error is a threat to your
output.
Many beginners are left scratching their heads when they load a PHP page into a browser and see
absolutely nothing.
Theres no error message, just a blank page. This happens when theres a parse errorin other words,
a mistake in the
codeand the display_errors directive in php.ini is turned off.
If you followed the advice in the previous chapter, display_errors should be enabled in your local
testing
environment. However, most hosting companies turn off display_errors. This is good for security, but it
can make
it difficult to troubleshoot problems on your remote server. As well as parse errors, a missing include
file often causes
blank pages.
You can turn on the display of errors for an individual script by adding the following code right at the
top
of the page:
ini_set('display_errors', '1');
Put this code on the first line after the opening PHP tag, or in a separate PHP block at the top of the
page if the
PHP is lower down the page. When you upload the page and refresh the browser, you should see any
error messages
generated by PHP.
If you still see a blank page after adding this line of code, it means theres an error in your syntax. Test
the page
locally with display_errors turned on to find out whats causing the problem.
Caution A fter correcting the error, remove the code that turns on the display of errors. If
something else breaks in
the script at a later stage, you dont want to expose potential vulnerabilities on your live
website.
Handling Exceptions
PHP 5 introduced a new way of handling errors, common to many other programming languages,
known as
exceptions. When a problem arises, many built-in classes automatically throw an exceptionor
generate a special
type of object that contains details of what caused the error and where it arose. You can also throw
custom exceptions,
using the keyword throw, like this:
if (error occurs) {
throw new Exception('Houston, we have a problem');
}
The string inside the parentheses is used as the error message. Obviously, in a real script, you need to
make
the message more explicit. When an exception