Need some help getting all images in folder into an array

Hi all,

Wondered if anyone could help me please.

I am looking for the php to put all the images in a folder into an array, there are other files in the folder but just need a script to get the jpegs.

Any help would be great

Thanks

Sent from my iPhone using Tapatalk

Here’s an example of how to do that.


<?php
class FileExtensionFilter extends FilterIterator
{
  protected
    $extensions = array();
    
  public function __construct($iterator, array $extensions){
    parent::__construct($iterator);
    $this->extensions = $extensions;
  }
  
  public function accept(){
    return in_array(
      pathinfo(parent::current(), PATHINFO_EXTENSION),
      $this->extensions
    );
  }
}

$iterator = new DirectoryIterator('path\\\	o\\\\directory');

foreach(new FileExtensionFilter($iterator, array('jpg', 'jpeg')) as $jpg){
  echo $jpg->getFilename(), PHP_EOL;
}

Hi,

Thanks for the reply, I’m newish to php just wondered what string holds the array

Thanks

Sent from my iPhone using Tapatalk

There isn’t one.

In this example though, $images holds the files it found. :slight_smile:


<?php
class FileExtensionFilter extends FilterIterator
{
  protected
    $extensions = array();
    
  public function __construct($iterator, array $extensions){
    parent::__construct($iterator);
    $this->extensions = $extensions;
  }
  
  public function accept(){
    return in_array(
      pathinfo(parent::current(), PATHINFO_EXTENSION),
      $this->extensions
    );
  }
}

$iterator = new DirectoryIterator('path\\\	o\\\\directory');
$images   = iterator_to_array(new FileExtensionFilter($iterator, array('jpg', 'jpeg')));

Hi Mate,

Thanks for that, I have now linked your script to a bit of code that will take the Array and create a zip file for downloading, but again i have run into problems it creates a zip file but you cant open the zip file, and when i check it was an error message not a zip.

Please find my code bellow


<?php
class FileExtensionFilter extends FilterIterator
{
  protected
    $extensions = array();
    
  public function __construct($iterator, array $extensions){
    parent::__construct($iterator);
    $this->extensions = $extensions;
  }
  
  public function accept(){
    return in_array(
      pathinfo(parent::current(), PATHINFO_EXTENSION),
      $this->extensions
    );
  }
}

$iterator = new DirectoryIterator('NewGallery/photos');
$file_names = iterator_to_array(new FileExtensionFilter($iterator, array('jpg', 'jpeg')));

//function to zip and force download the files using PHP
function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
  //create the object
  $zip = new ZipArchive();
  //create the file and throw the error if unsuccessful
  if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
    exit("cannot open <$archive_file_name>\
");
  }
  //add each files of $file_name array to archive
  foreach($file_names as $files)
  {
    $zip->addFile($file_path.$files,$files);
  }
  $zip->close();
  //then send the headers to foce download the zip file
  header("Content-type: application/zip");
  header("Content-Disposition: attachment; filename=$archive_file_name");
  header("Pragma: no-cache");
  header("Expires: 0");
  readfile("$archive_file_name");
  exit;
}

  # $file_names=$filesa;
  $archive_file_name='zipped.zip';
  $file_path=dirname(__FILE__).'/';
  zipFilesAndDownload($file_names,$archive_file_name,$file_path);
  echo $file_names;

?>

any help would be great

Sorry it’s me being a div I didn’t put the path of the files in it

Sent from my iPhone using Tapatalk

Nope still doesn’t work

Sent from my iPhone using Tapatalk

Include the filesize of $archive_file_name in the headers and do not echo out the $file_names variable.

Hi,

By file size what do you mean, as the folder gets further photos added and wouldn’t know the full file size.

Sorry to be thick

Sent from my iPhone using Tapatalk

… but you can get the filesize of the zip file you’ve just created, right? :wink:

I have found a proble with my code, the array is empty, so I have tried a different bit of code and still if i printR my array just comes up Array ( )

this is my new code

function stf_get_files( $directory, $filter = array( "*" ) ){
    $results = array(); // Result array
    $filter = (array) $filter; // Cast to array if string given
 
    // Open directory
    $handler = opendir( $directory );
 
    // Loop through files
    while ( $file = readdir($handler) ) {
 
        // Jump over directories.
        if( is_dir( $file ) )
            continue;
 
        // Prepare file extension
        $extension = end( explode( ".", $file ) ); // Eg. "jpg"
 
        // If extension fits add it to array
        if ( $file != "." && $file != ".." && ( in_array( $extension, $filter ) || in_array( "*", $filter ) ) ) {
            $results[] = $file;
        }
    }
 
    // Close handler
    closedir($handler);
 
    // Return
    return $results;
}
$dir = "NewGallery/photos";
$smeg = stf_get_files($dir, array( "php", "gif"));
print_r($smeg);

