How to get PHP files and their path changed after a date - php

I want to get all file names (and path) of files those updated after a date (in directory and subdirectories) using PHP.
like all files updated after 20.08.2017 ,
Below code provide only files from directory, i also need path,
$dir = "opendir(".")";
clearstatcache();
$yesdate = strtotime("-1 days");
while(false != ($file = readdir($dir)))
{
if ( substr($file,-4) == ".php" )
{
if (filemtime($file) >= $yesdate)
{
echo $file;
}
}
}
Thanks

If you're using relative paths like e.g. . or paths that follow a symbolic link, you can get the real path via the function realpath :
$actualDirectory = realpath(".");
$dir = opendir($actualDirectory);
clearstatcache();
$yesdate = strtotime("-1 days");
while(false != ($file = readdir($dir)))
{
if ( substr($file,-4) == ".php" && filemtime($file) >= $yesdate)
{
echo $actualDirectory."/".$file;
}
}

If you want to scan all sub directories until the end of the tree you need to use a recursive function.
function get_updated_files($date, $directory, $result = array())
{
$directory = realpath($directory);
$directory_content = glob($directory.'/*');
foreach($directory_content as $item) {
if(is_dir($item)) {
$result = get_updated_files($date, $item, $result);
} elseif(strtotime($date) < filemtime($item) && pathinfo($item, PATHINFO_EXTENSION) == 'php') {
$result[] = $item;
}
}
return $result;
}
$result = get_updated_files('2017-08-20', '.');

With a specified date:
$dir = opendir(dirname(__FILE__));
clearstatcache();
$dday = "20.08.2017.";
$yesdate = strtotime($dday);
while(false != ($file = readdir($dir))) {
if ( substr($file,-4) == ".php" ) {
if (filemtime($file) >= $yesdate) {
echo $file;
}
}
}
Or with today - 1 day:
$dday = date("d.m.Y", time());
$yesdate = strtotime($dday) - 86400;

You must proceed like this
function get_updated_files($date, $directory,$file_extension='php',$sameday=false, $result = array())
{
if(!$sameday){
/* really worth because actually
your code will return true for your given day and this maybe
is not the goal you are trying to achieve...*/
$date = strtotime($date)+86399;
}else{
$date=strtotime($date);
}
$directory = realpath($directory);
$directory_content = glob($directory.'\\*');
foreach($directory_content as $item) {
if(is_dir($item)) {
$result=get_updated_files($date, $item,$file_extension,$sameday,$result);
} elseif($date < filemtime($item)&& pathinfo($item, PATHINFO_EXTENSION)===$file_extension) {
$result[] = $item;
}
}
return $result;
}
$result = get_updated_files('2017-08-20', '.');

Related

copy a php file to every directory

