2013-07-19 116 views
0

我在函數中使用preg_match來阻止提交圖像擴展! 現在我想阻止「」字符也! 任何人都可以告訴我我該怎麼做?爲什麼這種模式在preg_match中不起作用

function is_valid($url) { 
    $res = 1; 
    if (isset($url['path'])) { 
     if (preg_match('/\b.jpg\b/i', $url['path'])) { $res = 0; } 
     if (preg_match('/\b.gif\b/i', $url['path'])) { $res = 0; } 
     if (preg_match('/\b.png\b/i', $url['path'])) { $res = 0; } 
     if (preg_match('/\b.bmp\b/i', $url['path'])) { $res = 0; } 
    } 
    return $res; 
} 

我嘗試這樣做,但它不工作:

if (strpos('~', $url['path'])) { 
    $res = 0; 
} 

回答

0

首先,你應該讀一些有關正則表達式!如果你已經這樣做了,請閱讀manual,以獲得更多信息strpos

您可以嘗試preg_match('/[^~]+\.(png|jpg|gif|bmp)/i', $url['path'])或者,如果你要堅持你的版本,

if (strpos($url['path'], '~') !== FALSE) { 
    $res = 0; 
} 

但無論如何,你的支票將只是不很安全。例如:有人將一個php文件重命名爲png並上傳,如果你的apache上有mime_magic被激活,代碼將被執行。因此檢查文件的mimetype會更安全。以How do I find the mime-type of a file with php?爲例。那裏接受的答案提到一個(現在)不推薦使用的函數,但是如果你有PHP 5.3+,你可以使用http://de3.php.net/manual/en/function.finfo-file.php

+0

哇!你的代碼有效:) 謝謝你花時間回答這個愚蠢的問題。我非常感謝幫助。 我只是一個新手,並試圖學習編碼!我一定會按照你的指示! 再次感謝你:) @Michael –

相關問題