Use of the parameter 'status' to exit - php

According to the documentation to exit:
If status is an integer, that value will be used as the exit status and not printed.
This made ​​me very confused. What is the difference between a exit(); and a exit(1);? What are the use cases? How should I choose? On what occasions? How php manages this state?

There's a numeric return code that can be read by the OS/the shell/the process that has invoked your PHP script. See: http://en.wikipedia.org/wiki/Exit_status

The difference between exit(); and exit(1); is, that the former sets the exit status of the process executing your PHP script to 0 and the latter sets it to 1.
An exit status of 0 usually means that the process finished sucessfully. No error occurred.
An exit status of 1 to 254 usually is used to signal that the process was aborted because some kind of error occurred. What error a specific exit status means is up to your PHP script.
Parent processes can use the exit statuses returned by child processes to decide how to continue, e.g. whether they should exit too, or retry, or execute another child process, or whatever.

I believe it's only useful if the script is being executed from the command line or another program is executing it, through the web server it's pointless.

it like the return code in C++, when usually the program returns 0 when everything is done successfully, negative when some error has occurred and positive number depending where that code can be used.
but in general as it is already said in previous answers, if the script won't be called from another script or program it doesn't make much sense what to return

Related

What are the PHP exit status codes?

From the docs for the exit() function:
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.
I had thought these were http status codes and had been using them as such (I was confused why my exit(400) call was returning an empty string).
The docs only explicitly mention 0 and 255 as having special meaning and I can't seem to find any documentation anywhere describing what the other 254 codes are meant to be or if they're reserved or anything like that. I also can't really figure out why it would even use a different status code system from http in the first place.
Also, since this isn't https status codes. What is the best way to send those? Should I just echo a number? Put the number as the 'message' in exit ie. exit('400')? Should I even use http status codes at all vs just sending boolean or flags or the like in my responses?
Exit codes are used for command line programming. They have no significance when writing PHP to be invoked by a web server.
Exit code meanings aren't standardised. Generally you would select arbitrary ones and document them so that scripts calling your program could handle them appropriately.
The simplest example of their use is for the shell script idiom for "Do something, then do something else if it is successful".
./uploadFile.php myFile.txt && ./annouceSuccessfulFileUpload.php
If ./uploadFile.php myFile.txt has a non-zero exit code, the second part won't run.
As opposed to "Do something, then do something else regardless":
./uploadFile.php myFile.txt; ./annouceHopefullySuccessfulFileUpload.php
The http_response_code function is used for setting HTTP response codes:
<?php
http_response_code(400);
?>
An exit status code is a code that a program that exits returns to the program that started it. Exit codes are useful in shell scripts (and not only there) but they are not used in the web programming.
Use the PHP function header() to produce an HTTP status code.
What its saying in the docs is that exit status are from 0-255, but only 0-254 are usable since the last one is reserved.
if you wanna set the http response code, perhaps this function might be of use : https://www.php.net/manual/en/function.http-response-code.php

Spawning a PHP script from inside another. Non-blockning

