2012-10-28 122 views
-3

目前我已允许上传.jpg文件。上传验证,允许其他扩展?

如何添加jpeg,gif和png?

我当前的代码如下...

$filename = basename($_FILES['photo']['name']); 
      $ext = substr($filename, strrpos($filename, '.') + 1); 

      //Check if the file is JPEG image and it's size is less than 5Mb 
$allowedExts = array('jpg', 'jpeg', 'gif', 'png'); 
      if ((in_array($ext, $allowedExts)) && ($_FILES["photo"]["type"] == "image/jpeg") && ($_FILES["photo"]["size"] <= 5242880)){ 
       //Determine the path to which we want to save this file 
       $newname = str_replace(' ', '_', trim(strip_tags($_POST['name']))) . _ . $formKey->generateKey() . '_' . time() . '.jpg'; 
+5

当然,你可以有至少一个猜测,并有一个很好的机会,它是正确的。走了,我们会告诉你它是否正确。 – alex

+0

@alex:谢谢。已上传编辑 – Dave

+0

更新了进一步尝试的编辑。 – Dave

回答

1

请允许扩展的阵列,以及对证。看看http://php.net/manual/en/function.in-array.php

你会喜欢的东西结束:

$allowedExts = array('jpg', 'jpeg', 'gif'); // Add more here 
if (in_array($ext, $allowedExts)) 
{ 
    // Do something here 
} 

此外,要检查文件的扩展名,我建议你使用PATHINFO:http://php.net/manual/en/function.pathinfo.php 有些人可以上传文件以.jpg结尾欺骗你,但这可能是.php文件。

[编辑]更新,因为我最讨厌的小评论:

$allowedExtensions = array("image/jpeg", "image/png", "image/gif", "image/pjpeg", "image/jpg"); 
    $pathInfo = pathinfo($_FILES["photo"]["type"]); 
    if (in_array($pathInfo['extension'], $allowedExtensions)) 
    { 
     // Do stuff 
    } 

Waaaay简单的这种方式。这甚至可以通过使用pathinfo的第二个参数来简化,但我假设你需要数组中的其他元素。

+0

感谢 - 更新的问题,仍然无法正常工作。 – Dave

+0

忘记了这个'if((in_array($ ext,$ allowedExts))&&($ _FILES [“photo”] [“type”] ==“image/jpeg”)| |($ _FILES [“photo”] [“type”] ==“image/png”)||($ _FILES [“photo”] [“type”] ==“image/gif”)||($ _FILES [“photo”] [“type”] ==“image/pjpeg”)&&($ _FILES [“photo”] [“size”] <= 5242880))' – Dave

+0

你太过于复杂。我编辑了我的答案。 – Warpten