Php add comand for search file on subfolders - php

I have this script that works good, but I need to add a command for searching on all subfolders.
Example: I have a folder data and this contains more another folders... I need to search files on this folders.
$dir = 'data';
$exclude = array('.', '..', '.htaccess');
$q = (isset($_GET['q'])) ? strtolower($_GET['q']) : '';
$res = opendir($dir);
while(false !== ($file = readdir($res))) {
if(strpos(strtolower($file), $q) !== false &&!in_array($file, $exclude)) {
echo "<a href='$dir/$file'>$file</a>";
echo "<br>";
}
}
closedir($res);

you can use scandir() function
$dir = '/tmp';
$file = scandir($dir);
print_r($file);

I think this is the recursive function you are looking for :
function dir_walk($dir, $q) {
$q = trim($q);
$exclude = array('.', '..', '.htaccess');
if($dh = opendir($dir)) {
while(($file = readdir($dh)) !== false) {
if(in_array($file, $exclude)) { continue; }
elseif(is_file($dir.$file)) {
if($q === '' || strpos(strtolower($file), $q) !== false) {
echo '<a href='.$dir.$file.'>'.$dir.$file.'</a><br/>';
}
}
elseif(is_dir($dir.$file)) {
dir_walk($dir.$file.DIRECTORY_SEPARATOR, $q);
}
}
closedir($dh);
}
}
$q = (isset($_GET['q'])) ? strtolower($_GET['q']) : '';
dir_walk('/data/', $q);
Edit: data need to be the absolute path to the main dir, with ending directory separator "/data/"

Related

limit results on php script search files in folder

I do not have much experience with php. I have one good script. It searches files in a folder by the name of the file, example pdf file. It works, but I need to limit the number of results because when I search for pdf for example it shows me all pdf files, I do not have a limit on the results. I need to limit this to only 15 results.
And another question: is it possible to add the message "file not found" to the results if nothing was found?
<?php
$dir = 'data';
$exclude = array('.','..','.htaccess');
$q = (isset($_GET['q']))? strtolower($_GET['q']) : '';
$res = opendir($dir);
while(false!== ($file = readdir($res))) {
if(strpos(strtolower($file),$q)!== false &&!in_array($file,$exclude)) {
echo "<a href='$dir/$file'>$file</a>";
echo "<br>";
}
}
closedir($res);
?>
You might just want to add a counter either before the if or inside the if statement, however you wish, and your problem may be solved:
Counter Before if
$dir = 'data';
$exclude = array('.', '..', '.htaccess');
$q = (isset($_GET['q'])) ? strtolower($_GET['q']) : '';
$res = opendir($dir);
$c = 0; // counter
while (false !== ($file = readdir($res))) {
$c++; // add 1
if (strpos(strtolower($file), $q) !== false && !in_array($file, $exclude)) {
echo "<a href='$dir/$file'>$file</a>";
echo "<br>";
}
if ($c > 15) {break;} // break
}
closedir($res);
Counter Inside if
$dir = 'data';
$exclude = array('.', '..', '.htaccess');
$q = (isset($_GET['q'])) ? strtolower($_GET['q']) : '';
$res = opendir($dir);
$c = 0; // counter
while (false !== ($file = readdir($res))) {
if (strpos(strtolower($file), $q) !== false && !in_array($file, $exclude)) {
$c++; // add 1
echo "<a href='$dir/$file'>$file</a>";
echo "<br>";
if ($c > 15) {break;} // break
}
}
closedir($res);

Find a keyword in a folder with files

I use a script that allows me to find a file in a folder whose keyword matches the word chosen by the user, but the problem is that the result does not match the search keyword.
For example the user searches for the word "Hyper-v" and either it comes out files that have no relationship or it comes out nothing.
Thank you for your help
$findThisString = stripcslashes($_POST["recherchemotcle"]);
$path = "tuto";
$dir = opendir($path);
while (false !== ($file = readdir($dir)))
{
$data = file_get_contents($path . '/' . $file);
if (stripos($data, $findThisString) !== false)
{
echo ''.$file.' <br/>';
}
}
$dir->close();
Try this,
$findThisString = stripcslashes($_POST["recherchemotcle"]);
$path = "tuto";
$dir = opendir($path);
while (false !== ($file = readdir($dir)))
{ $data = glob($path . '/' . $file);
if (stripos($data[0], $findThisString) !== false)
{
echo ''.$file.' <br/>';
}
}
closedir($dir);
You can use glob() function something like below:
<?php
$findThisString = stripcslashes($_POST["recherchemotcle"]);
$path = "tuto";
$list =glob($path."/".$findThisString."*.*");
foreach ($list as $l) {
$files[] = $l;
}
?>

PHP Directory, subdirectory and file Listing default sort order

i want to list all directory, sub-directory and files using php.
i have tried following code. it returns all the directory, sub directory and files but it's not showing in correct order.
for ex:default order is 1dir, 2dir, 7dir, 8dir while in browser it shows 1dir, 8dir, 7dir, 2dir which is not correct.
code:
function createDir($path = '.')
{
if ($handle = opendir($path))
{
echo "<ul>";
while (false !== ($file = readdir($handle)))
{
if (is_dir($path.$file) && $file != '.' && $file !='..') {
printSubDir($file, $path);
}
else if ($file != '.' && $file !='..'){
$allowed = array('pdf','doc','docx','xls','xlsx','jpg','png','gif','mp4','avi','3gp','flv','mov','PDF','DOC','DOCX','XLS','XLSX','JPG','PNG','GIF','MP4','AVI','3GP','FLV','MOV','html','HTML','css','CSS','js','JS');
$ext = pathinfo($file, PATHINFO_EXTENSION);
if(in_array($ext,$allowed) ) {
$queue[] = $file;
}
}
}
printQueue($queue, $path);
echo "</ul>";
}
}
function printQueue($queue, $path)
{
sort($queue);
foreach ($queue as $file)
{
//printFile($file, $path);
}
}
function printFile($file, $path) {
echo "<li><a href=\"".$path.$file."\" target='_blank'>$file</a></li>";
}
function printSubDir($dir, $path)
{
echo "<li><span class=\"toggle\">$dir</span>";
createDir($path.$dir."/");
echo "</li>";
}
createDir($path);
?>
need help to fix the code and display the direcotry , subdirectory and files in correct order.
I'm having the same problem during listing a directory files. But I have used DirectoryLister
This code is very useful. You can list out your files easily.
You can implement it by following steps.
Download and extract Directory Lister
Copy resources/default.config.php to resources/config.php
Upload index.php and the resources folder to the folder you want listed
Upload additional files to the same directory as index.php
I hope this might help you
You can start by looping the array and printing each directory:
public function dirtree($dir, $regex='', $ignoreEmpty=false) {
if (!$dir instanceof DirectoryIterator) {
$dir = new DirectoryIterator((string)$dir);
}
$dirs = array();
$files = array();
foreach ($dir as $node) {
if ($node->isDir() && !$node->isDot()) {
// print_r($node);
$tree = dirtree($node->getPathname(), $ignoreEmpty);
// print"<pre>";print_r($tree);
if (!$ignoreEmpty || count($tree)) {
$dirs[$node->getFilename()] = $tree;
}
} elseif ($node->isFile()) {
$name = $node->getFilename();
//if ('' == $regex || preg_match($regex, $name)) {
$files[] = $name;
}
}
asort($dirs);
sort($files);
return array_merge($files, $dirs);
}
Use like this:
$fileslist = dirtree('root');
echo "<pre style='font-size:15px'>";
print_r($fileslist);

php function to read subdir content

I would like to ask what I have to add to make this function to show not only the files on top dir but also the files in subdirs..
private function _populateFileList()
{
$dir_handle = opendir($this->_files_dir);
if (! $dir_handle)
{
return false;
}
while (($file = readdir($dir_handle)) !== false)
{
if (in_array($file, $this->_hidden_files))
{
continue;
}
if (filetype($this->_files_dir . '/' . $file) == 'file')
{
$this->_file_list[] = $file;
}
}
closedir($dir_handle);
return true;
}
Thank you in advance!
You could implement the recursion yourself, or you could use the existing iterator classes to handle the recursion and filesystem traversal for you:
$dirIterator = new RecursiveDirectoryIterator('.', FilesystemIterator::SKIP_DOTS);
$recursiveIterator = new RecursiveIteratorIterator($dirIterator);
$filterIterator = new CallbackFilterIterator($recursiveIterator, function ($file) {
// adjust as needed
static $badFiles = ['foo', 'bar', 'baz'];
return !in_array($file, $badFiles);
});
$files = iterator_to_array($filterIterator);
var_dump($files);
By this you can get all subdir content
customerdel('FolderPath');
function customerdel($dirname=null){
if($dirname!=null){
if (is_dir($dirname))
$dir_handle = opendir($dirname);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
echo $dirname."/".$file.'<br>';
else{
echo $dirname.'/'.$file.'<br> ';
customerdel($dirname.'/'.$file);
}
}
}
closedir($dir_handle);
}
}
Here is how you can get a recursive array of all files in a directory and its subdirectories.
The returned array is like: array( [fileName] => [filePath] )
EDIT: I've included a small check if there are filenames in the subdirectories with the same name. If so, an underscore and counter is added to the key-name in the returned array:
array( [fileName]_[COUNTER] => [filePath] )
private function getFileList($directory) {
$fileList = array();
$handle = opendir($directory);
if ($handle) {
while ($entry = readdir($handle)) {
if ($entry !== '.' and $entry !== '..') {
if (is_dir($directory . $entry)) {
$fileList = array_merge($fileList, $this->getFileList($directory . $entry . '/'));
} else {
$i = 0;
$_entry = $entry;
// Check if filename is allready in use
while (array_key_exists($_entry, $fileList)) {
$i++;
$_entry = $entry . "_$i";
}
$fileList[$_entry] = $directory . $entry;
}
}
}
closedir($handle);
}
return $fileList;
}

