2014-05-23 32 views
-1

我有一個圖像上傳到服務器與客戶的ID。但我不想兩次上傳多個格式的文件(例如,應該只有一個圖像,客戶id = 1,即1.jpg或1.png)檢查文件存在與正則表達式在php

如何在更新圖像時全局檢查文件已經存在或沒有?

我可以檢查文件存在沒有擴展名的文件?

我正在使用此命令來檢查文件。

file_exists('./media/customer-id/'.$cus_id); 
+1

檢查[重複答案](http://stackoverflow.com/questions/3303691/php-check-file-exists-without-knowing-the-擴展#回答3303718)從我發佈的鏈接。你需要使用'glob()'。 [評論](http://stackoverflow.com/questions/3303691/php-check-file-exists-without-knowing-the-extension#comment-3422841)_ @ Gumbo_完全回答你的問題。確保您搜索該網站以避免發佈重複問題。 – War10ck

回答

0

使用scandir()運行ls像命令和接收的目錄中的內容的陣列。然後遍歷文件並查看是否有任何內容與客戶ID匹配。

$exists = false; 
foreach(scandir('./media/customer-id') as $file) { 
    if(preg_match('/^' . $customer_id . '\.$/', $file)) { 
     $exists = true; 
     break; 
    } 
} 
1

您可以使用glob()來計算結果。

function patternExists($pattern) { 
    return count(glob($pattern)) > 0; 
} 

和使用這樣

if (patternExists("./media/customer-id/".$cus_id."*")) { 
    // bad! 
} 
+2

請注意'glob()'有點像一個準正則表達式。 '?'匹配除'/'和*之外的任何字符的1,匹配除了'/'以外的任何字符的0或更多。不過,對於簡單的解決方案來說,+1。 – Sam

+1

@Sam thx,我將它改名爲使用PHP的公式 – kero

+0

@kingkero:如何在瀏覽器中看到該圖像而不知道它的擴展名。 – user3609998