Page 1 of 1

Delete File/Folder Error

Posted: Tue Jan 03, 2006 12:52 pm
by chlln17
Jcart | Please use

Code: Select all

and

Code: Select all

tags where appropriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]


I'm running into this problem randomly.  The following is a file manager script I'm building for a client that would like to update their image gallery without using an FTP program.  It's pretty simple.  When deleting a file or folder, it works most of the time.  But [b]somtimes[/b] the script will produce the following error but [b]still delete the file/folder[/b] even though it says it cannot find it.

[quote]

Warning: opendir(/*/*/*/html/gallery/Test/Test/): failed to open dir: No such file or directory in /*/*/*/html/siteoffice/control_modules/pl_sitegallery.php on line 193

Warning: readdir(): supplied argument is not a valid Directory resource in /*/*/*/html/siteoffice/control_modules/pl_sitegallery.php on line 195

Warning: closedir(): supplied argument is not a valid Directory resource in /*/*/*/html/siteoffice/control_modules/pl_sitegallery.php on line 219

Warning: rmdir(/*/*/*/html/gallery/Test/Test/): No such file or directory in /*/*/*/html/siteoffice/control_modules/pl_sitegallery.php on line 223

[/quote]

All the replaced *'s were the correct directories.

Any thoughts?  Here is the code -

Code: Select all

/*
----------------------------------------------------------------------
	DEFINE FUNCTIONS
----------------------------------------------------------------------	
*/

include ("control_functions/upload_image.php");

function recur_dir($dir) 
{
	$dirlist = opendir($dir);
  	while ($file = readdir ($dirlist))
	{
		if ($file != '.' && $file != '..')
  	    {
  	    	$newpath = $dir.'/'.$file;
			$folderpath = $dir.'/'.$file.'/';
			$filepath = $dir.'/';
  	        $level = explode('/',$newpath);
  	        if (is_dir($newpath))
  	        {
  	        	$mod_array[] = array(
  	                         'level'=>count($level)-1,
  	                         'path'=>$newpath,
							 'nfpath'=>$folderpath,
  	                         'name'=>end($level),
  	                         'kind'=>'dir',
  	                         'mod_time'=>filemtime($newpath),
  	                         'content'=>recur_dir($newpath));
  	         }else{
  	         	$mod_array[] = array(
  	                         'level'=>count($level)-1,
  	                         'path'=>$newpath,
							 'nfpath'=>$filepath,
  	                         'name'=>end($level),
  	                         'kind'=>'file',
  	                         'mod_time'=>filemtime($newpath),
  	                         'size'=>filesize($newpath));
			}
		}
	}
	
	closedir($dirlist);
  	return $mod_array;
	
}



function rename_fd($path, $newname)
{
	
	/* Set the base directory - path to working directory from document root */
		$base = "";
		
	/* Exlode the path into an array */
		$pathArray = explode("/", $path);
		$count = count($pathArray);
		
	/* Rebuild the path so we can use it to rename the file */	
		for($i=0; ($i+1) < $count; $i++)
		{
			$newpath .= $pathArray[$i] . "/";
		}
		$newpath .= $newname;
	
	
	/* Rename the file or folder */
		$original = $_SERVER[DOCUMENT_ROOT] . $base . $path;
		$new = $_SERVER[DOCUMENT_ROOT] . $base . $newpath;
		
		$rename = rename($original, $new);	
		
		
	/* Return true if the file or was directory was renamed successfully */
		if (!$rename)
		{
			return false;
		}
		else
		{
			return true;
		}		
	 

}


function create_d($path, $dirname)
{
	
	/* Set the base directory - path to working directory from document root */
		$base = "/";
		
	
	/* Create folder */
		$dir = $_SERVER[DOCUMENT_ROOT] . $base . $path . "/" . $dirname;
		
		$create = mkdir($dir, 0755);	
		
		
	/* Create the index.php file required for the gallery script */
		$sourceFile = $_SERVER[DOCUMENT_ROOT] . "/gallery/July_2005_BSS_BRC_Web_Launch/index.php";
		$sourceHandle = fopen($sourceFile, 'r');
		$sourceData = fread($sourceHandle, filesize($sourceFile));
		fclose($sourceHandle);		
		
		
		$newFile = $dir . "/index.php";
		$newHandle = fopen($newFile, "w");
		
	    if (fwrite($newHandle, $sourceData) === FALSE) {
		    echo "Cannot write to file ($filename)";
	    }		
		
		
		fclose($newHandle);
	
	
	
	/* Return true if the file or was directory was renamed successfully */
		if (!$create)
		{
			return false;
		}
		else
		{
			return true;
		}		
	 

}



