How can i find which domain requests an iframe fro

2020-04-10 02:46发布

问题:

I have a set of various websites requesting an iframe html file from my server for various reasons

Is it possible to track onload which domain requests the iframe and then save it on a database.

If the domain already exists then don't add it to the database.

回答1:

It is not the domain that requests the contents for the iframe, it is the user's browser.

There is a slight chance to see which page this iframe is on: The referrer (mistakenly misspelled in the standard document as "referer", so every browser had to copy this typo), available in PHP via $_SERVER['HTTP_REFERER'].

You can try and parse the domain from there, best by using parse_url().



回答2:

You could use a combination of jQuery's post() functionality and PHP's $_SERVER variables:

$.post("collect.php", { source: "<?=$_SERVER['HTTP_REFERER']?>" } );

Your collect script could then check the database to see existing references to the source and enter a new one if required. An example using PDO:

if (isset($_POST['source']) && $source = $_POST['source']) {

   $db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password');

   // Be sure to sanitize $source

   if ($db->query("SELECT * FROM table WHERE source = $source")->rowCount() == 0) {
      $stmt = $db->prepare("INSERT INTO table(`time`, `source`) VALUES(?, ?)");
      $stmt->execute(array(time(), $source));
   }

}


标签: php html iframe