drll85318 2018-12-04 22:23 采纳率: 100%
浏览 86

这个保证上传的文件是否有图像后缀

I am in the process of writing an image upload script. I am adding lots of things e.g. store outside webroot and access through php script etc. One thing I have read to check is that a file is uploaded instead of an image. E.g. stop myimage.php.jpeg

I have written the following code to check it is an image file. Is this the best way to check this file has an image name?

$imagename= $_FILES['myimage']['name'];

//check there is only one fullstop in the imagename
 if (substr_count($imagename,".")===1){
    $imagesuffix = substr($imagename, strpos($imagename, ".") + 1); 

    //if image type is not a particular type of image
      if($imagesuffix != "jpg"|| $imagesuffix != "png"||$imagesuffix != "jpeg"||$imagesuffix != "gif"){
       echo"image filename is valid";
     }
     else{
       echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
     }
 }
 else{
    echo"this filename is invalid";
 }
  • 写回答

1条回答 默认 最新

  • doushi9856 2018-12-04 22:42
    关注

    If your concern is to only allow uploads of files that are images, then you'll have to look at the file contents.

        <?php
    
        $image = 'image_file_to_test.png';
    
        if (($imageInfo = getimagesize($image, $jpegInfo)) === FALSE)
                die('Not an image.');
    // OR    
    
        if (($imageType = exif_imagetype($image)) === FALSE)
                die('Not an image');
    

    If so desired, you can inspect either $imageInfo (docs) or $imageType (docs) to determine the image format. Please note that exif_imagetype() is the faster of the two, but it won't tell you as much as getimagesize().

    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示