Search code examples
phpxmlheadervimeoreferrer

PHP - Anyway of setting a referrer when using simplexml_load_file to load an XML file from a URL?


Vimeo.com allows restricing video embedding to specifics domains. However when embedding a video I have a script that queries Vimeo for details on the video. This request is made via PHP's simplexml_load_file() function, the target url is the Vimeo video URL. Since the referrer field is blank however Vimeo does not allow access to the video and the script cannot get any video details.

Unfortunately Vimeo does not allow whitelisting IP addresses, the only way around this privacy setting is to set a referrer to make it look like the request is coming from a browser trying to watch the video on my site.

I need to know how I can set a referrer- I'm not seeing any way- hoping there is something I missed.

The specific line is:

  $sxml = simplexml_load_file($target_url);

Solution

  • Yes you can. You can set all headers you want to including the referrer for simplexml_load_file by setting the header field in the so called stream context for that function.

    This is done via libxml_set_streams_context.

    Code example (the pinback does not work, it just shows that loading XML works and how to set headers):

    $options = [
        "http" => [
            "header"        => "Accept-language: en\r\n" .
                               "Referer: http://www.example.com\r\n",
            "ignore_errors" => true,
        ]
    ];
    $context = stream_context_create($options);
    libxml_set_streams_context($context);
    
    $url = "http://vimeo.com/_pingback";
    
    $sxl = simplexml_load_file($url);
    $sxl->asXML("php://output");
    

    Releated question:

    • simplexml_load_file problems - An answer there shows how to use stream contexts with file_get_contents then passing the HTTP response body to simplexml_load_string.