Return from include file - php

in PHP, how would one return from an included script back to the script where it had been included from?
IE:
1 - main script
2 - application
3 - included
Basically, I want to get back from 3 to 2, return() doesn't work.
Code in 2 - application
$page = "User Manager";
if($permission["13"] !=='1'){
include("/home/radonsys/public_html/global/error/permerror.php");
return();
}

includeme.php:
$x = 5;
return $x;
main.php:
$myX = require 'includeme.php';
also gives the same result
This is one of those little-known features of PHP, but it can be kind of nice for setting up really simple config files.

return should work, as stated in the documentation.
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.

I know that this has already been answered, but I think I have a nice solution...
main.php
function test()
{
$data = 'test';
ob_start();
include( dirname ( __FILE__ ) . '/included.php' );
return ob_get_clean();
}
included.php
<h1>Test Content</h1>
<p>This is the data: <?php echo $data; ?></p>
I just included $data to show that you can still pass data to the included file, as well as return the included file.

Hm, the PHP manual disagrees with you. return should bail you out of an included file. It won't work from within a function, of course.

See Example #5 in the documentation for include.
You can get the return value of the script when including it, like:
$foo = include 'script.php';

Related

Understanding PHP Script Return [duplicate]

in PHP, how would one return from an included script back to the script where it had been included from?
IE:
1 - main script
2 - application
3 - included
Basically, I want to get back from 3 to 2, return() doesn't work.
Code in 2 - application
$page = "User Manager";
if($permission["13"] !=='1'){
include("/home/radonsys/public_html/global/error/permerror.php");
return();
}
includeme.php:
$x = 5;
return $x;
main.php:
$myX = require 'includeme.php';
also gives the same result
This is one of those little-known features of PHP, but it can be kind of nice for setting up really simple config files.
return should work, as stated in the documentation.
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.
I know that this has already been answered, but I think I have a nice solution...
main.php
function test()
{
$data = 'test';
ob_start();
include( dirname ( __FILE__ ) . '/included.php' );
return ob_get_clean();
}
included.php
<h1>Test Content</h1>
<p>This is the data: <?php echo $data; ?></p>
I just included $data to show that you can still pass data to the included file, as well as return the included file.
Hm, the PHP manual disagrees with you. return should bail you out of an included file. It won't work from within a function, of course.
See Example #5 in the documentation for include.
You can get the return value of the script when including it, like:
$foo = include 'script.php';

Copying a file content to a variable

I would like to copy a php file content to a variable and execute it, not print it!
I found out that there are 2 ways:
file_get_contents('http://YOUR_HOST/YOUR/FILE.php');
In that way the code is executed but not as I want to, I will explain:
a.php:
<?php
require 'file.php';
$output = file_get_contents('http://example.com/b.php');
echo $output;
?>
b.php:
<?php
$hello = get_welcome_text();
echo $hello;
?>
When I execute file a.php I get the Call to undefined function error, I have no idea why it doesn't recognize the require line it seems like it executes b.php separately.
The other method is:
file_get_contents('path/to/YOUR/FILE.php');
This method is just print the php script instead of executing it.
So I would like to know if there is a way to copy a php file content into a variable and execute it the same way as include/require does, and please don't suggest me to use include/require because it's not what I'm looking for. thanks!
Files can return a value, so yes, you can use include.
included.php:
<?php
return 2 + 2;
parent.php:
<?php
$number = include 'included.php';
echo $number;
In first 'method' server executes separare request for your file_get_contents, so no environment from calling script will be available inside it.
Use second 'method' to get contents of the script and then just eval it.
eval(file_get_contents('http://.../b.php.txt'));
File evaluated that way can define new functionality to be plugged in calling script so that you can call some method and/or pass parameters from it.
a.php
$r = eval(file_get_contents('http://.../b.php.txt'));
if ($r) b_foo($bar);
b.php
function b_foo($baz) {
return 42;
}
return true; // module loaded ok
Surely you know that executing unverified code from third parties in server context is a bad practice, but if you really need it... :)

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!

How can I get a PHP script **results** included into another PHP script?

