Php - Delete files older than 7 days for multiple folders - php

i would like to create a PHP script that delete files from multiple folders/paths.
I managed something but I would like to adapt this code for more specific folders.
This is the code:
<?php
function deleteOlderFiles($path,$days) {
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
$filelastmodified = filemtime($path . $file);
if((time() - $filelastmodified) > $days*24*3600)
{
if(is_file($path . $file)) {
unlink($path . $file);
}
}
}
closedir($handle);
}
}
$path = 'C:/Users/Legion/AppData/Local/Temp';
$days = 7;
deleteOlderFiles($path,$days);
?>
I would like to make something like to add more paths and this function to run for every path.
I tried to add multiple path locations but it didn't work because it always takes the last $ path variable.
For exemple:
$path = 'C:/Users/Legion/AppData/Local/Temp';
$path = 'C:/Users/Legion/AppData/Local/Temp/bla';
$path = 'C:/Users/Legion/AppData/Local/Temp/blabla';
$path = 'C:/Users/Legion/AppData/Local/Temp/blalbalba';
$days = 7;
deleteOlderFiles($path,$days);
Thank you for you help!

The simple solution, call the function after setting the parameter not after setting all the possible parameters into a scalar variable.
$days = 7;
$path = 'C:/Users/Legion/AppData/Local/Temp';
deleteOlderFiles($path,$days);
$path = 'C:/Users/Legion/AppData/Local/Temp/bla';
deleteOlderFiles($path,$days);
$path = 'C:/Users/Legion/AppData/Local/Temp/blabla';
deleteOlderFiles($path,$days);
$path = 'C:/Users/Legion/AppData/Local/Temp/blalbalba';
deleteOlderFiles($path,$days);
Alternatively, place the directories in an array and then call the funtion from within a foreach loop.
$paths = [];
$paths[] = 'C:/Users/Legion/AppData/Local/Temp';
$paths[] = 'C:/Users/Legion/AppData/Local/Temp/bla';
$paths[] = 'C:/Users/Legion/AppData/Local/Temp/blabla';
$paths[] = 'C:/Users/Legion/AppData/Local/Temp/blalbalba';
$days = 7;
foreach ( $paths as $path){
deleteOlderFiles($path,$days);
}

It seems that you need a recursive function, i.e. a function that calls itself. In this case it calls itself when it finds a subdirectory to scan/traverse.
function delete_files($current_path, $days) {
$files_in_current_path = scandir($current_path);
foreach($files_in_current_path as $file) {
if (!in_array($release_file, [".", ".."])) {
if (is_dir($current_path . "/" . $file)) {
// Scan found subdirectory
delete_files($current_path . "/" . $file, $days);
} else {
// Here you add your code for checking date and deletion of the $file
$filelastmodified = filemtime($current_path . "/" . $file);
if((time() - $filelastmodified) > $days*24*3600) {
if(is_file($current_path . "/" . $file)) {
unlink($current_path . "/". $file);
}
}
}
}
}
}
delete_files("your/startpath/here", 7);
This code starts in your specified start path. It scans all files in that directory. If a sub directory is found, there will be a new call to delete_files, but with that sub directory as a start.

Related

Move file that aged

