In PHP, if I use the include() or require() functions to start running code in another script, is there a way to terminate the parent script from within the child?
So say I have this in parent.php:
require('child.php');
And this in child.php:
exit();
Will that terminate just child.php, or parent.php as well?
Is there a way to terminate parent.php from within child.php, without adding any further code to parent.php?
It's for an elaborate custom 404 error page in PHP which detects whether it's been called by Apache using ErrorDocument, or whether a user has requested a page from our custom CMS which doesn't exist. If it's the latter, then I want to just require my 404.php (child) and output from that and not continue executing the parent.
Anyone know if it's possible to terminate a parent PHP script from within an included/required script?
exit();
Will that terminate just child.php, or parent.php as well?
It will terminate the entire script.
If you don't want to do that, but return to the including script, you can return from within an include.
You are looking for return; command. This will terminate execution of only the child.php, and parent.php will be processed after that.
You can use return if you need to exist included file but continue from main script.
return
(PHP 4, PHP 5, PHP 7)
return returns program control to the calling module.Execution resumes at the expression 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
Anyone know if it's possible to
terminate a parent PHP script from
within an included/required script?
You can use
die();
to end the furthur execution of any script at any point. Use of Die puts an end to the parent scripts as well.
die("End");
Will output "end".
Actually an exit; line in your child.php will terminate current php process that means parent.php will be terminated well.
You can also terminate an script by throwing an exception and catch it in one of the parent scripts.
This way you can control with precission which scripts to terminate and where to continue in the stack of "include / require" files.
die and exit will both terminate without prejudice. It is an application level command which cannot be caught or undone.
Using exit() will stop script execution and terminate the child and all parents.
You can try to throw an exception:
throw new Exception('An Error Ocurred');
Related
A child script terminates the parent script because it has exit;
Since it is a third party extension, I need to avoid any core hack. Would it be possible somehow to ignore the exit of the child script from parent script. I am calling its controller and a method from an external script.
parent.php
<?php
require "child.php";
?>
child.php
<?php
does something;
exit;
?>
Update
Any alternative solution would be fine as long as we dont modify the child script.
Is it possible to ignore exit from included script in PHP?
No.
exit terminates execution of the script regardless from where it is called.
As noted in sjagr's answer, there are alternatives to using exit.
If you do in fact end up editing the core files, then it is possible to use return inside of the "child script." From the PHP docs:
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.
However, there is no way to prevent the parent script from preventing a child script from killing the process if it has an exit statement. Unfortunately you cannot override this functionality.
You might be able to run child.php in a thread. Use join to wait until that thread finishes before continuing with the main thread. This way, calling exit in child.php will terminate the child thread and the main thread will continue.
class myThread extends Thread {
public function run(){
include "child.php";
//Call methods from child.php here
}
}
$thread = new myThread();
$thread->start();
$thread->join();
Thank you so much everyone for answering the question. Finally I came up with the following alternative idea. I am not sure if it is similar to any design pattern. The following example does not get terminated from loop although the child.php has exit.
parent.php
<?php
require "temp.php";
for($i=1;$i<10;$i++){
file_get_contents("http://url/temp.php?var=$i");
}
?>
temp.php
<?php
$var = $_GET['var'];
// execute
require "child.php";
$testController = new TestController();
$testController->method($var);
?>
Yes.
In your child.php you can use a return to return the control back to the parent.php.
Otherwise if child.php isn't included, it will continue with its normal operation, which is exit.
<?php
does something;
return;
exit;
?>
If you want to check whether a file was included or run directly, you could this answer.
So in that case, make a check in the child file, if it isn't included, goto the exit command, otherwise continue with the rest of the 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
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); //
?>
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 using Codeigniter for a project and i usually call a series of models (let's say controllerA -> modelA -> modelB -> modelC) for some work. I want the php to stop executing when it reaches some exception where i invoke the exit() command. Now, if the command exit() is invoked in modelB, will it stop execution of only the script of modelB and continue executing rest of the modelA? Or will it stop the entire execution flow.
I really don't know how to put this question here. The question looks quite messy. Please let me know should i need to revise the question itself.
Yes, exit stops all script execution immediately, regardless where you call it.
The opposite is return which only stops execution of the current function (or current file when used at global level in an included file)
Read more here: https://stackoverflow.com/a/9853554/43959
Wherever you call the exit() function, all code will stop executing. This includes the other files because codeigniter just 'requires' them.
It stops the execution from that line.
I'm not sure if what you want, but maybe you can use exceptions to control PHP code execution.
http://es.php.net/manual/en/class.exception.php
Regards!
Like someone mentions above you should return from a function, or If your in a loop you could use continue or break