658

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?

4
  • 1
    coding.smashingmagazine.com/2011/11/30/… Commented Jul 15, 2012 at 14:54
  • 5
    @JuannStrauss, That's understating it. And when you finally see the errors, it says T_PAAMAYIM_NEKUDOTAYIM. Or maybe "must be an instance of integer, integer given". Commented Apr 3, 2015 at 20:02
  • 2
    Tutorial on this: code2real.blogspot.com/2015/06/… Commented Sep 9, 2015 at 7:21
  • 1
    If you have a parse error none of these will work on many web hosts, and you might not have access to the error logs. You will need to install php on your local machine (XAMPP on Windows etc) and do a command line synax check php.exe -l <your file name> Commented Aug 17, 2021 at 10:32

41 Answers 41

1
2
3

For those who use nginx and have a white screen even for file with <?php echo 123;. In my case I didn't have this required option for PHP in nginx config file:

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

This option wasn't in fastcgi_params file, so PHP didn't work and there wasn't any errors in logs.

Sign up to request clarification or add additional context in comments.

1 Comment

I had the same problem and its due to Nginx default configuration file missing that line .
2

Try setting your error reporting level in your actual php files. Or, as others have suggested, check your server settings--it could be something in php.ini, or some restriction as regards your host. Don't just rely on .htaccess. Also, when troubleshooting, print_r any variables you might think fishy.

7 Comments

I don't have access to php.ini. And when these errors pop up, it's a syntax error, so print_r doesn't help.
If you don't have access to php.ini, you should not be developing on that server. Use shared hosting for production, your local machine for development.
And when errors happen in production? We'd all like to believe that doesn't happen, but it does.
If you have a parse error in production, something is wrong with your development model. :) If you have a different error, you don't want that error displayed to the user anyways + you should have a proper error handling mechanism.
I would suggest you download the apache XAMP or WAMPserver and set up a development environments on your PC. If your workstation environment is as constrained as your server environment you could use portableapps.com/apps/development/xampp which doesnt requires any admin rights or special priviledges to install and run.
|
2

Are you sure PHP is actually picking up the 'display_errors' setting from .htaccess? Check the output of the phpinfo() function to make sure.

Also, you should check to make sure that you haven't used '@', it could be silencing your errors if you have used '@include ...' or '@some_function(...)', somewhere up the stack trace.

4 Comments

It is. display_errors is off in the serverwide config, but it displays lesser errors like parameter number mismatches, etc. I havn't used the @ operator at all in this project, and generally tend to avoid it for just that reason.
You should also check that display_errors is not being changed by a PHP script somewhere.
I've build this framework from the ground up, so no, it's not (unless something in the core changes it for some reason...)
If you call an undefined function (to generate a fatal error), do you see that error message?
2

PHP Error Handling

Sometimes your application will not run as it supposed to do, resulting in an error. There are a number of reasons that may cause errors, for example:

The Web server might run out of disk space A user might have entered an invalid value in a form field The file or database record that you were trying to access may not exist The application might not have permission to write to a file on the disk A service that the application needs to access might be temporarily unavailable These types of errors are known as run-time errors, because they occur at the time the script runs. They are distinct from syntax errors that need to be fixed before the script will run.

A professional application must have the capabilities to handle such run-time error gracefully. Usually this means informing the user about the problem more clearly and precisely.

Understanding Error Levels

Usually, when there's a problem that prevents a script from running properly, the PHP engine triggers an error. Each error is represented by an integer value and an associated constant. The following table list some of the common error levels:

enter image description here

The PHP engine triggers an error whenever it encounters a problem with your script, but you can also trigger errors yourself to generate more user friendly error messages. This way you can make your application more sofisticated. The following section describes some of common methods used for handling errors in PHP:

Basic Error Handling Using the die() Function

<?php // Try to open a non-existent file
     $file = fopen("sample.txt", "r");
?>

If the file does not exist you might get an error like this: Warning: fopen(sample.txt) [function.fopen]: failed to open stream: No such file or directory in C:\wamp\www\project\test.php on line 2

If we follow some simple steps we can prevent the users from getting such error message:

<?php
if(file_exists("sample.txt")){
    $file = fopen("sample.txt", "r");
} else{
    die("Error: The file you are trying to access doesn't exist.");
}
?>

Now if you run the above script you will get the error message like this: Error: The file you are trying to access doesn't exist.

As you can see by implementing a simple check whether the file exist or not before trying to access it, we can generate an error message that is more meaningful to the user.

The die() function used above simply display the custom error message and terminate the current script if 'sample.txt' file is not found.

Creating a Custom Error Handler

You can create your own error handler function to deal with the run-time error generated by PHP engine. The custom error handler provides you greater flexibility and better control over the errors, it can inspect the error and decide what to do with the error, it might display a message to the user, log the error in a file or database or send by e-mail, attempt to fix the problem and carry on, exit the execution of the script or ignore the error altogether.

