服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - PHP教程 - php 获取文件后缀名,并判断是否合法的函数

php 获取文件后缀名,并判断是否合法的函数

2021-06-21 15:54PHP教程网 PHP教程

有时候我们后台需要设置用户只能上传指定后缀名的文件,那么就可以使用下面的代码了

核心代码

php" id="highlighter_863099">
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
 * 获取文件后缀名,并判断是否合法
 *
 * @param string $file_name
 * @param array $allow_type
 * @return blob
 */
function get_file_suffix($file_name, $allow_type = array())
{
  $file_suffix = strtolower(array_pop(explode('.', $file_name)));
  if (empty($allow_type))
  {
    return $file_suffix;
  }
  else
  {
    if (in_array($file_suffix, $allow_type))
    {
      return true;
    }
    else
    {
      return false;
    }
  }
}

上面的对于php5.3以上的版本会报错Strict Standards: Only variables should be passed by reference in。所以服务器之家小编换了如下方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
/**
 * 获取文件后缀名,并判断是否合法
 *
 * @param string $file_name
 * @param array $allow_type
 * @return blob
*/
function get_file_suffix($file_name, $allow_type = array())
{
  $fnarray=explode('.', $file_name);
    $file_suffix = strtolower(array_pop($fnarray));
  if (empty($allow_type))
  {
    return $file_suffix;
  }
  else
  {
    if (in_array($file_suffix, $allow_type))
    {
      return true;
    }
    else
    {
      return false;
    }
  }
}
 
$allow_wj="jpg,gif,png,jpeg";
$allow=explode(",",$allow_wj);
 
if (get_file_suffix("sakjdfk1.jpg",$allow)){
echo "ok";
}else{
echo "no";
}

如此就解决了,希望大家以后多多支持服务器之家。

延伸 · 阅读

精彩推荐