php - scandir and return matched files - php

I am trying to get a matched array of files using scandir() and foreach().
when I run scandir() then it returns all file list. Its okey here.
now in second step when I do foreach scandir()s array then I get only one matched file. but there are two files called (please note before doing foreach my scandir() returns all files including this two files);
widget_lc_todo.php
widget_lc_notes.php
something is missing in my code, I dont know what :-(
here is my code:
$path = get_template_directory().'/templates';
$files = scandir($path);
print_r($files);
$template = array();
foreach ($files as $file){
if(preg_match('/widget_lc?/', $file)):
$template[] = $file;
return $template;
endif;
}
print_r($template);

Your code above is calling return as soon as it finds the first matching file, which means that the foreach loop exits as soon as preg_match returns true. You should not return until after the foreach loop exits:
// ...
foreach ($files as $file){
if(preg_match('/widget_lc?/', $file)) {
$template[] = $file;
}
}
return $template;
// ...

Related

PHP Find files with specific name part in folder

Is there a way to get all the files with a specific name from a folder with php?
For example I have in folder next files:
6546-da6sd.png
465-dasd.jpg
654-548484.jpg
654-sasaf.png
654-sakj879.jpg
776-54fsdfs.png
....
I want to get all files that start with "654-" (but not the first (6546-da6sd.png))
Thank You!
you can use glob() and strpos() like:
<?php
$dir = 'files/';
$key = '654-';//search key
foreach (glob("$dir*") as $file) {
$file = str_replace($dir,'',$file);
if (strpos($file, $key) == 0) {
echo($file."<br>");
}
}
?>

php glob() does not show files from another domain?

I am trying to read all files from a directory and store it in an array.But the file which contains this code is on www.xyz.com domain and i want to check files exist on https://www.test.com/prod_images/.But glob is returning empty array.Why is it returning empty array ?
foreach (glob('https://www.test.com/prod_images/*', GLOB_ONLYDIR) as $dir) {
$dirname = basename($dir);
$items[] = $dirname;
}
print_r($items);

PHP List Directories Recursively Issue

I'm trying to list all PHP files in a specified directory and for it to recursively check all sub-directories until it finds no more, there could be numerous levels.
The function I have below works fine with the exception that it only recurses down one level.
I've spent hours trying to see where I'm going wrong, I'm calling the scanFiles() when it finds a new directory but this only seems to work one level down and stop, any help greatly appreciated.
Updated:
function scanFiles($pParentDirectory)
{
$vFileArray = scandir($pParentDirectory);
$vDirectories = array();
foreach ($vFileArray as $vKey => $vValue)
{
if (!in_array($vValue, array('.', '..')) && (strpos($vValue, '.php') || is_dir($vValue)))
{
if (!is_dir($vValue))
$vDirectories[] = $vValue;
else
{
$vDirectory = $vValue;
$vSubFiles = scanFiles($vDirectory);
foreach ($vSubFiles as $vKey => $vValue)
$vDirectories[] = $vDirectory.DIRECTORY_SEPARATOR.$vValue;
}
}
}
return $vDirectories;
}
You can do this easily like this:
// helper function
function getFiles(&$files, $dir) {
$items = glob($dir . "/*");
foreach ($items as $item) {
if (is_dir($item)) {
getFiles($files, $item);
} else {
if (end(explode('.', $item)) == 'php') {
$files[] = basename($item);
}
}
}
}
// usage
$files = array();
getFiles($files, "myDir");
// debug
var_dump($files);
myDir looks like this: has php files in all dirs
Output:
P.S. if you want the function to return the full path to the found .php files, remove the basename() from this line:
$files[] = basename($item);
This will then produce result like this:
hope this helps.
This is because $vDirectory is just a folder name, so scanDir looks in the current folder for it, not the sub folder.
What you want to do is to pass in the path to the folder, not just the name. This should be as simple as changing your recursive call to scanFiles($pParentDirectory . DIRECTORY_SEPARATOR . $vDirectory)
Your main problem is functions like scanDir or isDir need the full file path to work.
If you pass the full file path to them, it should work correctly.

Delete files not matching a list

So I'm trying to make a simple script, it will have a list of predefined files, search for anything that's not on the list and delete it.
I have this for now
<?php
$directory = "/home/user/public_html";
$files = glob($directory . "*.*");
foreach($files as $file)
{
$sql = mysql_query("SELECT id FROM files WHERE FileName='$file'");
if(mysql_num_rows($sql) == 0)
unlink($directory . $file);
}
?>
However, I'd like to avoid the query so I can run the script more often (there's about 60-70 files, and I want to run this every 20 seconds or so?) so how would I embedd a file list into the php file and check against that instead of database?
Thanks!
You are missing a trailing / twice.. In glob() you are giving /home/user/public_html*.* as the argument, I think you mean /home/user/public_html/*.*.
This is why I bet nothing matches the files in your table..
This won't give an error either because the syntax is fine.
Then where you unlink() you do this again.. your argument home/user/public_htmltestfile.html should be home/user/public_html/testfile.html.
I like this syntax style: "{$directory}/{$file}" because it's short and more readable. If the / is missing, you see it immediately. You can also change it to $directory . "/" . $file, it you prefer it. The same goes for one line conditional statements.. So here it comes..
<?php
$directory = "/home/user/public_html";
$files = glob("{$directory}/*.*");
foreach($files as $file)
{
$sql = mysql_query("SELECT id FROM files WHERE FileName=\"{$file}\";");
if(mysql_num_rows($sql) == 0)
{
unlink("{$directory}/{$file}");
}
}
?>
EDIT: You requested recursion. Here it goes..
You need to make a function that you can run once with a path as it's argument. Then you can run that function from inside that function on subdirectories. Like this:
<?php
/*
ListDir list files under directories recursively
Arguments:
$dir = directory to be scanned
$recursive = in how many levels of recursion do you want to search? (0 for none), default: -1 (for "unlimited")
*/
function ListDir($dir, $recursive=-1)
{
// if recursive == -1 do "unlimited" but that's no good on a live server! so let's say 999 is enough..
$recursive = ($recursive == -1 ? 999 : $recursive);
// array to hold return value
$retval = array();
// remove trailing / if it is there and then add it, to make sure there is always just 1 /
$dir = rtrim($dir,"/") . "/*";
// read the directory contents and process each node
foreach(glob($dir) as $node)
{
// skip hidden files
if(substr($node,-1) == ".") continue;
// if $node is a dir and recursive is greater than 0 (meaning not at the last level or disabled)
if(is_dir($node) && $recursive > 0)
{
// substract 1 of recursive for ever recursion.
$recursive--;
// run this same function again on itself, merging the return values with the return array
$retval = array_merge($retval, ListDir($node, $recursive));
}
// if $node is a file, we add it to the array that will be returned from this function
elseif(is_file($node))
{
$retval[] = $node;
// NOTE: if you want you can do some action here in your case you can unlink($node) if it matches your requirements..
}
}
return $retval;
}
// Output the result
echo "<pre>";
print_r(ListDir("/path/to/dir/",1));
echo "</pre>";
?>
If the list is not dynamic, store it in an array:
$myFiles = array (
'some.ext',
'next.ext',
'more.ext'
);
$directory = "/home/user/public_html/";
$files = glob($directory . "*.*");
foreach($files as $file)
{
if (!in_array($file, $myFiles)) {
unlink($directory . $file);
}
}

