标头在foreach循环php中动态读取

时间:2017-03-08 07:55:40

标签: php codeigniter pdf

我有一个foreach循环下载pdf文件一次在第一次读取和下载文件后,另一个pdf文件没有下载?可以请帮助

foreach($file_names as $key)
{
    $fileeename=$fileenames.'.pdf';
    $dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})",'',$fileeename);
    $dl_file = filter_var($dl_file, FILTER_SANITIZE_URL);
    $fullPath = $path.$dl_file;

    if ($fd = fopen ($fullPath, "r"))
    {
        $fsize = filesize($fullPath);
        $path_parts = pathinfo($fullPath);
        $ext = strtolower($path_parts["extension"]);
        header("Content-type: application/pdf");
        header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
        header("Content-length: $fsize");
        header("Cache-control: private");

        while(!feof($fd)) {
            $buffer = fread($fd, 2048);
            echo $buffer;
        }
    }

    fclose ($fd);   
}

1 个答案:

答案 0 :(得分:0)

  

循环不等待PDF下载过程,这就是为什么你需要在循环内调用函数,因为循环正在等待函数进程结束。

function downloadFile(){

            $fileeename=$fileenames.'.pdf';
            $dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})",'',$fileeename);
            $dl_file = filter_var($dl_file, FILTER_SANITIZE_URL);
            $fullPath = $path.$dl_file;
            if ($fd = fopen ($fullPath, "r"))
            {
                    $fsize = filesize($fullPath);
                    $path_parts = pathinfo($fullPath);
                    $ext = strtolower($path_parts["extension"]);

                    header("Content-type: application/pdf");
                    header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
                    header("Content-length: $fsize");
                    header("Cache-control: private");
                    while(!feof($fd)) {
                        $buffer = fread($fd, 2048);
                        echo $buffer;
                    }
            }
            fclose ($fd);
        } 

    foreach($file_names as $key){
             downloadFile();
    }