0

I have some PDF files in public_html/site.com/pdf but in my index files is located in public_html/site.com/

I would like to use the glob() function to iterate through all the pdf files located In the pdf/ folder. The problem is that I am not getting any result.

Here is that I tried.

# public_html/index.php
<?php
foreach (glob("pdf/*.pdf") as $filename) {
    echo "$filename <br/>";
}
?> 
An_roid
  • 159
  • 1
  • 5
  • What do you think `pdf/*.pdf` would do? It'd search the current directory (which is `public_html`) for files that end with `.pdf` extension. Which is clearly not what you want. You need to specify the correct path. – Amal Murali May 21 '14 at 13:44
  • 1
    If you are not sure with the paths, just use the absolute path like `/var/www/public_html/site.com/`. You can obtain the full current path by `echo getcwd();`. – Daniel W. May 21 '14 at 13:44

2 Answers2

3

Alternatively, if you want to search your public folder recursively, you can use RecursiveDirectoryIterator to achieve this: Consider this example:

Lets say you have this directory structure:

/var/
  /www/
    /test/
      /images/
         image.png
         /files/
           /files2/
             pdf.pdf <-- searching for some pdf files, happens to be here

<?php

$filetype_to_search = 'pdf';
$root_path = '/var/www/test'; // your doc root (or maybe C:/xampp/htdocs/) :p

foreach ($iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($root_path, 
        RecursiveDirectoryIterator::SKIP_DOTS),
    RecursiveIteratorIterator::SELF_FIRST) as $value) {

    if($value->getExtension() == $filetype_to_search) {
        echo $value->getPathname() . "<br/>";
    }   
}

// ouput should be /var/www/test/images/files/files2/pdf.pdf

?>
user1978142
  • 7,946
  • 3
  • 17
  • 20
  • RecursiveDirectoryIterator is interesting, but what would the server load be from the each call hunting for files? – Giacomo1968 May 21 '14 at 14:38
  • 1
    @JakeGould yeah, i understood your point, actually i haven't tried it on super duper nested directories with many files so in terms of its benchmark, i cant attest to its performance. – user1978142 May 21 '14 at 14:43
2

My advice? Just set your full path as a variable & use it in cases like this.

In general you really cannot trust automatic methods used to get paths to be reliable for various reasons. This is why I have decided it’s best to set a base path explicitly as I explain here. I will assume you are on a standard Linux setup with /var/www/ as the root. So in your case you would set:

$BASE_PATH = '/var/www/public_html/site.com/';

And then your final code would be something like this:

$BASE_PATH = '/var/www/public_html/site.com/'

foreach (glob($BASE_PATH . "pdf/*.pdf") as $filename) {
  echo "$filename <br/>";
}
Community
  • 1
  • 1
Giacomo1968
  • 25,759
  • 11
  • 71
  • 103