I want to copy images from one folder to another on server, now I use this code:
<?php
function read_dir($dir)
{
$list = array();
if (is_dir($dir))
{
if ($handle = opendir($dir))
{
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$list[] = $file;
}
}
}
closedir($handle);
}
return $list;
}
$src="oldfolder";
$dest="newfolder";
$list= read_dir($src);
foreach($list as $key => $val)
{
copy("$src/$val","$dest/$val");
}
echo "Done";
?>
But I need to copy just images selected by time - for example images uploaded between "now" and 5 min. ago..
Can anyone help?
Thanks
Now my PHP is like below. It seems that it run with "Done" result, but nothing is copied..
<?php
function read_dir($dir)
{
$list = array();
if (is_dir($dir))
{
if ($handle = opendir($dir))
{
while (false !== ($file = readdir($handle)))
{
$fpath = 'oldfolder'.$file;
if (file_exists($fpath)) {
if($file != "." && $file != ".." &&
DateTime::createFromFormat('U', filemtime($file)) < new DateTime("-5
minutes"))
{
$list[] = $file;
}
}
}
}
closedir($handle);
}
return $list;
}
$src="oldfolder";
$dest="newfolder";
$list= read_dir($src);
foreach($list as $key => $val)
{
copy("$src/$val","$dest/$val");
}
echo "Done";
?>
So this is my code, that works for me well - copy images between folders according to time (- 5 sec) set by other code in "time.txt" file:
<?php
function read_dir($dir)
{
$list = array();
if (is_dir($dir))
{
if ($handle = opendir($dir))
{
while (false !== ($file = readdir($handle)))
{
$fpath = 'oldfolder/'.$file;
if (file_exists($fpath)) {
$subor = fopen("./time.txt", "r");
$cas_txt=fgets($subor, 11);
fclose($subor);
$cas_zac = DateTime::createFromFormat('U', $cas_txt)->modify('-5 seconds');
if ($file != "." && $file != ".." && DateTime::createFromFormat('U',
filemtime($fpath)) > $cas_zac)
{
$list[] = $file;
}
}
}
}
closedir($handle);
}
return $list;
}
$src="oldfolder";
$dest="newfolder";
$list= read_dir($src);
foreach($list as $key => $val)
{
//copy file to new folder
copy("$src/$val","$dest/$val");
}
echo "Done";
?>
I have two more questions:
Please how can I rotate images in 180° by or after copy? Is it possible in one php code?
How can I send multiple files - images from my code - like an attachments by mail in php?
Thanks for your help.
You should use the filemtime function
Related
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);
I am trying to sort a list of directories according to the contents of a text file within each directory.
So far, I am displaying the list of directories:
$user = $_GET['user'];
$task_list = $_GET['list'];
if ($handle = opendir("../users/$user/tasks/$task_list/"))
{
$files = array();
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && $file != ".htaccess")
{
array_push($files, $file);
}
}
closedir($handle);
}
//Display tasks
sort($files);
foreach ($files as $file)
{
echo "$file";
}
Each directory has a text file within it called due.txt, I would like to sort the list of directories according to the contents of this file due.txt.
So far, I have tried:
$user = $_GET['user'];
$task_list = $_GET['list'];
if ($handle = opendir("../users/$user/tasks/$task_list/"))
{
$files = array();
$tasksSort = array();
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && $file != ".htaccess")
{
$taskSort = file_get_contents("../users/$user/tasks/$task_list/$file/due.txt");
array_push($files, $file);
array_push($tasksSort, $taskSort);
}
closedir($handle);
}
//Sort tasks and display
sort($tasksSort);
foreach ($files as $file)
{
echo "$file";
}
}
But the $tasksSort array doesn't seem to have any content to sort...?
sort($tasksSort);
foreach ($tasksSort as $file)
{
echo "$file";
}
I'm trying to write a program that will open up a directory (in this case: files/), scan all of the filenames (not including any directories or ".." or ".") within this directory, and search for the filenames in the specified files from the "pages" array. If the filename is NOT found in the pages, the file will be moved to "unused-content".
My current code does not work. How can I achieve this goal?
<?php
if($handle = opendir('files/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$file_names[] = $entry;
}
}
closedir($handle);
}
$pages = array("page1.html","page2.shtml","page_three.shtml","page4.htm","page5.shtml");
for($x=0; $x<sizeOf($pages); $x++) {
$current_page = file_get_contents($pages[$x]);
for($i=0; $i<sizeOf($file_names); $i++) {
if(!strpos($current_page,$file_names[$i])) {
if (copy("files/".$file_names[$i],"files/unused-content/".$file_names[$i])) {
unlink("files/".$file_names[$i]);
}
}
}
}
?>
Thank you!
You don't need all that long code .. all you need is FilesystemIterator
$pages = array("1.xml","page2.shtml","page_three.shtml","page4.htm","page5.shtml");
$dir = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
foreach ( $dir as $file ) {
if ($file->isFile() && in_array(strlen($file->getFilename()), $pages)) {
// copy
// unlink
}
}
See another example using GlobIterator
Try to do something like this:
<?php
if($handle = opendir('files/')) {
$i=0;
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$file_names[$i] = $entry;
}
$i++;
}
closedir($handle);
}
$pages = array("page1.html","page2.shtml","page_three.shtml","page4.htm","page5.shtml");
for($x=0; $x<sizeOf($pages); $x++) {
$current_page = file_get_contents($pages[$x]);
for($i=0; $i<sizeOf($file_names); $i++) {
if(!strpos($current_page,$file_names[$i])) {
if (copy("files/".$file_names[$i],"files/unused-content/".$file_names[$i])) {
unlink("files/".$file_names[$i]);
}
}
}
}
?>
I have a function which returns an array of files in a folder recursive.
protected function getFiles($base) {
$files = array();
if(!is_dir($base)) return $files;
if (($handle = opendir($base)) != false) {
while (false !== ($file = readdir($handle))) {
if ($file == "." || $file == "..") continue;
if(is_dir("$base/$file")) {
$subfiles = $this->getFiles("$base/$file");
$files = array_merge($files, $subfiles);
} else {
if(File::type($file,false) == "xml")
$files[] = "$base/$file";
}
}
closedir($handle);
}
return $files;
}
How can I modify this so that it always lists the root files first before any sub folders? At the moment by default the folders always come first.
You may want to take a look at the PHP SPL DirectoryIterator Class. You can instantiate the object and then quickly iterate over to segment out directories vs. files vs. links and get the full SplFileInfo object for each (which makes it really easy to get whatever info you want about the files).
$directory = '/path/to/directory';
$iterator = new DirectoryIterator($directory);
$dirs = array();
$files = array();
$links = array();
foreach($iterator as $obj) {
if($obj->isFile()) {
$files[] = $obj;
} else if ($obj->isDir()) {
$dirs[] = $obj;
} else if ($obj->isLink()) {
$links[] = $obj;
}
}
Sorry just realized you wanted to do it recursively. Well for that use RecursiveDirectoryIterator , but concept is much the same.
Just create an array of sub-directories while you loop the directory pointer, and iterate the array of directories at the end:
protected function getFiles($base) {
$files = $dirs = array();
if(!is_dir($base)) return $files;
if (($handle = opendir($base)) != false) {
while (false !== ($file = readdir($handle))) {
if ($file == "." || $file == "..") continue;
if(is_dir("$base/$file")) {
$dirs[] = "$base/$file";
} else {
if(File::type($file,false) == "xml")
$files[] = "$base/$file";
}
}
closedir($handle);
foreach ($dirs as $dir) {
$subfiles = $this->getFiles($dir);
$files = array_merge($files, $subfiles);
}
}
return $files;
}
Use two arrays one for the files in the current folder and one for the those in subfolders then merge them.
protected function getFiles($base) {
$files = array();
$subFiles = array();
if(!is_dir($base)) return $files;
if (($handle = opendir($base)) != false) {
while (false !== ($file = readdir($handle))) {
if ($file == "." || $file == "..") continue;
if(is_dir("$base/$file")) {
$subFiles = array_merge($subFiles, $this->getFiles("$base/$file"));
} else {
if(File::type($file,false) == "xml")
$files[] = "$base/$file";
}
}
closedir($handle);
}
return array_merge($files, $subFiles);
}
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;
}
?>