I have a PHP script that I need to execute from inside another PHP webpage. However for the second one to run properly the first needs to have fully completed. Essentially I need the first page to spawn a new process/thread for the second script which will wait 1 second before starting.
Doing an include causes blocking which prevents it from working and I can't get it to start using exec
Edit:
Should have clarified. These pages have no output and are not interfaced with through a web interface. All pages are called by POST requests from another server.
Edit 2:
Solution: make server requesting the page send a request directly to the second page 1 second after the first returns.
proc_open is the correct choice, as #ChristopherMorrissey pointed out. I want to elaborate a little here, as there are some caveats to using proc_open that aren't entirely obviously.
In the first code example # http://php.net/manual/en/function.proc-open.php, it shows the overall usage and I will reference that.
The first caveat is with the pipes. The pipes are file streams in PHP that link to STDIN, STDOUT and STDERR of the child process. In the example, pipe index 0 represents a file stream from the parent PHP processes perspective. If the parent process writes to this stream, it will appear as STDIN input to the child process.
On POSIX compliant OSes, STDIN to a process needs to close before the process can terminate. Its very important to call fclose on the pipe from the parent, or your child process will be stuck. That is done with this line in the example:
fclose($pipes[0]);
The other caveat is on checking the exit code of the child process. Checking the exit code is the best way to determine if the child process has exited correctly, or if it erred out. At the very least, you will need to just know when the child process has completed. Checking this and the exit code are both done with http://www.php.net/manual/en/function.proc-get-status.php
If you want to ensure the process exits correctly, you will need to look at the exitcode field returned in the array from proc_get_status. Keep in mind this exit code will only return a valid value once. All other times it will return -1. So, the one time it returns > -1, this is your actual exit code. So, the first time running == false, check exitcode.
I hope this helps.
One option would be to redirect the page after the first script has finished.
You could do it this way:
//first script here
sleep(1); //wait one second
echo "<meta http-equiv=\"refresh\" content=\"0;URL='yoursecondscript.php'\" />"; //redirect
or even:
//first script here
//redirect after one sec
echo "<meta http-equiv=\"refresh\" content=\"1;URL='http://thetudors.example.com/'\" />";
You might be able to write a header going to the second page when you want it, then putting a header back to the original page at the end of the second page. Though there are many reasons this fix wouldn't work, like the PHP code being required to be in the HTML.
Headers reference
So something like: header(Location: seconddocument.php)
Or maybe you could put the PHP to execute in a function, and then call it from the original PHP document. I can't be exactly sure of your requirements here, but those would be my two best answers.

PHP: What is the difference between exit(), die() and return; within "self" and included files?

Am am still on a PHP learning curb. When terminating a script, what is the difference between exit(), die(); and return;?:
within the same file (Single script file)
Within the child of an include
Within the parent of an include
Return returns a value. This can be anything and is meant for functions.
What are the differences in die() and exit() in PHP?
http://php.net/manual/en/function.return.php
die and exit (equivalent functions)
Terminates execution of the script.
return
Returns program control to the calling module. Execution resumes at
the statement following the called module's invocation.
If called from within a function, the return statement immediately
ends execution of the current function, and returns its argument as
the value of the function call. return also ends the execution of an
eval() statement or script file.
If called from the global scope, then execution of the current script
file is ended. If the current script file was included or required,
then control is passed back to the calling file. Furthermore, if the
current script file was included, then the value given to return will
be returned as the value of the include call. If return is called from
within the main script file, then script execution ends. If the
current script file was named by the auto_prepend_file or
auto_append_file configuration options in php.ini, then that script
file's execution is ended.
die vs exit
The difference between die() and exit() in PHP is their origin.
exit() is from exit() in C.
die() is from die in Perl.
PHP Manual
PHP Manual for die:
This language construct is equivalent to exit().
PHP Manual for exit:
Note: This language construct is equivalent to die().
PHP Manual for List of Function Aliases:
die is an alias for master function exit()
DIFFERENT IN OTHER LANGUAGES
die() and exit() are different in other languages but in PHP they are identical.
From Yet another PHP rant:
...As a C and Perl coder, I was ready to answer, "Why, exit() just bails
off the program with a numeric exit status, while die() prints out the
error message to stderr and exits with EXIT_FAILURE status." But then
I remembered we're in messy-syntax-land of PHP.
In PHP, exit() and die() are identical.
The designers obviously thought "Hmm, let's borrow exit() from C. And Perl
folks probably will like it if we take die() as is from Perl too.
Oops! We have two exit functions now! Let's make it so that they both
can take a string or integer as an argument and make them identical!"
The end result is that this didn't really make things any "easier",
just more confusing. C and Perl coders will continue to use exit() to
toss an integer exit value only, and die() to toss an error message
and exit with a failure. Newbies and PHP-as-a-first-language people
will probably wonder "umm, two exit functions, which one should I
use?" The manual doesn't explain why there's exit() and die().
In general, PHP has a lot of weird redundancy like this - it tries to
be friendly to people who come from different language backgrounds,
but while doing so, it creates confusing redundancy.
Return is returns a value (char,int,string,array...) and exit from function.
From php manual :
Note: This language construct is equivalent to die().
But still there are difference between die and exit :
Using die() you can post a string : die("An error occurred");
Same result with using exit()
<?php
echo("An error occurred <br>");
exit(0);
?>
OR if you are cli or unix shell :
Using PHP on the command line, die("An error occurred") simply prints "An error occurred" to STDOUT and terminates the program with a normal exit code of 0.
<?php
fwrite(STDERR, "An error occurred \n");
exit(0); //
?>

