如何获取php资源的大小

时间:2014-09-17 10:50:48

标签: php download

我有一个常见的php函数,它接受资源并将其下载为csv文件,resoure是文件或php:// memory。如何找到此资源的大小,以便我可以设置标题内容长度

  /** Download a file as csv and exit */
  function downloadCsv($filName, $fil) {
    header("Content-Type: application/csv");
    header("Content-Disposition: attachement; filename=$filName");
    // header("Content-Length: ".......
    fpassthru($fil);
    exit;
  }

我可以看到如何使用filesize($ filename)从文件名中获取文件大小,但在此函数中我不知道/有文件名,只是资源

2 个答案:

答案 0 :(得分:1)

fstat()可以做到:

$stat = fstat($fil);
header('Content-Length: '.$stat['size']);

答案 1 :(得分:-3)

只需使用php:// temp / OR php:// memory /

php:// Reference

/** Download a file as csv and exit */
function downloadCsv($filName, $fil) {
  header("Content-Type: application/csv");
  header("Content-Disposition: attachement; filename=$filName");

  //here the code
  $tmp_filename = 'php://temp/'.$filName;
  $fp = fopen($tmp_filename,'r+');
  fwrite($fp, $fil);
  fclose($fp);

  header("Content-Length: ".filesize($tmp_filename));  //use temp filename
  readfile($fil);
  exit;
}