function delete_file($path)
{
	
	/* Set the base directory - path to working directory from document root */
		$base = "";
	
	
	/* Delete the file */
		$fileLocation = $_SERVER[DOCUMENT_ROOT] . $base . $path;
		$deleteFile = unlink($fileLocation);
		
				
	/* Return true if the file was deleted successfully */
		if (!$deleteFile)
		{
			return false;
		}
		else
		{
			return true;
		}

}



function delete_dir($path)
{


	/* Set the base directory - path to working directory from document root */
		$base = "";
		$fullpath = $_SERVER[DOCUMENT_ROOT] . $base . $path . "/";
	
	
	ini_set("memory_limit","50M");
	
	/* First, remove any files or directories under this directory */
		$handle = opendir($fullpath);
  
	    while (false !== ($file = readdir($handle))) {
			if ($file != "." & $file != "..")
			{
			
				/* Set the new path */
				$newpath = $path . "/" . $file;
				$testpath = $fullpath . $file;

				
				if (is_file($testpath))
				{
					delete_file($newpath);
				}
				
				if (is_dir($testpath))
				{
					delete_dir($newpath);
				}				
			
			}
			
	   	}	
		
	/* Close our directory */
		closedir($handle);		
		
	
	/* Now delete the directory */
		$deleteDir = rmdir($fullpath);

				
	/* Return true if the file was deleted successfully */
		if (!$deleteDir)
		{
			return false;
		}
		else
		{
			return true;
		}
	
}

/*
----------------------------------------------------------------------







/*
----------------------------------------------------------------------
	PRE-PROCESSING
----------------------------------------------------------------------	
*/

/* Deleting a file or directory? */
if (!empty($_GET['delete']) && !empty($_GET['path']))
{
	switch ($_GET['delete']) {
	case 'dir':
		delete_dir($_GET['path']);
		break;
	case 'file':
		delete_file($_GET['path']);
	   	break;
	}	
} 

/* Rename a file or directory? */
if (!empty($_POST['newname']) && !empty($_GET['path']))
{
	rename_fd($_GET['path'], $_POST['newname']);
} 


/* Upload an image or file? */
if (!empty($_FILES['upload']) && !empty($_GET['path']))
{
	
	/* Check to see if the file is an image, or a text file */
	$fileType = explode("/", $_FILES['upload']['type']);
	
	if($fileType[0] == "image")
	{
		$uploadPath = "" . $_GET['path'] . "/";
		
		  if(!upload_image("upload", $uploadPath, "0", "450")) {
			echo("<p class=\"normal\"><strong>ERROR:</strong> Image file was unable to be uploaded.</p>");
		  }	
		  	
	}
	
	
	if($fileType[0] == "text" && $fileType[1] == "plain")
	{	
	
		$uploadPath = $_SERVER[DOCUMENT_ROOT] . $_GET['path'] . "/";
		$uploadFile = $uploadPath . $_FILES['upload']['name'];
		
		echo '<pre>';
		if (!move_uploaded_file($_FILES['upload']['tmp_name'], $uploadFile)) {
			echo "Possible file upload attack!\n";		   
		}
		echo '</pre>'; 
		
	}
	
} 



/* Create a new directory? */
if (!empty($_POST['dirname']) && !empty($_GET['path']))
{
	
	create_d($_GET['path'], $_POST['dirname']);	
	
}















/*
----------------------------------------------------------------------
	BEGIN PAGE OUTPUT
----------------------------------------------------------------------	
*/

