我想删除在本地主机中找到的一个文件。
localhost/project/folder/file_to_delete
我正在使用代码点火器。
我想在php中使用unlink()函数,但我真的不明白如何使用它。
您可以使用;文件帮助程序";在代码点火器中。
CodeIgniter v3:http://codeigniter.com/userguide3/helpers/file_helper.html#delete_files
CodeIgniter v4:http://codeigniter.com/user_guide/helpers/filesystem_helper.html#delete_files
像这样:
$this->load->helper("file");
delete_files($path);
后期编辑:delete_files
方法使用一条路径通过unlink()
擦除其所有内容,您可以在CI中执行此操作
unlink($path);
有效路径。
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';
}
使用删除文件
unlink($file_name);
或使用删除目录
rmdir($dir);
试试这个,这对我有用:
unlink("./path/to/folder/file_name_do_delete");
例如:我把我的文件放在应用程序文件夹外的上传文件夹中,我的文件名是123.jpg。所以它应该是这样的:
unlink("./uploads/123.jpg");
在取消链接中使用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'];
}
$file = "test.txt";
if (!unlink($file))
{
echo ("Error deleting $file");
}
else
{
echo ("Deleted $file");
}
只需使用:
$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";
}
此代码还可以处理非空文件夹-只需在助手中使用即可。
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);
}
}
2018年9月此解决方案对我有效。
if(unlink(FCPATH . 'uploads/'.$filename)){
echo "Deleted";
}else{
echo "Found some error";
}