I've a simple problem of copying a a php folder to some directories, bu the problem is I can't the solution for that, the idea is that I've an Online Manga Viewer script, and what I want to do is I want to add comments page to every chapter, the I dea that I came with, is, I create a separate comments page file and once a new chapter added the the comments file will be copied to the folder of the chapter :
Description Image:
http://i.stack.imgur.com/4wYE0.png
What I to know is how can I do it knowing that I will use Disqus commenting System.
Functions used in the script:
function omv_get_mangas() {
$mangas = array();
$dirname = "mangas/";
$dir = #opendir($dirname);
if ($dir) {
while (($file = #readdir($dir)) !== false) {
if (is_dir($dirname . $file . '/') && ($file != ".") && ($file != "..")) {
$mangas[] = $file;
}
}
#closedir($dir);
}
sort($mangas);
return $mangas;
}
function omv_get_chapters($manga) {
global $omv_chapters_sorting;
$chapters = array();
$chapters_id = array();
$dirname = "mangas/$manga/";
$dir = #opendir($dirname);
if ($dir) {
while (($file = #readdir($dir)) !== false) {
if (is_dir($dirname . $file . '/') && ($file != ".") && ($file != "..")) {
$chapter = array();
$chapter["folder"] = $file;
$pos = strpos($file, '-');
if ($pos === false) {
$chapter["number"] = $file;
} else {
$chapter["number"] = trim(substr($file, 0, $pos - 1));
$chapter["title"] = trim(substr($file, $pos + 1));
}
$chapters_id[] = $chapter["number"];
$chapters[] = $chapter;
}
}
#closedir($dir);
}
array_multisort($chapters_id, $omv_chapters_sorting, $chapters);
return $chapters;
}
function omv_get_chapter_index($chapters, $chapter_number) {
$i = 0;
while (($i < count($chapters)) && ($chapters[$i]["number"] != $chapter_number)) $i++;
return ($i < count($chapters)) ? $i : -1;
}
function omv_get_pages($manga, $chapter) {
global $omv_img_types;
$pages = array();
$dirname = "mangas/$manga/$chapter/";
$dir = #opendir($dirname);
if ($dir) {
while (($file = #readdir($dir)) !== false) {
if (!is_dir($dirname . $file . '/')) {
$file_extension = strtolower(substr($file, strrpos($file, ".") + 1));
if (in_array($file_extension, $omv_img_types)) {
$pages[] = $file;
}
}
}
#closedir($dir);
}
sort($pages);
return $pages;
}
/*function add_chapter_comment($dirname){
$filename = $dirname.'comments.php';
if (file_exists($filename)) {
} else {
copy('comments.php', .$dirname.'comments.php');
}
}*/
function omv_get_previous_page($manga_e, $chapter_number_e, $current_page, $previous_chapter) {
if ($current_page > 1) {
return $manga_e . '/' . $chapter_number_e . '/' . ($current_page - 1);
} else if ($previous_chapter) {
$pages = omv_get_pages(omv_decode($manga_e), $previous_chapter["folder"]);
return $manga_e . '/' . omv_encode($previous_chapter["number"]) . '/' . count($pages);
} else {
return null;
}
}
function omv_get_next_page($manga_e, $chapter_number_e, $current_page, $nb_pages, $next_chapter) {
if ($current_page < $nb_pages) {
return $manga_e . '/' . $chapter_number_e . '/' . ($current_page + 1);
} else if ($next_chapter) {
return $manga_e . '/' . omv_encode($next_chapter["number"]);
} else {
return null;
}
}
function omv_get_image_size($img) {
global $omv_img_resize, $omv_preferred_width;
$size = array();
$imginfo = getimagesize($img);
$size["width"] = intval($imginfo[0]);
$size["height"] = intval($imginfo[1]);
if ($omv_img_resize) {
if ($size["width"] > $omv_preferred_width) {
$size["height"] = intval($size["height"] * ($omv_preferred_width / $size["width"]));
$size["width"] = $omv_preferred_width;
}
}
return $size;
}
And thanks for all of you!
Include the following line in all of your pages in a small php statement, if it covers two folder paths, use this. Which I think in your case it does.
<?php
include('../../header.php');
?>
And then save this in the main root directory. Which in your diagram is called "Main Folder"

Recursivly get all files in a directory, and sub directories by extension

I was looking at RecursiveDirectoryIterator and glob to say
"return me a list of files (in an array) based on the extension (for example) .less. Oh and look in all child, grandchild and so on and so forth, excluding . and .. until you find all files matching."
But I am not sure the best approach to create a recursive function that keeps going well beyond the grand child.
What I have is a mess, its worked for two years - but now I need to refactor and change it up:
public function get_directory_of_files($path, $filename, $extension) {
if (!is_dir($path)) {
throw new AisisCore_FileHandling_FileException("Could not find said path: " . $path);
}
if (file_exists($filename)) {
$handler = opendir($path);
while ($file = readdir($handler)) {
if ($file != "." && $file != "..") {
$this->package_files [] = $file;
$count = count($this->package_files);
for ($i = 0; $i < $count; $i++) {
if (substr(strrchr($this->package_files [$i], '.'), 1) == $extension) {
if ($this->package_files [$i] == $filename) {
$this->files_got_back = $this->package_files [$i];
}
}
}
}
}
}
return $this->_files_got_back;
}
This requires a file name to be passed in and thats not really my thing to do any more. So how can I re-write this function to do the above "pseudo code"
This function recursively finds files with a matching ending string
function getDirectoryContents($directory, $extension)
{
$extension = strtolower($extension);
$files = array();
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
while($it->valid())
{
if (!$it->isDot() && endsWith(strtolower($it->key()), $extension))
{
array_push($files, $it->key());
}
$it->next();
}
return $files;
}
function endsWith($haystack, $needle)
{
return $needle === "" || substr($haystack, -strlen($needle)) === $needle;
}
Used like so
print_r(getDirectoryContents('folder/', '.php'));
It converts the extension to lowercase to compare against
Take a look at this code:
<?php
class ex{
private function get_files_array($path,$ext, &$results){ //&to ensure it's a reference... but in php obj are passed by ref.
if (!is_dir($path)) {
//throw new AisisCore_FileHandling_FileException("Could not find said path: " . $path);
}
if ($dir = opendir($path)) {
$extLength = strlen($ext);
while (false !== ($file = readdir($dir))) {
if ($file != '.' && $file != '..'){
if (is_file($path.'/'.$file) && substr($file,-$extLength) == $ext){
$results[] = $path . '/' . $file; //it's a file and the correct extension
}
elseif (is_dir($path . '/'. $file)){
$this->get_files_array($path.'/'.$file, $ext, $results); //it's a dir
}
}
}
}else{
//unable to open dir
}
}
public function get_files_deep($path,$ext){
$results = array();
$this->get_files_array($path,$ext,$results);
return $results;
}
}
$ex = new ex();
var_dump($ex->get_files_deep('_some_path','.less'));
?>
It will retrieve all the files with the matching extension in the path and it's sub directories.
I hope it's what you need.

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.

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;
}
?>

PHP delete all subdirectories in a directory having expired date?

There is a directory /home/example/public_html/users/files/. Within the directory there are subdirectories with random names like 2378232828923_1298295497.
How do I completely delete the subdirectories which have creation date > 1 month?
There is a good script that I use to delete files, but it don't work with dirs:
$seconds_old = 2629743; //1 month old
$directory = "/home/example/public_html/users/files/";
if( !$dirhandle = #opendir($directory) )
return;
while( false !== ($filename = readdir($dirhandle)) ) {
if( $filename != "." && $filename != ".." ) {
$filename = $directory. "/". $filename;
if( #filectime($filename) < (time()-$seconds_old) )
#unlink($filename); //rmdir maybe?
}
}
you need a recursive function for this.
function remove_dir($dir)
{
chdir($dir);
if( !$dirhandle = #opendir('.') )
return;
while( false !== ($filename = readdir($dirhandle)) ) {
if( $filename == "." || $filename = ".." )
continue;
if( #filectime($filename) < (time()-$seconds_old) ) {
if (is_dir($filename)
remove_dir($filename);
else
#unlink($filename);
}
}
chdir("..");
rmdir($dir);
}
<?php
$dirs = array();
$index = array();
$onemonthback = strtotime('-1 month');
$handle = opendir('relative/path/to/dir');
while($file = readdir($handle){
if(is_dir($file) && $file != '.' && $file != '..'){
$dirs[] = $file;
$index[] = filemtime( 'relative/path/to/dir/'.$file );
}
}
closedir($handle);
asort( $index );
foreach($index as $i => $t) {
if($t < $onemonthback) {
#unlink('relative/path/to/dir/'.$dirs[$i]);
}
}
?>
If PHP runs on a Linux server, you could use a shell command, to improve performance (a recursive PHP function can be inefficient in very large directories):
shell_exec('rm -rf '.$directory);

Categories