How to load the result of a php function into a variable - php

I have a php file on my server that takes in two inputs through the URL and then comes back with a result. When a page is loaded, I'd like to have the result of that calculation already loaded. For example:
$var = load("http://mysite.com/myfile.php?&var1=var1&var2=var2");
I know that load isn't a real function for this, but is there something simple that suits what I'm looking for? thanks

Use file_get_contents
$foo = file_get_contents('http://mysite.com/myfile.php?&var1=var1&var2=var2');
Or, a better solution if the file is located on your server:
include('myfile.php');
and either set the $_GET variables in the included script itself, or prior to including it.

If they are running on the same server, consider calling the script directly?
$_GET["var1"] = "var1";
$_GET["var2"] = "var2";
include "myfile.php";

You could use file_get_contents, but it may be a more practical solution to simply include the file and call the function directly in the file, rather than trying to manually load the file.

Related

Calling a function from another PHP script via HTTP: is it slower or anything else?

Let's say I have a PHP file some_function.php which I can run with file_get_contents('some_function.php?' . $parameters_string) (or any similar function). The parameters to this function can be given via either GET or POST HTTP method.
Instead I could include needed file and use this function within one script.
I could figure out that it could be reasonable if I need to run a separate process or I need this function to be on a separate server. But if not, is there any reasons not to do it? May be this call will be much slower? Anything else I should take into account?
I know that I will not be able to use global variables (which I assume as a bad coding style anyway).
By using file_get_contents() you will not be actually calling the function in question but will make an HTTP request passing some predefined parameters which will then be passed on the function in your code.
Using include() you could have a library of classes or functions inside that file, and call them directly as needed and as many times as needed.
EXAMPLE:
library.php
function my_function_1() { }
function my_function_2() { }
index.php
include('library.php');
my_function_1(); // call the first function
my_function_2(); // call the second function
my_function_1(); // call the first function again, just because we can
You wouldn't be able to do that through the HTTP request and even if you did hardcode your some_function.php file to do some functionality like above, you would end up with really bad code that would be hard to customize to your needs and near impossible to maintain once it gets bigger.
You cannot pass a query string via a local file_get_contents call as shown.
If you use file_get_contents on a remote HTTP URL, you will be able to use a query string, but this will be significantly slower than a local include or file_get_contents.
You can, incidentally, still include something that needs $_GET/$_POST variables:
<?php
$_GET['something'] = true;
include('something.php');

How to Capture PHP Output into a Variable

