I am calling my php function from some other website which delete a folder on my server in background.
This is a function which I am using to delete a folder.
public static function remove($dir)
{
if (is_dir($dir)) {
$diropen = opendir($dir);
while($d = readdir($diropen)) {
if ($d!= '.' && $d != '..') {
self::remove($dir . "/$d");
}
}
#rmdir($dir);
} elseif (is_file($dir)) {
#unlink($dir);
}
}
If I am having three files in folder then it deletes only two and unable to delete last file or unlink fails on last file.
If I am having two files then it deletes only one file.
I have checked writable permission using is_writable it is true for all files.
Can somebody please help me out. or how to debug this behavior as this function is getting called in background.
my directory was open in some other function , so I closedir my folder and then above function working fine.
<?php
function delete_directory($target) {
if (is_dir($target))
$dir_handle = opendir($target);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
else
delete_directory($target.'/'.$file);
}
}
closedir($dir_handle);
rmdir($target);
return true;
}
?>
use closedir and you'll be fine.
I am trying to recursively loop through a bunch of subdirectories and include the files within them instead of 'hardcoding' them in, the problem is if I do hardcode the include path it displays correctly but using the below code I keep getting 'failed to open stream: No such file or directory'. I have tried many different approaches and keep getting similar errors. If anybody has a suggestion of what or where I am going wrong I would appreciate it.
include path would be like: (/core/edit_object/border/border_radius.php);
filesInDir('core/edit_object');
function filesInDir($tdir) {
$dirs = scandir($tdir);
foreach($dirs as $file) {
if (($file == '.') || ($file == '..') || ($file == '.DS_Store')) {
} else if (is_dir($tdir.'/'.$file)) {
filesInDir($tdir.'/'.$file);
} else {
//echo '/'.$tdir.'/'.$file."<br>";
include '/'.$tdir.'/'.$file;
}
}
}
Decided I would try a different approach, I found after running the code below that it was returning what I was after although with many many include errors as in my original post. I found after turning off error reporting in php.ini it ran perfectly. Thank to the posters above with their help and suggestions.
$dir = new RecursiveDirectoryIterator('test');
foreach (new RecursiveIteratorIterator($dir) as $filename => $file) {
$search = array('.DS_Store');
$file = str_replace($search, '', $file);
include $file;
}
I inherited a piece of code that has suddenly stopped working. I've isolated the code down to it appears this function is no longer reading the directory and locating the xml file found in it for later processing. I've uploaded versions of the xml file with uppercase and lowercase .xml/.XML extension with the same result: NO XML FILE FOUND
I've verified that the print_r is in fact reading the correct directory where the xml file resides. There are other files in the directory but that has been the case for years. Did something change recently in PHP to stop this code from working?
function GetXMLFile($path) {
$path .= "/";
print_r($path);
$filename = "";
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if (GetFileExtention($path . strtolower($file)) =="XML") {
$filename = $file;
}
}
}
closedir($handle);
}
return $filename;
}
Later in the code the function is called that is producing the NO XML error. I've confirmed the $config['xml_dir'] variable below matches the print_r directory location above as well.
$cur_xml_file = GetXMLFile($config['xml_dir']);
if ($cur_xml_file == "") {
echo "NO XML FILE FOUND";
exit(0);
}
No, nothing has changed in PHP recently that would cause the code you show to stop functioning. If it doesn't work anymore, the error is somewhere else.
Then again, that's a lot of code to find a file. Why don't you just do change it to
function GetXMLFile($path) {
$all_xml_files = glob("$path/*.{xml,XML}", GLOB_BRACE);
return !empty($all_xml_files) ? realpath($all_xml_files[0]) : "";
}
That will return the absolute path of the first file with an .XML or .xml extension in the given $path or an empty string if no files are found or an error occured.
See if the error goes away when you change it to that.
when moving one file from one location to another i use
rename('path/filename', 'newpath/filename');
how do you move all files in a folder to another folder? tried this one without result:
rename('path/*', 'newpath/*');
A slightly verbose solution:
// 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);
}
Please try this solution, it's tested successfully ::
<?php
$files = scandir("f1");
$oldfolder = "f1/";
$newfolder = "f2/";
foreach($files as $fname) {
if($fname != '.' && $fname != '..') {
rename($oldfolder.$fname, $newfolder.$fname);
}
}
?>
An alternate using rename() and with 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";
}
tried this one?:
<?php
$oldfolderpath = "old/folder";
$newfolderpath = "new/folder";
rename($oldfolderpath,$newfolderpath);
?>
So I tried to use the rename() function as described and I kept getting the error back that there was no such file or directory. I placed the code within an if else statement in order to ensure that I really did have the directories created. It looked like this:
$tempDir = '/home/site/images/tmp/';
$permanentDir = '/home/site/images/' . $claimid; // this was stored above
mkdir($permanentDir,0775);
if(is_dir($permanentDir)){
echo $permanentDir . ' is a directory';
if(is_dir($tempDir)){
echo $tempDir . ' is a directory';
}else{
echo $tempDir . ' is not a directory';
}
}else{
echo $permanentDir . ' is not a directory';
}
rename($tempDir . "*", $permanentDir);
So when I ran the code again, it spit out that both paths were directories. I was stumped. I talked with a coworker and he suggested, "Why not just rename the temp directory to the new directory, since you want to move all the files anyway?"
Turns out, this is what I ended up doing. I gave up trying to use the wildcard with the rename() function and instead just use the rename() to rename the temp directory to the permanent one.
so it looks like this.
$tempDir = '/home/site/images/tmp/';
$permanentDir = '/home/site/images/' . $claimid; // this was stored above
mkdir($permanentDir,0775);
rename($tempDir, $permanentDir);
This worked beautifully for my purposes since I don't need the old tmp directory to remain there after the files have been uploaded and "moved".
Hope this helps. If anyone knows why the wildcard doesn't work in the rename() function and why I was getting the error stating above, please, let me know.
Move or copy the way I use it
function copyfiles($source_folder, $target_folder, $move=false) {
$source_folder=trim($source_folder, '/').'/';
$target_folder=trim($target_folder, '/').'/';
$files = scandir($source_folder);
foreach($files as $file) {
if($file != '.' && $file != '..') {
if ($move) {
rename($source_folder.$file, $target_folder.$file);
} else {
copy($source_folder.$file, $target_folder.$file);
}
}
}
}
function movefiles($source_folder, $target_folder) {
copyfiles($source_folder, $target_folder, $move=true);
}
try this:
rename('path/*', 'newpath/');
I do not see a point in having an asterisk in the destination
If the target directory doesn't exist, you'll need to create it first:
mkdir('newpath');
rename('path/*', 'newpath/');
As a side note; when you copy files to another folder, their last changed time becomes current timestamp. So you should touch() the new files.
... (some codes for directory looping) ...
if (copy($source.$file, $destination.$file)) {
$delete[] = $source.$file;
$filetimestamp = filemtime($source.$file);
touch($destination.$file,$filetimestamp);
}
... (some codes) ...
Not sure if this helps anyone or not, but thought I'd post anyway. Had a challenge where I has heaps of movies I'd purchased and downloaded through various online stores all stored in one folder, but all in their own subfolders and all with different naming conventions. I wanted to move all of them into the parent folder and rename them all to look pretty. all of the subfolders I'd managed to rename with a bulk renaming tool and conditional name formatting. the subfolders had other files in them i didn't want. so i wrote the following php script to, 1. rename/move all files with extension mp4 to their parent directory while giving them the same name as their containing folder, 2. delete contents of subfolders and look for directories inside them to empty and then rmdir, 3. rmdir the subfolders.
$handle = opendir("D:/Movies/");
while ($file = readdir($handle)) {
if ($file != "." && $file != ".." && is_dir($file)) {
$newhandle = opendir("D:/Movies/".$file);
while($newfile = readdir($newhandle)) {
if ($newfile != "." && $newfile != ".." && is_file("D:/Movies/".$file."/".$newfile)) {
$parts = explode(".",$newfile);
if (end($parts) == "mp4") {
if (!file_exists("D:/Movies/".$file.".mp4")) {
rename("D:/Movies/".$file."/".$newfile,"D:/Movies/".$file.".mp4");
}
else {
unlink("D:/Movies/".$file."/".$newfile);
}
}
else { unlink("D:/Movies/".$file."/".$newfile); }
}
else if ($newfile != "." && $newfile != ".." && is_dir("D:/Movies/".$file."/".$newfile)) {
$dirhandle = opendir("D:/Movies/".$file."/".$newfile);
while ($dirfile = readdir($dirhandle)){
if ($dirfile != "." && $dirfile != ".."){
unlink("D:/Movies/".$file."/".$newfile."/".$dirfile);
}
}
rmdir("D:/Movies/".$file."/".$newfile);
}
}
unlink("D:/Movies/".$file);
}
}
i move all my .json files from root folder to json folder with this
foreach (glob("*.json") as $filename) {
rename($filename,"json/".$filename);
}
pd: someone 2020?
I tried to write a script to list all files in directories and subdirectories and so on.. The script works fine if I don't include the check to see whether any of the files are directories. The code doesn't generate errors but it generates a hundred lines of text saying "Directory Listing of ." instead of what I was expecting. Any idea why this isn't working?
<?php
//define the path as relative
$path = "./";
function listagain($pth)
{
//using the opendir function
$dir_handle = #opendir($pth) or die("Unable to open $pth");
echo "Directory Listing of $pth<br/>";
//running the while loop
while ($file = readdir($dir_handle))
{
//check whether file is directory
if(is_dir($file))
{
//if it is, generate it's list of files
listagain($file);
}
else
{
if($file!="." && $file!="..")
echo "<a href='$file'>$file</a><br/>";
}
}
//closing the directory
closedir($dir_handle);
}
listagain($path)
?>
The first enties . and .. refer to the current and parent directory respectivly. So you get a infinite recursion.
You should first check for that before checking the file type:
if ($file!="." && $file!="..") {
if (is_dir($file)) {
listagain($file);
} else {
echo ''.htmlspecialchars($file).'<br/>';
}
}
The problem is, variable $file contains only basename of path. So, you need to use $pth.$file.