ฟังก์ชั่นลบไฟล์อย่างง่าย
<?php
unlink("images/test.jpg"); // ฟังก์ชั่นลบไฟล์ที่มี พาธ images/test.jpg
?>ฟังก์ชั่นลบไฟล์แบบประยุกต์ สามารถลบไฟล์และโฟลเดอร์ได้
<?php
function fulldelete($location) {
if (is_dir($location)) {
$currdir = opendir($location);
while ($file = readdir($currdir)) {
if ($file <> ".." && $file <> ".") {
$fullfile = $location."/".$file;
if (is_dir($fullfile)) {
if (!fulldelete($fullfile)) {
return false;
}
} else {
if (!unlink($fullfile)) {
return false;
}
}
}
}
closedir($currdir);
if (! rmdir($location)) {
return false;
}
} else {
if (!unlink($location)) {
return false;
}
}
return true;
}
?>การใช้งาน
<?php
fulldelete($location); // กำหนด $location เป็นตำแหน่งไฟล์หรือโฟลเดอร์
?><?php
$dir = "files";
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
unlink($dir."/".$file);
}
closedir($dh);
}
}
?>
ลบทุกไฟล์เลยทั้งในโฟเดอร์และนอกโฟล์เดอร์และยังลบไฟล์ตัวเองด้วย
<html>
<body>
<?
$mainpath = dirname(__FILE__)."/";
function getdir($path) {
$flist = opendir($path);
$list = array();
while (false !== ($mfile = readdir($flist))) {
$list = array_merge((array)$list, (array)$mfile);
}
sort($list);
array_splice($list, 0, 2);
return $list;
}
function checkdir($path) {
$list = getdir($path);
foreach($list as $var) {
if(is_dir($path.$var)) {
//áÊ´§ÇèÒà»Ô´â¿Åà´ÍÃìä˹
echo "<br/><b>Dir :</b> ".$path.$var."/<br/>";
//µÃ§¹ÕéÁѹÍÐäùéÍ ÍÔæ
checkdir($path.$var."/");
} else {
//áÊ´§ª×èÍä¿Åì
unlink($path.$var);
}
}
}
checkdir($mainpath."");
?>
<html>ถ้าต้องการลบบางโฟลเดอร์
<?php
$files = (array) glob('lest1/*');
foreach ($files as $file)
{
if (is_file($file))
{
// บางไฟล์ติด permission ก็ลบไม่ได้นะคับ
@unlink($file);
}
}
?>code นี้ใช้ได้ครับ แต่ต้องกำหนด folder ที่จะลบให้ถูกต้องเท่านั้นเองครับ
อย่างเช่น ใน Folder ที่เราเขียนประกอบไปด้วย
1. File del_file.php
2. folder file ที่จะลบชื่อว่า images
กำหนด path ที่จะลบ folder ให้ถูกต้องก็สามารถใช้งานได้
ตัวอย่าง
$mainpath = "images/"; หรือ $mainpath = "./images/";
ลบทั้งไฟล์และโฟลเด้อ ซับโฟล์เด้อ (ลบทุกอย่างในโฟล์เดอ)
<?php
$mydir = 'xxxx/';
if ($handle = opendir($mydir)) {
umask(0777);
chmod($mydir,0777);
while (false !== ($file = readdir($handle))) {
chmod($file,0777);
if (is_file($file)) {
if (unlink($file)) { echo $file . ' deleted<br />'; }
else { echo $file . ' NOT deleted!<br />'; }
}
else if (is_dir($file)) {
echo $file . ' is directory, not deleted.<br />';
}
}
rmdir($mydir);
closedir($handle);
}
?>