phpjsonreferrer

How to get the referer from remote file_get_contents


I set a PHP script that output JSON like the following:

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

The above code is all the code in that file. From another file I tried to read the output as follows:

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

The above code returns NULL because the ref.php failed to get the $_SERVER["HTTP_REFERER"] value, so when I replace $_SERVER["HTTP_REFERER"] with any fixed value, such as 'blahh blahh` it returns json object.

My question is: How could I get the referral of file_get_contents() i.e the url that it runs from to get data from my application.


Solution

  • The referrer is transferred using the Origin header in HTTP. You would need to set that header in your file_get_contents() call. To achieve this, you would need to use a customized stream context using stream_context_create() and pass that as the third param to 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)
    );