I want to display images from multi derctories.
I have this main folder ( backgrounds ) and inside this DIR I have 45 folders each folder have between 10-20 images.
I want to display all the images from the directories.
regards
Al3in
Try this one instead:
<?php
// Recursivly search through a directory and sub-directories for all
// image files. The returned result will be an array will all matches
// and their path (relative to the path sent in through the $dir argument)
//
// $dir - Directory to search through
// $filetypes - Array of file extensions to match
//
// Returns: Array() of files that match the $filetypes filter (or standard
// image file extensions by default).
//
function recursiveFileSearch($dir = '.', $filetypes = null)
{
if (!is_dir($dir))
return Array();
// create a regex filter so we only grab image files
if (is_null($filetypes))
$filetypes = Array('jpg','jpeg','gif','png');
$fileFilter = '/\.('.implode('|',$filetypes).')$/i';
// build a results array
$images = Array();
// open the directory and begin searching
if (($dHandle = opendir($dir)) !== false)
{
// iterate all files
while (($file = readdir($dHandle)) !== false)
{
// we don't want the . or .. directory aliases
if ($file == '.' || $file == '..')
continue;
// compile the path for reference
$path = $dir . DIRECTORY_SEPARATOR . $file;
// is it a directory? if so, append the results
if (is_dir($path))
$results = array_merge($results, recursiveFileSearch($path,$filetypes));
// must be a file, see if it matches our patter and add it if necessary
else if (is_file($path) && preg_match($fileFilter,$file))
$results[] = str_replace(DIRECTORY_SEPARATOR,'/',$path);
}
// close the directory when we're through
closedir($dHandle);
}
// return the outcome
return $results;
}
?>
<html><body><?php array_map(create_function('$i','echo "<img src=\"{$i}\" alt=\"{$i}\" /><br />";'),recursiveFileSearch('backgrounds')); ?></body></html>
Related
I want to delete files in a specific directory in PHP. How can I achieve this?
I have the following code but it does not delete the files.
$files = array();
$dir = dir('files');
while ($file = $dir->read()) {
if ($file != '.' && $file != '..') {
$files[] = $file;
}
unlink($file);
}
I think your question isn't specific, this code must clear all files in the directory 'files'.
But there are some errors in that code I think, and here is the right code:
$files= array();
$dir = dir('files');
while (($file = $dir->read()) !== false) { // You must supply a condition to avoid infinite looping
if ($file != '.' && $file != '..') {
$files[] = $file; // In this array you push the valid files in the provided directory, which are not (. , ..)
}
unlink('files/'.$file); // This must remove the file in the queue
}
And finally make sure that you provided the right path to dir().
You can get all directory contents with glob and check if the value is a file with is_file() before unlinking it.
$files = glob('files/*'); // get directory contents
foreach ($files as $file) { // iterate files
// Check if file
if (is_file($file)) {
unlink($file); // delete file
}
}
If you want to remove files matching a pattern like .png or .jpg, you have to use
$files = glob('/tmp/*.{png,jpg}', GLOB_BRACE);
See manual for glob.
<?php
header("content-type: application/json");
$files = array();
$dir = "Img/House"; //folder src path
$dirHandle = opendir($dir);
while(($file = readdir($dirHandle) !== false)){
if ($file !== "." && $file !== "..")
{
$files[] = $file;
}
}
echo($files);
//echo json_encode($directoryfiles);
?>
I am using ajax to php to return how many folder I had inside that src path , I can count the folder number on ajax , but something wrong with my php file , it seem wont check how many folder I have.
My intention is to use ajax and php check how many folder i have and push those name into the array $files. Can anyone help me take a look. I have no experience one this.
If you only want to return the number of directories in the given path, you can easily use count and glob, see below
// this is not needed unless you output json
// header("content-type: application/json");
$dir = "Img/House"; //folder src path
$dirs = glob($dir . "/*",GLOB_ONLYDIR);
print count($dirs);
// or directly
// print count(glob($dir . "/*",GLOB_ONLYDIR));
// if glob returns the current and parent dirs, "." and ".."
// just remove 2 from the count
// test by doing
print_r($dirs);
// then
print $count($dirs)-2;
I need to get the contents of several files within a directory but which is the best way of doing this?
I am using
$data = file_get_contents('./files/myfile.txt');
but I want every file without having to specify the file individually as above.
You can use glob to get particular file extention and file_get_contents to get the content
$content = implode(array_map(function ($v) {
return file_get_contents($v);
}, glob(__DIR__ . "/files/*.txt")));
/**
* Change the path to your folder.
* This must be the full path from the root of your
* web space. If you're not sure what it is, ask your host.
*
* Name this file index.php and place in the directory.
*/
// Define the full path to your folder from root
$path = "/home/content/s/h/a/shaileshr21/html/download";
// Open the folder
$dir_handle = #opendir($path) or die("Unable to open $path");
// Loop through the files
while ($file = readdir($dir_handle)) {
$data = file_get_contents('$filet');
}
// Close
closedir($dir_handle);
You can dir the directory and loop through it to get the contents of all files.
<?php
$path = './files';
$d = dir($path);
$contents = '';
while (false !== ($entry = $d->read())) {
if (!($entry == '..' || $entry == '.')) {
$contents .= file_get_contents($path.'/'.$entry);
}
}
$d->close();
?>
If you only want .txt files you can change the if statement of the code above from:
if (!($entry == '..' || $entry == '.')) {
to:
if (substr($entry, -4) == '.txt') {
This will result to a variable $contents that is type string and has all the contents of all the files (or only txt files if you select the 2nd solution) that are in the ./files dir.
I am allowing users to upload portfolios in ZIP archives on my site.
The problem is that most archives have the following folder structure:
zipfile.zip
- zipfile
- file1.ext
- file2.ext
- file3.ext
is there any way to simply put the files (not the directory) onto my site (so the folder structure of their portfolio is like so)
user_name
- portfolio
- file1.ext
- file2.ext
- file3.ext
it currently uploads them like so:
user_name
- portfolio
- zipfile
- file1.ext
- file2.ext
- file3.ext
which creates all kinds of problems!
I have tried doing this:
$zip = new ZipArchive();
$zip->open($_FILES['zip']['tmp_name']);
$folder = explode('.', $_FILES['zip']['name']);
end($folder);
unset($folder[key($folder)]);
$folder = (implode('.', $folder));
$zip->extractTo($root, array($folder));
$zip->close();
to no avail.
You could do something like this:
Extract Zip file to a temp location.
Scan through it and move(copy) all the files to portfolio folder.
Delete the temp folder and its all contents (created in Step 1).
Code:
//Step 01
$zip = new ZipArchive();
$zip->open($_FILES['zip']['tmp_name']);
$zip->extractTo('temp/user');
$zip->close();
//Define directories
$userdir = "user/portfolio"; // Destination
$dir = "temp/user"; //Source
//Step 02
// Get array of all files in the temp folder, recursivly
$files = dirtoarray($dir);
// Cycle through all source files to copy them in Destination
foreach ($files as $file) {
copy($dir.$file, $userdir.$file);
}
//Step 03
//Empty the dir
recursive_directory_delete($dir);
// Functions Code follows..
//to get all the recursive paths in a array
function dirtoarray($dir, $recursive) {
$array_items = array();
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if (is_dir($dir. "/" . $file)) {
if($recursive) {
$array_items = array_merge($array_items, dirtoarray($dir. "/" . $file, $recursive));
}
} else {
$file = $dir . "/" . $file;
$array_items[] = preg_replace("/\/\//si", "/", $file);
}
}
}
closedir($handle);
}
return $array_items;
}
// Empty the dir
function recursive_directory_delete($dir)
{
// if the path has a slash at the end we remove it here
if(substr($directory,-1) == '/')
{
$directory = substr($directory,0,-1);
}
// if the path is not valid or is not a directory ...
if(!file_exists($directory) || !is_dir($directory))
{
// ... we return false and exit the function
return FALSE;
// ... if the path is not readable
}elseif(!is_readable($directory))
{
// ... we return false and exit the function
return FALSE;
// ... else if the path is readable
}else{
// we open the directory
$handle = opendir($directory);
// and scan through the items inside
while (FALSE !== ($item = readdir($handle)))
{
// if the filepointer is not the current directory
// or the parent directory
if($item != '.' && $item != '..')
{
// we build the new path to delete
$path = $directory.'/'.$item;
// if the new path is a directory
if(is_dir($path))
{
// we call this function with the new path
recursive_directory_delete($path);
// if the new path is a file
}else{
// we remove the file
unlink($path);
}
}
}
// close the directory
closedir($handle);
// return success
return TRUE;
}
}
How if change your zip file to this?
zipfile.zip
- file1.ext
- file2.ext
- file3.ext
myFolderi have thousands of image files that have keyword text for the name. i am trying to read from the list of images and upload the text into a dB field. the problem is that some of the text has utf8 characters like l’Été that show up like this ��t�
how can i read foreign characters so that the accents will insert into the dB field?
this is how im handling it now
function ListFiles($dir) {
if($dh = opendir($dir)) {
$files = Array();
$inner_files = Array();
while($file = readdir($dh)) {
if($file != "." && $file != ".." && $file[0] != '.') {
if(is_dir($dir . "/" . $file)) {
$inner_files = ListFiles($dir . "/" . $file);
if(is_array($inner_files)) $files = array_merge($files, $inner_files);
} else {
array_push($files, $dir . "/" . $file);//$dir = directory name
//array_push($files, $dir);
}
}
}
closedir($dh);
return $files;
}
}
foreach (ListFiles('../../myDirectory') as $key=>$file){
//$file = preg_replace( '#[^\0-\x80]#u',"", $file );
echo $file ."<br />";
}
this is producing the same result
$str = "l’Été";
utf8_decode($str);
echo $str;
This solution may work for you, it will loop through all files in a directoy and then recursivly through any directories found until it ends up with a massive array of files.
Ive added some points you may wish to change, eg either mutli or single dimension arrays ( all depend on if you may want to maintain the folder structure.
and also if you want the file extention to be saved when you save the file name to db.
Code
function recursive_search_dir($dir) {
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (in_array($file,array(".","..")))
continue; // We dont want to do anything with parent / current directory.
if (is_dir($file)) {
$result[] = recursive_search_dir($file); // Multi-dimension
# OR
array_merge($result,recursive_search_dir($file));// Single-dimension if you dont care about folder structure.
} else {
$result[] = utf8_decode($file); // full file name ( includes extention )
# OR
$result[] = utf8_decode(filename($file,PATHINFO_FILENAME)); // if you only want to capture the name and not the extention.
}
}
closedir($handle);
}
return $result;
}
$files = recursive_search_dir("."); // recursively searcht the current directory.