What causes php fatal error?

Asked 7 years, 2 months ago

Viewed 7k times

I want script to stop being executed at the point of the crash, while not to exhaust the memory or otherwise crash the server.

Any idea how to do that?

asked Jul 8, 2015 at 5:56

4

Bit late but this is a guaranteed natural fatal error:

Call an undefined function, eg:

noSuchFunction();

Or if you want this to be executed when you are in 'test' mode only, then put it into an eval

if($isTestMode==1){
  eval("noSuchFunction();");
}

Note: With the trigger_error() function the problem is that if you are using set_error_handler() it ceases to be fatal - your error handler will decide what to do with it.

answered Oct 19, 2016 at 5:09

Educative Answers Team

What causes php fatal error?

Fatal errors crash the program. There are three types of fatal errors in PHP:

  1. Startup fatal error: This error occurs when a system can’t run the code during installation.

  2. Compile time fatal error: This error occurs if a call is made to a non-existent code or variable.

  3. Runtime fatal error: This error occurs while the program is running, and will cause the program to quit.

The following code tried to call a function name without declaring the function. This gives a fatal error:

Notice how the print statement is not executed. This is because, as soon as a fatal error is thrown, the code stops compiling.

Solution

  • Look for the undeclared variables as given in the error.
  • If you are using inbuilt functions, ensure that there is no typo and the correct function is called.
  • Check if the spellings are correct.

Copyright ©2022 Educative, Inc. All rights reserved

1 Introduction: why does Fatal Error happen?

Out-of-memory errors are one of the most common and hard-to-fix problems that PHP developers run into — especially with applications that process large amounts of data — thanks to PHP's relatively conservative default memory settings. In fact, there are more than 1,300 questions related to PHP memory errors on Stack Overflow alone.

98% of the time this error comes from loading more into memory than what you set up PHP to handle in one process. There are other causes, but these are much less common — very rarely it can be a memory leak if you're on PHP 5.3 and above.

If you aren't sure what your PHP memory limit is set to, it's helpfully included in the error message. The size is reported in bytes, though, so we've done some conversions for you:

  • PHP: Fatal Error: Allowed Memory Size of 8388608 Bytes Exhausted - 8 MB
  • PHP: Fatal Error: Allowed Memory Size of 16777216 Bytes Exhausted - 16 MB
  • PHP: Fatal Error: Allowed Memory Size of 33554432 Bytes Exhausted - 32 MB
  • PHP: Fatal Error: Allowed Memory Size of 67108864 Bytes Exhausted - 64 MB
  • PHP: Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted - 128 MB
  • PHP: Fatal Error: Allowed Memory Size of 268435456 Bytes Exhausted - 256 MB
  • PHP: Fatal Error: Allowed Memory Size of 536870912 Bytes Exhausted - 512 MB
  • PHP: Fatal Error: Allowed Memory Size of 1073741824 Bytes Exhausted - 1 GB

2 What do I have to do to resolve it?

Your first course of action is to increase your memory limit. Note, this is a temporary debugging producedure. The goal is to increase the memory to a point where we have the application working again for the purpose of then reducing the memory usage. Once you decrease the memory usage you can lower the memory limit it to a value that's more suitable. Your plan should be to use as little memory as you could practically use where the application works and functions correctly in a production server based on the workload by your users (humans or programmatic). I usually recommend setting the memory limit to something high, like 1GB, assuming you have at least 150% of that free in RAM.

Also, never do these tests on a production server unless you're sure you have plenty of RAM and you fully understand how web server processes consume memory. You could easily bring a server to its knees if there are many concurrent processes running, each using a high amount of memory. I would never, ever recommend setting the memory limit to -1 (unlimited) in a production environment. That's a recipe for disaster. Don't make that newbie mistake.

So how do you do this? Simple — increase the memory limit programmatically early on in your code, before your process runs out of memory. If you do it this way, you can give PHP extra memory only when that piece of code gets called rather than increasing the memory limit for all PHP processes.

  • If by increasing the memory limit you have gotten rid of the error and your code now works, you'll need to take measures to decrease that memory usage. Here are a few things you could do to decrease it:
  • If you're reading files, read them line-by-line instead of reading in the complete file into memory. Look at fgets and SplFileObject::fgets.
  • Upgrade to a new version of PHP if you're using PHP 5.3. PHP 5.4 and 5.5 use much less memory.
  • Avoid loading large datasets into in an array. Instead, go for processing smaller subsets of the larger dataset and, if necessary, persist your data into a database to relieve memory use.
  • Try the latest version or minor version of a third-party library (1.9.3 vs. your 1.8.2, for instance) and use whichever is more stable. Sometimes newer versions of libraries are written more efficiently.
  • If you have an uncommon or unstable PHP extension, try upgrading it. It might have a memory leak.
  • If you're dealing with large files and you simply can't read it line-by-line, try breaking the file into many smaller files and process those individually.
  • Disable PHP extensions that you don't need.
  • In the problem area, unset variables which contain large amounts of data and aren't required later in the code.

