如何从URL-external-php-file获取'echo'内容

时间:2010-06-30 19:08:21

标签: php get external

我在2个不同的服务器上有2个文件:

file1.php - 居住在网站1上 - 我传递一个参数,脚本echo-ed答案依赖于(是函数)传递的参数 - 当我通过浏览器访问文件时,everithink就可以了

   http://site1.com/file1.php?parameterValue

file2.php - 居住在网站2上 - file2必须向file1.php发送一个参数并从中获取echo-ed输出作为变量。

我试图通过3种不同的方式来做,但没有人工作。

方式1. -------

function get_data($url)
{
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}  

$f="http://site1.com/file1.php?parameterValue";
$returned_content = get_data($f);
echo "=== $returned_content ===";exit;
方式2. -------

$f="http://site1.com/file1.php?parameterValue";
$returned_content='';
$file = fopen ($f, "r");
if (!$file) {
    echo "<p>Unable to open remote file.\n";
    exit;
    }
while (!feof ($file))  $returned_content.= fgets ($file, 1024);
fclose($file);
echo "=-= $returned_content =-=";exit;
方式3. -------

$f="http://site1.com/file1.php?parameterValue";
$returned_content=implode('',file($f));
echo "=-= $returned_content =-=";exit;

但是$ returned_content是空字符串......

任何人都可以帮助我吗? 提前谢谢!

赫里斯托斯

4 个答案:

答案 0 :(得分:5)

如果你尝试会发生什么:

<?PHP
$f="http://site1.com/file1.php?parameterValue";
$data = file_get_contents($f);
echo $data;

答案 1 :(得分:1)

您可以使用CURL修改您的第一个版本,以检查是否发生了任何错误。就像你一样,你盲目地假设卷曲请求有效,只返回curl_exec()返回的内容。

在mininum,你应该有类似的东西:

$data = curl_exec($ch)
$err = curl_error($ch);
curl_close($ch);
if ($data === FALSE) { // curl_exec returns boolean FALSE if something blew up
   return($err);
} else {
   return($data);
}

答案 2 :(得分:0)

我测试了所有这三种方法,并且都使用了

$f = "http://google.com/";

我会检查site1和file1.php的配置。也许是基于用户代理的阻止请求?

答案 3 :(得分:0)

这是我的错 - 我在file1中的脚本很复杂,我错过了另一个参数。因此,在我更正脚本后,一切正常。

方式2和3 的工作正确; 方式1 我没有测试过。使用 MARC B

的建议是goog的想法 TIMDEV 所假设的方式也可以正常工作。

我要感谢你们所有人给予我这么好的帮助!

谢谢各位朋友!

祝你好运 赫里斯托斯