PHP & Ziparchive() - Failed to load PDF document

Asked

Viewed 130 times

1

Good afternoon, I have a form that in certain input is opened a window or multiple windows to display a PDF(or PDF’s) specific(s). The folder where the path is, there may be only a PDF or a ZIP file with multiple PDF’s inside, according to the value filled in the input.

The Blur () event below is the code that calls the windows and passes the values to the ".php file" and "pdf.php". a file is to check if it is only a PDF or a ZIP, if it is a PDF it returns to the javascript code, stating that it is a PDF only, and then opens only a window to show, this part is ok.

Javascript/HTML code:

///////////PASSA OS VALORES PARA O "arquivo.php"////////////////
     $.post("arquivo.php", {nprocesso: document.getElementById("processo").value}, function(data){
        $( "#content3" ).html( data ); /*<-- return in this content if is a PDF or a ZIP(when is a zip it returns how many PDF's there are inner ZIP file too)*/

    ////////////ESTA PARTE É PARA CRIAR APENAS UMA JANELA OU MÚLTIPLAS JANELAS, PASSANDO OS VALORES RETORNADOS NO "content3" PARA "pdf.php" PARA EXIBIR O PDF OU OS PDF's//////////////////    
    setTimeout(function(){
               if(document.getElementById("content3").innerText == "PDF"){
                  window.open("pdf.php/"+document.getElementById("processo").value, '_blank', "toolbar=yes,scrollbars=yes,resizable=yes,width=800,height=800"); 
               }else{
                  var QuantPDF = Number(document.getElementById("content3").innerText.slice(Number(document.getElementById("content3").innerText.lastIndexOf(','))+1, document.getElementById("content3").innerText.length));//Number(document.getElementById("content3").innerText.replace(/[^0-9]/g, ""));
                  var NomesPDFS = []; NomesPDFS = document.getElementById("content3").innerText.slice(3, document.getElementById("content3").innerText.length-2).split(',');
                  if(QuantPDF > 1){
                   for(var i = 0; i < QuantPDF; i++){
                    window.open("pdf.php/"+document.getElementById("processo").value+"/"+NomesPDFS[i], '_blank', "toolbar=yes,scrollbars=yes,resizable=yes,width=800,height=800");  
                   }   
                  }else{
                   window.open("pdf.php/"+document.getElementById("processo").value, '_blank', "toolbar=yes,scrollbars=yes,resizable=yes,width=800,height=800");    
                  }
               }
              document.getElementById('closeBtn').click();
              }, 1000);
            }

This is the ".php file", where it checks if it is only a PDF or ZIP file, and extracts if it is a zip.

php code file:

<?php
  session_start();

  //////////ESTA PARTE VERIFICA SE O ARQUIVO É UM PDF E RETORNAR AO MEU CÓDIGO JAVASCRIPT/////////
  if(file_exists('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'].'.pdf')){

    echo 'PDF';
    $_SESSION['file'] = "PDF";

  }else{

//////////ESTA PARTE VERIFICA SE O ARQUIVO É UM ZIP E RETORNAR AO MEU CÓDIGO JAVASCRIPT/////////

    echo 'ZIP';
    $_SESSION['file'] = "ZIP";
     $zip = new ZipArchive;
     $path = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'].'.zip';
     ///////////////////////////////////////////////////////////////////

      if($zip->open($path) === true){
       //////////THIS PART IT OPENS THE ZIP AND EXTRACT/////////
if(!file_exists('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'])){
            mkdir('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'], 0777, true);
           }
            for($i = 0; $i < $zip->numFiles; $i++){
             $zip->extractTo('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'], array($zip->getNameIndex($i)));
             $path = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'];
             $files = scandir($path); array_shift($files); array_shift($files);
             $file = array(); $filename = array();
        ///////AGORA PEGO OS NOMES DOS PDF's E A QUANTIDADE DE PARA E VOLTO AO CÓDIGO JAVASCRIPT///////
             $file[$i] = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'].'/'.$files[$i];
             $filename[$i] = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'].'/'.$files[$i];
             $nomes_pdfs = array();
             $nomes_pdfs[$i] = substr(substr($filename[$i], strpos($filename[$i], $_POST['nprocesso'])+26, strlen($filename[$i])), 0, strpos(substr($filename[$i], strpos($filename[$i], $_POST['nprocesso'])+26, strlen($filename[$i])), '.pdf')).',';
             echo $nomes_pdfs[$i];
            }               
           $zip->close();

           $path = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$_POST['nprocesso'];
           $files = scandir($path);
           array_shift($files); array_shift($files); $_SESSION['quantidade_pdf'] = count($files);
           echo $_SESSION['quantidade_pdf'];
        }
      }
    ?>

My problem is actually partially in "pdf.php", where the window is loaded with the values returned from "content3". As I said earlier, when it is a single PDF, the window is displayed normally, but when it is a ZIP file with multiple PDF’s, the first PDF is displayed correctly, but from the second onwards it is not displayed. show this error: "Failed to load PDF document".

pdf.php code:

<?php
header ('Content-type: text/html; charset=utf-8');
if(file_exists('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/')+1).'.pdf') && is_file('//dsbimrj16/Vinculacao_Cadastro_Gestor/'.substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/')+1).'.pdf')){
 $processo = substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/')+1);
 $file = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$processo.'.pdf';
 $filename = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$processo.'.pdf';
 header('Content-type: application/pdf');
 header('Content-Disposition: inline; filename="' . $filename . '"');
 header('Content-Transfer-Encoding: binary');
 header('Content-Length: ' . filesize($file));
 header('Accept-Ranges: bytes');
 @readfile($file);
}else{
/////////////////////AQUI ESTÁ A PARTE QUANDO É UM ZIP////////////////////////
///////*Esta parte é apenas para verificar se o extração da pasta foi feita e ela existe*/////////
 function folder_exist($folder){ $path = realpath($folder); return ($path !== false AND is_dir($path)) ? $path : false; }
 chdir('//dsbimrj16/Vinculacao_Cadastro_Gestor/');
 $folder = '/'.substr(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'p/')+2), 0, strpos(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'p/')+2), '/')).'/';
 if(FALSE !== ($path = folder_exist($folder))){
 /////*Aqui começa a parte onde o código pega os PDF's e os exibe*/////
  $pasta = substr(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'p/')+2), 0, strpos(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'p/')+2), '/'));
  $processo = substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '/')+1);
  $file = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$pasta.'/'.$processo.'.pdf';
  $filename = '//dsbimrj16/Vinculacao_Cadastro_Gestor/'.$pasta.'/'.$processo.'.pdf';
  header('Content-type: application/pdf');
  header('Content-Disposition: inline; filename="' . $filename . '"');
  header('Content-Transfer-Encoding: binary');
  header('Content-Length: ' . filesize($file));
  header('Accept-Ranges: bytes');
  @readfile($file);
 }else{
  die('<h2 style="background-color:#FA5858"><center>Não foi encontrado a inicial do processo. Verifique se o mesmo encontra-se na pasta.</center></h2>');
 }
}
?>

What am I doing wrong? I’ve checked the folder, the file name, the address for the folder, it’s all right. I can’t see what’s causing this mistake

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.