Question

I have a couple images in my images folder for example:

User12345_gallery0.png
User12345_profilePic.jpg
User12345_gallery1.png
User12345_gallery2.jpg
User54321_gallery0.png

What I'm trying to do is pass the user to my getimages.php and get that user's images. I've never done this before so I'm struggling with the syntax. Here's what I have so far:

if($_REQUEST['user']){
$ext = array('jpeg', 'png', 'jpg');
$dir = 'images/';
$user = $_REQUEST['user'];
$images = array();
foreach ($ext as $ex){
    if (file_exists(strpos($dir.$user."_gallery", "gallery"))) {
        //add file to $images???
    }
}
}

I want to check if the file contains the username and the instance of "gallery". How can I do that? Am I on the right track?

Was it helpful?

Solution

Use glob() and stripos() for this..

<?php

if($_REQUEST['user']){

    $user = $_REQUEST['user'];
    $images = array();
     foreach (glob("images/*.{jpg,png,gif}", GLOB_BRACE) as $filename) {
         if(stripos($filename,$user)!==false && stripos($filename,'gallery')!==false)
            $images[]=$filename;
    }
}

OTHER TIPS

Why not just look at the pictures names in the directory and return the ones for your user ?

$ext = array('jpeg', 'png', 'jpg');
$dir = 'images/';
$user = $_REQUEST['user'];

// the length of your username (for the expression bellow)
$usernamelength  = strlen($user); 

// read a list of all files into an array
$filesindirarray = scandir($dir);

// loop through the list
foreach($filesindirarray as $filename)
{
   // does the filename start with
   if(substr($filename,0,($usernamelength+8)) ==  $user .'_gallery')
   {

      // fish out the files extension
      $fileext = pathinfo($filename, PATHINFO_EXTENSION);

      // if the extension of the files is in your list
      if(in_array($fileext,$ext))
         // add to images
    }
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top