debugging - How can I get useful error messages in PHP?

62

Quite often I will try and run a PHP script and just get a blank screen back. No error message; just an empty screen. The cause might have been a simple syntax error (wrong bracket, missing semicolon), or a failed function call, or something else entirely.

It is very difficult to figure out what went wrong. I end up commenting out code, entering "echo" statements everywhere, etc. trying to narrow down the problem. But there surely must be a better way, right?

Is there a way to get PHP to produce a useful error message, like Java does?

91

Answer

Solution:

For syntax errors, you need to enable error display in the php.ini. By default these are turned off because you don't want a "customer" seeing the error messages. Check this page in the PHP documentation for information on the 2 directives:error_reporting anddisplay_errors.display_errors is probably the one you want to change. If you can't modify the php.ini, you can also add the following lines to an .htaccess file:

php_flag  display_errors        on
php_value error_reporting       2039

You may want to consider using the value of E_ALL (as mentioned by Gumbo) for your version of PHP forerror_reporting to get all of the errors. more info

3 other items: (1) You can check the error log file as it will have all of the errors (unless logging has been disabled). (2) Adding the following 2 lines will help you debug errors that are not syntax errors:

error_reporting(-1);
ini_set('display_errors', 'On');

(3) Another option is to use an editor that checks for errors when you type, such as PhpEd. PhpEd also comes with a debugger which can provide more detailed information. (The PhpEd debugger is very similar to xdebug and integrates directly into the editor so you use 1 program to do everything.)

Cartman's link is also very good: http://www.ibm.com/developerworks/library/os-debug/

982

Answer

Solution:

The following enables all errors:

ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);

Also see the following links

445

Answer

Solution:

The following code should display all errors:

<?php

//

The only way to generate a blank page with this code is when you have a error in the shutdown handler. I copied and pasted this from my own cms without testing it, but I am sure it works.

86

Answer

// - Display Errors //
880

Answer

ini_set('display_errors', 'On'); ini_set('html_errors', 0); //
640

Answer

// - Error Reporting //
24

Answer

error_reporting(-1); //
716

Answer

// - Shutdown Handler //
449

Answer

function ShutdownHandler() { if(@is_array($error = @error_get_last())) { return(@call_user_func_array('ErrorHandler', $error)); }; return(TRUE); }; register_shutdown_function('ShutdownHandler'); //
981

Answer

// - Error Handler //
621

Answer

function ErrorHandler($type, $message, $file, $line) { $_ERRORS = Array( 0x0001 => 'E_ERROR', 0x0002 => 'E_WARNING', 0x0004 => 'E_PARSE', 0x0008 => 'E_NOTICE', 0x0010 => 'E_CORE_ERROR', 0x0020 => 'E_CORE_WARNING', 0x0040 => 'E_COMPILE_ERROR', 0x0080 => 'E_COMPILE_WARNING', 0x0100 => 'E_USER_ERROR', 0x0200 => 'E_USER_WARNING', 0x0400 => 'E_USER_NOTICE', 0x0800 => 'E_STRICT', 0x1000 => 'E_RECOVERABLE_ERROR', 0x2000 => 'E_DEPRECATED', 0x4000 => 'E_USER_DEPRECATED' ); if([email protected]_string($name = @array_search($type, @array_flip($_ERRORS)))) { $name = 'E_UNKNOWN'; }; return(print(@sprintf("%s Error in file \xBB%s\xAB at line %d: %s\n", $name, @basename($file), $line, $message))); }; $old_error_handler = set_error_handler("ErrorHandler"); // other php code ?>
154

Answer

Solution:

You can include the following lines in the file you want to debug:

error_reporting(E_ALL);
ini_set('display_errors', '1');

This overrides the default settings in php.ini, which just make PHP report the errors to the log.

936

Answer

Solution:

Errors and warnings usually appear in....\logs\php_error.log or....\logs\apache_error.log depending on your php.ini settings.

Also useful errors are often directed to the browser, but as they are not valid html they are not displayed.

So"tail -f" your log files and when you get a blank screen use IEs "view" -> "source" menu options to view the raw output.

489

Answer

Solution:

PHP Configuration

2 entries in php.ini dictate the output of errors:

In production,display_errors is usually set toOff (Which is a good thing, because error display in production sites is generally not desirable!).

However, in development, it should be set toOn, so that errors get displayed. Check!

error_reporting (as of PHP 5.3) is set by default toE_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED (meaning, everything is shown except for notices, strict standards and deprecation notices). When in doubt, set it toE_ALL to display all the errors. Check!

Whoa whoa! No check! I can't change my php.ini!

That's a shame. Usually shared hosts do not allow the alteration of their php.ini file, and so, that option is sadly unavailable. But fear not! We have other options!

Runtime configuration

In the desired script, we can alter the php.ini entries in runtime! Meaning, it'll run when the script runs! Sweet!

error_reporting(E_ALL);
ini_set("display_errors", "On");

These two lines will do the same effect as altering the php.ini entries as above! Awesome!

I still get a blank page/500 error!

That means that the script hadn't even run! That usually happens when you have a syntax error!

With syntax errors, the script doesn't even get to runtime. It fails at compile time, meaning that it'll use the values in php.ini, which if you hadn't changed, may not allow the display of errors.

Error logs

In addition, PHP by default logs errors. In shared hosting, it may be in a dedicated folder or on the same folder as the offending script.

If you have access to php.ini, you can find it under the entry.




495
votes

Answer

Solution:

I'm always using this syntax at the very top of the php script.

ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On');  //On or Off
587

Answer

Solution:

There is a really useful extension called "xdebug" that will make your reports much nicer as well.

927

Answer

Solution:

For quick, hands-on troubleshooting I normally suggest here on SO:

error_reporting(~0); ini_set('display_errors', 1);

to be put at the beginning of the script that is under trouble-shooting. This is not perfect, the perfect variant is that you also enable that in thephp.ini and that you log the errors in PHP to catch syntax and startup errors.

The settings outlined here display all errors, notices and warnings, including strict ones, regardless which PHP version.

Next things to consider:

  • Install Xdebug and enable remote-debugging with your IDE.

See as well:




285
votes

Answer

Solution:

It is possible to register an hook to make the last error or warning visible.

function shutdown(){
  var_dump(error_get_last());
}

register_shutdown_function('shutdown');

adding this code to the beginning of you index.php will help you debug the problems.

349

Answer

Solution:

If you are super cool, you might try:

$test_server = $_SERVER['SERVER_NAME'] == "127.0.0.1" || $_SERVER['SERVER_NAME'] == "localhost" || substr($_SERVER['SERVER_NAME'],0,3) == "192";

ini_set('display_errors',$test_server);
error_reporting(E_ALL|E_STRICT);

This will only display errors when you are running locally. It also gives you the test_server variable to use in other places where appropriate.

Any errors that happen before the script runs won't be caught, but for 99% of errors that I make, that's not an issue.

127

Answer

Solution:

On the top of the page choose a parameter

error_reporting(E_ERROR | E_WARNING | E_PARSE);
96

Answer

Solution:

This is a problem of loaded vs. runtime configuration

It's important to recognize that a syntax error or parse error happens during the compile or parsing step, which means that PHP will bail before it's even had a chance to execute any of your code. So if you are modifying PHP's{-code-1} configuration during runtime, (this includes anything from usingini_set in your code to using .htaccess, which is a runtime configuration file) then only the default loaded configuration settings are in play.

How to always avoid WSOD in development

