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.

  1. if (ini_get('allow_url_fopen') == '1') {
  2. // use fopen() or file_get_contents()
  3. } else {
  4. // use CURL or fsockopen
  5. }
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:

  1. if ($fp = fopen('http://www.google.com/', 'r')) {
  2. $content = '';
  3. while ($line = fread($fp, 1024)) {
  4. $content .= $line;
  5. }
  6. // do something with content here
  7. // ...
  8. } else {
  9. // an error occured - do something here
  10. }
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:

  1. function read_url_fopen($url) {
  2. if (ini_get('allow_url_fopen') != '1') {
  3. return '<p>ERROR - fopen wrappers is not enabled</p>';
  4. }
  5. if ($fp = fopen($url, 'r')) {
  6. $content = '';
  7. while ($line = fread($fp, 1024)) {
  8. $content .= $line;
  9. }
  10. return $content;
  11. } else {
  12. return '<p> ERROR reading: '.$url.'</p>';
  13. }
  14. }
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 *