So I managed to get all files in my directory using this:
$dir = PUBLIC_DIRECTORY . '/' . $login_session . '/';
$files = array();
$DirectoryIterator = new RecursiveDirectoryIterator($dir);
$IteratorIterator = new RecursiveIteratorIterator($DirectoryIterator, RecursiveIteratorIterator::SELF_FIRST);
foreach ($IteratorIterator as $file) {
$path = $file;
if ($file->isFile())
$files[] = realpath($path);
}
which resulted to this:
C:\xampp\htdocs\fms\public\kei\docx\FMS.docx
C:\xampp\htdocs\fms\public\kei\jpg\1.jpg
Now i used the code below which should move the files from inside their directory to C:\xampp\htdocs\fms\public\kei\Bin\ when aged
foreach($files as $f) {
if (filemtime($f) < time() - 86400) {
rename($f, realpath($dir . "/Bin/" . basename($f));
}
}
but nothing happens for some reasons. I tried different things to get the filename like...
echo realpath($dir . "/Bin/") . basename($f);
but this code shows
C:\xampp\htdocs\fms\public\kei\BinFMS.docx
C:\xampp\htdocs\fms\public\kei\Bin1.jpg
I managed to fixed it by doing this
$bin = "\Bin\";
and this rename($f, realpath($dir) . $bin . basename($f));

Select random file using OPENDIR()

I have tried:
function random_pic($dir = '../myfolder') {
$files = opendir($dir . '/*.*');
$file = array_rand($files);
return $files[$file];
}
This function works using glob() but not opendir.
This returns a failed to open directory error. I guess opendir cannot accept things like *.*? Is it possible to select all files in a folder and randomly choose one?
The opendir() function wont return a list of files/folders. It will only open a handle that can be used by closedir(), readdir() or rewinddir(). The correct usage here would be glob(), but as I see that you don't want that, you could also use scandir() like the following:
<?php
$path = "./";
$files = scandir($path);
shuffle($files);
for($i = 0; ($i < count($files)) && (!is_file($files[$i])); $i++);
echo $files[$i];
?>
I'd happily do the timing to see if this takes longer or if glob() takes longer after you admit that I'm not "wrong."
The following 2 methods make use of opendir to quickly read through a directory and return a random file or directory.
All Benchmarks done use CI3 and are average of 100 pulses. Using WAMP on Win10 Intel i54460 w/ 16GB RAM
Get Random File:
function getRandomFile($path, $type=NULL, $contents=TRUE) {
if (strpos($path, $_SERVER['DOCUMENT_ROOT']) === FALSE) $path = $_SERVER['DOCUMENT_ROOT'] . '/' . $path;
if (is_dir($path)) {
if ($dh = opendir($path)) {
$arr = [];
while (false !== ($file = readdir($dh))) {
// not a directory
if (!is_dir("$path/$file") && !preg_match('/^\.{1,2}$/', $file)) {
// fits file type
if(is_null($type)) $arr[] = $file;
elseif (is_string($type) && preg_match("/\.($type)$/", $file)) $arr[] = $file;
elseif (is_array($type)) {
$type = implode('|', $type);
if (preg_match("/\.($type)$/", $file)) $arr[] = $file;
}
}
}
closedir($dh);
if (!empty($arr)) {
shuffle($arr);
$file = $arr[mt_rand(0, count($arr)-1)];
return empty($contents) ? $file : ($contents == 'path' ? "$path/$file" : file_get_contents($file));
}
}
}
return NULL;
}
Use as simple as:
// Benchmark 0.0018 seconds *
$this->getRandomFile('directoryName');
// would pull random contents of file from given directory
// Benchmark 0.0017 seconds *
$this->getRandomFile('directoryName', 'php');
// |OR|
$this->getRandomFile('directoryName', ['php', 'htm']);
// one gets a random php file
// OR gets random php OR htm file contents
// Benchmark 0.0018 seconds *
$this->getRandomFile('directoryName', NULL, FALSE);
// returns random file name
// Benchmark 0.0019 seconds *
$this->getRandomFile('directoryName', NULL, 'path');
// returns random full file path
Get Random Directory:
function getRandomDir($path, $full=TRUE, $indexOf=NULL) {
if (strpos($path, $_SERVER['DOCUMENT_ROOT']) === FALSE) $path = $_SERVER['DOCUMENT_ROOT'] . '/' . $path;
if (is_dir($path)) {
if ($dh = opendir($path)) {
$arr = [];
while (false !== ($dir = readdir($dh))) {
if (is_dir("$path/$dir") && !preg_match('/^\.{1,2}$/', $dir)) {
if(is_null($indexOf)) $arr[] = $file;
if (is_string($indexOf) && strpos($dir, $indexOf) !== FALSE) $arr[] = $dir;
elseif (is_array($indexOf)) {
$indexOf = implode('|', $indexOf);
if (preg_match("/$indexOf/", $dir)) $arr[] = $dir;
}
}
}
closedir($dh);
if (!empty($arr)) {
shuffle($arr);
$dir = $arr[mt_rand(0, count($arr)-1)];
return $full ? "$path/$dir" : $dir;
}
}
}
return NULL;
}
Use as simple as:
// Benchmark 0.0013 seconds *
$this->getRandomDir('parentDirectoryName');
// returns random full directory path of dirs found in given directory
// Benchmark 0.0015 seconds *
$this->getRandomDir('parentDirectoryName', FALSE);
// returns random directory name
// Benchmark 0.0015 seconds *
$this->getRandomDir('parentDirectoryName', FALSE, 'dirNameContains');
// returns random directory name
Use in Combo Like:
$dir = $this->getRandomDir('dirName');
$file = $this->getRandomFile($dir, 'mp3', FALSE);
// returns a random mp3 file name.
// Could be used to load random song via ajax.
single line
/** getRandomFile(String)
* Simple method for retrieving a random file from a directory
**/
function getRandomFile($path, $type=NULL, $contents=TRUE) { if (strpos($path, $_SERVER['DOCUMENT_ROOT']) === FALSE) $path = $_SERVER['DOCUMENT_ROOT'] . '/' . $path; if (is_dir($path)) { if ($dh = opendir($path)) { $arr = []; while (false !== ($file = readdir($dh))) { if (!is_dir("$path/$file") && !preg_match('/^\.{1,2}$/', $file)) { if(is_null($type)) $arr[] = $file; elseif (is_string($type) && preg_match("/\.($type)$/", $file)) $arr[] = $file; elseif (is_array($type)) { $type = implode('|', $type); if (preg_match("/\.($type)$/", $file)) $arr[] = $file; } } } closedir($dh); if (!empty($arr)) { shuffle($arr); $file = $arr[mt_rand(0, count($arr)-1)]; return empty($contents) ? $file : ($contents == 'path' ? "$path/$file" : file_get_contents($file)); } } } return NULL; }
/** getRandomDir(String)
* Simple method for retrieving a random directory
**/
function getRandomDir($path, $full=TRUE, $indexOf=NULL) { if (strpos($path, $_SERVER['DOCUMENT_ROOT']) === FALSE) $path = $_SERVER['DOCUMENT_ROOT'] . '/' . $path; if (is_dir($path)) { if ($dh = opendir($path)) { $arr = []; while (false !== ($dir = readdir($dh))) { if (is_dir("$path/$dir") && !preg_match('/^\.{1,2}$/', $dir)) { if(is_null($indexOf)) $arr[] = $file; if (is_string($indexOf) && strpos($dir, $indexOf) !== FALSE) $arr[] = $dir; elseif (is_array($indexOf)) { $indexOf = implode('|', $indexOf); if (preg_match("/$indexOf/", $dir)) $arr[] = $dir; } } } closedir($dh); if (!empty($arr)) { shuffle($arr); $dir = $arr[mt_rand(0, count($arr)-1)]; return $full ? "$path/$dir" : $dir; } } } return NULL; }
/* This is only here to make copying easier. */
Just a Note about glob && scandir. I made alternate versions of the getRandomDir using each. Using scandir had very little if any difference in benchmarks (from -.001 to +.003) Using glob was quite noticeably slower! Anywhere from +.5 to +1.100 difference on each call.

Pull all images from multiple directories and display them with PHP

I have a folder on my server called 'images', and within that folder I could have a single folder to as many as 10 folders that contain images.
Instead of writing a tag for each image
<img src="images/people/001.jpg">
<img src="images/landscape/001.jpg">
etc etc
Can I use PHP to get all the images in all the folders in the main directory 'images'?
I have VERY little experience with PHP, so this is something I am struggling with.
I need php to return an array of '<div class="box"><img src="images/FOLDER/IMAGENAME.jpg"></div>'
Maybe someone can help.
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);
}
}
}
closedir($dh);
return $files;
}
}
foreach (ListFiles('/path/to/images') as $key=>$file){
echo "<div class=\"box\"><img src=\"$file\"/></div>";
}
Something like this?
A simpler soluton. You can use built-in glob function. Assuming that all of your images are .jpg:
$result = array();
$dir = 'images/';
foreach(glob($dir.'*.jpg') as $filename) {
$result[] = "<div class=\"box\"><img src=\"$filename\"></div>";
}
Then you can echo each element of $result or whatever you want.

