when we use return in PHP on global scope, after return, does execution just stop?
or processing will go on?
<?php
if(defined("A")) return;
define("A", true);
echo "Hello";
if(defined("A")) return;
define("A", true);
echo "Hello";
?>
If you want to stop a script, you'd better use exit, because return should be only used in functions !
http://php.net/manual/en/function.return.php
http://php.net/manual/en/function.exit.php
In your case, the script will end as said by the documentation : return will also end the execution of an eval() statement or script file
Your script will be stopped after first return
As documenation says:
If return is called from within the main script file, then script
execution ends
Related
I have php file where i use if statments and i call this file via ajax.. onSuccess it gives me result if file is upload successfully or error.
Code look like this:
if(empty($_FILES['file']['name'])){
return "no image was selected";
}
if($two_many_images){
return "Only x images are alowed to upload";
}
if($size>2014522){
return "Size error";
}
foreach($_FILES["file"]['tmp_name'] as $key=>$imgLocation){
uploadImage($_FILES["fileToUpload"]['tmp_name'][$key], $imgLocation);
}
Question : In first if statment condition is true, wil my second if statment execute ?
This can be easily demonstrated, for example you have a function:
funciton foo(){
echo "foo\n";
return;
echo 'bar';
}
if you call
foo();
It will print out
foo
But not bar. Once execution pointer hits the return it will return back to where foo() was called from. This can also be easily shown.
foo();
foo();
foo();
Prints
foo
foo
foo
UPDATE: based off your comments the correct way to do what you want is this
if(empty($_FILES['file']['name'])){
echo "no image was selected";
exit();
}
if($two_many_images){
echo "Only x images are alowed to upload";
exit();
}
if($size>2014522){
echo "Size error";
exit();
}
foreach($_FILES["file"]['tmp_name'] as $key=>$imgLocation){
uploadImage($_FILES["fileToUpload"]['tmp_name'][$key], $imgLocation);
}
I use exit() instead of return, because it's more readable and makes more sense, even though in your case return has the same effect. Exit will completely end execution for php, which is really what you want. You could also do something like
die( 'Message' );
Or
exit( 'Message' );
As well which will exit and output the message. They are all pretty much the same... I put echo first just because it always feels a bit dirty to me to put stuff in exit. Not sure why that is, maybe it I link it to unintended behavior because of seeing die() so much at the top of files not meant to be ran outside of framework. But I digress.
Just for the sake of completeness, based of your comments, if you call return from the global scope in PHP, it has no where to return to so execution just halts at that point. The reason it's better to use exit or die is that return has distinctly different behavior, which is to 'return' data from a function call. So it's more readable to use the method who's behavior best matches what you want. That being to end execution of the current script ( PHP instance ).
No, your second statement will not be executed. When the return is invoked, the rest of the code will not be executed. The PHP documentation says:
If called from the global scope, then execution of the current script file is ended.
Working with an MVC framework and the controller renders the page in the destructor. I am downloading a file through php, so at the end of the action the script should end.
How to end the script without calling the destructor?
Is there a better solution?
exit and die call the destructor.
See this answer.
Try creating a destructor in the class that downloads the file that checks if a file was indeed sent to the browser, and if so, call exit() in that destructor.
As David said: you'll need to call exit() inside a destructor to stop it.
If however you just want to halt the visual output caused by these destructors but not any other side-effects (file closing, database connection closing) they might do, then it's best to just kill the further output but leave the destructors alone. Which in my opinion would be the route to take since destructors tend to be there for one important reason: cleaning up.
you can do that by manipulating buffered output:
<?php
class Tester{
public function devNull($string){
return "";
}
public function runAndBreak(){
print "run" . PHP_EOL;
// if any output buffer is working, flush it and close it
if(ob_get_level()) ob_end_flush();
// redirect new buffer to our devNull
ob_start(array($this,'devNull'));
exit();
print "still running";
}
function __destruct(){
print "destructor" . PHP_EOL;
}
}
$t = new Tester();
$t->runAndBreak();
this will only print run and not what's in the destructor. It's done by giving your own callback routine to ob_start that handles and then returns the output. In our case here we simply discard it by returning an empty string.
This will certainly stop your script but be careful, if you run such a server where one process serves several PHP requests those will stop as well:
$pid = getmypid();
exec("kill $pid");
exec("TSKILL $pid");
Is there a way to use the die() function to stop executing PHP statements on a page included on another page, but continue the execution of PHP statements on the page on which the file containing the die() function was included?
use return; in your included file. It will stop this include execution. It works like a function. Also you can return a value from your included file
No. die is an alias for exit which immediately stops all script execution.
But you can use return instead, which does exactly what you want:
If called from the global scope, then execution of the current script file is ended. If the current script file was include()ed or require()ed, then control is passed back to the calling file. Furthermore, if the current script file was include()ed, 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.
As stated in the excerpt from the PHP docs, you can even use it to give a exit code / return value back from the include:
$include_retval = include('file_like_function.php');
if ($include_retval) {
die("include returned error code: " . $include_retval);
}
No. You could use try blocks instead?
try
{
include $file;
}
catch (Exception $e)
{
// Whatever
}
And throw an exception where you would use die() in $file.
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();}
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.