To avoid a WSOD you want to make sure that your loaded configuration file has{-code-1} on anderror_reporting set to-1 (this is the equivalent E_ALL because it ensures all bits are turned on regardless of which version of PHP you're running). Don't hardcode the constant value of E_ALL, because that value is subject to change between different versions of PHP.

Loaded configuration is either your loadedphp.ini file or yourapache.conf orhttpd.conf or virtualhost file. Those files are only read once during the startup stage (when you first start apache httpd or php-fpm, for example) and only overridden by runtime configuration changes. Making sure that{-code-1} = 1 anderror_reporting = -1 in your loaded configuration file ensures that you will never see a WSOD regardless of syntax or parse error that occur before a runtime change likeini_set('{-code-1}', 1); orerror_reporting(E_ALL); can take place.

How to find your (php.ini) loaded configuration files

To locate your loaded configuration file(s) just create a new PHP file with only the following code...

<?php
phpinfo();

Then point your browser there and look at Loaded Configuration File and Additional .ini files parsed, which are usually at the top of yourphpinfo() and will include the absolute path to all your loaded configuration files.

If you see(none) instead of the file, that means you don't have a php.ini in Configuration File (php.ini) Path. So you can download the stock php.ini bundled with PHP from here and copy that to your configuration file path as php.ini then make sure your php user has sufficient permissions to read from that file. You'll need to restart httpd or php-fpm to load it in. Remember, this is the development php.ini file that comes bundled with the PHP source. So please don't use it in production!


Just don't do this in production

This really is the best way to avoid a WSOD in development. Anyone suggesting that you putini_set('{-code-1}', 1); orerror_reporting(E_ALL); at the top of your PHP script or using .htaccess like you did here, is not going to help you avoid a WSOD when a syntax or parse error occurs (like in your case here) if your loaded configuration file has{-code-1} turned off.

Many people (and stock installations of PHP) will use a production-ini file that has{-code-1} turned off by default, which typically results in this same frustration you've experienced here. Because PHP already has it turned off when it starts up, then encounters a syntax or parse error, and bails with nothing to output. You expect that yourini_set('{-code-1}',1); at the top of your PHP script should have avoided that, but it won't matter if PHP can't parse your code because it will never have reached the runtime.

237

Answer

Solution:

To persist this and make it confortale, you can edit your php.ini file. It is usually stored in/etc/php.ini or/etc/php/php.ini, but more localphp.ini's may overwrite it, depending on your hosting provider's setup guidelines. Check aphpinfo() file forLoaded Configuration File at the top, to be sure which one gets loaded last.

Search for display_errors in that file. There should be only 3 instances, of which 2 are commented.

Change the uncommented line to:

display_errors = stdout
786

Answer

Solution:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
817

Answer

Solution:

I don't know if it will help, but here is a piece of my standard config file for php projects. I tend not to depend too much on the apache configs even on my own server.

I never have the disappearing error problem, so perhaps something here will give you an idea.

Edited to show APPLICATON_LIVE

/*
APPLICATION_LIVE will be used in process to tell if we are in a development or production environment.  It's generally set as early as possible (often the first code to run), before any config, url routing, etc.
*/

if ( preg_match( "%^(www.)?livedomain.com$%", $_SERVER["HTTP_HOST"]) ) {
    define('APPLICATION_LIVE', true);
} elseif ( preg_match( "%^(www.)?devdomain.net$%", $_SERVER["HTTP_HOST"]) ) {
    define('APPLICATION_LIVE', false);
} else {
    die("INVALID HOST REQUEST (".$_SERVER["HTTP_HOST"].")");
    // Log or take other appropriate action.
}


/*
757

Answer

-------- DEFAULT ERROR HANDLING
335

Answer

-------- Default error logging. Some of these may be changed later based on APPLICATION_LIVE. */ error_reporting(E_ALL & ~E_STRICT); ini_set ( "display_errors", "0"); ini_set ( "display_startup_errors", "0"); ini_set ( "log_errors", 1); ini_set ( "log_errors_max_len", 0); ini_set ( "error_log", APPLICATION_ROOT."logs/php_error_log.txt"); ini_set ( "display_errors", "0"); ini_set ( "display_startup_errors", "0"); if ( ! APPLICATION_LIVE ) { // A few changes to error handling for development. // We will want errors to be visible during development. ini_set ( "display_errors", "1"); ini_set ( "display_startup_errors", "1"); ini_set ( "html_errors", "1"); ini_set ( "docref_root", "http://www.php.net/"); ini_set ( "error_prepend_string", "<div style='color:red; font-family:verdana; border:1px solid red; padding:5px;'>"); ini_set ( "error_append_string", "</div>"); }
49

Answer

Solution:

error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
ini_set('html_errors', 1);

In addition, you can get more detailed information with xdebug.

559

Answer

Solution:

I recommend Nette Tracy for better visualization of errors and exceptions in PHP:

Nette Tracy screenshot

750

Answer

Solution:

error_reporting(E_ALL | E_STRICT);

And turn on display errors in php.ini

406

Answer

Solution:

You can register your own error handler in PHP. Dumping all errors to a file might help you in these obscure cases, for example. Note that your function will get called, no matter what your current error_reporting is set to. Very basic example:

function dump_error_to_file($errno, $errstr) {
    file_put_contents('/tmp/php-errors', date('Y-m-d H:i:s - ') . $errstr, FILE_APPEND);
}
set_error_handler('dump_error_to_file');
122

Answer

Solution:

The two key lines you need to get useful errors out of PHP are:

ini_set('display_errors',1);
 error_reporting(E_ALL);

As pointed out by other contributors, these are switched off by default for security reasons. As a useful tip - when you're setting up your site it's handy to do a switch for your different environments so that these errors are ON by default in your local and development environments. This can be achieved with the following code (ideally in your index.php or config file so this is active from the start):

switch($_SERVER['SERVER_NAME'])
{
    // local
    case 'yourdomain.dev':
    // dev
    case 'dev.yourdomain.com':
        ini_set('display_errors',1);
        error_reporting(E_ALL);
    break;
    //live
    case 'yourdomain.com':
        //...
    break;
}
716

Answer

Solution:

open your php.ini, make sure it's set to:

display_errors = On

restart your server.

722

Answer

Solution:

You might also want to try PHPStorm as your code editor. It will find many PHP and other syntax errors right as you are typing in the editor.

604

Answer

Solution:

if you are a ubuntu user then goto your terminal and run this command

sudo tail -50f /var/log/apache2/error.log

where it will display recent 50 errors. There is a error fileerror.log for apache2 which logs all the errors.

669

Answer

Solution:

To turn on full error reporting, add this to your script:

error_reporting(E_ALL);

This causes even minimal warnings to show up. And, just in case:

ini_set('display_errors', '1');

Will force the display of errors. This should be turned off in production servers, but not when you're developing.

232

Answer

Solution:

The “ERRORS” are the most useful things for the developers to know their mistakes and resolved them to make the system working perfect.

PHP provides some of better ways to know the developers why and where their piece of code is getting the errors, so by knowing those errors developers can make their code better in many ways.

Best ways to write following two lines on the top of script to get all errors messages:

error_reporting(E_ALL);
ini_set("display_errors", 1);

Another way to use debugger tools like xdebug in your IDE.

467

Answer

Solution:

In addition to all the wonderful answers here, I'd like to throw in a special mention for the MySQLi and PDO libraries.

In order to...

  1. Always see database related errors, and
  2. Avoid checking the return types for methods to see if something went wrong

The best option is to configure the libraries to throw exceptions.

MySQLi

Add this near the top of your script

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

This is best placed before you usenew mysqli() ormysqli_connect().

PDO

Set thePDO::ATTR_ERRMODE attribute toPDO::ERRMODE_EXCEPTION on your connection instance. You can either do this in the constructor

$pdo = new PDO('driver:host=localhost;...', 'username', 'password', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);

or after creation

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
200

Answer

Solution:

You can enable full error reporting (including notices and strict messages). Some people find this too verbose, but it's worth a try. Seterror_reporting toE_ALL | E_STRICT in your php.ini.

error_reporting = E_ALL | E_STRICT

E_STRICT will notify you about deprecated functions and give you recommendations about the best methods to do certain tasks.

If you don't want notices, but you find other message types helpful, try excluding notices:

error_reporting = (E_ALL | E_STRICT) & ~E_NOTICE

Also make sure thatdisplay_errors is enabled in php.ini. If your PHP version is older than 5.2.4, set it toOn:

display_errors = "On"

If your version is 5.2.4 or newer, use:

display_errors = "stderr"
208

Answer

Solution:

Aside from error_reporting and the display_errors ini setting, you can get SYNTAX errors from your web server's log files. When I'm developing PHP I load my development system's web server logs into my editor. Whenever I test a page and get a blank screen, the log file goes stale and my editor asks if I want to reload it. When I do, I jump to the bottom and there is the syntax error. For example:

[Sun Apr 19 19:09:11 2009] [error] [client 127.0.0.1] PHP Parse error:  syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in D:\\webroot\\test\\test.php on line 9
803

Answer

Solution:

This answer is brought to you by the department of redundancy department.

  1. ini_set() / php.ini / .htaccess / .user.ini

    The settingsdisplay_errors anderror_reporting have been covered sufficiently now. But just to recap when to use which option:

    And as crude alternative for runtime errors you can often use:

    set_error_handler("var_dump");   // ignores error_reporting and `@` suppression
    
  2. Can be used to retrieve the last runtime notice/warning/error, when error_display is disabled.

  3. Is a superlocal variable, which also contains the last PHP runtime message.

  4. isset() begone!

    I know this will displease a lot of folks, but and should not be used by newcomers. You can add the notice suppression after you verified your code is working. But never before.

    A lot of the "something doesn't work" questions we get lately are the result of typos like:

    if(isset($_POST['sumbit']))
    #                  ↑↑
    

    You won't get any useful notices if your code is littered withisset/empty/array_keys_exists. It's sometimes more sensible to use , so notices and warnings go to the logs at least.

  5. To get warnings forassert() sections. (Pretty uncommon, but more proficient code might contain some.)

    PHP7 requires in the php.ini as well.

  6. Bending PHP into a strictly typed language is not going to fix a whole lot of logic errors, but it's definitely an option for debugging purposes.

  7. PDO / MySQLi

    And @Phil already mentioned PDO/MySQLi error reporting options. Similar options exist for other database APIs of course.

  8. +

    For JSON parsing.

  9. For regexen.

  10. CURLOPT_VERBOSE

    To debug curl requests, you need CURLOPT_VERBOSE at the very least.

  11. Likewise will shell command execution not yield errors on its own. You always need2>&1 and peek at the $errno.

16

Answer

Solution:

For syntax errors, you need to enable error display in the php.ini. By default these are turned off because you don't want a "customer" seeing the error messages. Check this page in the PHP documentation for information on the 2 directives:error_reporting anddisplay_errors.display_errors is probably the one you want to change. If you can't modify the php.ini, you can also add the following lines to an .htaccess file:

php_flag  display_errors        on
php_value error_reporting       2039

You may want to consider using the value of E_ALL (as mentioned by Gumbo) for your version of PHP forerror_reporting to get all of the errors. more info

3 other items: (1) You can check the error log file as it will have all of the errors (unless logging has been disabled). (2) Adding the following 2 lines will help you debug errors that are not syntax errors:

error_reporting(-1);
ini_set('display_errors', 'On');

(3) Another option is to use an editor that checks for errors when you type, such as PhpEd. PhpEd also comes with a debugger which can provide more detailed information. (The PhpEd debugger is very similar to xdebug and integrates directly into the editor so you use 1 program to do everything.)

Cartman's link is also very good: http://www.ibm.com/developerworks/library/os-debug/

370

Answer

Solution:

The following enables all errors:

ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);

Also see the following links

122

Answer

Solution:

The following code should display all errors:

<?php

//

The only way to generate a blank page with this code is when you have a error in the shutdown handler. I copied and pasted this from my own cms without testing it, but I am sure it works.

907

Answer

// - Display Errors //
633

Answer

ini_set('display_errors', 'On'); ini_set('html_errors', 0); //
175

Answer

// - Error Reporting //
922

Answer

error_reporting(-1); //
539

Answer

// - Shutdown Handler //
788

Answer

function ShutdownHandler() { if(@is_array($error = @error_get_last())) { return(@call_user_func_array('ErrorHandler', $error)); }; return(TRUE); }; register_shutdown_function('ShutdownHandler'); //
572

Answer

// - Error Handler //
439

Answer

function ErrorHandler($type, $message, $file, $line) { $_ERRORS = Array( 0x0001 => 'E_ERROR', 0x0002 => 'E_WARNING', 0x0004 => 'E_PARSE', 0x0008 => 'E_NOTICE', 0x0010 => 'E_CORE_ERROR', 0x0020 => 'E_CORE_WARNING', 0x0040 => 'E_COMPILE_ERROR', 0x0080 => 'E_COMPILE_WARNING', 0x0100 => 'E_USER_ERROR', 0x0200 => 'E_USER_WARNING', 0x0400 => 'E_USER_NOTICE', 0x0800 => 'E_STRICT', 0x1000 => 'E_RECOVERABLE_ERROR', 0x2000 => 'E_DEPRECATED', 0x4000 => 'E_USER_DEPRECATED' ); if([email protected]_string($name = @array_search($type, @array_flip($_ERRORS)))) { $name = 'E_UNKNOWN'; }; return(print(@sprintf("%s Error in file \xBB%s\xAB at line %d: %s\n", $name, @basename($file), $line, $message))); }; $old_error_handler = set_error_handler("ErrorHandler"); // other php code ?>
904

Answer

Solution:

You can include the following lines in the file you want to debug:

error_reporting(E_ALL);
ini_set('display_errors', '1');

This overrides the default settings in php.ini, which just make PHP report the errors to the log.

568

Answer

Solution:

Errors and warnings usually appear in....\logs\php_error.log or....\logs\apache_error.log depending on your php.ini settings.

Also useful errors are often directed to the browser, but as they are not valid html they are not displayed.

So"tail -f" your log files and when you get a blank screen use IEs "view" -> "source" menu options to view the raw output.

756

Answer

Solution:

PHP Configuration

2 entries in php.ini dictate the output of errors:

In production,display_errors is usually set toOff (Which is a good thing, because error display in production sites is generally not desirable!).

However, in development, it should be set toOn, so that errors get displayed. Check!

error_reporting (as of PHP 5.3) is set by default toE_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED (meaning, everything is shown except for notices, strict standards and deprecation notices). When in doubt, set it toE_ALL to display all the errors. Check!

Whoa whoa! No check! I can't change my php.ini!

That's a shame. Usually shared hosts do not allow the alteration of their php.ini file, and so, that option is sadly unavailable. But fear not! We have other options!

Runtime configuration

In the desired script, we can alter the php.ini entries in runtime! Meaning, it'll run when the script runs! Sweet!

error_reporting(E_ALL);
ini_set("display_errors", "On");

These two lines will do the same effect as altering the php.ini entries as above! Awesome!

I still get a blank page/500 error!

That means that the script hadn't even run! That usually happens when you have a syntax error!

With syntax errors, the script doesn't even get to runtime. It fails at compile time, meaning that it'll use the values in php.ini, which if you hadn't changed, may not allow the display of errors.

Error logs

In addition, PHP by default logs errors. In shared hosting, it may be in a dedicated folder or on the same folder as the offending script.

If you have access to php.ini, you can find it under the entry.




611
votes

Answer

Solution:

I'm always using this syntax at the very top of the php script.

ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On');  //On or Off
478

Answer

Solution:

There is a really useful extension called "xdebug" that will make your reports much nicer as well.

110

Answer

Solution:

For quick, hands-on troubleshooting I normally suggest here on SO:

error_reporting(~0); ini_set('display_errors', 1);

to be put at the beginning of the script that is under trouble-shooting. This is not perfect, the perfect variant is that you also enable that in thephp.ini and that you log the errors in PHP to catch syntax and startup errors.

The settings outlined here display all errors, notices and warnings, including strict ones, regardless which PHP version.

Next things to consider:

  • Install Xdebug and enable remote-debugging with your IDE.

See as well:




766
votes

Answer

Solution:

It is possible to register an hook to make the last error or warning visible.

function shutdown(){
  var_dump(error_get_last());
}

register_shutdown_function('shutdown');

adding this code to the beginning of you index.php will help you debug the problems.

524

Answer

Solution:

If you are super cool, you might try:

$test_server = $_SERVER['SERVER_NAME'] == "127.0.0.1" || $_SERVER['SERVER_NAME'] == "localhost" || substr($_SERVER['SERVER_NAME'],0,3) == "192";

ini_set('display_errors',$test_server);
error_reporting(E_ALL|E_STRICT);

This will only display errors when you are running locally. It also gives you the test_server variable to use in other places where appropriate.

Any errors that happen before the script runs won't be caught, but for 99% of errors that I make, that's not an issue.

141

Answer

Solution:

On the top of the page choose a parameter

error_reporting(E_ERROR | E_WARNING | E_PARSE);
411

Answer

Solution:

This is a problem of loaded vs. runtime configuration

It's important to recognize that a syntax error or parse error happens during the compile or parsing step, which means that PHP will bail before it's even had a chance to execute any of your code. So if you are modifying PHP's{-code-1} configuration during runtime, (this includes anything from usingini_set in your code to using .htaccess, which is a runtime configuration file) then only the default loaded configuration settings are in play.

How to always avoid WSOD in development

To avoid a WSOD you want to make sure that your loaded configuration file has{-code-1} on anderror_reporting set to-1 (this is the equivalent E_ALL because it ensures all bits are turned on regardless of which version of PHP you're running). Don't hardcode the constant value of E_ALL, because that value is subject to change between different versions of PHP.

Loaded configuration is either your loadedphp.ini file or yourapache.conf orhttpd.conf or virtualhost file. Those files are only read once during the startup stage (when you first start apache httpd or php-fpm, for example) and only overridden by runtime configuration changes. Making sure that{-code-1} = 1 anderror_reporting = -1 in your loaded configuration file ensures that you will never see a WSOD regardless of syntax or parse error that occur before a runtime change likeini_set('{-code-1}', 1); orerror_reporting(E_ALL); can take place.

How to find your (php.ini) loaded configuration files

To locate your loaded configuration file(s) just create a new PHP file with only the following code...

<?php
phpinfo();

Then point your browser there and look at Loaded Configuration File and Additional .ini files parsed, which are usually at the top of yourphpinfo() and will include the absolute path to all your loaded configuration files.

If you see(none) instead of the file, that means you don't have a php.ini in Configuration File (php.ini) Path. So you can download the stock php.ini bundled with PHP from here and copy that to your configuration file path as php.ini then make sure your php user has sufficient permissions to read from that file. You'll need to restart httpd or php-fpm to load it in. Remember, this is the development php.ini file that comes bundled with the PHP source. So please don't use it in production!


Just don't do this in production

This really is the best way to avoid a WSOD in development. Anyone suggesting that you putini_set('{-code-1}', 1); orerror_reporting(E_ALL); at the top of your PHP script or using .htaccess like you did here, is not going to help you avoid a WSOD when a syntax or parse error occurs (like in your case here) if your loaded configuration file has{-code-1} turned off.

Many people (and stock installations of PHP) will use a production-ini file that has{-code-1} turned off by default, which typically results in this same frustration you've experienced here. Because PHP already has it turned off when it starts up, then encounters a syntax or parse error, and bails with nothing to output. You expect that yourini_set('{-code-1}',1); at the top of your PHP script should have avoided that, but it won't matter if PHP can't parse your code because it will never have reached the runtime.

544

Answer

Solution:

To persist this and make it confortale, you can edit your php.ini file. It is usually stored in/etc/php.ini or/etc/php/php.ini, but more localphp.ini's may overwrite it, depending on your hosting provider's setup guidelines. Check aphpinfo() file forLoaded Configuration File at the top, to be sure which one gets loaded last.

Search for display_errors in that file. There should be only 3 instances, of which 2 are commented.

Change the uncommented line to:

display_errors = stdout
623

Answer

Solution:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
480

Answer

Solution:

I don't know if it will help, but here is a piece of my standard config file for php projects. I tend not to depend too much on the apache configs even on my own server.

I never have the disappearing error problem, so perhaps something here will give you an idea.

Edited to show APPLICATON_LIVE

/*
APPLICATION_LIVE will be used in process to tell if we are in a development or production environment.  It's generally set as early as possible (often the first code to run), before any config, url routing, etc.
*/

if ( preg_match( "%^(www.)?livedomain.com$%", $_SERVER["HTTP_HOST"]) ) {
    define('APPLICATION_LIVE', true);
} elseif ( preg_match( "%^(www.)?devdomain.net$%", $_SERVER["HTTP_HOST"]) ) {
    define('APPLICATION_LIVE', false);
} else {
    die("INVALID HOST REQUEST (".$_SERVER["HTTP_HOST"].")");
    // Log or take other appropriate action.
}


/*
184

Answer

-------- DEFAULT ERROR HANDLING
270

Answer

-------- Default error logging. Some of these may be changed later based on APPLICATION_LIVE. */ error_reporting(E_ALL & ~E_STRICT); ini_set ( "display_errors", "0"); ini_set ( "display_startup_errors", "0"); ini_set ( "log_errors", 1); ini_set ( "log_errors_max_len", 0); ini_set ( "error_log", APPLICATION_ROOT."logs/php_error_log.txt"); ini_set ( "display_errors", "0"); ini_set ( "display_startup_errors", "0"); if ( ! APPLICATION_LIVE ) { // A few changes to error handling for development. // We will want errors to be visible during development. ini_set ( "display_errors", "1"); ini_set ( "display_startup_errors", "1"); ini_set ( "html_errors", "1"); ini_set ( "docref_root", "http://www.php.net/"); ini_set ( "error_prepend_string", "<div style='color:red; font-family:verdana; border:1px solid red; padding:5px;'>"); ini_set ( "error_append_string", "</div>"); }
664

Answer

Solution:

error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
ini_set('html_errors', 1);

In addition, you can get more detailed information with xdebug.

496

Answer

Solution:

I recommend Nette Tracy for better visualization of errors and exceptions in PHP:

Nette Tracy screenshot

591

Answer

Solution:

error_reporting(E_ALL | E_STRICT);

And turn on display errors in php.ini

35

Answer

Solution:

You can register your own error handler in PHP. Dumping all errors to a file might help you in these obscure cases, for example. Note that your function will get called, no matter what your current error_reporting is set to. Very basic example:

function dump_error_to_file($errno, $errstr) {
    file_put_contents('/tmp/php-errors', date('Y-m-d H:i:s - ') . $errstr, FILE_APPEND);
}
set_error_handler('dump_error_to_file');
287

Answer

Solution:

The two key lines you need to get useful errors out of PHP are:

ini_set('display_errors',1);
 error_reporting(E_ALL);

As pointed out by other contributors, these are switched off by default for security reasons. As a useful tip - when you're setting up your site it's handy to do a switch for your different environments so that these errors are ON by default in your local and development environments. This can be achieved with the following code (ideally in your index.php or config file so this is active from the start):

switch($_SERVER['SERVER_NAME'])
{
    // local
    case 'yourdomain.dev':
    // dev
    case 'dev.yourdomain.com':
        ini_set('display_errors',1);
        error_reporting(E_ALL);
    break;
    //live
    case 'yourdomain.com':
        //...
    break;
}
987

Answer

Solution:

open your php.ini, make sure it's set to:

display_errors = On

restart your server.

999

Answer

Solution:

You might also want to try PHPStorm as your code editor. It will find many PHP and other syntax errors right as you are typing in the editor.

71

Answer

Solution:

if you are a ubuntu user then goto your terminal and run this command

sudo tail -50f /var/log/apache2/error.log

where it will display recent 50 errors. There is a error fileerror.log for apache2 which logs all the errors.

472

Answer

Solution:

To turn on full error reporting, add this to your script:

error_reporting(E_ALL);

This causes even minimal warnings to show up. And, just in case:

ini_set('display_errors', '1');

Will force the display of errors. This should be turned off in production servers, but not when you're developing.

570

Answer

Solution:

The “ERRORS” are the most useful things for the developers to know their mistakes and resolved them to make the system working perfect.

PHP provides some of better ways to know the developers why and where their piece of code is getting the errors, so by knowing those errors developers can make their code better in many ways.

Best ways to write following two lines on the top of script to get all errors messages:

error_reporting(E_ALL);
ini_set("display_errors", 1);

Another way to use debugger tools like xdebug in your IDE.

18

Answer

Solution:

In addition to all the wonderful answers here, I'd like to throw in a special mention for the MySQLi and PDO libraries.

In order to...

  1. Always see database related errors, and
  2. Avoid checking the return types for methods to see if something went wrong

The best option is to configure the libraries to throw exceptions.

MySQLi

Add this near the top of your script

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

This is best placed before you usenew mysqli() ormysqli_connect().

PDO

Set thePDO::ATTR_ERRMODE attribute toPDO::ERRMODE_EXCEPTION on your connection instance. You can either do this in the constructor

$pdo = new PDO('driver:host=localhost;...', 'username', 'password', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);

or after creation

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
778

Answer

Solution:

You can enable full error reporting (including notices and strict messages). Some people find this too verbose, but it's worth a try. Seterror_reporting toE_ALL | E_STRICT in your php.ini.

error_reporting = E_ALL | E_STRICT

E_STRICT will notify you about deprecated functions and give you recommendations about the best methods to do certain tasks.

If you don't want notices, but you find other message types helpful, try excluding notices:

error_reporting = (E_ALL | E_STRICT) & ~E_NOTICE

Also make sure thatdisplay_errors is enabled in php.ini. If your PHP version is older than 5.2.4, set it toOn:

display_errors = "On"

If your version is 5.2.4 or newer, use:

display_errors = "stderr"
892

Answer

Solution:

Aside from error_reporting and the display_errors ini setting, you can get SYNTAX errors from your web server's log files. When I'm developing PHP I load my development system's web server logs into my editor. Whenever I test a page and get a blank screen, the log file goes stale and my editor asks if I want to reload it. When I do, I jump to the bottom and there is the syntax error. For example:

[Sun Apr 19 19:09:11 2009] [error] [client 127.0.0.1] PHP Parse error:  syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in D:\\webroot\\test\\test.php on line 9
496

Answer

Solution:

This answer is brought to you by the department of redundancy department.

  1. ini_set() / php.ini / .htaccess / .user.ini

    The settingsdisplay_errors anderror_reporting have been covered sufficiently now. But just to recap when to use which option:

    And as crude alternative for runtime errors you can often use:

    set_error_handler("var_dump");   // ignores error_reporting and `@` suppression
    
  2. Can be used to retrieve the last runtime notice/warning/error, when error_display is disabled.

  3. Is a superlocal variable, which also contains the last PHP runtime message.

  4. isset() begone!

    I know this will displease a lot of folks, but and should not be used by newcomers. You can add the notice suppression after you verified your code is working. But never before.

    A lot of the "something doesn't work" questions we get lately are the result of typos like:

    if(isset($_POST['sumbit']))
    #                  ↑↑
    

    You won't get any useful notices if your code is littered withisset/empty/array_keys_exists. It's sometimes more sensible to use , so notices and warnings go to the logs at least.

  5. To get warnings forassert() sections. (Pretty uncommon, but more proficient code might contain some.)

    PHP7 requires in the php.ini as well.

  6. Bending PHP into a strictly typed language is not going to fix a whole lot of logic errors, but it's definitely an option for debugging purposes.

  7. PDO / MySQLi

    And @Phil already mentioned PDO/MySQLi error reporting options. Similar options exist for other database APIs of course.

  8. +

    For JSON parsing.

  9. For regexen.

  10. CURLOPT_VERBOSE

    To debug curl requests, you need CURLOPT_VERBOSE at the very least.

  11. Likewise will shell command execution not yield errors on its own. You always need2>&1 and peek at the $errno.

626

Answer

Solution:

For syntax errors, you need to enable error display in the php.ini. By default these are turned off because you don't want a "customer" seeing the error messages. Check this page in the PHP documentation for information on the 2 directives:error_reporting anddisplay_errors.display_errors is probably the one you want to change. If you can't modify the php.ini, you can also add the following lines to an .htaccess file:

php_flag  display_errors        on
php_value error_reporting       2039

You may want to consider using the value of E_ALL (as mentioned by Gumbo) for your version of PHP forerror_reporting to get all of the errors. more info

3 other items: (1) You can check the error log file as it will have all of the errors (unless logging has been disabled). (2) Adding the following 2 lines will help you debug errors that are not syntax errors:

error_reporting(-1);
ini_set('display_errors', 'On');

(3) Another option is to use an editor that checks for errors when you type, such as PhpEd. PhpEd also comes with a debugger which can provide more detailed information. (The PhpEd debugger is very similar to xdebug and integrates directly into the editor so you use 1 program to do everything.)

Cartman's link is also very good: http://www.ibm.com/developerworks/library/os-debug/

788

Answer

Solution:

The following enables all errors:

ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);

Also see the following links

51

Answer

Solution:

The following code should display all errors:

<?php

//

The only way to generate a blank page with this code is when you have a error in the shutdown handler. I copied and pasted this from my own cms without testing it, but I am sure it works.

503

Answer

// - Display Errors //
28

Answer

ini_set('display_errors', 'On'); ini_set('html_errors', 0); //
896

Answer

// - Error Reporting //
362

Answer

error_reporting(-1); //
402

Answer

// - Shutdown Handler //
105

Answer

function ShutdownHandler() { if(@is_array($error = @error_get_last())) { return(@call_user_func_array('ErrorHandler', $error)); }; return(TRUE); }; register_shutdown_function('ShutdownHandler'); //
691

Answer

// - Error Handler //
382

Answer

function ErrorHandler($type, $message, $file, $line) { $_ERRORS = Array( 0x0001 => 'E_ERROR', 0x0002 => 'E_WARNING', 0x0004 => 'E_PARSE', 0x0008 => 'E_NOTICE', 0x0010 => 'E_CORE_ERROR', 0x0020 => 'E_CORE_WARNING', 0x0040 => 'E_COMPILE_ERROR', 0x0080 => 'E_COMPILE_WARNING', 0x0100 => 'E_USER_ERROR', 0x0200 => 'E_USER_WARNING', 0x0400 => 'E_USER_NOTICE', 0x0800 => 'E_STRICT', 0x1000 => 'E_RECOVERABLE_ERROR', 0x2000 => 'E_DEPRECATED', 0x4000 => 'E_USER_DEPRECATED' ); if([email protected]_string($name = @array_search($type, @array_flip($_ERRORS)))) { $name = 'E_UNKNOWN'; }; return(print(@sprintf("%s Error in file \xBB%s\xAB at line %d: %s\n", $name, @basename($file), $line, $message))); }; $old_error_handler = set_error_handler("ErrorHandler"); // other php code ?>
684

Answer

Solution:

You can include the following lines in the file you want to debug:

error_reporting(E_ALL);
ini_set('display_errors', '1');

This overrides the default settings in php.ini, which just make PHP report the errors to the log.

785

Answer

Solution:

Errors and warnings usually appear in....\logs\php_error.log or....\logs\apache_error.log depending on your php.ini settings.

Also useful errors are often directed to the browser, but as they are not valid html they are not displayed.

So"tail -f" your log files and when you get a blank screen use IEs "view" -> "source" menu options to view the raw output.

335

Answer

Solution:

PHP Configuration

2 entries in php.ini dictate the output of errors:

In production,display_errors is usually set toOff (Which is a good thing, because error display in production sites is generally not desirable!).

However, in development, it should be set toOn, so that errors get displayed. Check!

error_reporting (as of PHP 5.3) is set by default toE_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED (meaning, everything is shown except for notices, strict standards and deprecation notices). When in doubt, set it toE_ALL to display all the errors. Check!

Whoa whoa! No check! I can't change my php.ini!

That's a shame. Usually shared hosts do not allow the alteration of their php.ini file, and so, that option is sadly unavailable. But fear not! We have other options!

Runtime configuration

In the desired script, we can alter the php.ini entries in runtime! Meaning, it'll run when the script runs! Sweet!

error_reporting(E_ALL);
ini_set("display_errors", "On");

These two lines will do the same effect as altering the php.ini entries as above! Awesome!

I still get a blank page/500 error!

That means that the script hadn't even run! That usually happens when you have a syntax error!

With syntax errors, the script doesn't even get to runtime. It fails at compile time, meaning that it'll use the values in php.ini, which if you hadn't changed, may not allow the display of errors.

Error logs

In addition, PHP by default logs errors. In shared hosting, it may be in a dedicated folder or on the same folder as the offending script.

If you have access to php.ini, you can find it under the entry.




195
votes

Answer

Solution:

I'm always using this syntax at the very top of the php script.

ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On');  //On or Off
820

Answer

Solution:

There is a really useful extension called "xdebug" that will make your reports much nicer as well.

19

Answer

Solution:

For quick, hands-on troubleshooting I normally suggest here on SO:

error_reporting(~0); ini_set('display_errors', 1);

to be put at the beginning of the script that is under trouble-shooting. This is not perfect, the perfect variant is that you also enable that in thephp.ini and that you log the errors in PHP to catch syntax and startup errors.

The settings outlined here display all errors, notices and warnings, including strict ones, regardless which PHP version.

Next things to consider:

  • Install Xdebug and enable remote-debugging with your IDE.

See as well:




770
votes

Answer

Solution:

It is possible to register an hook to make the last error or warning visible.

function shutdown(){
  var_dump(error_get_last());
}

register_shutdown_function('shutdown');

adding this code to the beginning of you index.php will help you debug the problems.

110

Answer

Solution:

If you are super cool, you might try:

$test_server = $_SERVER['SERVER_NAME'] == "127.0.0.1" || $_SERVER['SERVER_NAME'] == "localhost" || substr($_SERVER['SERVER_NAME'],0,3) == "192";

ini_set('display_errors',$test_server);
error_reporting(E_ALL|E_STRICT);

This will only display errors when you are running locally. It also gives you the test_server variable to use in other places where appropriate.

Any errors that happen before the script runs won't be caught, but for 99% of errors that I make, that's not an issue.

305

Answer

Solution:

On the top of the page choose a parameter

error_reporting(E_ERROR | E_WARNING | E_PARSE);
425

Answer

Solution:

This is a problem of loaded vs. runtime configuration

It's important to recognize that a syntax error or parse error happens during the compile or parsing step, which means that PHP will bail before it's even had a chance to execute any of your code. So if you are modifying PHP's{-code-1} configuration during runtime, (this includes anything from usingini_set in your code to using .htaccess, which is a runtime configuration file) then only the default loaded configuration settings are in play.

How to always avoid WSOD in development

To avoid a WSOD you want to make sure that your loaded configuration file has{-code-1} on anderror_reporting set to-1 (this is the equivalent E_ALL because it ensures all bits are turned on regardless of which version of PHP you're running). Don't hardcode the constant value of E_ALL, because that value is subject to change between different versions of PHP.

Loaded configuration is either your loadedphp.ini file or yourapache.conf orhttpd.conf or virtualhost file. Those files are only read once during the startup stage (when you first start apache httpd or php-fpm, for example) and only overridden by runtime configuration changes. Making sure that{-code-1} = 1 anderror_reporting = -1 in your loaded configuration file ensures that you will never see a WSOD regardless of syntax or parse error that occur before a runtime change likeini_set('{-code-1}', 1); orerror_reporting(E_ALL); can take place.

How to find your (php.ini) loaded configuration files

To locate your loaded configuration file(s) just create a new PHP file with only the following code...

<?php
phpinfo();

Then point your browser there and look at Loaded Configuration File and Additional .ini files parsed, which are usually at the top of yourphpinfo() and will include the absolute path to all your loaded configuration files.

If you see(none) instead of the file, that means you don't have a php.ini in Configuration File (php.ini) Path. So you can download the stock php.ini bundled with PHP from here and copy that to your configuration file path as php.ini then make sure your php user has sufficient permissions to read from that file. You'll need to restart httpd or php-fpm to load it in. Remember, this is the development php.ini file that comes bundled with the PHP source. So please don't use it in production!


Just don't do this in production

This really is the best way to avoid a WSOD in development. Anyone suggesting that you putini_set('{-code-1}', 1); orerror_reporting(E_ALL); at the top of your PHP script or using .htaccess like you did here, is not going to help you avoid a WSOD when a syntax or parse error occurs (like in your case here) if your loaded configuration file has{-code-1} turned off.

Many people (and stock installations of PHP) will use a production-ini file that has{-code-1} turned off by default, which typically results in this same frustration you've experienced here. Because PHP already has it turned off when it starts up, then encounters a syntax or parse error, and bails with nothing to output. You expect that yourini_set('{-code-1}',1); at the top of your PHP script should have avoided that, but it won't matter if PHP can't parse your code because it will never have reached the runtime.

697

Answer

Solution:

To persist this and make it confortale, you can edit your php.ini file. It is usually stored in/etc/php.ini or/etc/php/php.ini, but more localphp.ini's may overwrite it, depending on your hosting provider's setup guidelines. Check aphpinfo() file forLoaded Configuration File at the top, to be sure which one gets loaded last.

Search for display_errors in that file. There should be only 3 instances, of which 2 are commented.

Change the uncommented line to:

display_errors = stdout
170

Answer

Solution:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
215

Answer

Solution:

I don't know if it will help, but here is a piece of my standard config file for php projects. I tend not to depend too much on the apache configs even on my own server.

I never have the disappearing error problem, so perhaps something here will give you an idea.

Edited to show APPLICATON_LIVE

/*
APPLICATION_LIVE will be used in process to tell if we are in a development or production environment.  It's generally set as early as possible (often the first code to run), before any config, url routing, etc.
*/

if ( preg_match( "%^(www.)?livedomain.com$%", $_SERVER["HTTP_HOST"]) ) {
    define('APPLICATION_LIVE', true);
} elseif ( preg_match( "%^(www.)?devdomain.net$%", $_SERVER["HTTP_HOST"]) ) {
    define('APPLICATION_LIVE', false);
} else {
    die("INVALID HOST REQUEST (".$_SERVER["HTTP_HOST"].")");
    // Log or take other appropriate action.
}


/*
20

Answer

-------- DEFAULT ERROR HANDLING
619

Answer

-------- Default error logging. Some of these may be changed later based on APPLICATION_LIVE. */ error_reporting(E_ALL & ~E_STRICT); ini_set ( "display_errors", "0"); ini_set ( "display_startup_errors", "0"); ini_set ( "log_errors", 1); ini_set ( "log_errors_max_len", 0); ini_set ( "error_log", APPLICATION_ROOT."logs/php_error_log.txt"); ini_set ( "display_errors", "0"); ini_set ( "display_startup_errors", "0"); if ( ! APPLICATION_LIVE ) { // A few changes to error handling for development. // We will want errors to be visible during development. ini_set ( "display_errors", "1"); ini_set ( "display_startup_errors", "1"); ini_set ( "html_errors", "1"); ini_set ( "docref_root", "http://www.php.net/"); ini_set ( "error_prepend_string", "<div style='color:red; font-family:verdana; border:1px solid red; padding:5px;'>"); ini_set ( "error_append_string", "</div>"); }
656

Answer

Solution:

error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
ini_set('html_errors', 1);

In addition, you can get more detailed information with xdebug.

40

Answer

Solution:

I recommend Nette Tracy for better visualization of errors and exceptions in PHP:

Nette Tracy screenshot

58

Answer

Solution:

error_reporting(E_ALL | E_STRICT);

And turn on display errors in php.ini

338

Answer

Solution:

You can register your own error handler in PHP. Dumping all errors to a file might help you in these obscure cases, for example. Note that your function will get called, no matter what your current error_reporting is set to. Very basic example:

function dump_error_to_file($errno, $errstr) {
    file_put_contents('/tmp/php-errors', date('Y-m-d H:i:s - ') . $errstr, FILE_APPEND);
}
set_error_handler('dump_error_to_file');
252

Answer

Solution:

The two key lines you need to get useful errors out of PHP are:

ini_set('display_errors',1);
 error_reporting(E_ALL);

As pointed out by other contributors, these are switched off by default for security reasons. As a useful tip - when you're setting up your site it's handy to do a switch for your different environments so that these errors are ON by default in your local and development environments. This can be achieved with the following code (ideally in your index.php or config file so this is active from the start):

switch($_SERVER['SERVER_NAME'])
{
    // local
    case 'yourdomain.dev':
    // dev
    case 'dev.yourdomain.com':
        ini_set('display_errors',1);
        error_reporting(E_ALL);
    break;
    //live
    case 'yourdomain.com':
        //...
    break;
}
86

Answer

Solution:

open your php.ini, make sure it's set to:

display_errors = On

restart your server.

139

Answer

Solution:

You might also want to try PHPStorm as your code editor. It will find many PHP and other syntax errors right as you are typing in the editor.

831

Answer

Solution:

if you are a ubuntu user then goto your terminal and run this command

sudo tail -50f /var/log/apache2/error.log

where it will display recent 50 errors. There is a error fileerror.log for apache2 which logs all the errors.

975

Answer

Solution:

To turn on full error reporting, add this to your script:

error_reporting(E_ALL);

This causes even minimal warnings to show up. And, just in case:

ini_set('display_errors', '1');

Will force the display of errors. This should be turned off in production servers, but not when you're developing.

676

Answer

Solution:

The “ERRORS” are the most useful things for the developers to know their mistakes and resolved them to make the system working perfect.

PHP provides some of better ways to know the developers why and where their piece of code is getting the errors, so by knowing those errors developers can make their code better in many ways.

Best ways to write following two lines on the top of script to get all errors messages:

error_reporting(E_ALL);
ini_set("display_errors", 1);

Another way to use debugger tools like xdebug in your IDE.

444

Answer

Solution:

In addition to all the wonderful answers here, I'd like to throw in a special mention for the MySQLi and PDO libraries.

In order to...

  1. Always see database related errors, and
  2. Avoid checking the return types for methods to see if something went wrong

The best option is to configure the libraries to throw exceptions.

MySQLi

Add this near the top of your script

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

This is best placed before you usenew mysqli() ormysqli_connect().

PDO

Set thePDO::ATTR_ERRMODE attribute toPDO::ERRMODE_EXCEPTION on your connection instance. You can either do this in the constructor

$pdo = new PDO('driver:host=localhost;...', 'username', 'password', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);

or after creation

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
290

Answer

Solution:

You can enable full error reporting (including notices and strict messages). Some people find this too verbose, but it's worth a try. Seterror_reporting toE_ALL | E_STRICT in your php.ini.

error_reporting = E_ALL | E_STRICT

E_STRICT will notify you about deprecated functions and give you recommendations about the best methods to do certain tasks.

If you don't want notices, but you find other message types helpful, try excluding notices:

error_reporting = (E_ALL | E_STRICT) & ~E_NOTICE

Also make sure thatdisplay_errors is enabled in php.ini. If your PHP version is older than 5.2.4, set it toOn:

display_errors = "On"

If your version is 5.2.4 or newer, use:

display_errors = "stderr"
893

Answer

Solution:

Aside from error_reporting and the display_errors ini setting, you can get SYNTAX errors from your web server's log files. When I'm developing PHP I load my development system's web server logs into my editor. Whenever I test a page and get a blank screen, the log file goes stale and my editor asks if I want to reload it. When I do, I jump to the bottom and there is the syntax error. For example:

[Sun Apr 19 19:09:11 2009] [error] [client 127.0.0.1] PHP Parse error:  syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in D:\\webroot\\test\\test.php on line 9
86

Answer

Solution:

This answer is brought to you by the department of redundancy department.

  1. ini_set() / php.ini / .htaccess / .user.ini

    The settingsdisplay_errors anderror_reporting have been covered sufficiently now. But just to recap when to use which option:

    And as crude alternative for runtime errors you can often use:

    set_error_handler("var_dump");   // ignores error_reporting and `@` suppression
    
  2. Can be used to retrieve the last runtime notice/warning/error, when error_display is disabled.

  3. Is a superlocal variable, which also contains the last PHP runtime message.

  4. isset() begone!

    I know this will displease a lot of folks, but and should not be used by newcomers. You can add the notice suppression after you verified your code is working. But never before.

    A lot of the "something doesn't work" questions we get lately are the result of typos like:

    if(isset($_POST['sumbit']))
    #                  ↑↑
    

    You won't get any useful notices if your code is littered withisset/empty/array_keys_exists. It's sometimes more sensible to use , so notices and warnings go to the logs at least.

  5. To get warnings forassert() sections. (Pretty uncommon, but more proficient code might contain some.)

    PHP7 requires in the php.ini as well.

  6. Bending PHP into a strictly typed language is not going to fix a whole lot of logic errors, but it's definitely an option for debugging purposes.

  7. PDO / MySQLi

    And @Phil already mentioned PDO/MySQLi error reporting options. Similar options exist for other database APIs of course.

  8. +

    For JSON parsing.

  9. For regexen.

  10. CURLOPT_VERBOSE

    To debug curl requests, you need CURLOPT_VERBOSE at the very least.

  11. Likewise will shell command execution not yield errors on its own. You always need2>&1 and peek at the $errno.

973

Answer

Solution:

For syntax errors, you need to enable error display in the php.ini. By default these are turned off because you don't want a "customer" seeing the error messages. Check this page in the PHP documentation for information on the 2 directives:error_reporting anddisplay_errors.display_errors is probably the one you want to change. If you can't modify the php.ini, you can also add the following lines to an .htaccess file:

php_flag  display_errors        on
php_value error_reporting       2039

You may want to consider using the value of E_ALL (as mentioned by Gumbo) for your version of PHP forerror_reporting to get all of the errors. more info

3 other items: (1) You can check the error log file as it will have all of the errors (unless logging has been disabled). (2) Adding the following 2 lines will help you debug errors that are not syntax errors:

error_reporting(-1);
ini_set('display_errors', 'On');

(3) Another option is to use an editor that checks for errors when you type, such as PhpEd. PhpEd also comes with a debugger which can provide more detailed information. (The PhpEd debugger is very similar to xdebug and integrates directly into the editor so you use 1 program to do everything.)

Cartman's link is also very good: http://www.ibm.com/developerworks/library/os-debug/

614

Answer

Solution:

The following enables all errors:

ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);

Also see the following links

70

Answer

Solution:

The following code should display all errors:

<?php

//

The only way to generate a blank page with this code is when you have a error in the shutdown handler. I copied and pasted this from my own cms without testing it, but I am sure it works.

220

Answer

// - Display Errors //
945

Answer

ini_set('display_errors', 'On'); ini_set('html_errors', 0); //
556

Answer

// - Error Reporting //
798

Answer

error_reporting(-1); //
930

Answer

// - Shutdown Handler //
737

Answer

function ShutdownHandler() { if(@is_array($error = @error_get_last())) { return(@call_user_func_array('ErrorHandler', $error)); }; return(TRUE); }; register_shutdown_function('ShutdownHandler'); //
299

Answer

// - Error Handler //
515

Answer

function ErrorHandler($type, $message, $file, $line) { $_ERRORS = Array( 0x0001 => 'E_ERROR', 0x0002 => 'E_WARNING', 0x0004 => 'E_PARSE', 0x0008 => 'E_NOTICE', 0x0010 => 'E_CORE_ERROR', 0x0020 => 'E_CORE_WARNING', 0x0040 => 'E_COMPILE_ERROR', 0x0080 => 'E_COMPILE_WARNING', 0x0100 => 'E_USER_ERROR', 0x0200 => 'E_USER_WARNING', 0x0400 => 'E_USER_NOTICE', 0x0800 => 'E_STRICT', 0x1000 => 'E_RECOVERABLE_ERROR', 0x2000 => 'E_DEPRECATED', 0x4000 => 'E_USER_DEPRECATED' ); if([email protected]_string($name = @array_search($type, @array_flip($_ERRORS)))) { $name = 'E_UNKNOWN'; }; return(print(@sprintf("%s Error in file \xBB%s\xAB at line %d: %s\n", $name, @basename($file), $line, $message))); }; $old_error_handler = set_error_handler("ErrorHandler"); // other php code ?>
96

Answer

Solution:

You can include the following lines in the file you want to debug:

error_reporting(E_ALL);
ini_set('display_errors', '1');

This overrides the default settings in php.ini, which just make PHP report the errors to the log.

448

Answer

Solution:

Errors and warnings usually appear in....\logs\php_error.log or....\logs\apache_error.log depending on your php.ini settings.

Also useful errors are often directed to the browser, but as they are not valid html they are not displayed.

So"tail -f" your log files and when you get a blank screen use IEs "view" -> "source" menu options to view the raw output.

789

Answer

Solution:

PHP Configuration

2 entries in php.ini dictate the output of errors:

In production,display_errors is usually set toOff (Which is a good thing, because error display in production sites is generally not desirable!).

However, in development, it should be set toOn, so that errors get displayed. Check!

error_reporting (as of PHP 5.3) is set by default toE_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED (meaning, everything is shown except for notices, strict standards and deprecation notices). When in doubt, set it toE_ALL to display all the errors. Check!

Whoa whoa! No check! I can't change my php.ini!

That's a shame. Usually shared hosts do not allow the alteration of their php.ini file, and so, that option is sadly unavailable. But fear not! We have other options!

Runtime configuration

In the desired script, we can alter the php.ini entries in runtime! Meaning, it'll run when the script runs! Sweet!

error_reporting(E_ALL);
ini_set("display_errors", "On");

These two lines will do the same effect as altering the php.ini entries as above! Awesome!

I still get a blank page/500 error!

That means that the script hadn't even run! That usually happens when you have a syntax error!

With syntax errors, the script doesn't even get to runtime. It fails at compile time, meaning that it'll use the values in php.ini, which if you hadn't changed, may not allow the display of errors.

Error logs

In addition, PHP by default logs errors. In shared hosting, it may be in a dedicated folder or on the same folder as the offending script.

If you have access to php.ini, you can find it under the entry.




933
votes

Answer

Solution:

I'm always using this syntax at the very top of the php script.

ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On');  //On or Off
608

Answer

Solution:

There is a really useful extension called "xdebug" that will make your reports much nicer as well.

282

Answer

Solution:

For quick, hands-on troubleshooting I normally suggest here on SO:

error_reporting(~0); ini_set('display_errors', 1);

to be put at the beginning of the script that is under trouble-shooting. This is not perfect, the perfect variant is that you also enable that in thephp.ini and that you log the errors in PHP to catch syntax and startup errors.

The settings outlined here display all errors, notices and warnings, including strict ones, regardless which PHP version.

Next things to consider:

  • Install Xdebug and enable remote-debugging with your IDE.

See as well:




994
votes

Answer

Solution:

It is possible to register an hook to make the last error or warning visible.

function shutdown(){
  var_dump(error_get_last());
}

register_shutdown_function('shutdown');

adding this code to the beginning of you index.php will help you debug the problems.

651

Answer

Solution:

If you are super cool, you might try:

$test_server = $_SERVER['SERVER_NAME'] == "127.0.0.1" || $_SERVER['SERVER_NAME'] == "localhost" || substr($_SERVER['SERVER_NAME'],0,3) == "192";

ini_set('display_errors',$test_server);
error_reporting(E_ALL|E_STRICT);

This will only display errors when you are running locally. It also gives you the test_server variable to use in other places where appropriate.

Any errors that happen before the script runs won't be caught, but for 99% of errors that I make, that's not an issue.

35

Answer

Solution:

On the top of the page choose a parameter

error_reporting(E_ERROR | E_WARNING | E_PARSE);
421

Answer

Solution:

This is a problem of loaded vs. runtime configuration

It's important to recognize that a syntax error or parse error happens during the compile or parsing step, which means that PHP will bail before it's even had a chance to execute any of your code. So if you are modifying PHP's{-code-1} configuration during runtime, (this includes anything from usingini_set in your code to using .htaccess, which is a runtime configuration file) then only the default loaded configuration settings are in play.

How to always avoid WSOD in development

To avoid a WSOD you want to make sure that your loaded configuration file has{-code-1} on anderror_reporting set to-1 (this is the equivalent E_ALL because it ensures all bits are turned on regardless of which version of PHP you're running). Don't hardcode the constant value of E_ALL, because that value is subject to change between different versions of PHP.

Loaded configuration is either your loadedphp.ini file or yourapache.conf orhttpd.conf or virtualhost file. Those files are only read once during the startup stage (when you first start apache httpd or php-fpm, for example) and only overridden by runtime configuration changes. Making sure that{-code-1} = 1 anderror_reporting = -1 in your loaded configuration file ensures that you will never see a WSOD regardless of syntax or parse error that occur before a runtime change likeini_set('{-code-1}', 1); orerror_reporting(E_ALL); can take place.

How to find your (php.ini) loaded configuration files

To locate your loaded configuration file(s) just create a new PHP file with only the following code...

<?php
phpinfo();

Then point your browser there and look at Loaded Configuration File and Additional .ini files parsed, which are usually at the top of yourphpinfo() and will include the absolute path to all your loaded configuration files.

If you see(none) instead of the file, that means you don't have a php.ini in Configuration File (php.ini) Path. So you can download the stock php.ini bundled with PHP from here and copy that to your configuration file path as php.ini then make sure your php user has sufficient permissions to read from that file. You'll need to restart httpd or php-fpm to load it in. Remember, this is the development php.ini file that comes bundled with the PHP source. So please don't use it in production!


Just don't do this in production

This really is the best way to avoid a WSOD in development. Anyone suggesting that you putini_set('{-code-1}', 1); orerror_reporting(E_ALL); at the top of your PHP script or using .htaccess like you did here, is not going to help you avoid a WSOD when a syntax or parse error occurs (like in your case here) if your loaded configuration file has{-code-1} turned off.

Many people (and stock installations of PHP) will use a production-ini file that has{-code-1} turned off by default, which typically results in this same frustration you've experienced here. Because PHP already has it turned off when it starts up, then encounters a syntax or parse error, and bails with nothing to output. You expect that yourini_set('{-code-1}',1); at the top of your PHP script should have avoided that, but it won't matter if PHP can't parse your code because it will never have reached the runtime.

128

Answer

Solution:

To persist this and make it confortale, you can edit your php.ini file. It is usually stored in/etc/php.ini or/etc/php/php.ini, but more localphp.ini's may overwrite it, depending on your hosting provider's setup guidelines. Check aphpinfo() file forLoaded Configuration File at the top, to be sure which one gets loaded last.

Search for display_errors in that file. There should be only 3 instances, of which 2 are commented.

Change the uncommented line to:

display_errors = stdout
307

Answer

Solution:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
509

Answer

Solution:

I don't know if it will help, but here is a piece of my standard config file for php projects. I tend not to depend too much on the apache configs even on my own server.

I never have the disappearing error problem, so perhaps something here will give you an idea.

Edited to show APPLICATON_LIVE

/*
APPLICATION_LIVE will be used in process to tell if we are in a development or production environment.  It's generally set as early as possible (often the first code to run), before any config, url routing, etc.
*/

if ( preg_match( "%^(www.)?livedomain.com$%", $_SERVER["HTTP_HOST"]) ) {
    define('APPLICATION_LIVE', true);
} elseif ( preg_match( "%^(www.)?devdomain.net$%", $_SERVER["HTTP_HOST"]) ) {
    define('APPLICATION_LIVE', false);
} else {
    die("INVALID HOST REQUEST (".$_SERVER["HTTP_HOST"].")");
    // Log or take other appropriate action.
}


/*
42

Answer

-------- DEFAULT ERROR HANDLING
11

Answer

-------- Default error logging. Some of these may be changed later based on APPLICATION_LIVE. */ error_reporting(E_ALL & ~E_STRICT); ini_set ( "display_errors", "0"); ini_set ( "display_startup_errors", "0"); ini_set ( "log_errors", 1); ini_set ( "log_errors_max_len", 0); ini_set ( "error_log", APPLICATION_ROOT."logs/php_error_log.txt"); ini_set ( "display_errors", "0"); ini_set ( "display_startup_errors", "0"); if ( ! APPLICATION_LIVE ) { // A few changes to error handling for development. // We will want errors to be visible during development. ini_set ( "display_errors", "1"); ini_set ( "display_startup_errors", "1"); ini_set ( "html_errors", "1"); ini_set ( "docref_root", "http://www.php.net/"); ini_set ( "error_prepend_string", "<div style='color:red; font-family:verdana; border:1px solid red; padding:5px;'>"); ini_set ( "error_append_string", "</div>"); }
949

Answer

Solution:

error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
ini_set('html_errors', 1);

In addition, you can get more detailed information with xdebug.

569

Answer

Solution:

I recommend Nette Tracy for better visualization of errors and exceptions in PHP:

Nette Tracy screenshot

715

Answer

Solution:

error_reporting(E_ALL | E_STRICT);

And turn on display errors in php.ini

850

Answer

Solution:

You can register your own error handler in PHP. Dumping all errors to a file might help you in these obscure cases, for example. Note that your function will get called, no matter what your current error_reporting is set to. Very basic example:

function dump_error_to_file($errno, $errstr) {
    file_put_contents('/tmp/php-errors', date('Y-m-d H:i:s - ') . $errstr, FILE_APPEND);
}
set_error_handler('dump_error_to_file');
942

Answer

Solution:

The two key lines you need to get useful errors out of PHP are:

ini_set('display_errors',1);
 error_reporting(E_ALL);

As pointed out by other contributors, these are switched off by default for security reasons. As a useful tip - when you're setting up your site it's handy to do a switch for your different environments so that these errors are ON by default in your local and development environments. This can be achieved with the following code (ideally in your index.php or config file so this is active from the start):

switch($_SERVER['SERVER_NAME'])
{
    // local
    case 'yourdomain.dev':
    // dev
    case 'dev.yourdomain.com':
        ini_set('display_errors',1);
        error_reporting(E_ALL);
    break;
    //live
    case 'yourdomain.com':
        //...
    break;
}
263

Answer

Solution:

open your php.ini, make sure it's set to:

display_errors = On

restart your server.

384

Answer

Solution:

You might also want to try PHPStorm as your code editor. It will find many PHP and other syntax errors right as you are typing in the editor.

28

Answer

Solution:

if you are a ubuntu user then goto your terminal and run this command

sudo tail -50f /var/log/apache2/error.log

where it will display recent 50 errors. There is a error fileerror.log for apache2 which logs all the errors.

604

Answer

Solution:

To turn on full error reporting, add this to your script:

error_reporting(E_ALL);

This causes even minimal warnings to show up. And, just in case:

ini_set('display_errors', '1');

Will force the display of errors. This should be turned off in production servers, but not when you're developing.

624

Answer

Solution:

The “ERRORS” are the most useful things for the developers to know their mistakes and resolved them to make the system working perfect.

PHP provides some of better ways to know the developers why and where their piece of code is getting the errors, so by knowing those errors developers can make their code better in many ways.

Best ways to write following two lines on the top of script to get all errors messages:

error_reporting(E_ALL);
ini_set("display_errors", 1);

Another way to use debugger tools like xdebug in your IDE.

10

Answer

Solution:

In addition to all the wonderful answers here, I'd like to throw in a special mention for the MySQLi and PDO libraries.

In order to...

  1. Always see database related errors, and
  2. Avoid checking the return types for methods to see if something went wrong

The best option is to configure the libraries to throw exceptions.

MySQLi

Add this near the top of your script

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

This is best placed before you usenew mysqli() ormysqli_connect().

PDO

Set thePDO::ATTR_ERRMODE attribute toPDO::ERRMODE_EXCEPTION on your connection instance. You can either do this in the constructor

$pdo = new PDO('driver:host=localhost;...', 'username', 'password', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);

or after creation

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
834

Answer

Solution:

You can enable full error reporting (including notices and strict messages). Some people find this too verbose, but it's worth a try. Seterror_reporting toE_ALL | E_STRICT in your php.ini.

error_reporting = E_ALL | E_STRICT

E_STRICT will notify you about deprecated functions and give you recommendations about the best methods to do certain tasks.

If you don't want notices, but you find other message types helpful, try excluding notices:

error_reporting = (E_ALL | E_STRICT) & ~E_NOTICE

Also make sure thatdisplay_errors is enabled in php.ini. If your PHP version is older than 5.2.4, set it toOn:

display_errors = "On"

If your version is 5.2.4 or newer, use:

display_errors = "stderr"
782

Answer

Solution:

Aside from error_reporting and the display_errors ini setting, you can get SYNTAX errors from your web server's log files. When I'm developing PHP I load my development system's web server logs into my editor. Whenever I test a page and get a blank screen, the log file goes stale and my editor asks if I want to reload it. When I do, I jump to the bottom and there is the syntax error. For example:

[Sun Apr 19 19:09:11 2009] [error] [client 127.0.0.1] PHP Parse error:  syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in D:\\webroot\\test\\test.php on line 9
109

Answer

Solution:

This answer is brought to you by the department of redundancy department.

  1. ini_set() / php.ini / .htaccess / .user.ini

    The settingsdisplay_errors anderror_reporting have been covered sufficiently now. But just to recap when to use which option:

    And as crude alternative for runtime errors you can often use:

    set_error_handler("var_dump");   // ignores error_reporting and `@` suppression
    
  2. Can be used to retrieve the last runtime notice/warning/error, when error_display is disabled.

  3. Is a superlocal variable, which also contains the last PHP runtime message.

  4. isset() begone!

    I know this will displease a lot of folks, but and should not be used by newcomers. You can add the notice suppression after you verified your code is working. But never before.

    A lot of the "something doesn't work" questions we get lately are the result of typos like:

    if(isset($_POST['sumbit']))
    #                  ↑↑
    

    You won't get any useful notices if your code is littered withisset/empty/array_keys_exists. It's sometimes more sensible to use , so notices and warnings go to the logs at least.

  5. To get warnings forassert() sections. (Pretty uncommon, but more proficient code might contain some.)

    PHP7 requires in the php.ini as well.

  6. Bending PHP into a strictly typed language is not going to fix a whole lot of logic errors, but it's definitely an option for debugging purposes.

  7. PDO / MySQLi

    And @Phil already mentioned PDO/MySQLi error reporting options. Similar options exist for other database APIs of course.

  8. +

    For JSON parsing.

  9. For regexen.

  10. CURLOPT_VERBOSE

    To debug curl requests, you need CURLOPT_VERBOSE at the very least.

  11. Likewise will shell command execution not yield errors on its own. You always need2>&1 and peek at the $errno.

272

Answer

Solution:

For syntax errors, you need to enable error display in the php.ini. By default these are turned off because you don't want a "customer" seeing the error messages. Check this page in the PHP documentation for information on the 2 directives:error_reporting anddisplay_errors.display_errors is probably the one you want to change. If you can't modify the php.ini, you can also add the following lines to an .htaccess file:

php_flag  display_errors        on
php_value error_reporting       2039

You may want to consider using the value of E_ALL (as mentioned by Gumbo) for your version of PHP forerror_reporting to get all of the errors. more info

3 other items: (1) You can check the error log file as it will have all of the errors (unless logging has been disabled). (2) Adding the following 2 lines will help you debug errors that are not syntax errors:

error_reporting(-1);
ini_set('display_errors', 'On');

(3) Another option is to use an editor that checks for errors when you type, such as PhpEd. PhpEd also comes with a debugger which can provide more detailed information. (The PhpEd debugger is very similar to xdebug and integrates directly into the editor so you use 1 program to do everything.)

Cartman's link is also very good: http://www.ibm.com/developerworks/library/os-debug/

164

Answer

Solution:

The following enables all errors:

ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);

Also see the following links

766

Answer

Solution:

The following code should display all errors:

<?php

//

The only way to generate a blank page with this code is when you have a error in the shutdown handler. I copied and pasted this from my own cms without testing it, but I am sure it works.

324

Answer

// - Display Errors //
738

Answer

ini_set('display_errors', 'On'); ini_set('html_errors', 0); //
664

Answer

// - Error Reporting //
239

Answer

error_reporting(-1); //
846

Answer

// - Shutdown Handler //
556

Answer

function ShutdownHandler() { if(@is_array($error = @error_get_last())) { return(@call_user_func_array('ErrorHandler', $error)); }; return(TRUE); }; register_shutdown_function('ShutdownHandler'); //
590

Answer

// - Error Handler //
915

Answer

function ErrorHandler($type, $message, $file, $line) { $_ERRORS = Array( 0x0001 => 'E_ERROR', 0x0002 => 'E_WARNING', 0x0004 => 'E_PARSE', 0x0008 => 'E_NOTICE', 0x0010 => 'E_CORE_ERROR', 0x0020 => 'E_CORE_WARNING', 0x0040 => 'E_COMPILE_ERROR', 0x0080 => 'E_COMPILE_WARNING', 0x0100 => 'E_USER_ERROR', 0x0200 => 'E_USER_WARNING', 0x0400 => 'E_USER_NOTICE', 0x0800 => 'E_STRICT', 0x1000 => 'E_RECOVERABLE_ERROR', 0x2000 => 'E_DEPRECATED', 0x4000 => 'E_USER_DEPRECATED' ); if([email protected]_string($name = @array_search($type, @array_flip($_ERRORS)))) { $name = 'E_UNKNOWN'; }; return(print(@sprintf("%s Error in file \xBB%s\xAB at line %d: %s\n", $name, @basename($file), $line, $message))); }; $old_error_handler = set_error_handler("ErrorHandler"); // other php code ?>
943

Answer

Solution:

You can include the following lines in the file you want to debug:

error_reporting(E_ALL);
ini_set('display_errors', '1');

This overrides the default settings in php.ini, which just make PHP report the errors to the log.

809

Answer

Solution:

Errors and warnings usually appear in....\logs\php_error.log or....\logs\apache_error.log depending on your php.ini settings.

Also useful errors are often directed to the browser, but as they are not valid html they are not displayed.

So"tail -f" your log files and when you get a blank screen use IEs "view" -> "source" menu options to view the raw output.

243

Answer

Solution:

PHP Configuration

2 entries in php.ini dictate the output of errors:

In production,display_errors is usually set toOff (Which is a good thing, because error display in production sites is generally not desirable!).

However, in development, it should be set toOn, so that errors get displayed. Check!

error_reporting (as of PHP 5.3) is set by default toE_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED (meaning, everything is shown except for notices, strict standards and deprecation notices). When in doubt, set it toE_ALL to display all the errors. Check!

Whoa whoa! No check! I can't change my php.ini!

That's a shame. Usually shared hosts do not allow the alteration of their php.ini file, and so, that option is sadly unavailable. But fear not! We have other options!

Runtime configuration

In the desired script, we can alter the php.ini entries in runtime! Meaning, it'll run when the script runs! Sweet!

error_reporting(E_ALL);
ini_set("display_errors", "On");

These two lines will do the same effect as altering the php.ini entries as above! Awesome!

I still get a blank page/500 error!

That means that the script hadn't even run! That usually happens when you have a syntax error!

With syntax errors, the script doesn't even get to runtime. It fails at compile time, meaning that it'll use the values in php.ini, which if you hadn't changed, may not allow the display of errors.

Error logs

In addition, PHP by default logs errors. In shared hosting, it may be in a dedicated folder or on the same folder as the offending script.

If you have access to php.ini, you can find it under the entry.

Write your answer




678
votes

Answer

Solution:

I'm always using this syntax at the very top of the php script.

ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On');  //On or Off
367

Answer

Solution:

There is a really useful extension called "xdebug" that will make your reports much nicer as well.

691

Answer

Solution:

For quick, hands-on troubleshooting I normally suggest here on SO:

error_reporting(~0); ini_set('display_errors', 1);

to be put at the beginning of the script that is under trouble-shooting. This is not perfect, the perfect variant is that you also enable that in thephp.ini and that you log the errors in PHP to catch syntax and startup errors.

The settings outlined here display all errors, notices and warnings, including strict ones, regardless which PHP version.

Next things to consider:

  • Install Xdebug and enable remote-debugging with your IDE.

See as well:

Write your answer




490
votes

Answer

Solution:

It is possible to register an hook to make the last error or warning visible.

function shutdown(){
  var_dump(error_get_last());
}

register_shutdown_function('shutdown');

adding this code to the beginning of you index.php will help you debug the problems.

216

Answer

Solution:

If you are super cool, you might try:

$test_server = $_SERVER['SERVER_NAME'] == "127.0.0.1" || $_SERVER['SERVER_NAME'] == "localhost" || substr($_SERVER['SERVER_NAME'],0,3) == "192";

ini_set('display_errors',$test_server);
error_reporting(E_ALL|E_STRICT);

This will only display errors when you are running locally. It also gives you the test_server variable to use in other places where appropriate.

Any errors that happen before the script runs won't be caught, but for 99% of errors that I make, that's not an issue.

437

Answer

Solution:

On the top of the page choose a parameter

error_reporting(E_ERROR | E_WARNING | E_PARSE);
41

Answer

Solution:

This is a problem of loaded vs. runtime configuration

It's important to recognize that a syntax error or parse error happens during the compile or parsing step, which means that PHP will bail before it's even had a chance to execute any of your code. So if you are modifying PHP's{-code-1} configuration during runtime, (this includes anything from usingini_set in your code to using .htaccess, which is a runtime configuration file) then only the default loaded configuration settings are in play.

How to always avoid WSOD in development

To avoid a WSOD you want to make sure that your loaded configuration file has{-code-1} on anderror_reporting set to-1 (this is the equivalent E_ALL because it ensures all bits are turned on regardless of which version of PHP you're running). Don't hardcode the constant value of E_ALL, because that value is subject to change between different versions of PHP.

Loaded configuration is either your loadedphp.ini file or yourapache.conf orhttpd.conf or virtualhost file. Those files are only read once during the startup stage (when you first start apache httpd or php-fpm, for example) and only overridden by runtime configuration changes. Making sure that{-code-1} = 1 anderror_reporting = -1 in your loaded configuration file ensures that you will never see a WSOD regardless of syntax or parse error that occur before a runtime change likeini_set('{-code-1}', 1); orerror_reporting(E_ALL); can take place.

How to find your (php.ini) loaded configuration files

To locate your loaded configuration file(s) just create a new PHP file with only the following code...

<?php
phpinfo();

Then point your browser there and look at Loaded Configuration File and Additional .ini files parsed, which are usually at the top of yourphpinfo() and will include the absolute path to all your loaded configuration files.

If you see(none) instead of the file, that means you don't have a php.ini in Configuration File (php.ini) Path. So you can download the stock php.ini bundled with PHP from here and copy that to your configuration file path as php.ini then make sure your php user has sufficient permissions to read from that file. You'll need to restart httpd or php-fpm to load it in. Remember, this is the development php.ini file that comes bundled with the PHP source. So please don't use it in production!


Just don't do this in production

This really is the best way to avoid a WSOD in development. Anyone suggesting that you putini_set('{-code-1}', 1); orerror_reporting(E_ALL); at the top of your PHP script or using .htaccess like you did here, is not going to help you avoid a WSOD when a syntax or parse error occurs (like in your case here) if your loaded configuration file has{-code-1} turned off.

Many people (and stock installations of PHP) will use a production-ini file that has{-code-1} turned off by default, which typically results in this same frustration you've experienced here. Because PHP already has it turned off when it starts up, then encounters a syntax or parse error, and bails with nothing to output. You expect that yourini_set('{-code-1}',1); at the top of your PHP script should have avoided that, but it won't matter if PHP can't parse your code because it will never have reached the runtime.

442

Answer

Solution:

To persist this and make it confortale, you can edit your php.ini file. It is usually stored in/etc/php.ini or/etc/php/php.ini, but more localphp.ini's may overwrite it, depending on your hosting provider's setup guidelines. Check aphpinfo() file forLoaded Configuration File at the top, to be sure which one gets loaded last.

Search for display_errors in that file. There should be only 3 instances, of which 2 are commented.

Change the uncommented line to:

display_errors = stdout
724

Answer

Solution:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
471

Answer

Solution:

I don't know if it will help, but here is a piece of my standard config file for php projects. I tend not to depend too much on the apache configs even on my own server.

I never have the disappearing error problem, so perhaps something here will give you an idea.

Edited to show APPLICATON_LIVE

/*
APPLICATION_LIVE will be used in process to tell if we are in a development or production environment.  It's generally set as early as possible (often the first code to run), before any config, url routing, etc.
*/

if ( preg_match( "%^(www.)?livedomain.com$%", $_SERVER["HTTP_HOST"]) ) {
    define('APPLICATION_LIVE', true);
} elseif ( preg_match( "%^(www.)?devdomain.net$%", $_SERVER["HTTP_HOST"]) ) {
    define('APPLICATION_LIVE', false);
} else {
    die("INVALID HOST REQUEST (".$_SERVER["HTTP_HOST"].")");
    // Log or take other appropriate action.
}


/*
222

Answer

-------- DEFAULT ERROR HANDLING
854

Answer

-------- Default error logging. Some of these may be changed later based on APPLICATION_LIVE. */ error_reporting(E_ALL & ~E_STRICT); ini_set ( "display_errors", "0"); ini_set ( "display_startup_errors", "0"); ini_set ( "log_errors", 1); ini_set ( "log_errors_max_len", 0); ini_set ( "error_log", APPLICATION_ROOT."logs/php_error_log.txt"); ini_set ( "display_errors", "0"); ini_set ( "display_startup_errors", "0"); if ( ! APPLICATION_LIVE ) { // A few changes to error handling for development. // We will want errors to be visible during development. ini_set ( "display_errors", "1"); ini_set ( "display_startup_errors", "1"); ini_set ( "html_errors", "1"); ini_set ( "docref_root", "http://www.php.net/"); ini_set ( "error_prepend_string", "<div style='color:red; font-family:verdana; border:1px solid red; padding:5px;'>"); ini_set ( "error_append_string", "</div>"); }
534

Answer

Solution:

error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
ini_set('html_errors', 1);

In addition, you can get more detailed information with xdebug.

44

Answer

Solution:

I recommend Nette Tracy for better visualization of errors and exceptions in PHP:

Nette Tracy screenshot

690

Answer

Solution:

error_reporting(E_ALL | E_STRICT);

And turn on display errors in php.ini

645

Answer

Solution:

You can register your own error handler in PHP. Dumping all errors to a file might help you in these obscure cases, for example. Note that your function will get called, no matter what your current error_reporting is set to. Very basic example:

function dump_error_to_file($errno, $errstr) {
    file_put_contents('/tmp/php-errors', date('Y-m-d H:i:s - ') . $errstr, FILE_APPEND);
}
set_error_handler('dump_error_to_file');
873

Answer

Solution:

The two key lines you need to get useful errors out of PHP are:

ini_set('display_errors',1);
 error_reporting(E_ALL);

As pointed out by other contributors, these are switched off by default for security reasons. As a useful tip - when you're setting up your site it's handy to do a switch for your different environments so that these errors are ON by default in your local and development environments. This can be achieved with the following code (ideally in your index.php or config file so this is active from the start):

switch($_SERVER['SERVER_NAME'])
{
    // local
    case 'yourdomain.dev':
    // dev
    case 'dev.yourdomain.com':
        ini_set('display_errors',1);
        error_reporting(E_ALL);
    break;
    //live
    case 'yourdomain.com':
        //...
    break;
}
543

Answer

Solution:

open your php.ini, make sure it's set to:

display_errors = On

restart your server.

856

Answer

Solution:

You might also want to try PHPStorm as your code editor. It will find many PHP and other syntax errors right as you are typing in the editor.

252

Answer

Solution:

if you are a ubuntu user then goto your terminal and run this command

sudo tail -50f /var/log/apache2/error.log

where it will display recent 50 errors. There is a error fileerror.log for apache2 which logs all the errors.

377

Answer

Solution:

To turn on full error reporting, add this to your script:

error_reporting(E_ALL);

This causes even minimal warnings to show up. And, just in case:

ini_set('display_errors', '1');

Will force the display of errors. This should be turned off in production servers, but not when you're developing.

591

Answer

Solution:

The “ERRORS” are the most useful things for the developers to know their mistakes and resolved them to make the system working perfect.

PHP provides some of better ways to know the developers why and where their piece of code is getting the errors, so by knowing those errors developers can make their code better in many ways.

Best ways to write following two lines on the top of script to get all errors messages:

error_reporting(E_ALL);
ini_set("display_errors", 1);

Another way to use debugger tools like xdebug in your IDE.

133

Answer

Solution:

In addition to all the wonderful answers here, I'd like to throw in a special mention for the MySQLi and PDO libraries.

In order to...

  1. Always see database related errors, and
  2. Avoid checking the return types for methods to see if something went wrong

The best option is to configure the libraries to throw exceptions.

MySQLi

Add this near the top of your script

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

This is best placed before you usenew mysqli() ormysqli_connect().

PDO

Set thePDO::ATTR_ERRMODE attribute toPDO::ERRMODE_EXCEPTION on your connection instance. You can either do this in the constructor

$pdo = new PDO('driver:host=localhost;...', 'username', 'password', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);

or after creation

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
522

Answer

Solution:

You can enable full error reporting (including notices and strict messages). Some people find this too verbose, but it's worth a try. Seterror_reporting toE_ALL | E_STRICT in your php.ini.

error_reporting = E_ALL | E_STRICT

E_STRICT will notify you about deprecated functions and give you recommendations about the best methods to do certain tasks.

If you don't want notices, but you find other message types helpful, try excluding notices:

error_reporting = (E_ALL | E_STRICT) & ~E_NOTICE

Also make sure thatdisplay_errors is enabled in php.ini. If your PHP version is older than 5.2.4, set it toOn:

display_errors = "On"

If your version is 5.2.4 or newer, use:

display_errors = "stderr"
757

Answer

Solution:

Aside from error_reporting and the display_errors ini setting, you can get SYNTAX errors from your web server's log files. When I'm developing PHP I load my development system's web server logs into my editor. Whenever I test a page and get a blank screen, the log file goes stale and my editor asks if I want to reload it. When I do, I jump to the bottom and there is the syntax error. For example:

[Sun Apr 19 19:09:11 2009] [error] [client 127.0.0.1] PHP Parse error:  syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in D:\\webroot\\test\\test.php on line 9
451

Answer

Solution:

This answer is brought to you by the department of redundancy department.

  1. ini_set() / php.ini / .htaccess / .user.ini

    The settingsdisplay_errors anderror_reporting have been covered sufficiently now. But just to recap when to use which option:

    And as crude alternative for runtime errors you can often use:

    set_error_handler("var_dump");   // ignores error_reporting and `@` suppression
    
  2. Can be used to retrieve the last runtime notice/warning/error, when error_display is disabled.

  3. Is a superlocal variable, which also contains the last PHP runtime message.

  4. isset() begone!

    I know this will displease a lot of folks, but and should not be used by newcomers. You can add the notice suppression after you verified your code is working. But never before.

    A lot of the "something doesn't work" questions we get lately are the result of typos like:

    if(isset($_POST['sumbit']))
    #                  ↑↑
    

    You won't get any useful notices if your code is littered withisset/empty/array_keys_exists. It's sometimes more sensible to use , so notices and warnings go to the logs at least.

  5. To get warnings forassert() sections. (Pretty uncommon, but more proficient code might contain some.)

    PHP7 requires in the php.ini as well.

  6. Bending PHP into a strictly typed language is not going to fix a whole lot of logic errors, but it's definitely an option for debugging purposes.

  7. PDO / MySQLi

    And @Phil already mentioned PDO/MySQLi error reporting options. Similar options exist for other database APIs of course.

  8. +

    For JSON parsing.

  9. For regexen.

  10. CURLOPT_VERBOSE

    To debug curl requests, you need CURLOPT_VERBOSE at the very least.

  11. Likewise will shell command execution not yield errors on its own. You always need2>&1 and peek at the $errno.

People are also looking for solutions to the problem: Subdomains with .htaccess (PHP)

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.