Question

There is a web page from a different domain that includes a script that is hosted and generated in my server. Say that page is in http://www.theirdomain.com/site and its markup is like this:

<html>
    <head>
        <script src="http://www.mydomain.com/script.php"></script>
    </head>
    <body>
        ...
    </body>
</html>

The script.php page does create and the JavaScript contents, but I want to know which is the URL that called script.php (i.e. http://www.theirdomain.com/site).

How can I get that info in PHP?

Was it helpful?

Solution

$_SERVER['HTTP_REFERER'] not 100% reliable.

OTHER TIPS

Log the referrer in your script.php to see where it came from. Like:

if(!empty($_SERVER['HTTP_REFERER'])) {
    $log = fopen('script_access.log', 'a');
    fwrite($log, 'The script has been accessed from ' . $_SERVER['HTTP_REFERER'] . PHP_EOL);
    fclose($log);
}

// Rest of your script here.

When you want to know the url of the page that called your file 'script.php' you should look at the $_SERVER variable.

In that variable, you will find some useful headers of where the script is called, try testing the values you get from $_SERVER['REQUEST_URL'] and $_SERVER['HTTP_REFERER'] for instance. More options can be found here: http://php.net/manual/en/reserved.variables.server.php

You could for instance store the data from such variables along with the time into a database to be able to output use statistics later.

you can get all these information through $_SERVER which is an array containing information such as headers, paths, and script locations. For more information please read. http://php.net/manual/en/reserved.variables.server.php

<?php
function get_path_info()
{
    if( ! array_key_exists('PATH_INFO', $_SERVER) )
    {
        $pos = strpos($_SERVER['REQUEST_URI'], $_SERVER['QUERY_STRING']);

        $asd = substr($_SERVER['REQUEST_URI'], 0, $pos - 2);
        $asd = substr($asd, strlen($_SERVER['SCRIPT_NAME']) + 1);

        return $asd;    
    }
    else
    {
        return trim($_SERVER['PATH_INFO'], '/');
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top