簡體   English   中英

無法取消鏈接PHP中的文件

[英]unable to unlink file in php

在一個網站上,我正在嘗試實現一個實用程序,該實用程序使用帶有復選框選擇的HTML表單和實際上應刪除所選圖像的php文件從某個文件夾中刪除所選圖像。 表單有效,並且復選框的值被解析為$_POST['images'] ,PHP代碼完成其余工作:

$dir=__ROOT__."/images/".$_POST['page'];
echo "dir=".$dir."<br>";
$files=array();
$fdir=opendir($dir);
while ($i = readdir($fdir)) {
    //detect images and put them into files()
    if (strpos(strtolower($i),".jpg")==true&&strpos(strtolower($i),".thumb")==false) $files[]=$i;
}
closedir($fdir);
for($a=0;$a<sizeof($files);$a++) {
    if(in_array($files[$a],$_POST['images'])) {
        $file="../images/".$_POST['page']."/".$files[$a];
        echo $file."<br>";
        echo('<img src="'.$file.'.thumb"><br>');
        if(unlink("../images/".$_POST['page']."/".$files[$a])) {
            echo ("deleted: ".$files[$a]."<br>");} 
            else {echo ("deletion of ".$files[$a]." failed<br>");}
        if(unlink("../images/".$_POST['page']."/".$files[$a].".thumb")) echo "deleted: ".$files[$a].".thumb";
    }
}

當嘗試刪除例如IMG_001.jpg(和縮略圖IMG_001.jpg.thumb)時,我得到以下回顯輸出:

dir={absolute path of the file}
../images/keramiek/IMG_001.jpg
{the correct thumbnail}
deletion of IMG_001.jpg fialed

怎么了 為什么不unlink()刪除文件? 我嘗試在777上設置權限,但仍然沒有成功...

解:

更改包含圖像的文件夾的權限后,刪除將按預期進行。 所有者已更改為www-data,並且權限設置為755。

新上傳的圖像(通過FTP)也可以刪除。

解決方案是像這樣設置正確的權限:

sudo chown your_user:www-data images/
sudo find images/ -type d -exec chmod 770 {} +
sudo find images/ -type f -exec chmod 660 {} +

編輯(通過OP):可以,但是請改用775和665,否則將無法訪問該文件夾

調用此新腳本:write.php,設置變量$ filename(將wud.png重命名為真實文件)並將其放置在需要刪除文件的目錄中!

error_reporting(E_ALL);
//$filename: enter the real file name
$filename = 'wud.png';
//$copy: any name is possible
$copy = 'mycopy.png';

if (copy($filename, $copy)){
  echo '<br><b>copy</b> '.$filename.' to '.$copy.' <b>success</b>';
}
else{
  echo '<br><b>copy</b> '.$filename.' to '.$copy.' <b>failed</b>';
}

if (is_writable($filename)) {
  echo '<br>The file '.$filename.' is detected and <b>writable</b>';
} 
else {
  echo '<br>The file '.$filename.' is <b>not writable</b> or not detected';
}


if (unlink($filename)){
  echo '<br>The file '.$filename.' is <b>deleted</b>';
}
else{
  echo '<br>The file '.$filename.' is <b>not deleted</b>';
}

if (copy($copy,$filename)){
  echo '<br><b>copy</b> '.$copy.' back to '.$filename.' <b>success</b>';
}
else{
  echo '<br><b>copy</b> '.$copy.' back to '.$filename.' <b>failed</b>';
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM