使用php/codeigniter删除文件

3bygqnnd  于 2022-12-07  发布在  PHP
关注(0)|答案(9)|浏览(120)

我想删除在本地主机中找到的文件。

localhost/project/folder/file_to_delete

我用的是 codeigniter 。
我想在php中使用unlink()函数,但我真的不知道如何使用它。

uelo1irk

uelo1irk1#

您可以使用codeigniter中的“文件助手”。
代码触发器v3:http://codeigniter.com/userguide3/helpers/file_helper.html#delete_files
代码触发器v4:http://codeigniter.com/user_guide/helpers/filesystem_helper.html#delete_files
就像这样:

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

Late Edit:delete_files方法使用一个路径通过unlink()清除其所有内容,在CI中也可以这样做。

unlink($path);

有效路径。

l2osamch

l2osamch2#

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

dm7nw8vv3#

删除文件使用

unlink($file_name);

或删除目录使用

rmdir($dir);
cbeh67ev

cbeh67ev4#

试试这个,这个对我很有效:

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

例如:我把我的文件上传文件夹内,这是应用程序文件夹外,我的文件名是123.jpg。所以它应该是这样的:

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

9bfwbjaz5#

在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'];
}
xeufq47z

xeufq47z6#

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

kxxlusnw7#

只需用途:

$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";
}
643ylb08

643ylb088#

这段代码也可以处理非空文件夹--只需在帮助器中使用它。

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

bkkx9g8r9#

2018年9月这个解决方案对我很有效。

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

相关问题