I'm not sure what the issue is, because I can delete and modify files in the same directory level with no problem. Here is the script I'm running to sort through all my directories and locate any TimThumb caches.
$caches = array();
function searchForThumbCaches($dir=false, &$results=false) {
if ( !is_array($results) )
$results = array();
if ( !$dir )
$dir = $_SERVER['DOCUMENT_ROOT'];
$thumbFileFound = false;
$cacheDirFound = false;
//echo 'Scanning dir `'.$dir.'`';
foreach(scandir($dir) as $item) {
$path = slash($dir.'/'.$item);
if ( $item == '.' || $item == '..' )
continue;
//echo 'Found item `'.$item.'` (`'.$path.'`)<br />';
if ( $item == 'cache' && is_dir($path) )
$cacheDirFound = true;
if ( $item == 'thumb.php' )
$thumbFileFound = true;
if ( is_dir($path) )
searchForThumbCaches($path, $results);
}
if ( $thumbFileFound && $cacheDirFound )
$results[] = slash($dir.'/cache');
return $results;
}
$thumbCaches = searchForThumbCaches();
foreach($thumbCaches as $cachePath) {
chmod($cachePath, 0777);
echo 'Cache `'.$cachePath.'`<br />';
foreach(scandir($cachePath) as $cacheFile) {
if ( $cacheFile == '.' || $cacheFile == '..' || $cacheFile == 'index.html' )
continue;
$path = slash($cachePath.'/'.$cacheFile);
unlink($path);
}
}
However, neither the chmod() or unlink() operations work, they both return errors, like this sample output:
Cache `/var/www/example.com/web/engine/img/dashboard/cache`
Warning: chmod(): Operation not permitted in /var/www/example.com/web/thumb.cache.clear.php on line 46
Cache `/var/www/example.com/web/engine/ui/themes/default/img/dashboard/cache`
Warning: unlink(/var/www/example.com/web/engine/ui/themes/default/img/dashboard/cache/timthumb_cacheLastCleanTime.touch): Permission denied in /var/www/example.com/web/thumb.cache.clear.php on line 52
I've tried deleting them in an FTP client like CyberDuck, but nothing I do seems to work. Is there anyway to override these permissions or am I just out of luck?
Related
I'm using Laravel 5.8 and I wanted to delete an image from storage directory.
Basically the images is placed at this dir:
/storage/app/public/laboratories/labs/21/pics
And I tried running this method:
public function removeAzPic($lab,$azpic)
{
$destinationPath = storage_path("laboratories/labs/$lab/pics/$azpic");
Storage::delete($destinationPath);
return redirect()->back();
}
But the problem is it does not delete the file from storage!
So what's going wrong here? How can I solve this issue?
You can add this function to the helper.php for to delete files/directories recursively:
Function will help you to delete files at the moment. If you want to delete directories change if ( is_dir($full) ) { to if ( is_file($full) ) {
public static function rrmdir($src = null) {
if(!is_dir($src)) return false;
$dir = opendir($src);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
$full = $src . '/' . $file;
if ( is_dir($full) ) {
self::rrmdir($full);
} else {
#unlink($full);
}
}
}
closedir($dir);
rmdir($src);
return true;
}
trying to find a way to copy entire directory but exclude certain files, in this case just need to exclude a directory which will always contain just 1 file a png... figured could use something similar to this code but have absolutely no clue as to how to exclude a file only
function xcopy($source, $dest, $permissions = 0755)
{
// Check for symlinks
if (is_link($source)) {
return symlink(readlink($source), $dest);
}
// Simple copy for a file
if (is_file($source)) {
return copy($source, $dest);
}
// Make destination directory
if (!is_dir($dest)) {
mkdir($dest, $permissions);
}
// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}
// Deep copy directories
xcopy("$source/$entry", "$dest/$entry", $permissions);
}
// Clean up
$dir->close();
return true;
}
Here is a function that may work for you. I have notated for clarification:
<?php
function CopyDirectory($settings = false)
{
// The script may take some time if there are lots of files
ini_set("max_execution_time",3000);
// Just do some validation and pre-sets
$directory = (isset($settings['dir']) && !empty($settings['dir']))? $settings['dir'] : false;
$copyto = (isset($settings['dest']) && !empty($settings['dest']))? $settings['dest'] : false;
$filter = (isset($settings['filter']) && !empty($settings['filter']))? $settings['filter'] : false;
// Add the copy to destinations not to copy otherwise
// you will have an infinite loop of files being copied
$filter[] = $copyto;
// Stop if the directory is not set
if(!$directory)
return;
// Create a recursive directory iterator
$dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory),RecursiveIteratorIterator::CHILD_FIRST);
try{
foreach($dir as $file) {
$copydest = str_replace("//","/",$copyto."/".str_replace($_SERVER['DOCUMENT_ROOT'],"",$file));
$compare = rtrim($file,".");
if(is_dir($file)) {
if(!is_dir($copydest)) {
if(!in_array($compare,$filter)) {
if(isset($skip) && !preg_match("!".$skip."!",$file) || !isset($skip))
#mkdir($copydest,0755,true);
else
$record[] = $copydest;
}
else {
$skip = $compare;
}
}
}
elseif(is_file($file) && !in_array($file,$filter)) {
copy($file,$copydest);
}
else {
if($file != '.' && $file != '..')
$record[] = $copydest;
}
}
}
// This will catch errors in copying (like permission errors)
catch (Exception $e)
{
$error[] = $e;
}
}
// Copy from
$settings['dir'] = $_SERVER['DOCUMENT_ROOT'];
// Copy to
$settings['dest'] = $_SERVER['DOCUMENT_ROOT']."/tester";
// Files and folders to not include contents
$settings["filter"][] = $_SERVER['DOCUMENT_ROOT'].'/core.processor/';
$settings["filter"][] = $_SERVER['DOCUMENT_ROOT'].'/config.php';
$settings["filter"][] = $_SERVER['DOCUMENT_ROOT'].'/client_assets/images/';
// Create instance
CopyDirectory($settings);
?>
I used the following code to display the contents of a Folder say images (Both Directories as well as Files in that folder)
<?php
$dir="images/"; // Directory where files are stored
if ($dir_list = opendir($dir))
{
while(($filename = readdir($dir_list)) !== false)
{
$newvar1="$dir$filename";// For Hyperlink Path
?>
<p><a href="<?php echo $newvar1; ?>"><?php echo $filename;
?></a></p>
<?php
}
closedir($dir_list);
}
?>
But the PHP file shows an output with two additional Links
A link to the folder 'images' and
A Link to the 'Homepage'.
I tried to filter those two links with "filesize" function but getting some error.
How can I resolve this?
Skip current dir and parent dir with a check.
while(...) {
if($filename == ".." || $filename == ".") continue;
...
}
Modify your code to something like this:
while(($filename = readdir($dir_list)) !== false)
{
if($filename != '.' || $filename != '..') // This part to check and ignore
$newvar1="$dir$filename";// For Hyperlink Path
else
continue; //while loop will no further be processed!
//...
}
This is a more in-depth answer and I'm so fed up with such things... This is absolutely an horrible piece of code, even though Php does permit such horrible things.
Something like this is easier to read, easier to maintain, and easier to debug:
<?php
$tab = array();
$dir="images/"; // Directory to parse
if ($dir_list = opendir($dir))
{
while(($filename = readdir($dir_list)) !== false)
{
if($filename != ".." && $filename != ".")
{
$tab[$filename] = $dir.$filename; // Hyperlink Path
}
}
closedir($dir_list);
}
/* Display separated from logic */
foreach ($tab as $filename => $hyperlink)
{
echo '<p>'.$filename.'</p>';
}
?>
More compact but a bit less easy to read:
<?php
$tab = array();
$dir="images/"; // Directory to parse
if ($dir_list = opendir($dir)) {
while(($filename = readdir($dir_list)) !== false) {
if($filename != ".." && $filename != ".") {
$tab[$filename] = $dir.$filename; // Hyperlink Path
}
}
closedir($dir_list);
}
/* Display separated from logic */
foreach ($tab as $filename => $hyperlink) {
echo '<p>'.$filename.'</p>';
}
?>
And some people (including my old teachers) tell that "if there's one line of code, don't use {}" (which I strongly disagree because it may lead to errors later on) but here's the "optimized" version:
<?php
$tab = array();
$dir="images/";
if ($dir_list = opendir($dir)) {
while(($filename = readdir($dir_list)) !== false)
if($filename != ".." && $filename != ".")
$tab[$filename] = $dir.$filename; // Hyperlink Path
closedir($dir_list);
}
foreach ($tab as $filename => $hyperlink)
echo '<p>'.$filename.'</p>';
?>
I have a code to check if directory is empty, so that i will be able to perform actions, but this simple code gives an error:
Warning: opendir(/Site/images/countries/abc/a/2.swf,/Site/images/countries/abc/a/2.swf) [function.opendir]: The system cannot find the path specified. (code: 3) in C:\wamp\www\Site\index.PHP on line 374
There is no such file
function IsNotEmpty($folder){
$files = array ();
if ( $handle = opendir ( $folder ) )
{
while ( false !== ( $file = readdir ( $handle ) ) )
{
if ( $file != "." && $file != ".." )
{
$files [] = $file;
}
}
closedir ( $handle );
}
return ( count ( $files ) > 0 ) ? TRUE: FALSE; }
$dir ="/Site/images/countries/abc/a/2.swf";
if (IsNotEmpty($dir)==true)
{
echo "There is no such file";
}
else
{
echo "The file exists!";
};
I don't understand what is wrong here. The file exits in the specified directory.
opendir is for opening directories, not files :-)
You can also try temporarily putting in debug stuff so that you can see what's happening:
function IsNotEmpty ($folder) {
$files = array ();
if ($handle = opendir ($folder)) {
echo "DEBUG opened okay ";
while (false !== ($file = readdir ($handle))) {
if ( $file != "." && $file != ".." ) {
$files [] = $file;
echo "DEBUG got a file ";
}
}
closedir ($handle);
} else {
echo "DEBUG cannot open ";
}
return (count($files) > 0 ) ? TRUE : FALSE;
}
$dir ="/Site/images/countries/abc/a";
if (IsNotEmpty($dir)) {
echo "There is no such file";
} else {
echo "The file exists!";
}
If that's still not working and you're sure the directory exists (remember, case is important for UNIX), you may want to look into the permissions on that directory to ensure that the user ID trying to access it is allowed.
You chould use the following snippet as body for your function:
$aFiles = glob($sFolder);
return (sizeof($aFiles) < 1) true : false;
This will get the contents of the folder as an array, when empty - your directory is empty.
Try for instance this:
function IsNotEmpty($dir) {
$dir = rtrim($dir, '/').'/';
return is_dir($dir) && count(glob($dir.'*.*') > 2);
}
Christine, try removing the trailing slash:
$dir ="/Site/images/countries/abc/a/"
Becomes
$dir ="/Site/images/countries/abc/a"
I am trying to delete a folder using this script :
function Delete($path)
{
if (is_dir($path) === true)
{
$files = array_diff(scandir($path), array('.', '..'));
foreach ($files as $file)
{
Delete(realpath($path) . '/' . $file);
}
return rmdir($path);
}
else if (is_file($path) === true)
{
return unlink($path);
}
return false;
}
Delete('tmp');
It works in my Xampp server, but not on my webserver. I have changed the permissions of the folder and of the file it contains to 0777. So it should be writable(or in this case erasable) but nothing happens. I have even tryied giving the absolute path of the folder as the parameter of the function, but still nothing.Any ideas?
Use this :
function delTree($dir)
{
$files = glob( $dir . '*', GLOB_MARK );
foreach( $files as $file
{
if( is_dir( $file ) )
delTree( $file );
else
#unlink( $file );
}
if( is_dir($dir) ) rmdir( $dir );
};
Does it return false? Or it returns true but doesn't actually remove?
Normally I'd just guess it's a permissions problem.
Try making a folder with mkdir from PHP so PHP is the owner (so to speak) and try to remove that with your function.
If it works, it's a permissions/owner issue.
You can Try this code
<?php
$files = glob('application/*'); foreach($files as $file){ if(is_file($file)) unlink($file); }
?>
Or,
function viewDir($path) {
return is_file($path) ?
#unlink($path) :
array_map(__FUNCTION__, glob($path.'/*')) == #rmdir($path);
}
$dir=$_SERVER["DOCUMENT_ROOT"]."/xxxx/xxxx";
echo $dir;
viewDir($dir);
May be some files are opened using php like fopen and that time it will not delete the folder or directory. I have faced the same issue when I tried to delete a file/folder
Try something like this.
<?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;
}
?>
Hope this helps.
Try this line of code to delete a folder or folder files
I hope this will help you
function deleteAll($str) {
if (is_file($str)) {
return unlink($str);
}
elseif (is_dir($str)) {
$scan = glob(rtrim($str,'/').'/*');
foreach($scan as $index=>$path) {
$this->deleteAll($path);
}
return #rmdir($str);
}
}