Using PHP's die() to end AJAX requests - php

What is the reason why you need to use die(); to end ajax requests? I read that it's recommended to use die() or exit() to terminate the script when its sole purpose is meant for AJAX call?
Is this recommended for my script when the output is the very last thing in the script? Because my index.php file loads the environment, gets the content from controller then the very last thing is using echo to output the data. It's either JSON encoded data for ajax, or HTML content for non ajax. I could add the die at the end by checking if it's an ajax call, but I don't understand why I would need it here.
// index.php
// Load environment
require '../load.php';
// Handle request
$controller = new App\Controllers\Controller();
$content = $controller->doRequest();
// Output the content
echo $content;
// Terminate script with die() for AJAX requests (is this needed?)
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
die();
}

If you use one of those php-frameworks which can output additional data by themselves -- then you need to use exit
Also do not forget to DO NOT use ?> at the end of your script. You may leave empty line after php closing tag so your web-server will add this empty line to answer if you do not use exit
Also, do not forget about register_shutdown_function -- it will run immediatly after exit, so exit is the good way to prevent adding any other shutdown functions after echo $content;
You may not use exit in this concrete script, but also don't forget to remove ?> too

Related

Ignoring included file's exit or die

I'm looking for a method to ignoring die() or exit functions.
Here is an example
Main file:
//Here some process
include 'seconfdile.php';
Second file:
//Some process
die();
//more process
Instead of die() use return in second file.
The die() in include/child file will kill the parent script execution as well.
So, its better to use return instead of die() it will terminate only child/include file not the parent file

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

Errors when calling exit() function for fastCGI?

I've been reading that people face problems when using the exit function in their php script while running fastCGI
https://serverfault.com/questions/84962/php-via-fastcgi-terminated-by-calling-exit
http://php.net/manual/en/function.exit.php
"It should be noted that if building a site that runs on FastCGI, calling exit will generate an error in the server's log file. This can quickly fill up."
However my error log isn't reporting this problem after running this simple script even though I have fastCGI configured:
<?php
$num=2;
if($num==2){
exit();
}
?>
Would it be safe to use the exit function while I have fastCGI configured? And are there any alternatives to the exit function in php?
EDIT: I'm using the exit() function form form validation (ie if a form is valid exit, if not parse all the posted variables into the text fields.)
There are a few legitimate reasons to use exit() which is the same as die(). One example would be to follow a header Location: redirect.
Form validation is not the place to use die(). Structure your code so that you utilize functions or classes with methods that return values instead, and utilize branching logic.
In terms of fastcgi, if exit is used appropriately for situations where code is reached that should not be, then those situations will be atypical and a few log messages should not be a problem. Having a log file fill up seems a pretty silly reason not to do something -- an active webserver is logging every request and nobody argues that you shouldn't have a web log.
There's a really nice alternative to exit() posted on the exit() man page by
"dexen dot devries at gmail dot com":
If you want to avoid calling exit() in FastCGI as per the comments
below, but really, positively want to exit cleanly from nested
function call or include, consider doing it the Python way:
define an exception named `SystemExit', throw it instead of calling
exit() and catch it in index.php with an empty handler to finish
script execution cleanly.
<?php
// file: index.php
class SystemExit extends Exception {}
try {
/* code code */
}
catch (SystemExit $e) { /* do nothing */ }
// end of file: index.php
// some deeply nested function or .php file
if (SOME_EXIT_CONDITION)
throw new SystemExit(); // instead of exit()
?>

PHP header in a loop

Is it possible to "call" a PHP script in a loop like this ?
...
while (...)
{
...
header("Location:myscript.php");
...
}
...
Nope. header("Location: ...") is supposed to redirect the browser to a different page, so only one of the calls you make will take effect.
What do you want to do?
You can always include the script from another to execute it's logic:
include('myscript.php');
In principle, this shouldn't require refactoring any myscript.php code. Be forewarned - myscript.php and the containing script will share the same global namespace, which may introduce bugs. (For instance, if the container outputs HTML and myscript calls session_start() a warning will be generated).
What you propose should work fine, however not in the way you expect. The header() function simply sends information to the browser in a single batch before the script content (You modify the http headers). So when the script finishes execution the browser will go to the specified page, hence only the last call to header('Location... will have any effect and that effect will only happen when the php script has finished executing.
A good way to do what I think you want to do would be to encapsulate the functionality of 'myscript.php' into a function.
include 'myscript.php';
while (...)
{
...
myscriptFunction();
...
}
...
You can call header() in a loop, but with the location header, the browser will only follow one.
location:<url> tells the browser to go to the url specified. it is known as a 301 redirect. Why you would call it in a loop, I don't know.
No. Rather pass it as a request parameter, assuming you're trying to redirect to self. E.g.
<?php
$i = isset($_GET['i']) ? intval($_GET['i']) : 10; // Or whatever loop count you'd like to have.
if ($i-- > 0) {
header("Location:myscript.php?i=" . $i);
}
?>
I however highly question the sense/value of this :)
Update, you just want to include a PHP script/template in a loop? Then use include() instead.
while ( ... )
include('myscript.php');
}
If it contains global code, then it will get evaluated and executed that many times.

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