How to search file in folder by using php? - php

I have a folder called allfiles, and there are some files in this folder, such as
1212-how-to-sddk-thosd.html
3454-go-to-dlkkl-sdf.html
0987-sfda-asf-fdf-12331.html
4789-how-to-fdaaf-65536.html
I use scandir to list all files, and now I need to find the file by with keywords, example to-dlkkl is the keyword, and I will get the file 3454-go-to-dlkkl-sdf.html.
Glob seems not work, and opendir and readdir are not work well, any ideas?

Use loop foreach and strpos function:
$files = scandir('allfiles');
foreach ($files as $file) {
if (strpos('to-dlkkl', $file) !== false) {
//file found
}
}

I wonder why glob() function not working for it?
The below code should work I guess,
$existing_dir = getcwd();
// path to dir
chdir( '/var/www/allfiles/' );
foreach( glob( '*to-dlkkl*.html' ) as $html_file ) {
echo $html_file . '<br />';
}
chdir( $existing_dir );

you can use strstr to get actual file
$allfiles = scandir('./');
foreach ($allfiles as $file) {
if (strstr($file, 'to-dlkkl')) {
echo "file found"; //do what you want
}
}

If You want to search specific file under directory then you can use preg_match() .
<?php
if ($handle = opendir('/var/www/html/j')) { // here add your directory
$keyword = "index.php"; // your keyword
while (false !== ($entry = readdir($handle))) {
// (preg_match('/\.txt$/', $entry)) {
if (preg_match('/'.$keyword.'/i', $entry)) {
echo "$entry\n";
}
}
closedir($handle);
}
?>

Related

Look for preg_match() for all files of a directory (recursively)

I would like to know how can I (recursively) scan a directory files (100+) looking for a preg_match() in files contents. I'm looking if any file contains a backtick (`).
Thanks for your answers.
you can do it, using php function opendir try this function :
<?php
function findbacktick ($dir){
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
preg_match("/'/", $file, $matches);
if (count($matches)>=1) {
echo 'file contains a backtick : '.$file.'</br>-----</br>';
}
}
closedir($dh);
}
}
}
$dir = "path/to/dir";
findbacktick ($dir);
?>
You can wrap glob in recursive function. I'm giving you the idea with following basic version of it.
function find_files($dir, $files = []) {
foreach (glob($dir."/*") as $file) {
if(is_dir($file)) {
$files = find_files($file, $files);
}
$content = file_get_contents($dir."/".$file);
if(preg_match('/[YOUR_PATTERN]/', $content)) {
$files[] = $file;
}
}
return $files;
}
I haven't tried it, but I guess it should work.
PS. It might give you the memory exhausted error or timeout error.

Copy all files from one folder to another Folder using PHP scripts?

