如何从PHP中的文件名中删除意外的点

时间:2019-03-08 06:51:17

标签: php

我有用于上传图像的代码,在存储图像之前,图像名称是随机生成的,图像也被压缩。但是有一个小问题,当我上传具有点(。)的图像(如a.k.kumar.jpg)时,该图像没有上传并根据代码显示错误,即文件类型无效。我也只想上传一个名称为a.k.kumar.jpg的图片。

这是我的php代码:

  $banner = "SELECT * FROM inventory_details where firm_email='$firm_email'";
  $resultp5 = mysqli_query($conn, $banner);
  mysqli_num_rows($resultp5) > 0;
  $rowp5 = mysqli_fetch_assoc($resultp5);

  if(!empty($_FILES['banner'] ['name'])){ 
        $extension = explode('.', $_FILES['banner'] ['name']);
        $banner = rand(10000,99999) . '.' . $extension[1];
        $valid_ext = array('png','jpeg','jpg');
        $location = "image/banner/".$banner;
        $file_extension = pathinfo($location, PATHINFO_EXTENSION);

        if(in_array($file_extension,$valid_ext)){  
            compressImage($_FILES['banner']['tmp_name'],$location,60);
        }else{
            echo "Invalid file type.";
        }
  } 
  else{
    $banner=$rowp5['banner'];
  }

我也尝试过这样做,但没有帮助:

 $banner = "SELECT * FROM inventory_details where firm_email='$firm_email'";
  $resultp5 = mysqli_query($conn, $banner);
  mysqli_num_rows($resultp5) > 0;
  $rowp5 = mysqli_fetch_assoc($resultp5);

  if(!empty($_FILES['banner'] ['name'])){ 
        $extension = explode('.', $_FILES['banner'] ['name']);
        $banner = rand(10000,99999) . '.' . $extension[1];
        $valid_ext = array('png','jpeg','jpg');


        $lastDot = strrpos($valid_ext, ".");
        $valid_ext = str_replace(".", "", substr($valid_ext, 0, $lastDot)) . substr($valid_ext, $lastDot);


        $location = "image/banner/".$banner;
        $file_extension = pathinfo($location, PATHINFO_EXTENSION);

        if(in_array($file_extension,$valid_ext)){  
            compressImage($_FILES['banner']['tmp_name'],$location,60);
        }else{
            echo "Invalid file type.";
        }
  } 
  else{
    $banner=$rowp5['banner'];
  }

谢谢。

1 个答案:

答案 0 :(得分:4)

您可以依靠pathinfo来代替explode来确定extension,例如

  $extension = pathinfo($_FILES['banner'] ['name'], PATHINFO_EXTENSION);

<?php
    if(!empty($_FILES['banner'] ['name'])) {
        $extension = pathinfo($_FILES['banner'] ['name'], PATHINFO_EXTENSION);
        $banner = rand(10000,99999) . '.' . $extension;
        $location = "image/banner/".$banner;

        if(in_array(strtolower($extension), [ 'png', 'jpeg', 'jpg', ])){
            compressImage($_FILES['banner']['tmp_name'],$location,60);
        }else{
            echo "Invalid file type.";
        }
    }