Skip to content

Dear Internet Explorer user: Your browser is no longer supported

Please switch to a modern browser such as Microsoft Edge, Mozilla Firefox or Google Chrome to view this website's content.

PHP file_get_contents over HTTP or HTTPS

A nifty PHP script which will detect whether a page is being served over HTTP or HTTPS and return the result as a string for use in PHP file_get_contents (or other) include functions.

When recently enabling HTTPS (Secure Sockets Layer) on a website, I successfully converted all of the a href URL links into a protocol-relative format (technically known as a network path reference):

<a href="//www.mysite.com.au/path/to/resource/">

Easy.

Unfortunately this doesn’t work with a PHP file_get_contents include function, which will break if expressed in such a format. For example, this simply won’t work:

<?PHP echo file_get_contents("//www.mysite.com.au/path/to/resource.inc.php");?>

Whilst it would be possible to hard-code PHP includes so that they point to the HTTPS version of the website (using an absolute file path), another good solution is to use a PHP function to return the URL protocol of the page being served and then incorporate that into each link.

The following code will determine whether a web page has been requested over HTTP or HTTPS:

if (isset($_SERVER['HTTPS']) &&
    ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
    isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
    $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
  $protocol = 'https://';
}
else {
  $protocol = 'http://';
}

PHP file_get_contents references can then be incorporated into the code of the page that will match the protocol/scheme of the page being served (ie HTTPS for the HTTPS version of your website or HTTP for the HTTP version):

<?PHP echo file_get_contents($protocol . "www.mysite.com.au/path/to/resource.inc.php");?>

Using this method, a PHP file_get_contents will always work, regardless of whether the page is served over HTTPS or HTTP. The above code can also be used within PHP includes to ensure (for instance) that images are served via the correct protocol to prevent browser mixed-content warnings.

   

Comments

No comments have yet been submitted. Be the first!

Have Your Say

The following HTML is permitted:
<a href="" title=""> <b> <blockquote cite=""> <code> <em> <i> <q cite=""> <strike> <strong>

Comments will be published subject to the Editorial Policy.