0

I have a one foreach loop to download pdf files once in first time header was read and download file after that another pdf file not download?can you please help

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

1 Answer 1

0

Loop doesn't wait for PDF download process, that why you need to call function inside the loop, because loop is waiting for function process end.

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();
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.