2013-02-22 49 views
1

我試圖從服務器上刪除一個文件。取消鏈接()不起作用

我的應用程序的文件位於文件夾名「/ public_html/app /」;

所有與應用程序位於以下路徑相關的圖片:「/的public_html /應用/圖像/ tryimg /」

的文件,在其中我寫了下面的代碼規範是「/的public_html /應用程序/」。

這是我的一小段代碼片段:

<?php 

$m_img = "try.jpg" 

$m_img_path = "images/tryimg".$m_img; 

if (file_exists($m_img_path)) 
{ 
    unlink($m_img_path); 
} 
// See if it exists again to be sure it was removed 
if (file_exists($m_img)) 
{ 
      echo "Problem deleting " . $m_img_path; 
} 
else 
{ 
     echo "Successfully deleted " . $m_img_path; 
} 
?> 

當上述腳本執行消息時,顯示「已成功刪除try.jpg」。

但是,當我導航到該文件夾​​時,文件不會被刪除。

的Apache:2.2.17 PHP版本:5.3.5

我在做什麼錯?

我必須給出圖像的相對或絕對路徑嗎?

+0

您使用'$ m_img_path'調用'unlink()',而使用'$ m_img'調用'file_exists()'。 – kolen 2013-02-22 10:03:30

+1

除了走錯了路,你應該考慮調用'clearstatcache()函數',以避免第二個'file_exist()'的錯誤的結果。 – Federkun 2013-02-22 10:14:04

回答

1

你缺少一個目錄分隔符:

$m_img = "try.jpg" 

$m_img_path = "images/tryimg".$m_img; 

// You end up with this.. 
$m_img_path == 'images/tryimgtry.jpg'; 

您需要添加一個斜槓:

$m_img_path = "images/tryimg". DIRECTORY_SEPARATOR . $m_img; 

您還需要爲您所使用的圖像名稱更改第二file_exists調用而不是路徑:

if (file_exists($m_img_path)) 
+0

嗨安德魯,感謝您的幫助。我用image_path更改了第二個file_exists。但它仍然無法正常工作 – mkb 2013-02-22 10:45:12

+0

嗨安德魯,路徑錯了它的代碼...感謝您的幫助,非常感謝它 – mkb 2013-02-22 10:53:32

1

你檢查錯誤的路徑:

if (file_exists($m_img)) 

,而你(嘗試)刪除(d)$m_img_path,所以用

if (file_exists($m_img_path)) 

unlink()更換您的支票返回一個布爾值,指示是否刪除成功與否,因此使用此值更容易/更好:

if (file_exists($m_img_path)) 
{ 
    if(unlink($m_img_path)) 
    { 
     echo "Successfully deleted " . $m_img_path; 
    } 
    else 
    { 
     echo "Problem deleting " . $m_img_path; 
    } 
} 

此外,當前目錄位於腳本執行的位置,因此在使用相對路徑時需要記住這一點。在大多數情況下,儘可能使用絕對路徑可能更好/更容易。

如果你需要的路徑很多您的服務器上的文件,你可能想要把絕對路徑中的變量和使用,所以很容易改變,如果你的服務器的配置更改的絕對位置。

+0

+1檢查取消鏈接返回值 – Federkun 2013-02-22 10:21:52

+0

嗨Veger,感謝您的幫助。當我使用您提供的代碼時,不會顯示任何消息。我搞不清楚了.... – mkb 2013-02-22 10:43:15

+0

這是因爲'$ m_img_path'指定的文件可能不存在(或者因爲您的相對/絕對路徑不正確而無法找到)。嘗試回顯此變量的值並手動檢查它是否不正確,[安德魯指出,您已經缺少目錄分隔符](http://stackoverflow.com/questions/15021390/unlink-not-working/15021696#15021696 ),所以至少添加一個! – Veger 2013-02-22 10:47:20