0

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?

matt
  • 42,713
  • 103
  • 264
  • 397

2 Answers2

1

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

Miroshko
  • 863
  • 6
  • 14
  • Ok, thank you. Is it also possible to also filter for *.jpgs as well. So I want to read the directory for .jpgs and .pngs – matt Jul 21 '12 at 16:38
  • 1
    Yes. You have to set second parameter of glob to GLOB_BRACE like this: glob( 'img/*.{jpg,png}', GLOB_BRACE ); – Miroshko Jul 21 '12 at 16:51
  • Thank you very much, and the last question is how I do write those img paths into a JS array. I updated my question with the snippet i'm working with. What do I do wrong here? Thank you in advance for the great help. – matt Jul 21 '12 at 16:57
  • Just use json_encode - this will automatically transform php array to js array. var imgs = ; – Miroshko Jul 21 '12 at 16:59
0

Very simple.. don't use realpath..

Evert
  • 93,428
  • 18
  • 118
  • 189