【问题标题】:how to get the size of a php resource如何获取php资源的大小
【发布时间】:2014-09-17 10:50:47
【问题描述】:

我有一个常用的 php 函数,它接受资源并将其下载为 csv 文件,资源是文件或 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) 但在这个函数中我不知道/没有文件名,只是一个资源

【问题讨论】:

    标签: php download


    【解决方案1】:

    fstat() 可以胜任:

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

    【讨论】:

      【解决方案2】:

      只需使用 php://temp/ 或 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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-28
        • 1970-01-01
        • 2016-01-26
        • 1970-01-01
        • 1970-01-01
        • 2010-12-06
        • 2012-03-28
        • 2012-01-20
        相关资源
        最近更新 更多