Reading a Remote File in PHP using fopen()

You can only use fopen() and file_get_contents() when fopen wrappers is enabled. This parameter is specified in the php.ini file and cannot be changed at run time using ini_set(), To know whether you can use these two function (fopen and file_get_contents) or not you can use the following code to check the value of fopen wrapper seting.

if (ini_get('allow_url_fopen') == '1') {
  // use fopen() or file_get_contents()
} else {
  // use CURL or fsockopen
}

Wen you use fopen() php function to read a remote file the code is as simple as reading from a local file:

if ($fp = fopen('http://www.google.com/', 'r')) {
  $content = '';
  while ($line = fread($fp, 1024)) {
    $content .= $line;
  }
  // do something with content here
  // ...
} else {
  // an error occured - do something here
}

Now, all code in one function:

function read_url_fopen($url) {
  if (ini_get('allow_url_fopen') != '1') { 
    return '<p>ERROR - fopen wrappers is not enabled</p>'; 
  }
  if ($fp = fopen($url, 'r')) {
    $content = '';
    while ($line = fread($fp, 1024)) {
      $content .= $line;
    }
    return $content;
  } else {
    return '<p> ERROR reading: '.$url.'</p>';
  }
}

 

byrev Written by:

Be First to Comment

    Leave a Reply

    Your email address will not be published. Required fields are marked *