Check if folder is empty outputs error (PHP) - php

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"

Related

Deleting a file from storage does not delete an image

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

TimThumb cache folder cannot be deleted or edited

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?

Scanning folder for files instead of array

I have this code:
<?php
$allowed = array('file1', 'file2', 'file3');
if (in_array($_GET["url"], $allowed)) {
// You can include
} else {
// Error message and dont include
}
?>
But instead of writing all the filenames in the array, how can i do so that the files in for example my folder FILES/ is accepted an no other files. How to do that?
Use the file_exists function like this:
if (file_exists('FILES/'.basename($_GET["url"]))) {
// You can include
} else {
// Error message and dont include
}
Function to retrieve files in a folder:
<?
function fGetFilesInFolder($sFolder) {
$aFiles = array();
if(file_exists($sFolder)) {
if ($handle = opendir($sFolder)) {
while (false !== ($sFile = readdir($handle))) {
if ($sFile != "." && $sFile != "..") $aFiles[] = $sFile;
}
closedir($handle);
}
}
return $aFiles;
}
?>

return in function not working but echo works in PHP

i have the following function when i try and return the vaule its only shows 1 folder but when i echo the function it show the correct informaion.
PHP Code:
$FolderList = "";
function ListFolder($path) {
$path = str_replace("//","/",$path);
//using the opendir function
$dir_handle = #opendir($path) or die("Unable to open $path");
//Leave only the lastest folder name
$dirname = end(explode("/", $path));
//display the target folder.
$FolderList .= ('<option value="">'.$path.'</option>');
while(false !== ($file = readdir($dir_handle))) {
if($file!="." && $file!="..") {
if(is_dir($path."/".$file)) {
//Display a list of sub folders.
ListFolder($path."/".$file);
}
}
}
//closing the directory
closedir($dir_handle);
return $FolderList; //ERROR: Only Shows 1 Folder
echo $FolderList; //WORKS: Show All The Folders Correctly
}
Thanks
Give this a shot:
function ListFolder($path)
{
$path = str_replace("//","/",$path);
//using the opendir function
$dir_handle = #opendir($path) or die("Unable to open $path");
//Leave only the lastest folder name
$dirname = end(explode("/", $path));
//display the target folder.
$FolderList = ('<option value="">'.$path.'</option>');
while (false !== ($file = readdir($dir_handle)))
{
if($file!="." && $file!="..")
{
if (is_dir($path."/".$file))
{
//Display a list of sub folders.
$FolderList .= ListFolder($path."/".$file);
}
}
}
//closing the directory
closedir($dir_handle);
return $FolderList;
}
echo ListFolder('/path/to/folder/');
I simply changed the $FolderList to be assigned to the return value of the ListFolder function.
Inside your while loop, you're calling ListFolder again. This is okay to do but you're not storing the result anywhere and just echoing the result every time ListFolder is called.
That correct format you're seeing on the page is not that 1 string being echoed at the end. its a single directory being echoed every time ListFolder is being called.
Below is the code that works.
function ListFolder($path)
{
$FolderList = "";
$path = str_replace("//","/",$path);
//using the opendir function
$dir_handle = #opendir($path) or die("Unable to open $path");
//Leave only the lastest folder name
$dirname = end(explode("/", $path));
//display the target folder.
$FolderList .= ('<option value="">'.$path.'</option>');
while (false !== ($file = readdir($dir_handle)))
{
if($file!="." && $file!="..")
{
if (is_dir($path."/".$file))
{
//Display a list of sub folders.
$FolderList .= ListFolder($path."/".$file);
}
}
}
//closing the directory
closedir($dir_handle);
return $FolderList;
}
Each function call has its own variable scope. You need to union the returned value from your recursive call with the one that you’ve gathered in the while loop:
while(false !== ($file = readdir($dir_handle))) {
if($file!="." && $file!="..") {
if(is_dir($path."/".$file)) {
$FolderList .= ListFolder($path."/".$file);
}
}
}
You forgot to catch the return value of the function calls
$FolderList .= ListFolder($path."/".$file);
You just add one folder to the string, than call the function, but do nothing with the return value. Then you return $FolderList, which only contains the one entry you add before the while-loop
When *echo*ing it, its just send directly to the browser independently on which level of recursion you are, so you think, that $FolderList is full, but in fact its just every sungle $FolderList from each recursion step.
Alternative Method
function ListFolder($path, &$FolderList = array()) {
$path = str_replace("//","/",$path);
//using the opendir function
$dir_handle = #opendir($path) or die("Unable to open $path");
//Leave only the lastest folder name
$dirname = end(explode("/", $path));
//display the target folder.
$FolderList[] = '<option value="">'.$path.'</option>';
while(false !== ($file = readdir($dir_handle))) {
if($file!="." && $file!="..") {
if(is_dir($path."/".$file)) {
//Display a list of sub folders.
ListFolder($path."/".$file, $FolderList);
}
}
}
//closing the directory
closedir($dir_handle);
return $FolderList;
}
$paths = ListFolder(getcwd());
echo "<select>".implode("", $paths)."</select>";

Delete folder in php

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

Categories