Basically, my requirement is, I want to move all files from one folder to another folder using PHP scripts. Any one can help me. I am trying this, but I am getting error
$mydir = dirname( __FILE__ )."/html/images/";
if(!is_dir($mydir)){
mkdir("html/images");
}
// Move all images files
$files = glob("images/*.");
foreach($files as $file){
$file_to_go = str_replace("images/","html/images/",$file);
copy($file, $file_to_go);
}
// images folder creation using php
$mydir = dirname( __FILE__ )."/html/images";
if(!is_dir($mydir)){
mkdir("html/images");
}
// Move all images files
$files = glob("images/*.*");
foreach($files as $file){
$file_to_go = str_replace("images/","html/images/",$file);
copy($file, $file_to_go);
}
Try this :
<?php
$src = 'pictures';
$dst = 'dest';
$files = glob("pictures/*.*");
foreach($files as $file){
$file_to_go = str_replace($src,$dst,$file);
copy($file, $file_to_go);
}
?>
foreach(glob('old_directory/*.*') as $file) {
copy('old_directory/'.$file, 'new_directory/'.$file);
}
Use array_map:
// images folder creation using php
function copyFile($file) {
$file_to_go = str_replace("images/","html/images/",$file);
copy($file, $file_to_go);
}
$mydir = dirname( __FILE__ )."/html/images";
if(!is_dir($mydir)){
mkdir("html/images");
}
// Move all images files
$files = glob("images/*.*");
print_r(array_map("copyFile",$files));
This One Works for me...........
Thanks to this man
http://www.codingforums.com/php/146554-copy-one-folder-into-another-folder-using-php.html
<?php
copydir("admin","filescreate");
echo "done";
function copydir($source,$destination)
{
if(!is_dir($destination)){
$oldumask = umask(0);
mkdir($destination, 01777); // so you get the sticky bit set
umask($oldumask);
}
$dir_handle = #opendir($source) or die("Unable to open");
while ($file = readdir($dir_handle))
{
if($file!="." && $file!=".." && !is_dir("$source/$file"))
copy("$source/$file","$destination/$file");
}
closedir($dir_handle);
}
?>
This should work just fine:
// Get array of all source files
$files = scandir("source");
// Identify directories
$source = "source/";
$destination = "destination/";
// Cycle through all source files
foreach ($files as $file) {
if (in_array($file, array(".",".."))) continue;
// If we copied this successfully, mark it for deletion
if (copy($source.$file, $destination.$file))
{
$delete[] = $source.$file;
}
}
// Delete all successfully-copied files
foreach ($delete as $file)
{
unlink($file);
}
or with rename() and some error checking:
$srcDir = 'dir1';
$destDir = 'dir2';
if (file_exists($destDir)){
if (is_dir($destDir)) {
if (is_writable($destDir)) {
if ($handle = opendir($srcDir)) {
while (false !== ($file = readdir($handle))) {
if (is_file($srcDir . '/' . $file)) {
rename($srcDir . '/' . $file, $destDir . '/' . $file);
}
}
closedir($handle);
} else {
echo "$srcDir could not be opened.\n";
}
} else {
echo "$destDir is not writable!\n";
}
} else {
echo "$destDir is not a directory!\n";
}
} else {
echo "$destDir does not exist\n";
}
You can use this recursice function.
<?php
function copy_directory($source,$destination) {
$directory = opendir($source);
#mkdir($destination);
while(false !== ( $file = readdir($directory)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($source . '/' . $file) ) {
copy_directory($source . '/' . $file,$destination . '/' . $file);
}
else {
copy($source . '/' . $file,$destination . '/' . $file);
}
}
}
closedir($directory);
}
?>
Referrence : http://php.net/manual/en/function.copy.php
I had a similar situation where I needed to copy from one domain to another, I solved it using a tiny adjustment to the "very easy answer" given by "coDe murDerer" above:
Here is exactly what worked in my case, you can as well adjust to suit yours:
foreach(glob('../folder/*.php') as $file) {
$adjust = substr($file,3);
copy($file, '/home/user/abcde.com/'.$adjust);
Notice the use of "substr()", without it, the destination becomes '/home/user/abcde.com/../folder/', which might be something you don't want.
So, I used substr() to eliminate the first 3 characters(../) in order to get the desired destination which is '/home/user/abcde.com/folder/'. So, you can adjust the substr() function and also the glob() function until it fits your personal needs. Hope this helps.

PHP Delete all folder content without deleting root folder

I'm trying to delete the content of a folder with PHP. This folder has subfolders and files. I want to delete all but the root folder.
For example:
FolderFather
--Folderchild1
--FolChild2
----SubFolChild2
------Anotherfile.jpg
--MyFile.jpg
I want remove all folder except root directory Folder.
Something like
function empty_dir($directory, $delete = false)
{
$contents = glob($directory . '*');
foreach($contents as $item)
{
if (is_dir($item))
empty_dir($item . '/', true);
else
unlink($item);
}
if ($delete === true)
rmdir($directory);
}
should work.
E.g. empty_dir('/some/path/'); should empty that directory without removing,
empty_dir('/some/path/', true); should empty and than remove the directory.
Try:
function deleteAll($path)
{
$dir = dir($path);
while ($file = $dir->read())
{
if ($file == '.' || $file == '..') continue;
$file = $path . '/' . $file;
if (is_dir($file))
{
deleteAll($file);
rmdir($file);
}
else
{
unlink($file);
}
}
}
Calling deleteAll('/path/to/FolderFather'); should work as expected.
You can use scandir() for directory contents and unlink() for deleting contents.
<?php
$dir = "/yourfolder";
$dir_contents = scandir($dir);
foreach($dir_contents as $content)
{
unlink($dir.'/'.$content);
}
$contents = glob('path/*'); // to get all the contents
foreach ($contents as $file) { // loop the files
if (is_file($file)) {
unlink($file); //------- delete the file
}
}

How to get the file name under a folder?

Suppose I have a directory look like:
ABC
|_ a1.txt
|_ a2.txt
|_ a3.txt
|_ a4.txt
|_ a5.txt
How can I use PHP to get these file names to an array, limited to a specific file extension and ignoring directories?
You can use the glob() function:
Example 01:
<?php
// read all files inside the given directory
// limited to a specific file extension
$files = glob("./ABC/*.txt");
?>
Example 02:
<?php
// perform actions for each file found
foreach (glob("./ABC/*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
Example 03: Using RecursiveIteratorIterator
<?php
foreach(new RecursiveIteratorIterator( new RecursiveDirectoryIterator("../")) as $file) {
if (strtolower(substr($file, -4)) == ".txt") {
echo $file;
}
}
?>
Try this:
if ($handle = opendir('.')) {
$files=array();
while (false !== ($file = readdir($handle))) {
if(is_file($file)){
$files[]=$file;
}
}
closedir($handle);
}
scandir lists files and directories inside the specified path.
Here is the most Efficient way based on this article's benchmarks:
function getAllFiles() {
$files = array();
$dir = opendir('/ABC/');
while (($currentFile = readdir($dir)) !== false) {
if (endsWith($currentFile, '.txt'))
$files[] = $currentFile;
}
closedir($dir);
return $files;
}
function endsWith($haystack, $needle) {
return substr($haystack, -strlen($needle)) == $needle;
}
just use the getAllFiles() function, and you can even modify it to take the folder path and/or the extensions needed, it is easy.
Aside from scandir (#miku), you might also find glob interesting for wildcard matching.
If your text files is all that you have inside of the folder, the simplest way is to use scandir, like this:
<?php
$arr=scandir('ABC/');
?>
If you have other files, you should use glob as in Lawrence's answer.
$dir = "your folder url"; //give only url, it shows all folder data
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != '.' and $file != '..'){
echo $file .'<br>';
}
}
closedir($dh);
}
}
output:
xyz
abc
2017
motopress

