Where does the php exit function print its message to? - php

According to http://www.w3schools.com/php/func_misc_exit.asp the php exit function prints a message and exits the current script. Where does the message get printed?

The exit() function outputs to standard out. Typically this is sent right back to the client (Browser), but a lot of things might interfere with that: Bad Output buffering or redirection e.g.

If you pass it a string, it gets echoed to the screen (just like if you were to use echo).
If you pass it an int, it's not displayed, but instead "returned" as the program's return code.

It outputs it to the browser, you see a plain page with the exit message, or if previous output was printed then it appends this to the bottom.

Related

PHP - Should I add the die() function at the end of every php script? [duplicate]

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

Is the die() or exit() function needed in the end of a php script?

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

Get full output from a PHP script

I am running a script every night and the output of the script will only be send to a mail address. But the problem is that I need to receive a copy of the output in my own mailbox. I registered an shutdown handler in the script and I tried to send a mail with functions like ob_get_contents which actually shows data. But only the last thing I printed to the terminal.
cronMail('Cron', ob_get_contents());
The function called is just a simple function which adds the default receiver and sender and call the PHP Mail function.
The output in the mail is:
array()
While the terminal has te following output:
Starting cron...
Exiting...
array()
Can anyone tell me how to receive the whole output? I started the output buffer by using the ob_start method. And after each line I make sure there is an ob_flush method called so the output will also be send to the browser if the script is called directly.
ob_flush stands in your way, see the linked description on the manual page, it is pretty clear about that: It flushes the buffer so outputs it.
You do not want that. Remove the calls to it and you should be fine.
ob_start();
... your script without "ob_flush()" ...
$buffer = ob_get_clean(); # finally get the output buffer as string
echo $buffer; # pass output along for cron
cronMail('Cron', $buffer); # send your mail
This variant ensures that you get your own email but also the output is passed along to cron. This can be useful if you do some error reporting in the cronMail function, so that at least there is some way to further debug that.
Another alternative is to register an output handling function that stores the output on the go. But that is less trivial so I keep it out.

stop php displaying to screen - run silent

I have a php page that when called from a browser displays a page, it also generates a static html page so - http://somewebsite/create.php when run from a browser creates newpage.html.
I also run this page from the CLI #php create.php it creates newpage.html but I get all the output on the screen, this slows down execution and if I have to run it many times can take hours.
Is there a way to run #php create.php and to supress all output to the screen
MArtyn
Check out Output Buffering
You begin with ob_start() to start buffering output, then you can use $output = ob_get_clean() to get everything that would have been displayed and store it in $output, so you can do whatever you want with it.
I believe there are $_SERVER variables you can use to check if you're running from the command line or not. (Obviously you can check for the HTTP headers that are normally there, they will not be set from the CLI)
var_dump($_SERVER) and see if there's anything intuitive looking :)
You can pipe the output on the command-line to /dev/null such as:
php http://somewebsite/create.php > /dev/null
This doesn't actually stop output from being produced by php, only from being displayed.
If you actually want to stop the output from being produced, you could use php's output buffering with ob_start() and put the output into a variable with ob_get_flush() at the end of the code and only echo the output if a certain param is/is not passed to the script.

Will php code exit after echo for ajax?

I am running a typical php-engined ajax webpage. I use echo to return a html string from the php code. My question is, if I have some other code after the echo, will those code get executed? Or echo behaves similar to exit, which immediately return and stop running the php code? Thanks.
No, echo in no way exits, you normally have more than one echo in a script. exit does take a string argument that it will output before exiting, however, so you can do:
exit("your string here");
and it will output the string and exit
No, echo would not. To exit after echoing things, you'd say
echo "Dear me, good bye!"; exit();
echo will simply return text to ajax javascript part; however the code after or before echo/echos will execute
No. PHP scripts are rendered in their entirety unless you explicitly exit them. ANY output on a script will be passed back to the ajax function if it was called through ajax.
echo 'This gets outputted<br />';
echo 'As does this';
If you must use a single file and you want your script to exit after performing ajax request with out having to add extra vars to your ajax url or evaluate vars to exit, i would suggest creating a function that performs your ajax, have the function return true on success, then do:
if(ajaxFunction($paramOne, $paramTwo)){exit();}

Categories