By Candidasa


2009-05-10 09:48:12 8 Comments

I find programming in PHP quite frustrating. Quite often I will try and run the script and just get a blank screen back. No error message, just 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?.

So, is there a way to get PHP to produce useful error message like Java does? Can anyone recommend good PHP debugging tips, tools and techniques?

29 comments

@Phil 2018-09-14 03:31:55

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 use new mysqli() or mysqli_connect().

PDO

Set the PDO::ATTR_ERRMODE attribute to PDO::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);

@siniradam 2016-06-29 14:59:53

Use Kint. It is combination of debugging commands on steroids. https://kint-php.github.io/kint/ It is very similar to Nette Tracy

@Yousha Aleayoub 2018-08-05 20:38:50

404 not found...

@siniradam 2018-08-06 23:12:31

yep it's been a while, link updated now. @YoushaAleayoub

@Abuzer Firdousi 2017-12-04 20:54:29

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

@Ram 2011-07-04 19:54:31

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 local php.ini's may overwrite it, depending on your hosting provider's setup guidelines. Check a phpinfo() file for Loaded 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

@Ondřej Šotek 2015-07-15 22:38:32

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

Nette Tracy screenshot

@AStopher 2016-06-17 19:34:09

This does not answer the question...

@Jan Drábek 2016-07-05 12:25:28

Tracy takes care about proper setting of all display errors and error reporting options to provide output in such situations as described in original post... So this tool is especially helpful for addressing asker "Can anyone recommend good PHP debugging tips, tools and techniques?".

@user3176739 2014-02-01 06:24:06

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.

@Yan.Zero 2014-08-19 15:36:37

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.

@jewelhuq 2016-01-05 12:32:29

Xdebug can be enable from php.ini

@Eljakim 2011-07-04 19:46:13

The following enables all errors:

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

Also see the following links

@Marc B 2011-07-04 19:49:18

Best to make these changes at the .ini file level. Turning on error reporting from within a script is useless, as it won't help with syntax errors or other fatal errors that kill the compile phase. The script gets killed long before it begins executing and reaches the reporting overrides.

@Eljakim 2011-07-04 19:51:15

You are correct indeed. I did not notice that the move is to your own server.

@Eljakim 2011-07-04 19:52:41

Try to find the file php.ini that is used. On my ubuntu machine it is stored in /etc/php5/apache2/php.ini

@borrible 2011-07-05 08:01:41

Run phpinfo() to find the correct php.ini file. Look for the Loaded Configuration File line.

@Subie 2014-01-22 19:01:29

I come here at least once a day copying this..I should probably just memorize it.

@csi 2014-02-21 22:08:10

If you are looking for errors that occur during the compile phase, check your apache logs often located at /var/log/apache2/error.log

@PeeHaa 2015-09-04 18:16:31

This answer will fail on php7 when strict typing is enabled, because the second parameter of ini_set is a string.

@Lamy 2016-09-13 09:17:02

@Subie Development is so much copy/paste nowadays...

@Code Synthesis 2014-06-10 13:37:38

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;
}

@Darryl Hein 2009-05-10 09:52:35

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 and display_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 for error_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/

@Tomalak 2009-05-10 10:02:57

Can it be you just downvoted two people that gave the same advice as you did (see your second code sample)?

@Darryl Hein 2009-05-10 10:04:57

Did you read my entire answer? I specifically say this won't work for syntax errors, whereas you don't mention that. Putting your code in would make no difference.

@Tomalak 2009-05-10 10:10:58

That's right. I should have thought of mentioning it.

@Gumbo 2009-05-10 17:59:01

2039 is the value of E_ERROR | E_WARNING | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING | E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE. See docs.php.net/manual/en/errorfunc.constants.php

@ts. 2010-12-29 14:12:24

so why not error_reporting(-1) ?

@aendrew 2012-11-27 16:09:26

Wow, I'd tried a ton of ways over the last two hours to change error reporting and this is the one that finally did it -- begone, useless Error 500 screens! THANK YOU.

@jacekn 2013-06-15 01:39:16