Remove folders from php scandir listing

I have a php script $filelist = scandir('myfolder/') which list outs files from my folder. But it is adding child folders also to the array so that they are also populated when i print the result using foreach. I want to remove folders from getting added to the array. How can I do this??
Simple way
$dir = 'myfolder/';
$filelist = scandir($dir);
foreach ($filelist as $key => $link) {
if(is_dir($dir.$link)){
unset($filelist[$key]);
}
}
A clean concise solution could be to use array_filter to exclude all sub-directories like this
$files = array_filter(scandir('directory'), function($item) {
return !is_dir('directory/' . $item);
});
This effectively also removes the . and .. which represent the current and the parent directory respectively.
You can use the function glob(), and check if the item of array is_dir().
If you know what the name of the folders are, you could create an array of these folders and then use array_diff to remove them from the result:
$folders = array('..', '.', 'folder');
$files = array_diff(scandir($dir), $folders);
scandir returns an array of folders. You can remove any element of the array like this:
unset( $filelist[0] );
where 0 is the index of the element you wish to remove. You can also use array_search() if you need to find directories by name.
try
<?php
$dir = "/example";
$filelist = new Array();
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (!is_dir($file)) {
$filelist[] = $file;
}
}
closedir($dh);
}
}
?>
It's like doing a scandir, but checking the type of the returned files

Categories