finding files in a dir

I have a directory with a lot of files inside:
pic_1_79879879879879879.jpg
pic_1_89798798789798789.jpg
pic_1_45646545646545646.jpg
pic_2_12345678213145646.jpg
pic_3_78974565646465645.jpg
etc...
I need to list only the pic_1_ files. Any idea how I can do?
Thanks in advance.
Use the glob() function
foreach (glob("directory/pic_1_*") as $filename) {
echo "$filename";
}
Just change directory in the glob call to the proper path.
This does it all in one shot versus grabbing the list of files and then filtering them.
The opend dir function will help you
$dir ="your path here";
$filetoread ="pic_1_";
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (strpos($file,$filetoread) !== false)
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
good luck see php.net opendir
This is what glob() is for:
glob — Find pathnames matching a pattern
Example:
foreach (glob("pic_1*.jpg") as $file)
{
echo $file;
}
Use scandir to list all the files in a directory and then use preg_grep to get the list of files which match the pattern you are looking for.
This is one of the samples from the manual
http://nz.php.net/manual/en/function.readdir.php
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
?>
you can modify that code to test the filename to see if it starts with pic_1_
using something like this
if (substr($file, 0, 6) == 'pic_1_')
Manual reference for substr
http://nz.php.net/manual/en/function.substr.php

Categories