php 如何判断是否上传了文件、图片

假设前端有字段

复制代码
<input type="file" name="user_avatar_image"/>

php使用$_FILES进行判断

  1. 当没有文件上传时,打印$_FILES

    ^ array:1 [▼
    "user_profile_image" => array:5 [▼
    "name" => ""
    "type" => ""
    "tmp_name" => ""
    "error" => 4
    "size" => 0
    ]
    ]

  2. 当有文件上传是,打印$_FILES

    ^ array:1 [▼
    "user_profile_image" => array:5 [▼
    "name" => "软件开发原则.pptx"
    "type" => "application/vnd.openxmlformats-officedocument.presentationml.presentation"
    "tmp_name" => "/Applications/MAMP/tmp/php/phpPHWyCh"
    "error" => 0
    "size" => 3031121
    ]
    ]

  3. 假如前端没有传user_avatar_image的字段,打印$_FILES

    []

因此,可以使用error字段判断是否上传了指定的文件

复制代码
// 获取表单上传文件 字段名为user_profile_image
$field_name = 'user_profile_image';
        
if(!(array_key_exists($field_name, $_FILES) && $_FILES[$field_name]['error'] == 0)){
    $this->error('参数不足');
}
相关推荐
ServBay1 天前
告别面条代码,PSL 5.0 重构 PHP 性能与安全天花板
后端·php
JaguarJack3 天前
FrankenPHP 原生支持 Windows 了
后端·php·服务端
BingoGo3 天前
FrankenPHP 原生支持 Windows 了
后端·php
JaguarJack4 天前
PHP 的异步编程 该怎么选择
后端·php·服务端
BingoGo4 天前
PHP 的异步编程 该怎么选择
后端·php
JaguarJack5 天前
为什么 PHP 闭包要加 static?
后端·php·服务端
ServBay6 天前
垃圾堆里编码?真的不要怪 PHP 不行
后端·php
用户962377954486 天前
CTF 伪协议
php
BingoGo8 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php
JaguarJack8 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php·服务端