簡體   English   中英

使用 php/codeigniter 刪除文件

[英]Deleting a File using php/codeigniter

我想刪除在我的本地主機中找到的文件。

localhost/project/folder/file_to_delete

我為此使用了 codeigniter。

我想在 php 中使用 unlink() 函數,但我真的不明白如何使用它。

您可以在 codeigniter 中使用“文件助手”。

CodeIgniter v3: http : //codeigniter.com/userguide3/helpers/file_helper.html#delete_files

CodeIgniter v4: http : //codeigniter.com/user_guide/helpers/filesystem_helper.html#delete_files

像這樣:

$this->load->helper("file");
delete_files($path);

后期編輯: delete_files方法使用路徑通過unlink()清除其所有內容,您可以在 CI 中執行相同操作。 像這樣:

unlink($path); 

一個有效的路徑。

http://php.net/manual/en/function.unlink.php

這是最好的理解方式。 閱讀!

$path_to_file = '/project/folder/file_to_delete';
if(unlink($path_to_file)) {
     echo 'deleted successfully';
}
else {
     echo 'errors occured;
}

刪除文件使用

unlink($file_name);

或刪除目錄使用

rmdir($dir);

試試這個,這對我有用:

unlink("./path/to/folder/file_name_do_delete");

例如:我將我的文件放在應用程序文件夾之外的上傳文件夾中,我的文件名為 123.jpg。 所以它應該是這樣的:

unlink("./uploads/123.jpg");

在取消鏈接中使用FCPATH 你可以嘗試如下這對我有用:

$file_name = $SBLN_ROLL_NO."_ssc";
$file_ext = pathinfo($_FILES['ASSIGNMENT_FILE']['name'],PATHINFO_EXTENSION);

//File upload configuration
$config['upload_path'] = $upload_path;
$config['allowed_types'] = 'jpg|jpeg|png|gif|pdf';
$config['file_name'] = $file_name.'.'.$file_ext;

//First save the previous path for unlink before update
$temp = $this->utilities->findByAttribute('SKILL_DEV_ELEMENT', array('APPLICANT_ID'=>$STUDENT_PERSONAL_INFO->APPLICANT_ID, 'SD_ID'=>$SD_ID));

//Now Unlink
if(file_exists($upload_path.'/'.$temp->ELEMENT_URL))
{
    unlink(FCPATH . $upload_path.'/'.$temp->ELEMENT_URL);
}

//Then upload a new file
if($this->upload->do_upload('file'))
{
    // Uploaded file data
    $fileData = $this->upload->data();
    $file_name = $fileData['file_name'];
}

簡單地可以使用:

$file = "uploads/my_test_file.txt";

if (is_readable($file) && unlink($file)) {
    echo "The file has been deleted";
} else {
    echo "The file was not found";
}
$file = "test.txt";
if (!unlink($file))
  {
  echo ("Error deleting $file");
  }
else
  {
  echo ("Deleted $file");
  }

2018 年 9 月,此解決方案對我有用。

if(unlink(FCPATH . 'uploads/'.$filename)){
    echo "Deleted";
}else{
    echo "Found some error";
}

此代碼還可以處理非空文件夾 - 只需在幫助程序中使用它。

if (!function_exists('deleteDirectory')) {
    function deleteDirectory($dir) {
    if (!file_exists($dir)) return true;
    if (!is_dir($dir) || is_link($dir)) return unlink($dir);
        foreach (scandir($dir) as $item) {
            if ($item == '.' || $item == '..') continue;
            if (!deleteDirectory($dir . "/" . $item)) {
                chmod($dir . "/" . $item, 0777);
                if (!deleteDirectory($dir . "/" . $item)) return false;
            };
        }
        return rmdir($dir);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM