Read a php file

Asked

Viewed 699 times

2

My screen, can list the files as link and even displays in another tab with target ,I just can’t get the clicked file to display the content.

I’m using the fopento open and the fread to read...

Follow the code as it is:

<?php

   foreach(new DirectoryIterator('C:\xampp\htdocs\testtoclassificados\log') as $fileInfo){

       if($fileInfo->isDot())continue;
       if($fileInfo->isFile()){ 

       $arquivo  = $fileInfo->getPathname(); 

       if($fileInfo->isReadable() == true){
         $fp       = fopen($arquivo,"r");
        $texto    = fread($fp, filesize($arquivo));
         fclose($fp);
          echo"<li><a href='".$arquivo."' target='_blank'>".$arquivo."</a>
          <br/></li>";
       }else echo "O arquivo ".$arquivo." não possuí permissão de leitura.";
      }
   }         
  ?>

Displays these errors, when I use fopen and fread:

Warning: fopen(.): failed to open stream: Permission denied in 
C:\xampp\htdocs\testtoclassificados


Warning: fread() expects parameter 1 to be resource, boolean given in

Warning: fopen(apostila2.pdf): failed to open stream: No such file or directory in C:\xampp\htdocs\testtoclassificados

The logic of the code is wrong?

My screen only does not open another tab with the contents of the file...

listagem

  • Ricardo checks the permissions and user of the folder and files contained within testtoclassified. The error in question refers to this.

  • Then add this logic after your foreach if ($fileinfo->isFile()) to make sure it’s a file before reading with fopen. The unveiled eye is what I realized.

  • Fatal error: Uncaught Error: Call to a member function isFile() on null in C:\xampp\htdocs\testtoclassificados\ this message displays after I put isFile shows that it is null

  • I put if ($fileinfo->isFile()) no comments, and you in your code used $fileInfo with uppercase letter in info checks there in your code.

  • Just one question, why use fopen inside the iterator? The variable text seems to serve no purpose $texto.

  • Because previously he was printing a piece of decoy text on the screen. I don’t know if he’ll keep it!

Show 1 more comment

1 answer

0


To better understand the problem, you can add a debugger to your code this way.

<?php
    foreach(new DirectoryIterator('C:\xampp\htdocs\testtoclassificados\log') as $fileInfo){
       echo "<pre>"; print_r($fileInfo); echo "</pre>";
       /*$fp = fopen($fileInfo,"r");
       $texto = fread($fp, filesize($fileInfo));
       if($fileInfo->isDot())continue;
       $arqName = $fileInfo->getFilename();  
       // $handle = $fileInfo->fopen("c:\\data\\info.txt", "r");*/
    }
?>

Use print_r to print on the screen the instance of the Directoryiterator class returned by each interaction of your foreach loop. Each printable object is a file or directory within the log directory. You are using the fileInfo object instance as the path for the file and in reality it is an object instance with methods and attributes. Follow the documentation examples Directoryiterator Then remove the comment I added and check which last file or directory the php code displays the error message. Make sure you are not trying to use fopen in a directory. You have to validate the condition for fopen to read only files.

<?php
    foreach(new DirectoryIterator('C:\xampp\htdocs\testtoclassificados\log') as $fileInfo){
           //Se for . ou .. pular para a próxima interação do laço.               
           if($fileInfo->isDot())continue;
           if($fileInfo->isFile()){
               //DirectoryIterator::getPathname — Retorna o caminho e o nome 
               //do arquivo do elemento atual do diretório
               $arquivo  = $fileInfo->getPathname(); 
               // Abre para leitura mas antes verifica se o arquivo
               // tem permissão de leitura.
               if($fileInfo->isReadable() == true){
                  $fp       = fopen($arquivo,"r");
                  $texto    = fread($fp, filesize($arquivo));
                  echo $texto."<br/><br/>";
                  fclose($fp);
              }else echo "O arquivo ".$arquivo." não possuí permissão de leitura.";  
          }
    }
?>

To make a file listing with links and open in new tab do so :

<?php
    foreach(new DirectoryIterator('C:\xampp\htdocs\testtoclassificados\log') as $fileInfo){
      //Se for . ou .. pular para a próxima interação do laço.               
      if($fileInfo->isDot())continue;
        if($fileInfo->isFile()){
          //DirectoryIterator::getPathname — Retorna o caminho e o nome 
          //do arquivo do elemento atual do diretório
          $arquivo  = $fileInfo->getPathname(); 
          // Abre para leitura mas antes verifica se o arquivo
          // tem permissão de leitura.
          if($fileInfo->isReadable() == true){
              $fp       = fopen($arquivo,"r");
              $texto    = fread($fp, filesize($arquivo));
              fclose($fp);
              // A variavel $arquivo recebeu o valor do método contido 
              //dentro da intância da classe DirectoryInterator.
              //Dentro desse objeto existe o método que retorna o caminho 
              //completo até o arquivo, como mostrado abaixo
              //$fileInfo->getPathname(), portanto a variavel $arquivo possuí 
              //o path completo uma vez que definida acima.
              $urlLeitor  = "http://localhost/leitor.php?arquivo=".$fileInfo->getFilename(); 
              echo"<li><a href='".$urlLeitor."' target='_blank'>".$texto."</a>
              <br/></li>";
           }else echo "O arquivo ".$arquivo." não possuí permissão de leitura.";  
       }
    }
?>
  • Rafael got good just the way you posted it. Now I would like this same page when I click on the file it opens on another page.. showing the contents of the file.

  • I did not understand edit your comment. You used in your link target='_Blank' will always open in new tab. What do you want to do?

  • <li><?php echo "<a href=\"$fileInfo\" target=\"_blank\">$fileInfo</a><br>"?></li> do jeito que estar ,mostra arquivo não encontrado..404 quando abre em outra aba&#xA;

  • I explained above $fileInfo is not the path to your file is an instance of the Directoryinterator class to get the complete path to the file use $fileInfo->getPathname(). I’ll edit my answer.

  • Okay, Rafael, I get it.. except that the way the content appears as link and on the same page,I want the name of the file that is in a folder and when I click opens another tab with the content .. type : notes.txt and open in another tab the notes understood the way being appears in the same . Sorry to require so much I’m still green in php

  • It looks like this and displays error 404 <li><?php echo "<a href=\"arquivo\" target=\"_blank\">$fileInfo</a><br>"?></li>&#xA;

  • If you put as example in my Aki appears the content on the page and as link , but that does not open the other tab

  • But you should replace c: xamp htdocs with http://localhost if you are running from the browser. I have never tested it in xamp but I believe that by the local path there should be some blocking. Replace it using the str_replace function. Or try opening the file from your browser with http://localhost/testtoclassified/log/Classe1.txt see what happens.

  • http://localhost:8080/log/classe1.txt so with my xampp enabled with apache it displays the contents of the file...

  • and another.. the folder with the files only appears the name according to the image if it is inside the project folder.. if it does not say that it cannot find the specified path... foreach(new DirectoryIterator('localhost\testtoclassificados\startbootstrap-full-slider-gh-pages\log'

Show 6 more comments

Browser other questions tagged

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