I've been wanting to do this because my site does about 3 HTTP requests per page load, because each PHP's output is retrieved with cURL. This is too slow, and I want to avoid using cURL. I found this question on Stack Overflow, and it basically does what I want. The accepted answer's suggestion is to use ob_start(); to start getting output then use ob_get_clean(); to put the output into a variable. My issue now is that the PHP scripts I'm trying to capture output from need variables passed to them using HTTP Get. The access those variables like this:
$term = $_GET['term'];
And I don't want to change that, because although I'm going to access these PHP scripts' outputs from another PHP script, I'm also planning on accessing them from elsewhere. So, is there a way to fool these PHP scripts into accepting some arguments through Get, then capturing their outputs with the method suggested above?
You can $_GET variables from any php script if its set (use isset to check that). Then just cURL to such url's will work.
If you have changed the method to POST earlier, you can use CURLOPT_HTTPGET. See the curl_setopt functions page (http://www.php.net/manual/en/function.curl-setopt.php) for more details.
For a non-cURL method, use jQuery ajax. It is quite simple to use, just read the documentation here.
EDIT: This is what you wanted (haven't checked the code though)
<?php
function get_include_contents($filename, $get) {
if (is_file($filename)) {
ob_start();
$_GET = array();
while (list($key, $val) = each($get)) {
$_GET[$key]=$val;
}
include $filename;
return ob_get_clean();
}
return false;
}
$string = get_include_contents('somefile.php', array('param1'=>'x', 'param2'=>'y'));
?>
And I don't want to change that, because although I'm going to access these PHP scripts' outputs from another PHP script, I'm also planning on accessing them from elsewhere. So, is there a way to fool these PHP scripts into accepting some arguments through Get, then capturing their outputs with the method suggested above?
Your question is a bit unclear as to why you're using cURL in the first place. If your scripts are on the same server, you can simply set the correct $_GET variables and use:
<?php
ob_start( );
// include the file.
$_GET['foo'] = 'bar';
include 'the_file.php';
$output = ob_get_clean( );
If your scripts are located on another server, where include is not viable, you will always have to do a HTTP request to get their contents, regardless of whether your this with cURL or Ajax, or sockets for all I care.
well you can access a $_GET from any script loaded as long as its in the URI, the variable $term can be used in any script. You can also include the script.
When you include a script you can access some of its content after the include.

PHP include with HTTP get paramters

How would one go about using php include() with GET paramters on the end of the included path?
IE:
include("/home/site/public_html/script.php?id=5");
How would one go about using php include() with GET paramters on the end of the included path?
You could write into $_GET:
$_GET["id"] = 5; // Don't do this at home!
include(".....");
but that feels kludgy and wrong. If at all possible, make the included file accept normal variables:
$id = 5;
include("....."); // included file handles `$id`
You don't, include loads files via the local filesystem.
If you really wanted to, you could just do this, which would have the same result.
<?php
$_GET['id'] = 5;
include "/home/site/public_html/script.php";
?>
but then you might as well just define the variable and include it
<?php
$id = 5;
include "/home/site/public_html/script.php";
?>
and reference the variable as $id inside script.php.
Well you could use:
include("http://localhost/include/that/thing.php?id=554&y=16");
But that's very seldomly useful.
It might be possible to write a stream wrapper for that, so it becomes possible for local scripts too.
include("withvars:./include/that/thing.php?id=554");
I'm not aware if such a solution exists yet.

What is the difference between include() and calling a function in PHP?

What is the difference between include() and calling a function in PHP?
For example :
1-
<?php
$foo = '<p>bar</p>';
return $foo;
?>
<html><body><?php echo $foo; ?></body></html>
2-insert above php code in a php file and include()
thanks in advance
include() simply takes the full contents of the file and inserts it in, replacing the include() with the contents of the file.
If you have HTML in the included file, it will be output. If you only have PHP in it, the PHP will be run.
To call a function, the function must be available. If the function is in another file, you will still need to include() or require() that file to have it available.
Generally, including is used to get a set of functions or objects into your running script, so that they can be used, although it can also be used as a standalone page or some bit of HTML, like you posted. In reality, it depends on whether you'd rather have another function on the same script or in a remote script, for aesthetics or organization, whatever your reason.
Functions will usually run a bit faster, as server response time and parsing time may make the include function run a bit slower, but for all intents and purposes you wont notice much. Most of the lag will be due to the fact that a local function will be executed with the page, whereas the include function must execute the page, load another page, and then execute that page as well. If that makes sense.
Just as an addition to the existing answers, you can also do this:
sample.php:
<?php
$foo = include('include_with_return_value.php');
?>
<html><body><?php echo $foo; ?></body></html>
and include_with_return_value.php:
<?php
return '<p>bar</p>';
So, include() files can also have a return value, just like functions.

passing URL variables to exec() with php

I have a dedicated server that I use to crunch lots of data. The way I have it now, I can open a script with a process ID like example.php?ex_pid=123 and just let it go. It downloads a small portion of data, processes it, then uploads it into a database then starts again.
Ideally, I would like to call example.php?ex_pid=123 directly and not by passing a variable to example.php like exec('./example.php'.' '.EscapeShellArg($variable)); to keep it from acting globally.
I don't care about the output, if it could execute in the background, that would be brilliant. The server is an Ubuntu distribution btw.
Is this even possible? If so, any help and examples would be more then appreciated.
You could do something like:
exec("./example.php '".addslashes(serialize($_GET))."');
And then in example.php do something like this:
count($_GET) == 0 && $_GET = unserialize(stripslashes($_SERVER['argv'][1]))
The main issue with that is that ?ex_pid is GET data which is generally associated with either including the file or accessing it through a browser. If you were including the file or accessing it from a web browser this would be trivial, but running it as CLI, your only option would be to pass it as an argument, unfortunately. You can pass it as ex_pid=123 and just parse that data, but it would still need to be passed as an argument but doing that you could use parse_str() to parse it.
Depending on what the script does, you could call lynx to call the actual page with the get data attached and generate a hash for an apikey required to make it run. Not sure if that is an option, but it is another way to do it how you want.
Hope that helps!
I had a real problem with this and couldn't get it to work running something like example.php?variable=1.
I could however get an individual file to run using the exec command, without the ?variable=1 at the end.
What I decided to do was dynamically change the contents of a template file , depending on the variables I wanted to send. This file is called template.php and contains all the code you would normally run as a $_GET. Instead of using $_GET, set the value of the variable right at the top. This line of code is then searched and replaced with any value you choose.
I then saved this new file and ran that instead.
In the following example I needed to change an SQL query - the template file has the line $sql="ENTER SQL CODE HERE";. I also needed to change the value of a a variable at the top.
The line in template.php is $myvar=999999; The code below changes these line in template.php to the new values.
//Get the base file to modify - template.php
$contents=file_get_contents("template.php");
$sql="SELECT * FROM mytable WHERE foo='".$bar."'";
$contents=str_replace("ENTER SQL CODE HERE",$sql,$contents);
//Another search
$contents=str_replace("999999",$bar,$contents);
$filename="run_standalone_code".$bar.".php";
//If the file doesnt't exist, create it
if(!file_exists($filename)){
file_put_contents($filename, $contents);
}
//Now run this file
$cmd="/usr/local/bin/php ".$filename." >/dev/null &";
exec($cmd);
I had completely forgotten about this question until #Andrew Waugh commented on it (and I got an email reminder).
Anyways, this question stemmed from a misunderstanding as to how the $argv array is communicated to the script when using CLI. You can pretty much use as many arguments as you need. The way I accomplish this now is like:
if (isset($argv)) {
switch ($argv[1]) {
case "a_distinguishing_name_goes_here":
$pid = $argv[2];
sample_function($pid);
break;
case "another_name_goes_here":
do_something_else($argv[2]);
break;
}
}

Categories