使用php / codeigniter删除文件

问题描述 投票:11回答:9

我想删除在我的localhost中找到的文件。

localhost/project/folder/file_to_delete

我正在使用codeigniter。

我想在php中使用unlink()函数,但我真的无法理解如何使用它。

php codeigniter delete-file unlink
9个回答
31
投票

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

http://codeigniter.com/user_guide/helpers/file_helper.html

和这样:

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

延迟编辑:delete_filesmethod使用路径通过unlink()消除其所有内容,您可以在CI中执行相同操作。像这样:

unlink($path); 

一条有效的道路。


8
投票

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

6
投票

删除文件使用

unlink($file_name);

或删除目录使用

rmdir($dir);

4
投票

试试这个,这对我有用:

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

例如:我把我的文件放在应用程序文件夹之外的uploads文件夹中,我的文件名是123.jpg。所以它应该是这样的:

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

2
投票
$file = "test.txt";
if (!unlink($file))
  {
  echo ("Error deleting $file");
  }
else
  {
  echo ("Deleted $file");
  }

0
投票

此代码还可以处理非空文件夹 - 只需在帮助程序中使用它。

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

0
投票

2018年9月,这个解决方案对我有用。

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

0
投票

在unlink中使用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'];
}

0
投票

可以使用:

$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";
}
© www.soinside.com 2019 - 2024. All rights reserved.