I have this code that reads all the content of a folder and converts it to an array, but I want to only the code reads folders and no files.
For example in language file are these files and folders:
../
en_EN/
fr_FR/
happy.rar
And the code is:
$folder = '../language/';
$return = scandir($folder, 1);
$return = array_diff($return, array('.', '..','error_log','_notes'));
$return = str_replace(".php", "", $return);
I can make exceptions in the 3rd line, but I want to create an exception for all the files.
Is there a way to make that?
Thank you
You can use glob() to select only folders simply as per below with GLOB_ONLYDIR flag.
and use basename() to get only folder name.
$a = glob("../language/*", GLOB_ONLYDIR ); // $a has only folders
foreach($a as $file){
echo(basename($file));
}
Related
My directory structure is like D:/dir1/dir2/project_dir/dir3/dir4/dir5/cache/all_files
So i want to get all the files under cache folder.
So i wrote
glob("project_dir/*/*/*/cache/*");
But cache folder is also there in dir3 or dir4 like
D:/dir1/dir2/project_dir/dir3/dir4/dir5/dir6/dir7/cache/all_files
or
D:/dir1/dir2/project_dir/dir3/cache/all_files
So can anyone give me the regex to get the files from 'cache' folder,
like
glob("project_dir/*/cache/*");
Btw, this is not working because it is searching for immediate directory after project_dir.
Thanks in advance.
Hope this helps!
Supports PHP 5 and 7 only,check your version before using this code
for more info refer : http://php.net/manual/en/class.directoryiterator.php
$searchCacheFolderUnder = 'D:\xampp\htdocs\mygit\\';
$pathOfAllCacheFolders = array();
$dir = new DirectoryIterator(realpath($searchCacheFolderUnder));
foreach ($dir as $fileInfo) {
if($fileInfo->isDir()) {
// optimize strpos with inbuild directory iterator methods
if( strpos($fileInfo->getPathname(), 'cache') !== false ){
$pathOfAllCacheFolders[] = $fileInfo->getPathname();
}
}
}
// contains all cache folders path
echo "<pre>";
print_r($pathOfAllCacheFolders);
echo "</pre>";
// loop on all cache folders
foreach($pathOfAllCacheFolders as $cachePath)
$dirCache = new DirectoryIterator(realpath($cachePath));
foreach ($dirCache as $fileInfo) {
//$fileInfo object will have everything you need
echo "<pre>";
print_r($fileInfo);
echo "</pre>";
}
You have to modify this code a bit to meet your requirement. Refer Directory Iterator for more available options.
You can use glob('*') but the only perk for using this is it ignores all hidden files. If you want all the files that includes hidden files in a folder then use:
$files = glob('project_dir/cache/{,.}*', GLOB_BRACE);
Remember this will return all the files for "." and "" and even the directory entries . and .. Let me know in case of any issues.
Hope this helps.
I intend to create a simple codes using php that can replace strings inside the files much like replace function in the notepad and ms word but the difference is it will replace all strings match to the desired string to change in all files inside the folder any Idea how to do that?
You can use useful glob() php function.
Example
<?php
$files_in_your_folder = glob('c:\wamp\www\FindReplace\*');
foreach(glob('c:\wamp\www\FindReplace\*') as $path_to_file) {
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace("Hello","World",$file_contents);
file_put_contents($path_to_file,$file_contents);
}
?>
If You have sub folders in your directory then you can get files with the below code
$path = realpath(__DIR__ . '/textfiles/'); // Path to your textfiles
$files_in_your_folder = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path), \RecursiveIteratorIterator::SELF_FIRST);
See previous Question which was partly answered but there has been a change in requirements for the script: PHP - Exploding / Moving / Filename
i'm new to php and am stuck. I have loads of files that look like this:
2014-04-01 NS122345 - The date, the initials of the person and there employee code.
I want to be able to move the files that have NS or JB Or GA into there relevant folder/directories. So for NS it would go into the Nathan Saunders Folder, for JB into the Joe Bailey folder.
My directory structure looks like this:
root/wan/upload - Where files/images/docs are stored. Inside upload folder i have:
>2014-04-08 NS6565.doc
>2012-01-03 JB8932.doc
>2013-02-01 GA5434.doc
>etc
root/wan/administrator/components/com_upload - where my code is stored
This is my php code for moving, creating and checking the filename and putting it in the correct folder:
$dir = JPATH_BASE . DS . "upload";
$folders = array('SE528733B'=>'/var/www/vhosts/test.cariss.co.uk/httpdocs/wan/upload/528733B','SE125673B'=>'/var/www/vhosts/test.cariss.co.uk/httpdocs/wan/upload/125673B','SE3452312'=>'/var/www/vhosts/test.cariss.co.uk/httpdocs/wan/upload/3452312');
$files = scandir($dir);
foreach($files AS $file){
if(!is_file($dir.DS.$file)){ continue; }
$array = explode(' ', $file);
if(count($array)<2){ continue; }
$firstTwoLetters = substr($array[1], 0, 9);
$foldername = $firstTwoLetters;
if(is_dir($folders[$firstTwoLetters])||mkdir($foldername[$firstTwoLetters],0777, 1))
rename($dir.DS.$file,$foldername[$firstTwoLetters].DS.$file);
That code currently reads the filename if its already in the array "folders" it moves to the correct folder, I have changed it recently to make the folder automatically reading whatever file is in the upload section, but the problem comes when making the folder, the mkdir seems to make the directory:
1) in the wrong place it makes it where the code is stored which is in the com_upload section instead of making it in the upload folder.
2) Names it wrong it takes the first letter not the letters or numbers after it. E.g. "2014-04-08 NS6565.doc", makes the directory "N"
Any help to fixing those 2 problems would be great.
Thanks,
1) If you want to create the directory in another place or you use a relative path from the directory your code is or you use an absolute path.
2) When you are creating the directory you use $foldername but it isn't a name of any directory. It's instead the name of the file. Also, you use it as an array when it's a string (so it only take one char)
Try this:
$dir = JPATH_BASE . DS . "upload";
$folders = array('SE528733B'=>'/var/www/vhosts/test.cariss.co.uk/httpdocs/wan/upload/528733B','SE125673B'=>'/var/www/vhosts/test.cariss.co.uk/httpdocs/wan/upload/125673B','SE3452312'=>'/var/www/vhosts/test.cariss.co.uk/httpdocs/wan/upload/3452312');
$files = scandir($dir);
foreach($files AS $file){
if(!is_file($dir.DS.$file)){ continue; }
$array = explode(' ', $file);
if(count($array)<2){ continue; }
$firstTwoLetters = substr($array[1], 0, 9);
$foldername = substr($firstTwoLetters,0,2);
if(is_dir($dir. DS . $foldername)||mkdir($dir. DS . $foldername,0777, 1))
rename($dir.DS.$file,$dir . DS . $foldername . DS.$file);
I am trying to show the file and directory contents of a zip file without extracting it.
Zip library is not installed with PHP and I don't have permission to install it.
I am trying now to parse the output of unzip -l <zipfile> to get the directory structure of the zip file together with other file information. I can easily get the file information by parsing the result line by line.
However, I found it difficult to convert it a directory structure in array since I'm just a newbie in php. the structure is something like below (please ignore the syntax I'm just trying to show the structure).
Subdirectories or sub files are placed inside the children index.
$file[0]['file_name'] = 'dir1',
$file[0]['children'] = array($subfile[0]['file_name'] = 'subdir1',
$subfile[0]['children'] = .....,
$subfile[1]['file_name'] = 'subdir1',
$subfile[1]['children'] = .....)
$file[1]['file_name'] = 'dir2',
$file[1]['children'] = array($subfile[0]['file_name'] = 'subdir1',
$subfile[0]['children'] = .....,
$subfile[1]['file_name'] = 'subdir1',
$subfile[1]['children'] = .....)
Below is the sample output of unzip -l <zipfile>.
12363 08-18-2010 13:07 lsmaps/aka.gif
10299 03-10-2010 12:34 lsmaps/aob.gif
26095 03-10-2010 12:34 lsmaps/cba.gif
Would you know of better way of doing it?
Thanks
pclzip a pure PHP (read: you can just copy the files into your project) reader and writer for zip, like this:
require_once('pclzip.lib.php');
$archive = new PclZip('zipfile.zip');
var_export($archive->listContent());
To convert the flat information into a tree, you can use the following helper function:
function flatToTree($flat) {
$res = array();
foreach ($flat as $e) {
$parent =& $res;
$path = explode('/', $e['filename']);
for ($i = 0;$i < count($path) - 1;$i++) {
if (! array_key_exists($path[$i], $parent)) {
$parent[$path[$i]] = array('file_name'=>$path[$i],
'children'=>array());
}
$parent =& $parent[$path[$i]]['children'];
}
$basename = $path[count($path)-1];
if ($basename != '') { // A file, not a directory
$parent[$basename] = array('file_name' => $path[$i]);
}
}
return $res;
}
var_export(flatToTree($archive->listContents()));
Note that it uses associative arrays (or dictionary/maps) to allow faster access to the files by name. You can still iterate over it with foreach. If you, however, must have numeric arrays, simply call array_values on each element.
In the script below, I'm attempting to iterate over the folders and files inside of the $base folder. I expect it to contain a single level of child folders, each containing a number of .txt files (and no subfolders).
I'm just needing to understand how to reference the elements in comments below...
Any help much appreciated. I'm really close to wrapping this up :-)
$base = dirname(__FILE__).'/widgets/';
$rdi = new RecursiveDirectoryIterator($base);
foreach(new RecursiveIteratorIterator($rdi) as $files_widgets)
{
if ($files_widgets->isFile())
{
$file_name_widget = $files_widgets->getFilename(); //what is the filename of the current el?
$widget_text = file_get_contents(???); //How do I reference the file here to obtain its contents?
$sidebar_id = $files_widgets->getBasename(); //what is the file's parent directory name?
}
}
//How do I reference the file here to obtain its contents?
$widget_text = file_get_contents(???);
$files_widgets is a SplFileInfo, so you have a few options to get the contents of the file.
The easiest way is to use file_get_contents, just like you are now. You can concatenate together the path and the filename:
$filename = $files_widgets->getPathname() . '/' . $files_widgets->getFilename();
$widget_text = file_get_contents($filename);
If you want to do something funny, you can also use openFile to get a SplFileObject. Annoyingly, SplFileObject doesn't have a quick way to get all of the file contents, so we have to build a loop:
$fo = $files_widgets->openFile('r');
$widget_text = '';
foreach($fo as $line)
$widget_text .= $line;
unset($fo);
This is a bit more verbose, as we have to loop over the SplFileObject to get the contents line-by-line. While this is an option, it'll be easier for you just to use file_get_contents.