Codeigniter delete the directory and its contents - php

I am trying to make codeigniter delete a product image folder.
Furthermore, the delete function I am trying to make needs to delete also all of its contents, so empty or not, the folder gets deleted. I'm guessing, it would use a recursive type of deletion...I'm not so sure at all.
I have tried the below functions for deleting :
function delete_directory($path)
{
$path=base_url().'products/thumb/';
$this->load->helper("file"); // load the helper
delete_files($path, true); // delete all files/folders
//rmdir($dirname);
if(rmdir($path)){
echo 'deleted';die;}
else{
echo 'not';die; }
return true;
}
But it always returning not

Deleting directory content:
It will probably work, I have used
$this->load->helper('directory');
$this->load->helper("file");
$dir_fiels = directory_map('resources/captcha/');
$len = sizeOf($dir_fiels);
for($i=0; $i<$len;$i++){
unlink('resources/captcha/'.$dir_fiels[$i]);
}

create an helper. see below:-
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('remove_directory'))
{
function remove_directory($directory, $empty=FALSE)
{
if(substr($directory,-1) == '/') {
$directory = substr($directory,0,-1);
}
if(!file_exists($directory) || !is_dir($directory)) {
return FALSE;
} elseif(!is_readable($directory)) {
return FALSE;
} else {
$handle = opendir($directory);
while (FALSE !== ($item = readdir($handle)))
{
if($item != '.' && $item != '..') {
$path = $directory.'/'.$item;
if(is_dir($path)) {
remove_directory($path);
}else{
unlink($path);
}
}
}
closedir($handle);
if($empty == FALSE)
{
if(!rmdir($directory))
{
return FALSE;
}
}
return TRUE;
}
}
}
then load this helper in Your controller and call function remove_directory()
/* End of file recursive_helper.php */
/* Location: /application/helpers/recursive_helper.php */

Delete all files:
delete_files('./path/to/your/directory/');
Include sub-folder(s):
delete_files('./path/to/your/directory/', TRUE);

Related

copy entire directory but exclude some files php

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

php function return blank value on return statement and print right on echo

i create this function for search resume file from directory, if resume is available then function return full path, problem is function return nothing if i use "return", if i use "echo" then it will print right path
function search_resume($resume,$dir="uploads/resumes")
{
$root = scandir($dir);
foreach($root as $value)
{
/* echo $value."<br/>"; */
if($value === '.' || $value === '..') {continue;}
if(is_file("$dir/$value"))
{
if($value==$resume)
{
$path="$dir/$value";
return $path;
}
}
else
{
search_resume($resume,"$dir/$value");
}
}
}
A very typical, basic problem with recursive functions: you need to return recursive calls as well, they're not going to return themselves.
...
else {
$path = search_resume($resume,"$dir/$value");
if ($path) {
return $path;
}
}

PHP recursive delete function

I wrote recursive PHP function for folder deletion. I wonder, how do I modify this function to delete all files and folders in webhosting, excluding given array of files and folder names (for ex. cgi-bin, .htaccess)?
BTW
to use this function to totally remove a directory calling like this
recursive_remove_directory('path/to/directory/to/delete');
to use this function to empty a directory calling like this:
recursive_remove_directory('path/to/full_directory',TRUE);
Now the function is
function recursive_remove_directory($directory, $empty=FALSE)
{
// if the path has a slash at the end we remove it here
if(substr($directory,-1) == '/')
{
$directory = substr($directory,0,-1);
}
// if the path is not valid or is not a directory ...
if(!file_exists($directory) || !is_dir($directory))
{
// ... we return false and exit the function
return FALSE;
// ... if the path is not readable
}elseif(!is_readable($directory))
{
// ... we return false and exit the function
return FALSE;
// ... else if the path is readable
}else{
// we open the directory
$handle = opendir($directory);
// and scan through the items inside
while (FALSE !== ($item = readdir($handle)))
{
// if the filepointer is not the current directory
// or the parent directory
if($item != '.' && $item != '..')
{
// we build the new path to delete
$path = $directory.'/'.$item;
// if the new path is a directory
if(is_dir($path))
{
// we call this function with the new path
recursive_remove_directory($path);
// if the new path is a file
}else{
// we remove the file
unlink($path);
}
}
}
// close the directory
closedir($handle);
// if the option to empty is not set to true
if($empty == FALSE)
{
// try to delete the now empty directory
if(!rmdir($directory))
{
// return false if not possible
return FALSE;
}
}
// return success
return TRUE;
}
}
Try something like this:
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('%yourBaseDir%'),
RecursiveIteratorIterator::CHILD_FIRST
);
$excludeDirsNames = array();
$excludeFileNames = array('.htaccess');
foreach($it as $entry) {
if ($entry->isDir()) {
if (!in_array($entry->getBasename(), $excludeDirsNames)) {
try {
rmdir($entry->getPathname());
}
catch (Exception $ex) {
// dir not empty
}
}
}
elseif (!in_array($entry->getFileName(), $excludeFileNames)) {
unlink($entry->getPathname());
}
}
I'm using this function to delete the folder with all files and subfolders:
function removedir($dir) {
if (substr($dir, strlen($dir) - 1, 1) != '/')
$dir .= '/';
if ($handle = opendir($dir)) {
while ($obj = readdir($handle)) {
if ($obj != '.' && $obj != '..') {
if (is_dir($dir . $obj)) {
if (!removedir($dir . $obj))
return false;
}
else if (is_file($dir . $obj)) {
if (!unlink($dir . $obj))
return false;
}
}
}
closedir($handle);
if (!#rmdir($dir))
return false;
return true;
}
return false;
}
$folder_to_delete = "folder"; // folder to be deleted
echo removedir($folder_to_delete) ? 'done' : 'not done';
Iirc I got this from php.net
You could provide an extra array parameter $exclusions to recursive_remove_directory(), but you'll have to pass this parameter every time recursively.
Make $exclusions global. This way it can be accessed in every level of recursion.

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

index files from a folder with subfolders and store location and filename

Hi I am looking for help to write a short script which will locate all files in a folder (which has sub-folders) list the path and filename in two seperate values before submitting to a database.
Can anyone help?
i have a recursive function to delete a folder, you'd have to change it so instead of calling the ´unlink´ function you could save it in a variable or in a database..
public function deleteFolder($dirname) {
if (is_dir($dirname)){
$dir_handle = opendir($dirname);
}
if (!isset($dir_handle) || !$dir_handle){
return false;
}
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file)){
//change this line
unlink($dirname."/".$file);
} else {
//recursive call
$this->deleteFolder($dirname.'/'.$file);
}
}
}
closedir($dir_handle);
//also change this one
rmdir($dirname);
return true;
}
hope this helps.. good luck!
<?php
print_r(getPathFiles("./"));
function getPathFiles($dir) {
$ite=new RecursiveDirectoryIterator($dir);
$foo=new RecursiveIteratorIterator($ite);
$ret=array();
foreach ($foo as $path=>$cur) {
$ret[]=array('dir'=>dirname($path),'file'=>basename($path));
}
return $ret;
}
?>

Categories