How to sync two folders in PHP?

I am using windows, Mysql DB, PHP
I am building the Joomla Component whose one of the functionality is to synchronize the folders
I want to sync two folders of different name.. How can I do this? It has to be dne in the same machine, no two different servers are involved in it..
How to sync two folders in PHP?
UPDATED
IN Context of Alex Reply
What if i am editing any .jpg file in one folder and saving it with same name as it has, also this file is already present in other folder. And I want this edited pic to be transfered to the other folder.? also I have Joomla's nested file structured to be compared
UPDATE 2
I have a recursive function which will output me the complete structure of folder... if u can just use it to concat ur solution in...
<?
function getDirectory($path = '.', $ignore = '') {
$dirTree = array ();
$dirTreeTemp = array ();
$ignore[] = '.';
$ignore[] = '..';
$dh = #opendir($path);
while (false !== ($file = readdir($dh))) {
if (!in_array($file, $ignore)) {
if (!is_dir("$path/$file")) {
$stat = stat("$path/$file");
$statdir = stat("$path");
$dirTree["$path"][] = $file. " === ". date('Y-m-d H:i:s', $stat['mtime']) . " Directory == ".$path."===". date('Y-m-d H:i:s', $statdir['mtime']) ;
} else {
$dirTreeTemp = getDirectory("$path/$file", $ignore);
if (is_array($dirTreeTemp))$dirTree = array_merge($dirTree, $dirTreeTemp);
}
}
}
closedir($dh);
return $dirTree;
}
$ignore = array('.htaccess', 'error_log', 'cgi-bin', 'php.ini', '.ftpquota');
$dirTree = getDirectory('.', $ignore);
?>
<pre>
<?
print_r($dirTree);
?>
</pre>
I just ran this, and it seems to work
function sync() {
$files = array();
$folders = func_get_args();
if (empty($folders)) {
return FALSE;
}
// Get all files
foreach($folders as $key => $folder) {
// Normalise folder strings to remove trailing slash
$folders[$key] = rtrim($folder, DIRECTORY_SEPARATOR);
$files += glob($folder . DIRECTORY_SEPARATOR . '*');
}
// Drop same files
$uniqueFiles = array();
foreach($files as $file) {
$hash = md5_file($file);
if ( ! in_array($hash, $uniqueFiles)) {
$uniqueFiles[$file] = $hash;
}
}
// Copy all these unique files into every folder
foreach($folders as $folder) {
foreach($uniqueFiles as $file => $hash) {
copy($file, $folder . DIRECTORY_SEPARATOR . basename($file));
}
}
return TRUE;
}
// usage
sync('sync', 'sync2');
You simply give it a list of folders to sync, and it will sync all files. It will attempt to skip files that appear the same (i.e. of whom their hash collides).
This however does not take into account last modified dates or anything. You will have to modify itself to do that. It should be pretty simple, look into filemtime().
Also, sorry if the code sucks. I had a go at making it recursive, but I failed :(
For a one way copy, try this
$source = '/path/to/source/';
$destination = 'path/to/destination/';
$sourceFiles = glob($source . '*');
foreach($sourceFiles as $file) {
$baseFile = basename($file);
if (file_exists($destination . $baseFile)) {
$originalHash = md5_file($file);
$destinationHash = md5_file($destination . $baseFile);
if ($originalHash === $destinationHash) {
continue;
}
}
copy($file, $destination . $baseFile);
}
It sounds like you just want to copy all files from one folder to another. The second example will do this.
I using this, and it seems to work, also make new dir if not exist .....
//sync the files and folders
function smartCopy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0755))
{
//$result = false;
if (is_file($source)) {
if ($dest[strlen($dest)-1]=='/') {
if (!file_exists($dest)) {
cmfcDirectory::makeAll($dest,$options['folderPermission'],true);
}
$__dest=$dest."/".basename($source);
} else {
$__dest=$dest;
}
$result = copy($source, $__dest);
chmod($__dest,$options['filePermission']);
} elseif(is_dir($source)) {
if ($dest[strlen($dest)-1]=='/') {
if ($source[strlen($source)-1]=='/') {
//Copy only contents
} else {
//Change parent itself and its contents
$dest=$dest.basename($source);
#mkdir($dest);
chmod($dest,$options['filePermission']);
}
} else {
if ($source[strlen($source)-1]=='/') {
//Copy parent directory with new name and all its content
#mkdir($dest,$options['folderPermission']);
chmod($dest,$options['filePermission']);
} else {
//Copy parent directory with new name and all its content
#mkdir($dest,$options['folderPermission']);
chmod($dest,$options['filePermission']);
}
}
$dirHandle=opendir($source);
while($file=readdir($dirHandle))
{
if($file!="." && $file!="..")
{
if(!is_dir($source."/".$file)) {
$__dest=$dest."/".$file;
} else {
$__dest=$dest."/".$file;
}
echo "$source/$file ||| $__dest<br />";
$result=smartCopy($source."/".$file, $__dest, $options);
}
}
closedir($dirHandle);
} else {
$result=false;
}
return $result;
}
//end of function
echo smartCopy('media', 'mobile/images');
function recurse_copy($src,$dst) {
$dir = opendir($src);
#mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_copy($src . '/' . $file,$dst . '/' . $file);
}
else {
if(md5_file($src . '/' . $file) !== md5_file($dst . '/' . $file))
{
echo 'copying' . $src . '/' . $file; echo '<br/>';
copy($src . '/' . $file, $dst . '/' . $file);
}
}
}
}
closedir($dir);
}
If its on a Linux/Posix system then (depending on what access you have) it may be a lot simpler / faster to:
$chk=`rsync -qrRlpt --delete $src $dest`;
C.

