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
Related
In a php script I have some test and after the script the html page.
When a test fail i call die("Test 1 failed");
If no test fail the php script reach the end ?> and then load the html code after the php script.
Is this a good procedure? Or I need to write die() or exit() before the end of php script?
No you don't have to write that and this is not best practice. If the script reaches the end without fatal errros it will exit.
If this means "testing" for you, you're wrong. Testing should be done using unit tests. For php there is phpunit. Give it a try, that's the proper way of testing your code.
Edit: As CompuChip says in a comment, the only useful use case for exit is when you're writing a php based shell script that should return an error code. See the parameter section of the documentation for the exit() function.
You should never be using die() or exit in your production PHP scripts except in very specific cases. Instead, re-work your code paths to simply show an error message to the user rather than exiting the script early.
No you don't need that, but when writing console PHP scripts, you might want to check with for example Bash if the script completed everything in the right way. That's when you use exit() or die()
Is the die() or exit() function needed in the end of a php script?
No, PHP will end the script itself. If the script is an included file (called from another file) then it will end script in the included file and then continue with any code in the original file after where you included (if there is any code).
So you put die() or exit() where ever you want or need it.
For testing, put it after each block of code you test. I use them in some parts of testing if I just want PHP to show me something then stop, such as print out an array to make sure it's being constructed correctly etc.
eg:
print_r($array);
exit();
For other code tests, I sometimes just echo "Section A worked", etc, such as within if/else. If I want to know if a particular part of code is working or if some criteria is being met or not (basically, it lets you trace where PHP itself is going within your code).
All that said, don't use die() or exit() in production code. You should use a more friendly and controlled messaging setup. For security reasons and visual, as you could potentially give them some info like "ERROR Failed to load SomethingSecret". Also it doesn't look pretty when you page only half loads and then puts out an on screen error message which likely means nothing to the end user.
Have a read through this:
PHP Error handling: die() Vs trigger_error() Vs throw Exception
No !
This is not recommanded to use it
Use trigger_error or error_log to log the tests in your error.log. Then check it.
No you don't have to use these functions at the end of the script, because it exists anyway at the end of the script.
No need to put a die or an exit at the end of the scipt.
But you may use exit to terminate your script with a specific exit code (by default it's 0).
E.g
$ php -r "/* does nothing */;"
$ echo $?
0
$ php -r "exit(123);"
$ echo $?
123
http://php.net/exit
From the documentation:
The link to the server will be closed as soon as the execution of the
script ends, unless it's closed earlier by explicitly calling
mysql_close().
https://secure.php.net/function.mysql-connect
Nope, you don't need to call die() or exit(0 if you have another code to run, like you HTML code
In a php script I have some test and after the script the html page.
When a test fail i call die("Test 1 failed");
If no test fail the php script reach the end ?> and then load the html code after the php script.
Is this a good procedure? Or I need to write die() or exit() before the end of php script?
No you don't have to write that and this is not best practice. If the script reaches the end without fatal errros it will exit.
If this means "testing" for you, you're wrong. Testing should be done using unit tests. For php there is phpunit. Give it a try, that's the proper way of testing your code.
Edit: As CompuChip says in a comment, the only useful use case for exit is when you're writing a php based shell script that should return an error code. See the parameter section of the documentation for the exit() function.
You should never be using die() or exit in your production PHP scripts except in very specific cases. Instead, re-work your code paths to simply show an error message to the user rather than exiting the script early.
No you don't need that, but when writing console PHP scripts, you might want to check with for example Bash if the script completed everything in the right way. That's when you use exit() or die()
Is the die() or exit() function needed in the end of a php script?
No, PHP will end the script itself. If the script is an included file (called from another file) then it will end script in the included file and then continue with any code in the original file after where you included (if there is any code).
So you put die() or exit() where ever you want or need it.
For testing, put it after each block of code you test. I use them in some parts of testing if I just want PHP to show me something then stop, such as print out an array to make sure it's being constructed correctly etc.
eg:
print_r($array);
exit();
For other code tests, I sometimes just echo "Section A worked", etc, such as within if/else. If I want to know if a particular part of code is working or if some criteria is being met or not (basically, it lets you trace where PHP itself is going within your code).
All that said, don't use die() or exit() in production code. You should use a more friendly and controlled messaging setup. For security reasons and visual, as you could potentially give them some info like "ERROR Failed to load SomethingSecret". Also it doesn't look pretty when you page only half loads and then puts out an on screen error message which likely means nothing to the end user.
Have a read through this:
PHP Error handling: die() Vs trigger_error() Vs throw Exception
No !
This is not recommanded to use it
Use trigger_error or error_log to log the tests in your error.log. Then check it.
No you don't have to use these functions at the end of the script, because it exists anyway at the end of the script.
No need to put a die or an exit at the end of the scipt.
But you may use exit to terminate your script with a specific exit code (by default it's 0).
E.g
$ php -r "/* does nothing */;"
$ echo $?
0
$ php -r "exit(123);"
$ echo $?
123
http://php.net/exit
From the documentation:
The link to the server will be closed as soon as the execution of the
script ends, unless it's closed earlier by explicitly calling
mysql_close().
https://secure.php.net/function.mysql-connect
Nope, you don't need to call die() or exit(0 if you have another code to run, like you HTML code
I need to execute a bunch of functions that consume nearly 50 seconds to complete. But i want redirect to page after execution few function itself and also continue further execution.
The below function execute on form submit as in process.php // it wont echo anything
// all function in serprate process page.
func1
func2
func3
// After above 3 function i need to php redirect to redirect now immediately example.com
func4
func5
func6
I tried using php header but it won't immediately redirecting.
header("Location:http://www.example.com");
If I use exit(); it will redirect but not process function 4,5 and 6.
what i need is any way to redirect immediately after first 3 functions and continue execution.
On paper, you can achieve this by combining flush() and ignore_user_abort():
ignore_user_abort(true);
do_stuff();
send_redirect();
flush();
do_more_stuff();
Manual pages:
http://php.net/manual/en/function.flush.php
http://php.net/manual/en/function.ignore-user-abort.php
Note the known caveats: some browsers (old IEs in particular, and possibly new ones) want a minimum amount of bytes received before processing what you send them, so you might end up needing to toss in some long string in an html comment for it to work as expected.
In practice, the more conventional approach is to register a cron job task in some table, and have a cron.php file take care of pending tasks in a completely separate (and independent) request.
A less conventional approach is also highlighted in the comments: issue a shell command or something to that order β be very wary of sanitizing input if you do that.
Adding this for reference (see comments below):
<!-- IE bug fix: pad the page with enough characters such that it is greater than 512 bytes, even after gzip compression abcdefghijklmnopqrstuvwxyz1234567890aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz11223344556677889900abacbcbdcdcededfefegfgfhghgihihjijikjkjlklkmlmlnmnmononpopoqpqprqrqsrsrtstsubcbcdcdedefefgfabcadefbghicjkldmnoepqrfstugvwxhyz1i234j567k890laabmbccnddeoeffpgghqhiirjjksklltmmnunoovppqwqrrxsstytuuzvvw0wxx1yyz2z113223434455666777889890091abc2def3ghi4jkl5mno6pqr7stu8vwx9yz11aab2bcc3dd4ee5ff6gg7hh8ii9j0jk1kl2lmm3nnoo4p5pq6qrr7ss8tt9uuvv0wwx1x2yyzz13aba4cbcb5dcdc6dedfef8egf9gfh0ghg1ihi2hji3jik4jkj5lkl6kml7mln8mnm9ono
β>
References:
http://www.clintharris.net/2009/ie-512-byte-error-pages-and-wordpress/
http://core.trac.wordpress.org/ticket/8942
http://core.trac.wordpress.org/ticket/11289
(Actually applies only for http errors, after re-going through it.)
Try to split your process.php in two files : process.php and process_more.php (i.e.). Assuming your are under a unix os server :
Code for process.php :
// code to execute before redirect
func1();
func2();
func3();
// code to execute after redirect in background
// you can pass some parameters
$command = "php -f /path/to/process_more.php param1 param2"
exec($command . " > /dev/null &");
header('Location: http://dn.tld/');
exit();
See more to use parameters with $argv variable, and be careful to prevent the user for injecting another command within the parameters
Code for process_more.php :
func2();
func3();
func4();
Not that you won't be able to access $_GET or $_POST variables. You need to pass any variable you want within the call command.
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
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.