2.1 Did everything, set it to unlimited and still get the error

Call the ER, because you're probably going to end up there. No, seriously, here are a couple of things you could do.

First, you need to ask yourself when this started happening. Was it working before, and now it's not? If so, think about what could have changed. Isolate the problem.

Maybe you didn't touch your code before the problem appeared. Well, what else could have changed? Are there external dependencies? Perhaps a database, or files that were imported by a user? Put that on your list of suspects and start investigating.

Start off small; begin with what you "think" the problem is and try to prove yourself wrong. If you can't, move on to the next suspect. See how far you get into your code before it exits prematurely, then start working up the call stack from there (var_dump debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) if you don't have Xdebug installed). If you can interactively debug with Xdebug or Zend Debugger, do that and put a breakpoint right before the problem area.

I once had an issue where an Excel file kept running out of memory after being imported. It was working fine for months, but suddenly stopped. I think it took me at least 5 hours of relentless debugging before I discovered the problem: random data that had somehow been inserted into one of the worksheet's cells by the user. Apparently PHP just went haywire, and I still haven't discovered the root cause, despite knowing the trigger.

I could've saved a lot of time by asking myself what changed. The answer was very obvious — data input by the user and the database. You could have a similar experience.

3 Xdebug, the Swiss Army Knife

In any situation, there's one tool you can count on to help diagnose how much memory you're using and where in your code large amounts of memory are being used: Xdebug. You can install it using package managers like yum, apt-get, port, and homebrew; install a pre-built binary; use pecl; or simply compile it yourself.

After installing Xdebug, all you need to do is refresh the page or, if your code is meant to run in a shell, re-run it in the CLI. PHP will now throw much more informative errors, including a call stack that will tell you exactly where the script stopped with a file path, line number, and even the last function that was called.

If you want more detailed information you'll need to generate what's called a "trace file." To do this, set the xdebug.auto_trace and xdebug.show_mem_delta config directives to 1. Trace files are normally saved in /tmp or /var/tmp, but you can check the output path by looking at the xdebug.trace_output_dir directive in phpinfo().

Just run the code, and a trace file — including memory usage — will be created even if you run out of memory early.

To locate the problem, begin at the bottom of the trace file and work your way up. Look for deltas (numbers with + or –) with a large number, and keep in mind that they're shown in bytes. 1024 bytes = 1 kilobyte.

Once you're finished debugging, make sure to set xdebug.auto_trace back to 0. Trace files can become very large, very quickly, and eat up disk space.

4 PHP Memory management

Here's a great slide deck on how PHP deals with memory internally.

5 Challenge

Use the following script and try to pinpoint where the problem is. Even better, install Xdebug and generate a trace file.

startTime = microtime(true);
    }

    function timerEnd(){
        echo number_format( (microtime(true) - $this->startTime)*1000, 2 ), ' ms';
    }
}

class ProfilerHolder {
    protected $profiler;

    public function __construct( Profiler $profiler ){
        $this->profiler = $profiler;
    }
}

ini_set('memory_limit', '1M');

$profiler = new Profiler();

$profiler->timerStart();

get_usage_in_kb();

$holder = new ProfilerHolder( $profiler );

$b = null;

/**
 * @return string
 */
function make_dummy_data()
{
    return str_repeat( "Hello|", 114242 );
}

$a = make_dummy_data();

$data = explode( '|', $a ); // comment this after narrowing down that a lot of memory is being used here
//$data = array(); // uncomment this and memory usage will drop

$buffer = array();

foreach( $data as $key => $item ){
    $buffer[] = $item;
}

get_usage_in_kb();

unset($a);

get_usage_in_kb();

echo memory_get_peak_usage(TRUE)/1024, ' kb', "\n";

$profiler->timerEnd();

unset( $profiler );
xdebug_debug_zval( 'profiler' );

//var_dump( $holder );

With all of these tips in mind you should be able to fix any memory exhaustion error. If you're still having issues, I'd be glad to jump on an AirPair session and help get to the root of the problem so you can focus on what's important.

What would occur if a fatal error was thrown in your PHP program?

It's an error that caused the script to abort and exit immediately. All statements after the fatal error are never executed. I strongly recommend you use an editor that will alert you to errors as you code. It will safe you a lot of time.

How do I fix PHP errors?

Editing the php..
Log into your cPanel..
Go to the File Manager. ... .
Find the “Error handling and logging” section in the php.ini. ... .
Next you can set the display_errors variable to On or Off to either show the errors on your website or not..

What are the most common errors in PHP?

1. PHP Parse error: syntax error, unexpected end of file. A parse error occurs when code that contains a syntax error is executed. Syntax errors needn't be large, not complicated, as the following example demonstrates.

What does fatal error message mean?

A condition that halts processing due to faulty hardware, program bugs, read errors or other anomalies. If you get a fatal error, you generally cannot recover from it, because the operating system has encountered a condition it cannot resolve.