PHP read sub-directories and loop through files how to?

I need to create a loop through all files in subdirectories. Can you please help me struct my code like this:
$main = "MainDirectory";
loop through sub-directories {
loop through filels in each sub-directory {
do something with each file
}
};
Use RecursiveDirectoryIterator in conjunction with RecursiveIteratorIterator.
$di = new RecursiveDirectoryIterator('path/to/directory');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
}
You need to add the path to your recursive call.
function readDirs($path){
$dirHandle = opendir($path);
while($item = readdir($dirHandle)) {
$newPath = $path."/".$item;
if(is_dir($newPath) && $item != '.' && $item != '..') {
echo "Found Folder $newPath<br>";
readDirs($newPath);
}
else{
echo ' Found File or .-dir '.$item.'<br>';
}
}
}
$path = "/";
echo "$path<br>";
readDirs($path);
You probably want to use a recursive function for this, in case your sub directories have sub-sub directories
$main = "MainDirectory";
function readDirs($main){
$dirHandle = opendir($main);
while($file = readdir($dirHandle)){
if(is_dir($main . $file) && $file != '.' && $file != '..'){
readDirs($file);
}
else{
//do stuff
}
}
}
didn't test the code, but this should be close to what you want.
I like glob with it's wildcards :
foreach (glob("*/*.txt") as $filename) {
echo "$filename\n";
}
Details and more complex scenarios.
But if You have a complex folders structure RecursiveDirectoryIterator is definitively the solution.
Come on, first try it yourself!
What you'll need:
scandir()
is_dir()
and of course foreach
http://php.net/manual/en/function.is-dir.php
http://php.net/manual/en/function.scandir.php
Another solution to read with sub-directories and sub-files (set correct foldername):
<?php
$path = realpath('samplefolder/yorfolder');
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $filename)
{
echo "$filename <br/>";
}
?>
Minor modification on what John Marty posted, if we can safely eliminate any items that are named . or ..
function readDirs($path){
$dirHandle = opendir($path);
while($item = readdir($dirHandle)) {
$newPath = $path."/".$item;
if (($item == '.') || ($item == '..')) {
continue;
}
if (is_dir($newPath)) {
pretty_echo('Found Folder '.$newPath);
readDirs($newPath);
} else {
pretty_echo('Found File: '.$item);
}
}
}
function pretty_echo($text = '')
{
echo $text;
if (PHP_OS == 'Linux') {
echo "\r\n";
}
else {
echo "</br>";
}
}
<?php
ini_set('max_execution_time', 300); // increase the execution time of the file (in case the number of files or file size is more).
class renameNewFile {
static function copyToNewFolder() { // copies the file from one location to another.
$main = 'C:\xampp\htdocs\practice\demo'; // Source folder (inside this folder subfolders and inside each subfolder files are present.)
$main1 = 'C:\xampp\htdocs\practice\demomainfolder'; // Destination Folder
$dirHandle = opendir($main); // Open the source folder
while ($file = readdir($dirHandle)) { // Read what's there inside the source folder
if (basename($file) != '.' && basename($file) != '..') { // Ignore if the folder name is '.' or '..'
$folderhandle = opendir($main . '\\' . $file); // Open the Sub Folders inside the Main Folder
while ($text = readdir($folderhandle)) {
if (basename($text) != '.' && basename($text) != '..') { // Ignore if the folder name is '.' or '..'
$filepath = $main . '\\' . $file . '\\' . $text;
if (!copy($filepath, $main1 . '\\' . $text)) // Copy the files present inside the subfolders to destination folder
echo "Copy failed";
else {
$fh = fopen($main1 . '\\' . 'log.txt', 'a'); // Write a log file to show the details of files copied.
$text1 = str_replace(' ', '_', $text);
$data = $file . ',' . strtolower($text1) . "\r\n";
fwrite($fh, $data);
echo $text . " is copied <br>";
}
}
}
}
}
}
static function renameNewFileInFolder() { //Renames the files into desired name
$main1 = 'C:\xampp\htdocs\practice\demomainfolder';
$dirHandle = opendir($main1);
while ($file = readdir($dirHandle)) {
if (basename($file) != '.' && basename($file) != '..') {
$filepath = $main1 . '\\' . $file;
$text1 = strtolower($filepath);
rename($filepath, $text1);
$text2 = str_replace(' ', '_', $text1);
if (rename($filepath, $text2))
echo $filepath . " is renamed to " . $text2 . '<br/>';
}
}
}
}
renameNewFile::copyToNewFolder();
renameNewFile::renameNewFileInFolder();
?>
$allFiles = [];
public function dirIterator($dirName)
{
$whatsInsideDir = scandir($dirName);
foreach ($whatsInsideDir as $fileOrDir) {
if (is_dir($fileOrDir)) {
dirIterator($fileOrDir);
}
$allFiles.push($fileOrDir);
}
return $allFiles;
}

Categories