Search code examples
phpregexjoinreaddir

how to find a file in a directory based on a known id in php?


i have some images in a folder on a server:

/9_123456.jpg
/10_123457.jpg
/21_123458.jpg
/14_123459.jpg
...

also i have a database that holds those file names.

id    file
9     9_123456.jpg
10    10_123457.jpg
21    21_123458.jpg
14    14_123459.jpg

what i am doing at this point is query the picture name and show it on a webpage.

the issue is that i have millions of pictures and sometimes it takes a while for those images to come back, in special if i have to join that table with some other ones.

What i am thinking to do is to ignore that database table and write a php function that gets me the pic like this:

look in that directory and find a pic that begins with 9, or 10 , or whatever, because i know that number. some kind of a regexp.

my question is, will this method be faster than the query? and how would i look for that file?

hope i made myself clear enough.

thnaks


Solution

  • There is glob to help you out: Try glob($id.'_*.jpg');

    Performance depends on your system. Very generally speaking: On Windows it will be slower (due to the way the * semantics are built), on Unices YMMV. I have experienced excellent results with Linux and ReiserFS and very usable results with Linux and ext*. If many images are accessed, chances are, you have the directory in cache. Mind though, that memory pressure is an ingredient to this!