Rob
Rob

Reputation: 2362

Can you trigger a specific exit status on a php fatal error?

I've tried the following:

<?php
function shutdown_find_exit()
{
    exit(50);
}
register_shutdown_function('shutdown_find_exit');

trigger_error("Fatal error", E_USER_ERROR);

?>

But that still exists with an error code of 255.

I'm trying to have an error code of 50 returned.

I'm checking it with the following bash script:

php tester.php
status=$?
echo Exit Code: ${status}

Updated code based on the accepted answer for anyone interested:

<?php
function shutdown_find_exit()
{
    exit('50');
}
register_shutdown_function('shutdown_find_exit');

trigger_error("Fatal error", E_USER_ERROR);
?>

and the bash script

output="$(php tester.php)"
status=$?
echo Exit Code: ${status}
if [[ $output == *"50"* ]]
then
  echo "Got 50";
fi

Upvotes: 1

Views: 951

Answers (2)

daxeh
daxeh

Reputation: 1085

TL;DR: use a string, instead of an int.

php exit( status )

If status is a string, this function prints the status just before exiting.

If status is an integer, that value will be used as the exit status and not printed. Exit statuses should be in the range 0 to 254, the exit status 255 is reserved by PHP and shall not be used. The status 0 is used to terminate the program successfully.

Note: PHP >= 4.2.0 does NOT print the status if it is an integer.

Execute php script in bash, assign output to variable.

variable = $(/path/to/php -f $HOME/path/to/my.php)

For example:

# just executing php, but capturing output then, prints it to console
status = $(/usr/bin/php -f $HOME/path/to/tester.php)
echo Exit Code: ${status}

Hope this helps.

Upvotes: 1

Jahid
Jahid

Reputation: 22428

See if this does what you want to do:

trigger_error("Fatal error", shutdown_find_exit());

Upvotes: 1

Related Questions