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('参数不足');
}
相关推荐
JaguarJack6 小时前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
后端·php·服务端
BingoGo6 小时前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
php
JaguarJack1 天前
告别 Laravel 缓慢的 Blade!Livewire Blaze 来了,为你的 Laravel 性能提速
后端·php·laravel
郑州光合科技余经理2 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1232 天前
matlab画图工具
开发语言·matlab
dustcell.2 天前
haproxy七层代理
java·开发语言·前端
norlan_jame2 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone2 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054962 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
QQ5110082852 天前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php