The custom error handler function must be able to handle at least two parameters (errno and errstr), however it can optionally accept an additional three parameters (errfile, errline, and errcontext), as described below:

enter image description here

Here's an example of a simple custom error handling function. This handler, customError() is triggered whenever an error occurred, no matter how trivial. It then outputs the details of the error to the browser and stops the execution of the script.

<?php
// Error handler function
function customError($errno, $errstr){
    echo "<b>Error:</b> [$errno] $errstr";
}
?>

You need to tell the PHP to use your custom error handler function — just call the built-in set_error_handler() function, passing in the name of the function.

<?php
// Error handler function
function customError($errno, $errstr){
    echo "<b>Error:</b> [$errno] $errstr";
}
 
// Set error handler
set_error_handler("customError");
 
// Trigger error
echo($test);
?>

Error Logging

Log Error Messages in a Text File

You can also logs details of the error to the log file, like this:

<?php
function calcDivision($dividend, $divisor){
    if($divisor == 0){
        trigger_error("calcDivision(): The divisor cannot be zero", E_USER_WARNING);
        return false;
    } else{
        return($dividend / $divisor);
    }
}
function customError($errno, $errstr, $errfile, $errline, $errcontext){
    $message = date("Y-m-d H:i:s - ");
    $message .= "Error: [" . $errno ."], " . "$errstr in $errfile on line $errline, ";
    $message .= "Variables:" . print_r($errcontext, true) . "\r\n";
    
    error_log($message, 3, "logs/app_errors.log");
    die("There was a problem, please try again.");
}
set_error_handler("customError");
echo calcDivision(10, 0);
echo "This will never be printed.";
?>

Trigger an Error

Although the PHP engine triggers an error whenever it encounters a problem with your script, however you can also trigger errors yourself. This can help to make your application more robust, because it can flag potential problems before they turn into serious errors.

To trigger an error from within your script, call the trigger_error() function, passing in the error message that you want to generate:

trigger_error("There was a problem.");

Consider the following function that calculates division of the two numbers.

<?php
function calcDivision($dividend, $divisor){
    return($dividend / $divisor);
}
 
// Calling the function
echo calcDivision(10, 0);
?>

If a value of zero (0) is passed as the $divisor parameter, the error generated by the PHP engine will look something like this: Warning: Division by zero in C:\wamp\www\project\test.php on line 3

This message doesn't look very informative. Consider the following example that uses the trigger_error() function to generate the error.

<?php
function calcDivision($dividend, $divisor){
    if($divisor == 0){
        trigger_error("The divisor cannot be zero", E_USER_WARNING);
        return false;
    } else{
        return($dividend / $divisor);
    }
}
 
// Calling the function
echo calcDivision(10, 0);
?>

Now the script generates this error message: Warning: The divisor cannot be zero in C:\wamp\www\project\error.php on line 4

As you can see the error message generated by the second example explains the problem more clearly as compared to the previous one.

Reference: https://www.tutorialrepublic.com/php-tutorial/php-error-handling.php

1 Comment

You have copied your answer from tutorialrepublic.com/php-tutorial/php-error-handling.php without attribution. Do not present the work of others as your own.
1

using @inexistent_function_call(); in your code will cause the intepreter to quietly die and abort the script parsing. You should check for invalid functions and try not to use the error-supressing operator(the @ char )

Comments

1

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) { /* ... */

Comments

1

You can also run the file in the Terminal (command line) like so: php -f filename.php.

This runs your code and gives you the same output in case of any errors that you'd see in the error.log. It mentions the error and the line number.

Comments

0

Some applications do handle these instructions themselves, by calling something like this:

error_reporting(E_ALL & ~E_DEPRECATED); or error_reporting(0);

And thus overriding your .htaccess settings.

Comments

0

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

Comments

0

I fixed my entire 500 problem like this:

A. Check php.ini parameters

  1. php.ini >> error_reporting = E_ALL | E_STRICT
  2. php.ini >> display_errors = On
  3. php.ini >> display_startup_errors = Off

B. Update IIS manager parameters

  1. IIS Manager >> Error Pages >> 500 >> Edit feature settings >> detailed errors

in this step, you get 500 errors like this and with no html loading.

enter image description here

  1. IIS Manager >> FastCGI Settings >> php-cgi.exe >> standard error mode >> IgnoreAndReurn200

in this step, you can see html page including php errors like this. enter image description here

AND DONE :)

Comments

-1

If the error is in PHP code, you can use error_reporting() function within your code to set to the report all.

However, this does not handle the situation when PHP crashes. Information about that is only available in server logs. Maybe you don't have access to those, but many hosting providers I've worked with have some way to let you access it. For example, the approach I like best is that it creates the error_log file in the current directory where .php resides. Try searching there or contact your hosting provider about this.

Comments

1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.