Question

Im using glob() to retrieve a load of photos matching a rule. the page is located in /stocklist/222/page.php. the photos are located in /stocklist/photo/

i've tried using the code below, but it seems to return no results.

$photo = glob("/photo/".$row['Scientific']."?.jpg");

i have a feeling it's looking in stocklist/222/photo

EDIT:

Following suggestions (@Niels Keurentjes, @Gasim), ive used

echo getcwd() ;
$photo = (glob('/var/www/web/stocklist/photo/'.$row['Scientific'].'*.jpg'));
print_r(glob('/var/www/web/stocklist/photo/'.$row['Scientific'].'*.jpg'));

Which produces the following:

/var/www/web/stocklist

Array ( [0] => /var/www/web/stocklist/photo/Pituophis deppei jani.jpg 
[1] => /var/www/web/stocklist/photo/Pituophis deppei jani1.jpg )

But the images are displaying as missing files.

Was it helpful?

Solution

The solution for you could be:

$photo = "../photo/" . $row['Scientific'] . ".jpg";

glob() returns an array not the string.

Try doing the following to understand more of what glob is doing:

print_r(glob("../photo/".$row['Scientific']."/*"));

As a result you will have an array with all .jpg files in given folder, e.g.:

Array
(
    [0] => /stocklist/222/photo/1.jpg
    [1] => /stocklist/222/photo/2.jpg
    [2] => /stocklist/222/photo/3.jpg
    [3] => /stocklist/222/photo/4.jpg
    [4] => /stocklist/222/photo/5.jpg
    [5] => /stocklist/222/photo/6.jpg
    [6] => /stocklist/222/photo/7.jpg  
)

EDIT 1:

In case your example is correct you could just access your first photo in array using:

$photo[0];

EDIT 2:

Another problem in your code, is that you're using ? as wildcard operator but it's not recognized, and should be replaced with * instead.

EDIT 3:

According to your last update, you have spaces in your filenames - it's a bad practice, from my point of view, you should fix it!

EDIT 4:

Example, of how I would use it further, instead of using for loop:

$photos = glob('/var/www/web/stocklist/photo/'.$row['Scientific'].'*.jpg');

if (!empty($photos))
  {
    echo "<ul id='slide'>";
    foreach ($photos as $photo)
      {
        echo "<li><img src='" . $photo . "' alt='' class='img-right'></li>";
      }
    echo "</ul>";

  }



Acording to PHP: glob - Manual :

Description:

The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells.

Return Values:

Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top