Any help would be great

I have got the script working sort of, I have check all the way through it now populates the array with jpg only , it creates a zip file and also starts the download, my problem now it that when you open the zip file there is only 1 photo in it but in the directory (and array) there are 27.

this is doing my head in now any help would be great, please see my code bellow

<?php

function zip_files($files_to_add = array(), $save_to = '', $overwrite_existing = true)
{
	//if the file already exists and overwrite is
	//set to false then return false and get out
	if(file_exists($save_to) && !$overwrite_existing)
	{
		return false;
	}
	
	//now on to the action
	$files = array();
	
	//check for an array
	if(is_array($files_to_add))
	{
		//loop through each file in the array
		foreach($files_to_add as $valid_file)
		{
			//if the file exists then add to the file array
			if(file_exists($valid_file))
			{
				$files[] = $valid_file;
			}
			
			//check the count of files
			if(count($files))
			{
				//create a new zip archive object
				$zip_archive = new ZipArchive();
				
				//open zip archive for modifying and check for a value
				//of true with the modes specified
				if($zip_archive->open($save_to, $overwrite_existing ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) != true)
				{
					return false;
				}
				
				//loop through the file array
				//adding each file to the new zip archive
				foreach($files as $file)
				{
					$zip_archive->addFile($file, $valid_file);
				}
				
				//close the zip archive
				$zip_archive->close();
				
				//finally make sure the new zip file exists
				return((file_exists($save_to)) ? true : false);
			}
		}
	}
}



function stf_get_files( $directory, $filter = array( "*" ) ){
    $results = array(); // Result array
    $filter = (array) $filter; // Cast to array if string given
 
    // Open directory
    $handler = opendir( $directory );
 
    // Loop through files
    while ( $file = readdir($handler) ) {
 
        // Jump over directories.
        if( is_dir( $file ) )
            continue;
 
        // Prepare file extension
        $extension = end( explode( ".", $file ) ); // Eg. "jpg"
 
        // If extension fits add it to array
        if ( $file != "." && $file != ".." && ( in_array( $extension, $filter ) || in_array( "*", $filter ) ) ) {
            $results[] = $file;
        }
    }
 
    // Close handler
    closedir($handler);
 
    // Return
    return $results;
}


$dir = ".";
$my_files = stf_get_files($dir, array( "JPG", "php", "GIF"));


$zip = zip_files($my_files,'ThePhotos.zip');

if(!$zip)
{
    echo('There was a problem creating the zip file');
}
else
{
     //BUILD THE FILE INFORMATION
     
     $file = "ThePhotos.zip";
 
     //CREATE/OUTPUT THE HEADER
     header("Content-type: application/force-download");
     header("Content-Transfer-Encoding: Binary");
     header("Content-length: ".filesize($file));
     header("Content-disposition: attachment; filename=\\"".basename($file)."\\"");
     readfile($file);
}
?>

Why not just use glob?


// Directory to read images from
$dir = "./";

// Read the directory and select jpg only
$filenames = glob("$dir*.{jpg,JPG,jpeg,JPEG}", GLOB_BRACE);

The array is in $filenames and only .jpg files are selected - allowing for lower and uppercase. May need to modify the filename for your use - echo them out to view what it is as the path is included in the filename.

Thanks mate will give it a go

Sent from my iPhone using Tapatalk

Hi Guys,

thanks for all your help, I have finaly got it sorted and it works perfect, thought I would post the code just incase anyone else needs it

<?php

//function to zip and force download the files using PHP
function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
  //create the object
  $zip = new ZipArchive();
  //create the file and throw the error if unsuccessful
  if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
    exit("cannot open <$archive_file_name>\
");
  }
  //add each files of $file_name array to archive
  foreach($file_names as $files)
  {
    $zip->addFile($file_path.$files,$files);
  }
  $zip->close();
  //then send the headers to foce download the zip file
  header("Content-type: application/zip");
  header("Content-Disposition: attachment; filename=$archive_file_name");
  header("Pragma: no-cache");
  header("Expires: 0");
  readfile("$archive_file_name");
  exit;
}

// Directory to read files from

$dir = ""; // blank = directory script is in

// Read the directory and select jpg only

$filenames_to_download = glob("$dir*.{jpg,JPG,jpeg,JPEG}", GLOB_BRACE); 

// The Zip Funtion 

  $archive_file_name='zipped.zip';
  $file_path=dirname(__FILE__).'/';
  zipFilesAndDownload($filenames_to_download,$archive_file_name,$file_path);

?>