首页 > 解决方案 > 下载通过 file_get_contents() php 打开的 pdf 文件时出现网络错误

问题描述

有人可以请教为什么PDF没有下载吗?当我点击下载时,它总是显示为网络错误。PDF 文件大小为 95 MB,这是网络错误的原因吗?我正在使用file_get_contents().

标签: phpfile-get-contents

解决方案


您可以尝试使用 cURL:

// downloads a file and stores it into a file
function getPage($url,$file_ptr) 
{
  $ch = curl_init();
    curl_setopt_array($ch, Array(
    CURLOPT_USERAGENT => "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36",
    CURLOPT_SSL_VERIFYPEER => FALSE,
    CURLOPT_HEADER => FALSE,
    CURLOPT_AUTOREFERER => TRUE,
    CURLOPT_FOLLOWLOCATION => TRUE,
    CURLOPT_MAXREDIRS => 5,
    CURLOPT_URL => $url,
    CURLOPT_REFERER => $url,
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_FILE => $file_ptr
  ));
  $result = curl_exec($ch);
  if(curl_errno ($ch)) $err = curl_error($ch);
    else $err = '';
  curl_close($ch);
  if($err != '') return $err;
  return $result;
} 

  $in_file = tempnam(sys_get_temp_dir(), 'pdf_'); 
  $fp = fopen ($in_file, 'w+');
  $ret = getPage($url,$fp); 
  if($ret === TRUE)
  {
    fclose($fp); 
    // do something with the file
  }
    else
  {
    fclose($fp);
    @unlink($in_file); 
  }

推荐阅读