0

I have a folder unit_images that is full of images with random names except they have a prefix that corresponds to a PRIMARY KEY in a db table.

1_4534534fw4.jpg

2_43534tw4t45.png

You get my point. I am using YoxView to view images and am doing something like this:

<?php
$query = "SELECT id FROM images WHERE unit = ".$_GET['id']."";
$result = mysqli_query($con, $query);
echo '<div class="yoxview">';
while ($row = mysqli_fetch_assoc($result))
{
    echo '<img src="unit_images/01.jpg" alt="First" title="First image" />
    <img src="unit_images/02.jpg" alt="Second" title="Second image" />'
}
echo '</div>';
?>

I want to list the images from my folder unit_images WHERE the unit is the one currently being shown.I just do not know how to tell PHP the filename. I want to do something similar to a 1_% in SQL. Does that make sense? Since I do not know what the rest of the filename looks like I just need to tell php it doesn't matter.

Kita
  • 2,604
  • 19
  • 25
Burning Hippo
  • 787
  • 1
  • 20
  • 47
  • 1
    So I guess you haven't stored the string of the file after the `id` part in your database, right? – Mosty Mostacho Nov 18 '13 at 02:07
  • Your `$query` is vulnerable to [sql injection](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1). For your own safety, you'll want to fix that before you take this code live. – Dan Nov 18 '13 at 02:13

3 Answers3

1

The closest equivalent to SQL's % wildcard that works for files is the shell's * wildcard, which is available in php through the glob() function. You can iterate through its results as follows:

foreach (glob("unit_images/1_*.jpg") as $filename) {
  echo '<img src="unit_images/' . htmlspecialchars(basename($filename)) 
     . '" />';
}
Dan
  • 4,312
  • 16
  • 28
1

If I understand you correctly, you want to get a list of items in a directory with a certain prefix. Step 1 (use sandir() to determine the items in the directory):

$files = scandir('unit_images');

Step 2 (eliminate the unwanted image names):

for ($i=0; $i<count($files); i++)
{
    $file = $files[i];
    $prefix = explode("_", $file)[0];
    if ($prefix != $_GET['id'])
    {
        unset($files[i]);
    }
}

$files is now an array of only the file names prefixed with $_GET['id]

735Tesla
  • 3,162
  • 4
  • 34
  • 57
0

My advice would be to store the whole name of the file in a column so that you can reference it directly instead of having to search in the file system for a matching name.

Having said that, you can search for a file using the glob PHP function.

Maybe you can do something like this:

glob("unit_images/<YOUR_PRIMARY_KEY>_*.{png,jpg}", GLOB_BRACE);
Mosty Mostacho
  • 42,742
  • 16
  • 96
  • 123