Search code examples
phpglobrealpath

PHP: glob( realpath() ) reads directory but paths are incorrect


I don't know what I don't get here but I'm trying to read a directory with php and create a JS array with all the image-paths inside of it.

So right now I have the following structure on my local server.

  • project
    • one
      • index.php
      • imgs
        • image1.png
        • image2.png

So I'm working with my index.php right now. I simply want to read the imgs folder in the same directory as the `index.php``

$images = glob( realpath('img')."/*.png" );

print_r($images);

// just for testing purposes / creating a JS array later
foreach( $images as $image ):
    echo "<img src='" . $image . "' />";
endforeach;

the print_r function puts out this …

Array ( 
    [0] => /Users/my/htdocs/test.com/project/one/img/image1.png 
    [1] => /Users/my/htdocs/test.com/project/one/img/image2.png 
) 

For me this seems pretty ok, but it seems the paths are not correct since they don't really link to the images. Isn't it somehow possible to use relative path's for this? I mean I would just need to get imgs/image1.png not the absolute path.

Any ideas on that what I'm doing wrong here?


Solution

  • Get rid of realpath('img') if you include full path into glob argument, you'll get it in results. Just use glob( 'img/*.png" );