How to scan all the .m files using php? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
php scandir --> search for files/directories
I have a folder, inside this folder, have many subfolders, but I would like to scan all the subfolders, and scan all the .m file... How can I do so??
Here is the file:
/MyFilePath/
/myPath.m
/myPath2.m
/myPath3.m
/MyClasses/
/my.m
/my1.m
/my2.m
/my3.m
/Utilities/
/u1.m
/u2.m
/External/
/a.m
/b.m
/c.m
/Internal/
/d.m
/e.m
/f.m
/Views/
/a_v.m
/b_v.m
/c_v.m
/Controllers/
/a_vc.m
/b_vc.m
/c_vc.m
/AnotherClasses/
/anmy.m
/anmy1.m
/anmy2.m
/anmy3.m
/Networking/
/net1.m
/net2.m
/net3.m
/External/
/Internal/
/Views/
/Controllers/
You could also use some of the SPL's iterators. A quick and basic example would look like:
$directories = new RecursiveDirectoryIterator('path/to/search');
$flattened = new RecursiveIteratorIterator($directories);
$filter = new RegexIterator($flattened, '/\.in$/');
foreach ($filter as $file) {
echo $file, PHP_EOL;
}
More infos (mostly incomplete):
http://php.net/recursivedirectoryiterator
http://php.net/recursiveiteratoriterator
http://php.net/regexiterator
You can use a recursive function like this:
function searchFiles($dir,$pattern,$recursive=false)
{
$matches = array();
$d = dir($dir);
while (false !== ($entry = $d->read()))
{
if (is_dir($d->path.$entry) && $recursive)
{
$subdir = $d->path.$entry;
$matches = array_merge($matches,searchFiles($dir,$pattern,$recursive));
}
elseif (is_file($d->path.$entry) && preg_match($pattern,$entry))
{
$matches[] = $d->path.$entry;
}
}
$d->close();
return $matches;
}
Usage:
$matches = searchFiles("/mypath/","'[.]m$'i",true);
function ScanForMFiles($dir){
$return = array();
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(is_dir($dir.$file)){
$return = array_merge($return, ScanForMFiles($dir.$file."/"));
}
else {
if(substr($file, -2) == '.m')
$return[] = $file;
}
}
}
closedir($handle);
}
return $return;
}
var_dump(ScanForMFiles('./'));
You'll want to look to the PHP docs for details on this: http://php.net/manual/en/function.readdir.php
Here's an example that should do what you you want. It will return an array of all .m files in the sub directories. You can then loop through each file and read the contents if that is what you are interested in.
<?php
function get_m_files($root = '.'){
$files = array();
$directories = array();
$last_letter = $root[strlen($root)-1];
$root = ($last_letter == '\\' || $last_letter == '/') ? $root : $root.DIRECTORY_SEPARATOR;
$directories[] = $root;
while (sizeof($directories)) {
$dir = array_pop($directories);
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file == '.' || $file == '..') {
continue;
}
$file = $dir.$file;
if (is_dir($file)) {
$directory_path = $file.DIRECTORY_SEPARATOR;
array_push($directories, $directory_path);
} elseif (is_file($file)) {
if (substr( $file, -strlen( ".m" ) ) == ".m") {
$files[] = $file;
}
}
}
closedir($handle);
}
}
return $files;
}
?>

Categories