如何从远程file_get_contents获取引用者

时间:2014-07-04 19:20:51

标签: php json referrer

我设置了一个输出JSON的PHP脚本,如下所示:

<?php
 // ref.php
print json_encode(array('ref' => $_SERVER["HTTP_REFERER"]), JSON_UNESCAPED_SLASHES);
?>

上面的代码是该文件中的所有代码。从另一个文件我尝试读取输出如下:

<?php
// ref_index.php
$json = file_get_contents('http://localhost/4test/ref.php'); 
$data = json_decode($json);
var_dump($data);
?>

上面的代码返回NULL,因为ref.php无法获得$_SERVER["HTTP_REFERER"]值,所以当我用任何固定值替换$_SERVER["HTTP_REFERER"]时,例如&#39; blahh blahh`它会返回json对象

我的问题是:我怎样才能获得file_get_contents()的引用,即它运行的url以从我的应用程序中获取数据。

1 个答案:

答案 0 :(得分:1)

使用HTTP中的Origin标头传输引荐来源。您需要在file_get_contents()来电中设置该标头。为此,您需要使用stream_context_create()使用自定义的流上下文,并将其作为第三个参数传递给file_get_contents()

$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Origin: SET REFERRER URL HERE"
  )
);

echo file_get_contents(
    'http://localhost/4test/ref.php',
    false,
    stream_context_create($opts)
);