Tutorials

PHP: What to Do When Your Web Host Turns Off Fopen


Many web hosts have turned off the PHP function fopen(). Because of the security problems is cause they have set the default PHP setting to "allow_url_fopen=false". A number of CMS use this function to communicate to websites to gather information and notices. So what do you do when those nasty errors start showing and your scripts no longer work?

There are two solutions here. The first is a freestanding one that does not require more than a standard PHP install. The second requires that the web host have cURL installed and running on your web server.

Simple class to fetch a HTTP URL. Supports "Location:"-redirections. Useful for servers with allow_url_fopen=false. Works with SSL-secured hosts.

#usage:
$r = new HTTPRequest('http://www.php.net');
echo $r->DownloadToString();

class HTTPRequest
{
var $_fp; // HTTP socket
var $_url; // full URL
var $_host; // HTTP host
var $_protocol; // protocol (HTTP/HTTPS)
var $_uri; // request URI
var $_port; // port

// scan url
function _scan_url()
{
$req = $this->_url;

$pos = strpos($req, '://');
$this->_protocol = strtolower(substr($req, 0, $pos));

$req = substr($req, $pos+3);
$pos = strpos($req, '/');
if($pos === false)
$pos = strlen($req);
$host = substr($req, 0, $pos);

if(strpos($host, ':') !== false)
{
list($this->_host, $this->_port) = explode(':', $host);
}
else
{
$this->_host = $host;
$this->_port = ($this->_protocol == 'https') ? 443 : 80;
}

$this->_uri = substr($req, $pos);
if($this->_uri == '')
$this->_uri = '/';
}

// constructor
function HTTPRequest($url)
{
$this->_url = $url;
$this->_scan_url();
}

// download URL to string
function DownloadToString()
{
$crlf = "\r\n";

// generate request
$req = 'GET ' . $this->_uri . ' HTTP/1.0' . $crlf
. 'Host: ' . $this->_host . $crlf
. $crlf;

// fetch
$this->_fp = fsockopen(($this->_protocol == 'https' ? 'ssl://' : '') . $this->_host, $this->_port);
fwrite($this->_fp, $req);
while(is_resource($this->_fp) && $this->_fp && !feof($this->_fp))
$response .= fread($this->_fp, 1024);
fclose($this->_fp);

// split header and body
$pos = strpos($response, $crlf . $crlf);
if($pos === false)
return($response);
$header = substr($response, 0, $pos);
$body = substr($response, $pos + 2 * strlen($crlf));

// parse headers
$headers = array();
$lines = explode($crlf, $header);
foreach($lines as $line)
if(($pos = strpos($line, ':')) !== false)
$headers[strtolower(trim(substr($line, 0, $pos)))] = trim(substr($line, $pos+1));

// redirection?
if(isset($headers['location']))
{
$http = new HTTPRequest($headers['location']);
return($http->DownloadToString($http));
}
else
{
return($body);
}
}
}
?>

If you are getting message "Warning: fopen(): URL file-access is disabled in the server configuration", you can use function below to get the content from a local or remote file.

Function uses CURL lib, follow the link to get help: http://www.php.net/curl

/*
* @return string
* @param string $url
* @desc Return string content from a remote file
* @author Luiz Miguel Axcar (lmaxcar@yahoo.com.br)
*/

function get_content($url)
{
$ch = curl_init();

curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_HEADER, 0);

ob_start();

curl_exec ($ch);
curl_close ($ch);
$string = ob_get_contents();

ob_end_clean();

return $string;
}

#usage:
$content = get_content ("http://www.php.net");
var_dump ($content);
?>

My first encounter with the absense of fopen() happens just recently while installing Clever Copy CMS to the Demo Matrix. Clever Copy uses fopen to harvest Homeland Security levels and as part of an update notification system. Problems like this are one of the reasons that we a building the Demo Matrix on a web host rather than our own server. Things like this would go unnoticed and solutions not found if the demo sites where located on a server where we had complete control. Here is the code prior to being fixed.

function getthreat($mainurl,$backupurl)
{
$thefile = fopen("$mainurl", "r");
$return = fread($thefile, '500');
fclose($thefile);
// update next line if hsas site changes.
eregi("THREAT_ADVISORY CONDITION\=\"([a-z]+)\"", $return, $regs);
$got_threat_lvl = $regs[1];
$got_threat_lvl = strtolower($got_threat_lvl);
// Parse backup file at whitehouse site if first url fails
if ($got_threat_lvl == "")
{
$thefile = fopen("$backupurl", "r");
$return = fread($thefile, '20000');
fclose($thefile);
// update next line if whitehouse site changes.
eregi("/images/threat/([a-z]+)\.jpg", $return, $regs);
$got_threat_lvl = $regs[1];
}
return $got_threat_lvl;
}
?>

To solve the problem I used the first method shown here . The code was placed into a file and then included where needed. This is what a normal user would do. They would look for a solution and implement it as best they could. I mention this because many CMS projects frown on "hacks" as they call them. I prefer the words "working code".

include('httprequest.class.php');
function getthreat($mainurl,$backupurl)
{
#usage:
$r = new HTTPRequest($mainurl);
$thefile = $r->DownloadToString();
$return =$thefile;
// update next line if hsas site changes.
eregi("THREAT_ADVISORY CONDITION\=\"([a-z]+)\"", $return, $regs);
$got_threat_lvl = $regs[1];
$got_threat_lvl = strtolower($got_threat_lvl);
// Parse backup file at whitehouse site if first url fails
if ($got_threat_lvl == "")
{
$r = new HTTPRequest($backupurl);
$thefile = $r->DownloadToString();
$return =$thefile;
// update next line if whitehouse site changes.
eregi("/images/threat/([a-z]+)\.jpg", $return, $regs);
$got_threat_lvl = $regs[1];
}
return $got_threat_lvl;
}
?>

If your CMS or code requires hundreds or thousands of iterations through fopen() you will want to use curl to solve the problem cURL is a much more robust solution.

Happy Publishing!

Discussion

One comment for “PHP: What to Do When Your Web Host Turns Off Fopen”

  1. any hints on how to display RSS news on a website hosted on on disabled fopen php webhost??? i used “RSS JavaScript Ticker” from http://www.DynamicDrive.com and my host is http://www.awardspace.com

    i’m php newbie :) so php basic plzz

    Posted by Anonymous | May 21, 2007, 04:17

Post a comment

© 2003-2009 Hiveminds Magazine. Entries (RSS)
Powered by WordPress Theme by The Masterplan