I like the option of .htaccess file. It helps me debug in an area that is not part of the public website. Thanks a lot for this tip!

@vaxquis 2014-04-12 16:36:17

@ts. exactly. or, per docs, 32767 (E_ALL)...

@Ivan Yarych 2016-03-26 20:44:18

I would add that logging errors to file (and looking them up there) is the best solution. Don't rely on displaying errors on-page - they can ruin it, you can forget to turn error reporting for production site and this will cause you trouble in future

@Aaron Franke 2019-01-05 17:33:40

Where is the error log file?

@Vladimir Ramik 2015-03-07 18:16:51

In addition to the very many excellent answers above you could also implement the following two functions in your projects. They will catch every non-syntax error before application/script exit. Inside the functions you can do a backtrace and log or render a pleasant 'Site is under maintenance' message to the public.

Fatal Errors:

register_shutdown_function

http://php.net/manual/en/function.register-shutdown-function.php

Errors:

set_error_handler

http://php.net/manual/en/function.set-error-handler.php

Backtracing:

debug_backtrace

http://php.net/manual/en/function.debug-backtrace.php

@Ashutosh Jha 2014-11-10 11:23:56

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 file error.log for apache2 which logs all the errors.

@PHPCoder 2014-10-01 19:48:54

http://todell.com/debug can be useful as well. You can see your object values or thrown debug errors behind the scene even in production mode.

@user1681048 2014-06-18 01:03:15

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.

@Madara Uchiha 2014-02-02 20:47:47

PHP Configuration

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

  1. display_errors
  2. error_reporting

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

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

error_reporting (as of PHP 5.3) is set by default to E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED (meaning, everything is shown except for notices, strict standards and deprecation notices). When in doubt, set it to E_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 error_log entry.

@MBaas 2013-07-09 18:05:23

My usual problem are "little, stupid" parser errors which unfortunately do not show up.

However, when a .PHP-File includes a file that has parser-errors, they are shown! So I had the idea of writing a little "executor-script" that is launched with the name of the buggy file as argument, i.e. example.com/sx.php?sc=buggy.php

It had already saved me from a lot of headache, maybe it will be helpful to someone else, too :)

sx.php

$sc = $_GET["sc"];
if ((!isset($_GET["sc"]) && empty($_GET["sc"]))) {
    echo "Please select file to execute using ?sc= (you may omit the .PHP-extension)";
} else {
    $sc = $_GET["sc"];
    if (false==stripos('.php',$sc)) $sc.='.php';  // adjust this if your preferred extension is php5!
    require($sc);
}
?>

@Darren 2014-06-27 07:57:29

Hate to be that guy, but this is a bad example. Local File Inclusion

@MBaas 2014-07-02 07:36:53

You are right - this mechanism should not be used for production, it's simply a tool to catch these things while developing/debugging/testing.

@kris 2013-06-15 11:55:04

Turning on error reporting is the correct solution, however it does not seem to take effect in the program that turns it on, but only in subsequently included programs.

Thus, I always create a file/program (which I usually call "genwrap.php") which has essentially the same code as the popular solution here (ie. turn on error reporting) and it also then includes the page I actually want to call.

There are 2 steps to implement this debugging;

One - create genwrap.php and put this code in it:

<?php
error_reporting(-1);
ini_set('display_errors', 'On');

include($_REQUEST['page']);
?>

Two - change the link to the program/page you want to debug to go via genwrap.php,

Eg: change:

