user2035347
user2035347

Reputation:

Can I Get the url of iframe parent window with PHP?

I have an iframe on a webpage, and from the iframe i want to get the url of the parent window. Yes, i have been searching the web, but i keep getting solutions with JavaScript.

So do your guys know any solutions that only uses PHP?

Upvotes: 20

Views: 33479

Answers (3)

gary talman
gary talman

Reputation: 71

I had the same problem, I was running a search routine within an iframe and wanted to be able to create links from other pages that would automate the search function of the said iframe.

After reading all the 'can only be done in javascript' I used this:

$topurl=$_SERVER['HTTP_REFERER'];
$q=substr($topurl,strpos($topurl,'=')+1);

Crude but effective for my needs. I know you can get fancy and break out all the parameters of the url but I only needed one search term.

Upvotes: 7

thordarson
thordarson

Reputation: 6241

A server-side script has no way of knowing anything about the client-side without the client side explicitly sending data, e.g. using AJAX.

If you have control over the iframe itself, you could always pass variables along in the query string and access them using $_GET:

HTML

<iframe src="http://example.com/file.php?variable=value"></iframe>

PHP

<?php

    echo $_GET['variable'] // Outputs 'value'

?>

UPDATE (this might actually be possible)

There might be a way using $_SERVER['HTTP_REFERER']. An HTML file containing an iframe sends some headers as it requests the file, and one of them appears to be the HTTP_REFERER. I tested this locally and it seems to work.

The only downside is you have no idea of knowing whether the referrer is an iframe or not. Again, if you have control over the iframe, you could pass a variable along using the method above saying it's an iframe, and use the method below to get the URL dynamically.

Example, let's say this file's URL is http://example.com/:

<iframe src="http://example.com/file.php"></iframe>

The PHP file, we'll call it file.php:

<?php
    echo $_SERVER['HTTP_REFERER']; // Should output http://example.com.
?>

Upvotes: 23

Thijmen
Thijmen

Reputation: 127

That's not going to work, you could use JavaScript.

Upvotes: 0

Related Questions