CODE让用户只上传图片

时间:2017-08-12 19:31:46

标签: php

我有upload.php文件,我希望用户只上传图片。 任何人都可以检查我的代码,并告知是否可以吗?

$file_ext = strrchr($_FILES['my_files']['name'], '.');   // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php
$copy = copy($_FILES['my_files']['tmp_name'], "$idir" . $_FILES['my_files']['name']);   // Move Image From Temporary Location To Permanent Location
if ($copy) {   // If The Script Was Able To Copy The Image To It's Permanent Location
  print 'Image uploaded successfully.<br />';   // Was Able To Successfully Upload Image
   $nomDestination = "Img_".date("YmdHis").".".$extensionFichier;

   if($extensionFichier == 'jpg'){$destination = imagecreatefromjpeg("$idir" . $url);}
   else if($extensionFichier == 'gif'){$destination = imagecreatefromgif("$idir" . $url);}
    else if($extensionFichier == 'png'){$destination = imagecreatefrompng("$idir" . $url);}
     else if($extensionFichier == 'jpeg'){$destination = imagecreatefromjpeg("$idir" . $url);}

3 个答案:

答案 0 :(得分:0)

如果它有效,那么它还可以,但总有更好的方法!

$allowed = ['png', 'jpg', 'gif', 'jpeg'];
$extension = pathinfo($_FILES['my_files']['name'], PATHINFO_EXTENSION);

if(!in_array(strtolower($extension), $allowed)){
    // fail
}
else {
    // success
}

答案 1 :(得分:0)

如果你想让用户只上传图像,你必须在复制功能之前进行验证。我曾经用move_uploaded_file()函数进行编码。而是使用if else,您可以使用数组。

       $errors= array();
       $file_name = $_FILES['my_files']['name'];
       $file_tmp =$_FILES['my_files']['tmp_name'];
       $file_nameArr = explode('.',$file_name);

       $file_ext=strtolower(end($file_nameArr));

       $expensions= array("jpeg","jpg","png");

       if(in_array($file_ext,$expensions)=== false){
          $errors[]="Invalid file type.";
       }

       if(empty($errors)==true){
            move_uploaded_file($file_tmp, $upload_path.$file_name);
       }

在上传之前,请考虑在客户端进行验证。

答案 2 :(得分:0)

我更喜欢验证文件是图像并以编程方式获取正确的文件扩展名,而不是信任将文件上传到我的服务器的人。您应该在将文件移动到可公开访问的目录之前执行此操作。

<?php
function getImageFileExtension($pathToImage)
{
    if(file_exists($pathToImage))
    {
        list($width, $height, $type) = getimagesize($pathToImage);

        $fileExtensions = array(
            IMAGETYPE_GIF => 'gif',
            IMAGETYPE_JPEG => 'jpg',
            IMAGETYPE_PNG => 'png',
            IMAGETYPE_WBMP => 'bmp',
            IMAGETYPE_XBM => 'xbm');

        if(!array_key_exists($type, $fileExtensions))
        {
            throw new Exception('File '.$pathToImage.' is not an image.');
        }

        return $fileExtensions[$type];
    }
    else
    {
        throw new Exception('Image file '.$pathToImage.' not found.');
    }
}

try
{
    $allowed = ['gif', 'jpg', 'png'];
    $ext = getImageFileExtension($imgPath);

    if(!in_array($ext, $allowed))
    {
        throw new Exception('Invalid image file');
    }

    print $ext."\n";
}
catch(Exception $e)
{
    print $e->getMessage()."\n";
}