Delete files with Codeigniter

Asked

Viewed 2,430 times

1

I want to delete a BD record that contains an image. When you do this, also delete that image from the folder where it is. How to proceed to make such action?

  • Your question talks about one thing, but your code mirrors another. Specifically, what do you want to do is delete a file when you delete a comic book entry or delete the "recipes" directory? With your code you have now entered in the question, you are deleting the folder and not a file within it. Regarding the error you get, it is a lack of permissions in the folder to delete it, probably the user who created it is not trying to delete it.

  • Sorry for my mistakes. I edited the question, I think I could clarify more, otherwise, sorry again!

2 answers

4

The helper of files from Codeigniter allows you to delete files in a given path:

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

If you want to delete only one file, you will be better served using the function unlink() of PHP:

$caminhoParaFicheiro = '/caminho/para/ficheiro/bubu.jpg';

if (unlink($caminhoParaFicheiro)) {
     echo 'Bubu morreu';
}
else {
     echo 'Não foi possível matar o BuBu';
}

How can you call the unlink function of PHP:

  • You understand its logic. But the image deletion is done through a record list, where I will have the button to perform such action. How could I proceed?

  • 2

    +1 for the use of Bubu ahahah

1

To delete only one file:

<?php

$file = '/dir/src/arquivo.png';

if(unlink($file)){

echo 'Excluido com sucesso';

}else{

echo 'Erro ao excluir';

}

?>

To delete multiple files:

<?php

$dir = '/dir/src/'; //Irá excluir todos do diretório src

$open = opendir($dir);

while($read = readdir($open)){

if($read != '.' && $read != '..'){

$e = @unlink($dir.$read);

if($e){
echo 'Arquivo {$read} excluido com sucesso <br>';
}else{
echo 'Erro ao excluir o arquivo {$read} <br>';
}

}

}

?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.