I'd like to include the results of a given script (let's say a.php) into another script (let's say b.php).
Although there is the PHP include statement and their other counterparts (include_once, require and require_once), it seems all of them include the file contents instead of its processing results as I would expect.
So how can I get a.php processed first and then include its results (not the file contents itself) into b.php script ?
On the other hand, if my included file (a.php) has a return statement, is the entire file expected to be processed first or its contents are also included into b.php as is ?
Thanks in advance for your replies.
a.php:
<?php
echo "world";
b.php:
<?php
ob_start();
include("a.php");
$a= ob_get_clean();
echo "Hello, $a!";
perhaps?
Sounds like you want to use the backtick operator followed by eval.
Something like this:
$code = `/path/to/myscript.php`;
eval($code);
If myscript.php isn't executable you'll have to prefix it with php, as in:
$code = `php /path/to/myscript.php`;
Note that you need to completely trust myscript.php, otherwise this is an security problem.
This probably isn't a very good design, you might want to think hard about whether or not there's a better way to do what you want.
If a.php is accessible via the web, you could use file_get_contents with an http:// (or https://) URL. This will access your script like an ordinary web page, having your web server process it through PHP and return the results.
a.php:
<?php
echo 2+2;
b.php:
<?php
echo file_get_contents('http://example.com/a.php');
Output:
4
You can also use output buffering, as mentioned in DaveRandom's comment above. That said, this is generally not exemplary application design. It's preferred to have code that will return the results you need rather than echo them. So maybe something like this:
a.php:
<?php
function calculateA()
{
return 2+2;
}
b.php:
<?php
include('a.php');
echo calculateA();
Output:
4
Edit: Several alternatives are nicely detailed on the include page in the PHP documentation.
Summary:
If php file belongs to your server:
ob_start();
$result = eval(file_get_contents('/path/to/your/script.php'));
ob_end_clean();
If not, but it's accessible via HTTP:
$result = file_get_contents('http://path.to/your/script.php');

In PHP, is there a way to capture the output of a PHP file into a variable without using output buffering?

In PHP, I want to read a file into a variable and process the PHP in the file at the same time without using output buffering. Is this possible?
Essentially I want to be able to accomplish this without using ob_start():
<?php
ob_start();
include 'myfile.php';
$xhtml = ob_get_clean();
?>
Is this possible in PHP?
Update: I want to do some more complex things within an output callback (where output buffering is not allowed).
A little known feature of PHP is being able to treat an included/required file like a function call, with a return value.
For example:
// myinclude.php
$value = 'foo';
$otherValue = 'bar';
return $value . $otherValue;
// index.php
$output = include './myinclude.php';
echo $output;
// Will echo foobar
From what I can tell in the PHP documentation, no. Why do you want to avoid output buffering?
The only way to get around this would be hacky methods involving either invoking the command line php client or doing a curl request based on what's available and what the particular requirements are.
After reading everybody's suggestions, reading a bunch of documentation, and playing around with some things, I came up with this:
<?php
$file = file_get_contents('/path/to/file.php');
$xhtml = eval("?>$file");
?>
It's as close as I could get but it unfortunately doesn't work. The key to this is to include the closing PHP bit (?>) before the contents of the file. This will take the eval() out of PHP-evaluation mode and will treat the contents of the file starting as non-PHP code. Then if there are PHP code blocks within the file, those will be evaluated as PHP. The bummer is that it doesn't save the eval'd content in the variable, it just outputs it to the page.
Thanks for the help everybody!
Joeri Sebrechts is correct.
An equivalent and slightly easier method is available if the PHP script is HTTP accessible:
$data = file_get_contents('http://google.com/');
It should be noted that using output buffering would be easier on resources.
Do a curl request to the php page, essentially pretending to be the browser.
What you could do, if the file is local, is load the script into a variable as a string, then run eval on the string. Then you can do all your other stuff afterwards. Otherwise, you have to use output buffering.
$fileData = file_get_contents('fileOnDisk.php');
$results = eval($fileData);
But check the documentation on eval, because you actually have to have the file you are calling return its results rather than just echo them:
http://us2.php.net/eval
Hack Alert! You could do the evaluation of the PHP yourself with a bit of hackery using preg_replace_callback to search and replace the PHP blocks.
function evalCallback($matches)
{
// [0] = <?php return returnOrEcho("hi1");?>
// [1] = <?php
// [2] = return returnOrEcho("hi1");
// [3] = ?>
return eval($matches[2]);
}
function evalPhp($file)
{
// Load contents
$contents = file_get_contents($file);
// Add returns
$content_with_returns = str_replace(
"returnOrEcho"
,"return returnOrEcho"
,$contents);
// eval
$modified_content = preg_replace_callback(
array("|(\<\?php)(.*)(\?\>)|"
,"evalCallback"
,$content_with_returns);
return $modified_content;
}
You would have to modify the PHP file you are including to use a returnOrEcho function so that it can be overloaded for this case and the normal case. In this case you want to return so that it will be picked up by the eval in the way you want, but the normal case is to echo without a return.
So for this case you would define:
function returnOrEcho($str)
{
return $str;
}
and for the normal case you would define:
function returnOrEcho($str)
{
echo $str;
}
In your included PHP file (or view file) you would have something like this:
<?php returnOrEcho("hi1");?>
<?php returnOrEcho("hi3"."oo");?>
<?php returnOrEcho(6*7);?>
I couldn't get preg_replace_callback inline callback working so I used a separate function, but there is an example of how to do it: preg_replace_callback() - Calback inside current object instance.

Categories