Scorpion King
Scorpion King

Reputation: 1938

get URL of parent page inside when inside an iframe

I have an iframe (iframe.php) inside my main page (index.php). I want to echo the URL of the main page inside the iframe. I know how to echo the URL of any page but not when it is inside an iframe. When i try this, it is echoing only the URL of the iframe and not of the main page. It sounds simple but not able to figure it out.

REASON: the reason why i chose php and why i am trying to do this is, i need to verify the URL from which this page is being accessed... do not want the iframe to be accessed unless the user is in index.php and reject the user from accessing it if he is not in the iframe of the main page.

Upvotes: 0

Views: 25543

Answers (3)

Emanuele
Emanuele

Reputation: 101

You can use

$_SERVER["HTTP_REFERER"]

to read the parent.

It work for me.

The javascript code can't talk easily with PHP The ?from=

Upvotes: 10

Chris Sobolewski
Chris Sobolewski

Reputation: 12925

PHP has no idea about an iframe, it's just served as another page and interpreted by the browser...

You could do something like...

<iframe src="frame.php?from=<?php echo currentPageURL() ?>">

Then inside the iframe, you can access $_GET['from']. Just make sure you verify, as that would be insecure.

Here is the code I typically use to return the current page URL:

function currentPageURL() {
    $pageURL = 'http';
    if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
        } else {
        $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    }
    return $pageURL;
}

Upvotes: 4

Maertien
Maertien

Reputation: 11

Try this in iframe:

<script type="text/javascript">alert(top.location.href);</script>

I think it should work. :-)

Upvotes: 1

Related Questions