I'm writing a bit of the code and I have parent php script that does include() and includes second script, here is snippet from my second code:
echo ($GLOBALS['key($_REQUEST)']);
I'm trying to grab a key($_REQUEST) from the parent and use it in child, but that doesn't work..
this is when I run script using command line:
mbp:digaweb alexus$ php findItemsByKeywords.php test
PHP Notice: Undefined index: key($_REQUEST) in /Users/alexus/workspace/digaweb/findItemsByKeywords.php on line 3
PHP Stack trace:
PHP 1. {main}() /Users/alexus/workspace/digaweb/findItemsByKeywords.php:0
mbp:digaweb alexus$
i heard that globals isn't recommended way also, but i don't know maybe it's ok...
$_REQUEST is a superglobal and will be directly available inside of any function or script, so you don't need to worry about passing it to the child script. However, PHP won't populate $_REQUEST when used from the command line, unless you're using a configuration option I'm unfamiliar with. You'll need to use the $_SERVER['argv'] array.
Globals are indeed not recommended. You'll have an easier time long-term if you go with what outis suggested. Here's an example:
script1.php:
<?php
$file = $_SERVER['argv'][1]; // 0 is the script's name
require_once ('script2.php');
$result = doSomething ($file);
echo $result;
?>
script2.php:
<?php
function doSomething ($inputfile)
{
$buf = file_get_contents($inputfile);
$buf = strtolower($buf); // counts as something!
return $buf;
}
?>
This example doesn't make use of the key($_REQUEST), but I'm not sure what the purpose of that is so I just went with $_SERVER['argv'].
Based on your comment to my other answer, I think I understand what you're trying to do. You're just trying to pass a variable from one script into another script that's included.
As long as you define a variable before you include the script, it can be used in the included script. For instance:
// script1.php
$foo = 'bar';
include_once('script2.php');
// script2.php
echo $foo; // prints "bar"
echo $_GLOBALS[key($_REQUEST)];
You just need to remove the single quotation marks. It was looking for the literal 'key($_REQUEST)' key, which obviously doesn't exist.
It all depends on what you are trying to do though... what are you trying to do?
Related
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';
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... :)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP passing $_GET in linux command prompt
i want execute php file with Shell script but i dont know how i can pass GET variables.
This script "php script.php?var=data" don't work because Shell can't find the file "script.php?var=data".
So ,do you know how i can pass my variables ? If it's really impossible to use GET variable, can i pass variables by an other way and use it in my php script ?
If you're executing your script via the command-line (such as php your_script.php), you will not be able to use the $_GET parameters, as you're experiencing.
However, you can make use of PHP's CLI which graciously gives you the $argv array.
To use it, you will call your script like this:
php your_script.php variable1 "variable #2"
Inside your script, you can access the variables with:
<?php
$variable1 = $argv[1];
$variable2 = $argv[2];
?>
My idea would be to write some kind of wrapper script to feed to /usr/bin/php and give that a string of arguments to grab the data from. Make no mistake, it is a hack and probably not a good one at that, but it should get the job done.
<?php
/** Wrapper.php
**
** Description: Adds the $_GET hash to a shell-ran PHP script
**
** Usage: $ php Wrapper.php <yourscript.php> arg1=val1 arg2=val2 ...
**/
//Grab the filenames from the argument list
$scriptWrapperFilename = array_shift($argv); // argv[0]
$scriptToRunFilename = array_shift($argv); // argv[1]
// Set some restrictions
if (php_sapi_name() !== "cli")
die(" * This should only be ran from the shell prompt!\n");
// define the $_GET hash in global scope
$_GET;
// walk the rest and pack the $_GET hash
foreach ($argv as $arg) {
// drop the argument if it's not a key/val pair
if(strpos($arg, "=") === false)
continue;
list($key, $value) = split("=", $arg);
// pack the $_GET variable
$_GET[$key] = $arg;
}
// get and require the PHP file we're trying to run
if (is_file($scriptToRunFilename))
require_once $scriptToRunFilename;
else
die(" * Could not open `$scriptToRunFilename' for inclusion.\n");
?>
PHP CLI takes variables within a command structure like:
php woop.php --path=/home/meow/cat.avi
You can then use something like http://php.net/manual/en/function.getopt.php to get that option like so in your PHP script:
getopt('path')
Or you can get them directly form argv.
As an alternative as #GBD says you can use a bash script to wget a page of your site as well.
I have a php script, let's call it main_script.php and if you run it through a console it returns bunch of interesting data.
I have another script, let's call it second_script.php.
in second_script.php I am using shell_exec command such as
$main_script = "php main_script.php --array=true";
$output = $shell_exec($main_script);
That will, however, return output from main_script.php
What if I want main_script.php return an array. Something like this
if ($con->console_parm['array'] ){
$whatever = array("test"=> "data son!");
return $whatever;
}
Is there a way I can execute it through second_script.php and get that array?!
If you print serialize($whatever); in the main script, and say $array = unserialize($output); in the second script, you'll basically end up with a copy of the main script's array.
Just be sure that there's no extra output from the main script (i'm not sure how whitespace, for example, will affect unserialization...but it certainly can't help). And if your array has objects in it, be sure those classes are loaded (or can be autoloaded) in the other script...or you'll end up with a bunch of "incomplete class" objects that won't be useful for much.
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.