function print_dir($tree, $expand)
{
	$rowcount = count($tree);
	
	
	/* Begin by starting our list by print a ul for formatting */
	echo "<ul>";
	
	
	
	
	for($i = 0; $i < $rowcount; $i++)
	{
		
		if (substr($tree[$i]['name'],-3) != 'php' && substr($tree[$i]['name'],-3) != 'old' && substr($tree[$i]['name'],-2) != 'db')
		{
		
			
			
			/* If this is a directory, display an open folder for expanded view, or a closed folder if not expanded */
			switch ($tree[$i]['kind']) {
			case 'dir':
				echo "<li class=\"dir\">";
				
				$found = strpos($expand, substr($tree[$i]['nfpath'], 2));
				
						
				if ($found == true)
				{
				
					$dir = substr($expand, 1);
					
					/* Exlode the directory into an array */
						$dirArray = explode("/", $dir);
						$dirCount = count($dirArray) - 1;
						
											
					/* Rebuild the directory so we can use it to collapse the current directory if we need to */	
						for($c=0; ($c+1) < $dirCount; $c++)
						{
							if($c == 0)
								// $newDir = "/";
								
							if($dirArray[$c] == $tree[$i]['name'])
								break;
								
							$newDir .= $dirArray[$c] . "/";
						}
								
				
				
					echo "<a href=\"?show=pl_sitegallery&expand=" . $newDir . "\"><img src=\"images/gallerymanager/folder_open.gif\" class=\"icon\" alt=\"Open Folder\"></a>";
				}
				else
				{
					echo "<a href=\"?show=pl_sitegallery&expand=" . substr($tree[$i]['nfpath'], 1) . "\"><img src=\"images/gallerymanager/folder.gif\" class=\"icon\"></a>";
				}
				break;
				
			default:
				echo "<li class=\"file\">";
				echo "<img src=\"images/gallerymanager/file.gif\" class=\"icon\">";
		   		break;
				
			}
				
			

				
			
			/* Display file or folder name and edit/trash buttons */
			echo $tree[$i]['name'];
			echo " <a href=\"?show=pl_sitegallery&rename=" . $tree[$i]['name'] . "&path=" . substr($tree[$i]['path'], 2)  . "&expand=" . substr($tree[$i]['nfpath'], 1) . "\"><img src=\"images/gallerymanager/edit.gif\"></a> <a href=\"?show=pl_sitegallery&delete=" . $tree[$i]['kind'] . "&path=" . substr($tree[$i]['path'], 2) . "&expand=" . substr($tree[$i]['nfpath'], 1) . "\"><img src=\"images/gallerymanager/trash.gif\"></a> ";
			
			
			
			
			
			/* If this is an expanded directory, display the add file button */
			switch ($tree[$i]['kind']) {
			case 'dir':
				if ($found == true)
				{
					echo "<br><span class=\"expandedTools\">";
					echo "<a href=\"?show=pl_sitegallery&mdir=" . $tree[$i]['name'] . "&path=" . substr($tree[$i]['path'], 2)  . "&expand=" . substr($tree[$i]['nfpath'], 1) . "\"><img src=\"images/gallerymanager/add_folder.gif\" class=\"icon\" alt=\"Add File\"></a>";
					echo "<a href=\"?show=pl_sitegallery&upload=" . $tree[$i]['name'] . "&path=" . substr($tree[$i]['path'], 2)  . "&expand=" . substr($tree[$i]['nfpath'], 1) . "\"><img src=\"images/gallerymanager/add_file.gif\" class=\"icon\" alt=\"Add File\"></a>";
					echo "</span>";
				}
				break;
				
			}			
			
			
			
			
			
			
			/* Edit form which shows when edit button is pressed */
			if ($_GET['rename'] == $tree[$i]['name'])
			{
				echo "<form action=\"?show=pl_sitegallery&path=" . substr($tree[$i]['path'], 2) . "&expand=" . substr($tree[$i]['nfpath'], 1) . "\" method=\"post\" id=\"editform\">"; 
				echo "Rename to: <input type=\"text\" name=\"newname\" size=\"45\">";
				echo "<input type=\"submit\" value=\"Submit\">";
				echo "</form>";
			}
			
			
			/* Create directory form which shows when create folder button is pressed */
			if ($_GET['mdir'] == $tree[$i]['name'])
			{
				echo "<form action=\"?show=pl_sitegallery&path=" . substr($tree[$i]['path'], 2) . "&expand=" . substr($tree[$i]['nfpath'], 1) . "\" method=\"post\" id=\"editform\">"; 
				echo "Directory name: <input type=\"text\" name=\"dirname\" size=\"45\">";
				echo "<input type=\"submit\" value=\"Submit\">";
				echo "</form>";
			}			
			
			
			/* Upload form which shows when upload button is pressed */
			if ($_GET['upload'] == $tree[$i]['name'])
			{
				echo "<form action=\"?show=pl_sitegallery&path=" . substr($tree[$i]['path'], 2) . "&expand=" . substr($tree[$i]['nfpath'], 1) . "\" method=\"post\" id=\"editform\" enctype=\"multipart/form-data\">"; 
				echo "<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"2500000\" />";
				echo "<input type=\"hidden\" name=\"max_size\" value=\"2500000\" />";				
				echo "Upload File: <input type=\"file\" name=\"upload\">";
				echo "<br>Acceptable File Formats:</strong> JPEG or PNG files under 2.5 MB, or plain text files.";
				echo "<br><strong>Warning:</strong> Any files with the same name will be overwritten";
				echo "<br><br><input type=\"submit\" value=\"Submit\">";
				echo "</form>";
			}			
			
					
			
			if(is_array($tree[$i]['content']))
			{
				if ($found == true)
				{				
					print_dir($tree[$i]['content'], $expand);
				}
				
			}
			
			
		
		
			echo "</li>";
			
			
		}	
	
	
	}
	
	
	
	/* End with a closing ul */
	echo "</ul>\n";
	
} 



print "\n\n<div id=\"gallery\">\n\n";

echo "<a href=\"?show=pl_sitegallery&mdir=gallery&path=gallery\"><img src=\"images/gallerymanager/add_folder.gif\" class=\"icon\" alt=\"Add File\"></a>";
echo "<a href=\"?show=pl_sitegallery&upload=gallery&path=gallery\"><img src=\"images/gallerymanager/add_file.gif\" class=\"icon\" alt=\"Add File\"></a><br>";


			/* Create directory form which shows when create folder button is pressed */
			if ($_GET['mdir'] == "gallery")
			{
				echo "<form action=\"?show=pl_sitegallery&path=gallery\" method=\"post\" id=\"editform\">"; 
				echo "Directory name: <input type=\"text\" name=\"dirname\" size=\"45\">";
				echo "<input type=\"submit\" value=\"Submit\">";
				echo "</form>";
			}			
			
			
			/* Upload form which shows when upload button is pressed */
			if ($_GET['upload'] == "gallery")
			{
				echo "<form action=\"?show=pl_sitegallery&path=gallery\" method=\"post\" id=\"editform\" enctype=\"multipart/form-data\">"; 
				echo "<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"2500000\" />";
				echo "<input type=\"hidden\" name=\"max_size\" value=\"2500000\" />";				
				echo "Upload File: <input type=\"file\" name=\"upload\">";
				echo "<br>Acceptable File Formats:</strong> JPEG or PNG files under 2.5 MB, or plain text files.";
				echo "<br><strong>Warning:</strong> Any files with the same name will be overwritten";
				echo "<br><br><input type=\"submit\" value=\"Submit\">";
				echo "</form>";
			}	
 


$directoryTree = recur_dir('../gallery');

print_dir($directoryTree, $_GET['expand']);

print "\n\n</div>";



?>

Jcart | Please use

Code: Select all

and

Code: Select all

tags where appropriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]

Posted: Tue Jan 03, 2006 1:06 pm
by Chris Corbyn
The directories might not have read & execute permission to the world group.

Use FTP or a real shell to get a file list and check.

Code: Select all

drwxr-xr-x  4 d11wtq users   4096 Dec  23 22:57 cpp_learn
The last 3 attributes ( "r-x" above) must have at least read and execute permissions on *all* directories leading up to the directory you want to access.

Posted: Tue Jan 03, 2006 2:33 pm
by chlln17
Thanks for your reply! All the permissions are set to 755. The strange part of this whole problem is the randomness of it. I can create a folder called "New" ten times and delete it 10 times in the same manner but maybe once or twice out of the group I'll run across this error.

And even when it gives this error the folder will still get deleted.

Posted: Tue Jan 03, 2006 2:38 pm
by Charles256
lol.is put error suppression on it a valid answer ? :-D

Posted: Tue Jan 03, 2006 3:29 pm
by chlln17
Yes! I thought maybe I would get lucky, and that others would have ran into this problem at some point.

It's almost like the script deletes the folder before it tries to handle the folder, which makes absolutely no sense at all.