how to stop the current included execution in PHP? - php

I know it sounds a bit hacky but is there a way of stopping the execution of an included script in php ? Giving this example here
Is there a function or a tiny trick to use to have this effect here ?
note 1 : I know b.php in the example has a closed conditional structure but if there is code after that structure It will get executed.
note 2 : exit will stop the whole php running execution, that is not what I need.

You can use a return statement in the included file to return to the file that includes it.
From the documentation of include:
It is possible to execute a return statement inside an included file in order to terminate processing in that file and return to the script which called it.

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

stop php execution instead of just a php script in codeigniter

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

PHP exit() from within included script, exit parent script?

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');

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.

Categories