Secure file_get_contents PHP function

on 19th November
  • php
  • file_get_contents
  • secure
  • password protected
  • authorization basic
This crops up all the time. We install a particular software suite on a clients' server and when we execute the script, it spits out an error about file_get_contents not expecting some arguments. Grrr, that's our first warning sign that we're probably running PHP4 on the server. A lot of companies continue to run PHP4 and while the upgrade from PHP4 to PHP5 is generally very smooth, not all server components update as well. Thus, rather than upgrading the entire server, we provide some simple bridging functions for some of the most commonly used PHP5 functions. file_get_contents is one such function.

A really handy feature added in PHP 5.0.0 was the concept of context support. A stream context can be very handy for defining such things as authorisation tokens. There is no in-built support for stream contexts within PHP 4 so we provide the following function to our clients and a small wrapper function to decide what to do depending on our environment. Here's file_get_contents_secure:

function file_get_contents_secure($url, $username, $password)
$opts = array('http'=>
'header'=>sprintf("Authorization Basic %s\r\n",
"Content-type: application/x-www-form-urlencoded\r\n"
$context = stream_context_create($opts);
$fh = fopen($url, 'r', false, $context);
$contents = ob_get_contents();
return $contents;

That's it, it's really straightforward to call this function:

print file_get_contents_secure('',

This is a really handy function that you can utilise if you are being forced to run off a PHP 4 server. We're presented with this task quite frequently and I'm sure you're no different.

As with all articles on Celtic Productions, this article is protected by international copyright laws. It may be linked to (we are of course most grateful of links to our articles), however, it may never be reproduced without the prior express permission of its owners, Celtic Productions.