Can a PHP script abort itself or detect abortion?

PHP scripts can continue executing after the HTTP page request, so how do I finally stop it executing when I'm done with it?
Also, is there an event to detect when the OS is going to forcibly abort the script? or how do I keep an internal timer to predict max_execution_time?
exit()/die() will stop a php script.
To know when to stop the script, you'll just have to use microtime as a timer and save as a constant (or fetch from the php.ini file) the maximum execution time.
You can also look at the Connection handling information. Where we have things like connection_aborted() and connection_status()
But what is the problem you're trying to solve?
You can use register_shutdown_function to register a function to be called at the end of script execution. You can use this to detect when the script has been terminated and perform a certain set of actions.
To have a callback at the moment your request is shutting down, use register_shutdown_function( myfunction ).
Much like most POSIX environments, PHP also supports signal handlers. You can register your own handler for the SIGTERM event.
function my_abort_handler( $signo ) {
echo "Aborted";
}
pcntl_signal( SIGTERM, "my_abort_handler" );
You may want to take a look at pcntl-alarm which allows a script to send a signal to itself. Also contains some sample on how to catch the kill signals which can be send by the OS. And die() indeed.
Well, you could start a $start=microtime(true) which will return a timestamp. Then you can just keep checking microtime(true) and subtract that from your start time to get the number of seconds since executing.
But no, you can't "catch" the script as its terminating for the reason of the request being too long. You could try to do some last minute stuff in the shutdown handler, but I'm not sure if PHP will honor that.
It looks like there used to be a function that does exactly what you want, connection_timeout(), but it was deprecated and removed. Don't know if there is any kind of replacement for this, however.

what does PHP die() return

in PHP Does die() gives anything in return when we use it?
In PHP the function die() just quit running the script and prints out the argument (if there's any).
http://php.net/die
Obviously, die() or its equivalent exit() don't return anything to the script itself; to be precise, this code doesn't make much sense:
if (die())) {
echo 'are we dead yet?';
}
However, depending on what you pass as the (optional) argument of die() or exit(), it does return something to the caller, i.e. the command that caused your script to run. Its practical use is usually limited to the cli SAPI though, when you call the script from a command line using php /path/to/script.php.
Observe:
die('goodbye cruel world');
This code would print goodbye cruel world and then return an exit status code of 0, signalling to the caller that the process terminated normally.
Another example:
die(1);
When you pass an integer value instead of a string, nothing is printed and the exit status code will be 1, signalling to the caller that the process didn't terminate normally.
Lastly, die() without any arguments is the same as die(0).
The exit status of a process can be changed to signal different kinds of errors that may have occurred, e.g. 1 means general error, 2 means invalid username, etc.
It is the same as exit() and according to documentation it returns nothing
It does not return. The script is terminated and nothing else is executed.
There's no reason to return something in die/exit. This function terminates php interpreter process inside and returns exit-code to shell. So after calling die() there is no script execution as far as there is no interpreter process which executes the script and that's why there is no way to handle function's return.

Categories