$.ajax('dir/pgm.php?param=val').done(function(data) { /* ... */

to

$.ajax('dir/genwrap.php?page=pgm.php&param=val').done(function(data) { /* ... */

@Kld 2013-05-06 14:14:25

On the top of the page choose a parameter

error_reporting(E_ERROR | E_WARNING | E_PARSE);

@hakre 2013-01-24 15:06:56

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 the php.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:

@Rodney McIntosh 2012-11-25 13:30:20

Try this PHP error reporting reference tool. It's a very good visual reference and helped me understand the complex error reporting mechanism.

@MarcoZen 2013-10-30 04:53:48

Awesome ..... also something equivalent here too w3schools.com/php/func_error_reporting.asp

@Rich Bradshaw 2011-07-04 19:49:30

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.

@Michael Antonio 2014-01-26 01:05:23

This is what i looking for ! :), Why no one give it upvote ? Debuging a website is only neeeded by webmaster and not client. So run it locally is the best for security.

@Jaap Haagmans 2014-06-23 11:50:46

If you're differentiating between local and production environments, you should simply enable or disable errors globally (in your php.ini) and not in code that can also be production code. If you need to debug a production website in its production environment and only want you to be able to view the errors, use $_SERVER['REMOTE_HOST'] to check whether the client is, well, you.

@jmucchiello 2009-05-10 18:16:21

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

@Daniel Sorichetti 2009-05-10 12:09:01

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.

@Darryl Hein 2009-05-10 17:58:09

As with Tomalak's answer, this doesn't work for syntax errors.

@Rich Bradshaw 2009-05-10 10:21:42

FirePHP can be useful as well.

@Ayman Hourieh 2009-05-10 09:58:55

You can enable full error reporting (including notices and strict messages). Some people find this too verbose, but it's worth a try. Set error_reporting to E_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 that display_errors is enabled in php.ini. If your PHP version is older than 5.2.4, set it to On:

display_errors = "On"

If your version is 5.2.4 or newer, use:

display_errors = "stderr"

@gnarf 2009-05-10 09:59:30

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

@hbw 2009-05-10 10:06:33

Indeed, this is a very useful debugging tool—makes error messages much more verbose, with full stack traces and variable dumps and everything.

@Sander Marechal 2009-05-10 10:20:58

Yes. And then use something like the VimDebugger plugin to step through your code and find out where it goes wrong.

@Wayne 2009-05-10 10:26:29

+1 I use eclipse with xdebug for full step over/step into debugging. Makes PHP development sane!

@Some Canuck 2009-05-10 12:10:17

NetBeans with xdebug here. It's so awesome. I'm new to PHP (usually ASP.NET) and had been issuing echo statements before.

@Jonathan 2018-05-09 18:24:32

See also "Whoops" error handler

@Ólafur Waage 2009-05-10 09:54:53

error_reporting(E_ALL | E_STRICT);

And turn on display errors in php.ini

@Tomalak 2009-05-10 09:54:31

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.

@Darryl Hein 2009-05-10 09:56:06

This doesn't work for syntax errors as Candidasa mentioned.

@Tomalak 2009-05-10 10:00:32

That's true. In this case the values must be set in the ini directly -- for a pure development environment this may be preferable anyway.

@shady sherif 2018-04-17 15:38:51

worked for ipage host. thanks

@soulmerge 2009-05-10 09:54:10

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');

@Darryl Hein 2009-05-10 09:58:04

This doesn't work for syntax errors as Candidasa mentioned.

@soulmerge 2009-05-10 09:59:11

Yes, but that is already covered in all other answers.

Related Questions

Sponsored Content

32 Answered Questions

[SOLVED] Reference - What does this error mean in PHP?

34 Answered Questions

[SOLVED] PHP: Delete an element from an array

  • 2008-12-15 20:28:55
  • Ben
  • 2157805 View
  • 2153 Score
  • 34 Answer
  • Tags:   php arrays

18 Answered Questions

[SOLVED] Reference — What does this symbol mean in PHP?

28 Answered Questions

[SOLVED] How can I prevent SQL injection in PHP?

24 Answered Questions

[SOLVED] How do I get PHP errors to display?

29 Answered Questions

[SOLVED] How Do You Parse and Process HTML/XML in PHP?

16 Answered Questions

[SOLVED] PHP parse/syntax errors; and how to solve them?

15 Answered Questions

[SOLVED] Why shouldn't I use mysql_* functions in PHP?

  • 2012-10-12 13:18:39
  • Madara Uchiha
  • 195893 View
  • 2313 Score
  • 15 Answer
  • Tags:   php mysql database

7 Answered Questions

[SOLVED] How does PHP 'foreach' actually work?

31 Answered Questions

[SOLVED] How do I get a YouTube video thumbnail from the YouTube API?

Sponsored Content