Deleting a File using php/codeigniter

前端 未结 9 1941
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-04 07:47

I would like to delete a file that is found in my localhost.

localhost/project/folder/file_to_delete

I\'m using codeigniter for this.

相关标签:
9条回答
  • 2021-01-04 08:10

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

    It is the best way to understand. Read it!

    $path_to_file = '/project/folder/file_to_delete';
    if(unlink($path_to_file)) {
         echo 'deleted successfully';
    }
    else {
         echo 'errors occured;
    }
    
    0 讨论(0)
  • 2021-01-04 08:12

    September 2018 this solution worked for me.

    if(unlink(FCPATH . 'uploads/'.$filename)){
        echo "Deleted";
    }else{
        echo "Found some error";
    }
    
    0 讨论(0)
  • 2021-01-04 08:14

    simply can use:

    $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";
    }
    
    0 讨论(0)
  • 2021-01-04 08:14

    Use FCPATH in unlink. You can try as follows this works for me:

    $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 讨论(0)
  • 2021-01-04 08:19

    to delete file use

    unlink($file_name);
    

    or to delete directory use

    rmdir($dir);
    
    0 讨论(0)
  • 2021-01-04 08:22

    This code can also handle non-empty folders - just use it in a helper.

    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 讨论(0)
提交回复
热议问题