CodeIgniter - Delete file, pathing issue

2019-04-13 12:58发布

问题:

I have 3 folders in my root, "application", "system", and "uploads". In application/controllers/mycontroller.php I have this line of code.

delete_files("../../uploads/$file_name");

The file does not get deleted and I have tried a number of pathing options like ../ and ../../../ any ideas? Thanks.

回答1:

$file_name is a variable. You should concatenate it to your own string in order to execute the function:

delete_files("../../uploads/" . $file_name);

EDIT:

Make sure that this sentence:

echo base_url("uploads/" . $file_name);

Is echoing a valid path. If the answer is YES, try this:

$this->load->helper("url");
delete_files(base_url("uploads/" . $file_name));

Supposing that your "uploads" folder is in your root directory.

EDIT 2:

Using unlink function:

$this->load->helper("url");
unlink(base_url("uploads/" . $file_name));


回答2:

Use the FCPATH constant provided to you by CodeIgniter for this.

unlink(FCPATH . '/uploads/' . $filename);

base_url() generates HTTP urls, and cannot be used to generate filesystem paths. This is why you must use one of the CI path constants. They are defined in the front controller file (index.php).

The three ones you would use are:

  • FCPATH - path to front controller, usually index.php
  • APPPATH - path to application folder
  • BASEPATH - path to system folder.


回答3:

Try this one.. this just a very simple solution to your problem.. If you notice CI has there on defining of base_path to your directory e.g. in the upload library's config:

$imagePath = './picture/Temporary Profile Picture/';

$config['upload_path'] = $imagePath;

$config['allowed_types'] = 'gif|jpg|jpeg|png';

$this->load->library('upload', $config);

if you notice the upload_path is './picture/Temporary Profile Picture/'

so if you want to delete a file from a directory all you have to do is use unlink() function.

unlink($imagePath . $file_name);

or

@unlink($imagePath . $file_name);

Enjoy..^^



回答4:

This code was working for me. Try this in your Model or Controller. Change the file path according to yours.

file path -->> project_name/assets/uploads/file_name.jpg

public function delete_file()
{
    $file = 'file_name.jpg';
    $path = './assets/uploads/'.$file;
    unlink($path);
}


回答5:

You should try this code:

$imagepath = $config['upload_path'];
unlink($imagepath . $images);

or

delete_files($imagepath . $images);


标签: codeigniter