Skip to content

Instantly share code, notes, and snippets.

@rattfieldnz
Created August 6, 2017 10:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rattfieldnz/8b70c8a0a0cc35ede64139b0c4866f15 to your computer and use it in GitHub Desktop.
Save rattfieldnz/8b70c8a0a0cc35ede64139b0c4866f15 to your computer and use it in GitHub Desktop.
A class containing a function which checks if a URL can be shown in iframes. Revisions, suggestions, and optimization tips are very welcome!
<?php
/**
* Class Http
*
* A class to manage HTTP-related functionality.
*
* @author Rob Attfield <emailme@robertattfield.com> <http://www.robertattfield.com>
*
* @package App\Helpers\Functions
*/
class Http
{
/**
* Check if a given URL can be displayed in iframes.
*
* @param $url
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
* https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
*
* @todo Improve this code, with respect to performance when checking various number of headers for a select few.
*
* @return bool
*/
public static function canShowInIframes($url): bool {
$headers = get_headers($url);
$xFrameOptions = "X-Frame-Options: ";
$contentSecurityPolicy = "Content-Security-Policy: frame-ancestors ";
$canShow = true;
if(count($headers) == 0){
return false;
}
foreach($headers as $key => $value){
if(substr($value, 0, strlen($xFrameOptions)) == $xFrameOptions){
$xFrameOption = substr($value, strlen($xFrameOptions), strlen($value));
if(
strtoupper($xFrameOption) == "SAMEORIGIN" || strtoupper($xFrameOption) == "DENY"
){
$canShow = false;
}
}
else if(substr($value, 0, strlen($contentSecurityPolicy)) == $contentSecurityPolicy){
$cspFrameAncestorsOption = substr($value, strlen($contentSecurityPolicy), strlen($value));
if(strtoupper($cspFrameAncestorsOption) == "'NONE'" || strtoupper($cspFrameAncestorsOption) == "'SELF'"){
$canShow = false;
}
}
}
return $canShow;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment