سؤال
يمكنني إنشاء مجلد صورة عند إنشاء فئة ، حتى أتمكن من تحميل الصور هناك.
الآن أريد حذف هذا المجلد عندما أحذف الفئة.
رمز لإنشاء مجلد هو ما يلي ويعمل بشكل جيد.
function create(){
if ($this->input->post('name')){
$this->MCats->addCategory();
$folder = $this->input->post('name');
$folder = strtolower($folder);
$folder = str_replace(" ", "_", $folder);
$folder = 'images/'.$folder;
$this->_create_path($folder);
...
...
}
function _create_path($folder)
{
// create dir if not exists
$folder = explode( "/" , $folder );
$mkfolder = "";
//sets the complete directory path
for( $i=0 ; isset( $folder[$i] ) ; $i++ )
{
$mkfolder .= $folder[$i] . '/';
if(!is_dir($mkfolder )) mkdir("$mkfolder");
}
}
وتوصلت إلى الرمز التالي. لكنني لست متأكدًا من كيفية استخدام RMDIR حتى لا يزيل مجلد الصور. أريد إزالة المجلد فقط للطفل من الصور.
function delete($id){
$cat = $this->MCats->getCategory($id);
// This will pull the name of category name.
$catname = $cat['name'];
$catname = strtolower($catname);
$catname = str_replace(" ", "_", $catname);
$catname = 'images/'.$catname;
$this->_remove_path($catname);
...
...
}
function _remove_path($folder)
{
}
لست متأكدًا من كيفية المتابعة بعد هذا.
هل يمكن لأي شخص أن يعطيني بعض الاقتراحات من فضلك؟
المحلول
$this->_remove_path($catname); // because previous parts you're using $catname
ثم وظيفة إزالة المسار
// recursively remove all files and sub-folder in that particular folder
function _remove_path($folder){
$files = glob( $folder . DIRECTORY_SEPARATOR . '*');
foreach( $files as $file ){
if($file == '.' || $file == '..'){continue;}
if(is_dir($file)){
$this->_remove_path( $file );
}else{
unlink( $file );
}
}
rmdir( $folder );
}
نصائح أخرى
ستحتاج إلى استخدام غير محدود و RMDIR:
$handler = opendir($folder);
if (!$handler) {
trigger_error('File Error: Failed to open the directory ' . $folder, E_USER_ERROR);
return false;
}
// list the files in the directory
while ($file = readdir($handler)) {
// if $file isn't this directory or its parent,
if ($file != '.' && $file != '..' && !is_dir($file)) {
// delete it
if (!unlink($file)) {
trigger_error('File Error: Failed to remove file ' . $file, E_USER_ERROR);
}
}
}
// tidy up: close the handler
closedir($handler);
if (!rmdir($folder)) {
trigger_error('File Error: Failed to remove folder ' . $folder, E_USER_ERROR);
}
نسختي المعدلة من داريل هاين'س شفرة يعمل مثل سحر لي.
function remove_path2($path) {
if(is_dir($path)) {
$handler = opendir($path);
if (!$handler) {
trigger_error('File Error: Failed to open the directory ' . $path, E_USER_ERROR);
return;
}
// list the files in the directory
while ($file = readdir($handler)) {
if ($file != '.' && $file != '..')
remove_path2($path.DIRECTORY_SEPARATOR.$file);
}
// tidy up: close the handler
closedir($handler);
if (!rmdir($path)) {
trigger_error('File Error: Failed to remove folder ' . $path, E_USER_ERROR);
}
}
else {
// delete it
if (!unlink($path)) {
trigger_error('File Error: Failed to remove file ' . $path, E_USER_ERROR);
}
}
}
لا تنتمي إلى StackOverflow