Skip the rest of the (included) file in PHP - php

I'm including file inner.php in outer.php, I have a condition in inner.php on which I want to stop executing inner.php but NOT the whole script, i.e. I want to jump to the first line in outer.php after the inclusion of inner.php, and I don't want to wrap all of the code in inner.php in an if statement.
Is there a way to do this otherwise?

Just do return; or return($value); on top level of the inner.php file.
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.

You can just call return in your include file, but if you're having to do this then it suggests there is something wrong with your architecture. For example, consider this include file:
<?php
// include.php
echo "This is my include";
return;
echo "This is after the include";
..included on the following page:
<?php
// index.php
include('include.php');
The output you'd get is: This is my include.

How about having two files for inner. The first and the second part and place the condition on the second include?

Throw an exception on the point where you want to stop
// in inner.php:
// ...some code...
throw new Exception('Error description');
// ...some code which will not always execute...
and catch it in the file where you want to resume
// in outer.php
try {
include 'inner.php';
} catch (Exception $e) {
//TODO: add error handling here
}
UPDATE
Unlike using return; as other answers here suggest, using exceptions will break anywhere, even if you're in some function inside inner.php

Related

Include file and nothing else in PHP?

I am currently including a new php file to an already existing page in the form of
if (...) {
...
}
include("old_file");
Is there a way to include this new file in the conditional without changing the part outside / including an else?
e.g.
if (...) {
Code that should be executed if condition is set.
include("new_file");
}
Code that should not be executed if condition is set.
include("old_file");
...
You can call exit to stop execution, or call return inside an included file (probably works fine outside an include as well).
if (...) {
Code that should be executed if condition is set.
include("new_file");
exit(); // terminates execution
}
// Code that should not be executed if condition is set.
include("old_file");
...
if (...) {
// Code that should be executed if condition is set.
include("new_file");
return; // <-- now you skip the rest of the file. Actually, everything after the if block.
}

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 it possible to ignore exit of child script from parent script in PHP?

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.

PHP Include file but only first few lines

I am using PHP Include:
<?php include 'file1.php'; ?>
i want to only include the first few lines of file1.php - is this possible?
If you really want to include (run as PHP), then just pull those lines out into a new file:
new.php:
<?php
// line 1
// line 2
And include it in both files:
existing.php and other.php:
<?php
include('new.php');
...
<?php
$return_from_inc = include('file1.php');
?>
file1.php
<?php
if ($x === 1) { return 'A'; }
else { return 'B'; }
//... return ("break") running script wherever you want to
?>
Depending on the content of those first lines, why don't you use PHP Functions?
file1.php
<?php
function what_i_want_to_include(){
//"First lines" content
}
}
existing.php
<?php
include('file1.php');
what_i_want_to_include();
?>
Using functions it's the simplest way to do it.
You can simply use return on the line of your choice and control will be sent back to the calling file.
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 will also end 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.
Source: PHP Manual
There are a few options to achieve this, but let me stress out that if this is necessary for your application to work you should really consider reviewing the app design.
If you want it programatically you can either grab the first x lines and use eval() to parse them. Example:
$file_location = '/path/to/file.php';
$number_of_lines = 5; //
$file_array = file($file_location);
if(!$file) {
return false; // file could not be read for some reason
}
$first_lines = array_slice($file_array, 0, $number_of_lines);
$to_be_evaluated = implode('', $first_lines);
eval($to_be_evaluated);
But you should take not that eval expects a string without the php opening tag (<?php), at least, not at the start. So you should search for it and delete it in the first line (if present):
if(strpos($first_lines[0], '<?php') !== false) {
$first_lines[0] = substr(strpos($first_lines[0], '<?php') + 5);
}
Another, and better option, and as suggested above, just pull out the required lines, save them to another file, and include them in both. You could also do this programatically, you could even extract the needed lines and save them to a temporary file on the fly.
Edit it is a 'weird' question, in the sense that it should not be necessary. Could you explain what exactly you are trying to do? Most probably we can come up with a nice alternative.
Edit
As I understand it correctly you have in the file-to-be-included a lot of stuff, but only the database settings are needed. In that case, put them elsewhere! Example:
settings.php
$connection = new mysqli($host, $user, $pass, $db);
if($connection->connect_error) {
die('This failed...');
}
header.php
<?php require_once('settings.php'); ?>
<html>
<head>
<title>My awesome website</title>
... other stuff
</head>
other_file.php
<?php
require_once('settings.php');
$r = $connection->query('SELECT * FROM `my_table` WHERE `random_field`=`random_value`');
etc. etc.
In settings.php you could also put everything in functions to ensure pieces are only executed when needed. You could in example create a get_connection() function, which checks if a database connection exists, otherwise creates it and returns it for usage.
No need for fancy eval() functions at all!
Please bear in mind that it isn't a crime to divide your application in a thousand files. It really isn't!

PHP die() from included page without dying from main page

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.

Categories