How to check if the URL is iframe embeddable in PHP?

4.8k Views Asked by At

Some websites are not allowed to be embedded via iframe. They produce the following error:

Refused to display 'https://news.ycombinator.com/news' in a frame because it 
set 'X-Frame-Options' to 'DENY'. 

Our app allows URL submissions from users. We want to check on the server side if the website could be embedded in iframe and add a corresponding flag. On the client we check for the flag, and either do iframe embed or just provide a direct link to a webpage.

How do I check whether website will support iframe or not?

3

There are 3 best solutions below

0
On BEST ANSWER

X-Frame-Options is a response header sent by the server, so have your server perform an HTTP GET on the URL you'd like to test, see if the X-Frame-Options header is present, and if it is... judging by the spec you're not likely to be allowed to embed it at all.

0
On

Try this code:

$url = "http://www.google.com/";
$url_headers = get_headers($url);
foreach ($url_headers as $key => $value)
{
    $x_frame_options_deny = strpos(strtolower($url_headers[$key]), strtolower('X-Frame-Options: DENY'));
    $x_frame_options_sameorigin = strpos(strtolower($url_headers[$key]), strtolower('X-Frame-Options: SAMEORIGIN'));
    $x_frame_options_allow_from = strpos(strtolower($url_headers[$key]), strtolower('X-Frame-Options: ALLOW-FROM'));
    if ($x_frame_options_deny !== false || $x_frame_options_sameorigin !== false || $x_frame_options_allow_from !== false)
    {
        echo 'url prevent iframe!';
    }
}
1
On

I wrote this function:

function allowEmbed($url) {
    $header = @get_headers($url, 1);

    // URL okay?
    if (!$header || stripos($header[0], '200 ok') === false) return false;

    // Check X-Frame-Option
    elseif (isset($header['X-Frame-Options']) && (stripos($header['X-Frame-Options'], 'SAMEORIGIN') !== false || stripos($header['X-Frame-Options'], 'deny') !== false)) {
        return false;
    }

    // Everything passed? Return true!
    return true;
}