user1010775
user1010775

Reputation: 371

calling php script within php with return value

I am trying to get a return value from a script which returns per echo "complete" or "error". First I tought I could get this working with the php function file_get_contents, but it returns my whole script, not only the things I am printing in the script. Then I believed in the cURL method, but it can't get it working....

The script which is called:

<?php 
include("config.php");
print "complete";
?>

the script with my curl:

$url="caller.php";
$ch = curl_init(); //initialize curl handle
curl_setopt($ch, CURLOPT_URL, $url); //set the url
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //return as a variable
$response = curl_exec($ch); //run the whole process and return the response
curl_close($ch); //close the curl handle

echo "test". $response."|";

Why isn't this working? And how can I get it working?! FILE Method?

Upvotes: 2

Views: 7443

Answers (5)

vfsoraki
vfsoraki

Reputation: 2307

You can use php cgi to run script and get content. Use shell_exec

Upvotes: 0

Gerald Schneider
Gerald Schneider

Reputation: 17797

Rewrite caller.php in a way that fills a variable instead of echoing text, ideally put it in a function that returns that variable. Everything else is a dirty hack, prone to error and a source for performance problems.

Upvotes: 0

jondinham
jondinham

Reputation: 8499

In the script to be called, make sure "<?php" start from the first line, first character. And, remove the "?>" away.

<?php
//this is 'to-be-called.php'
include("config.php");
echo "complete";

Now call it this way:

<?php
//this is 'caller.php'
//should it come with full url?
$Url      = "http://localhost/path/to-be-called.php"; 
$Handle   = curl_init($Url);
$Response = curl_exec($Handle);
curl_close($Handle);

echo $Response;

Or take Jeroen's answer, it's the best way for calling on the same server! If you need to pass in parameters in POST/GET, tell 'caller.php' to save these values in global variables, then tell 'to-be-called.php' to get from these global ones.

Upvotes: 0

Ignas
Ignas

Reputation: 1965

As far as I know, you need a valid http (or other protocol) with a full URL to the script for curl to work e.g. http://localhost/caller.php

Or try jeroen's solution and get the output of the script.

Upvotes: 0

jeroen
jeroen

Reputation: 91792

If you want to capture the echoed values of an included script, you can use output buffering:

<?php
ob_start();    // start output buffering
include("caller.php");
$returned_value = ob_get_contents();    // get contents from the buffer
ob_end_clean();    // stop output buffering
?>

Upvotes: 5

Related Questions