PHP实战:安全实现文件上传功能教程

HTML部分:

<form action="upload.php" method="post" enctype="multipart/form-data">

<input type="file" name="userfile">

<input type="submit" value="上传">

</form>

PHP部分:

<?php

$upload_dir = 'uploads/';

$max_size = 1024 * 1024; //1MB

$allowed_types = 'image/jpeg', 'image/png';

if($_FILES'userfile''error' !== UPLOAD_ERR_OK){

die('上传错误:'.$_FILES'userfile''error');

}

if(_FILES\['userfile'\]\['size'\] \> max_size){

die('文件大小超过限制');

}

$finfo = finfo_open(FILEINFO_MIME_TYPE);

detected_type = finfo_file(finfo, $_FILES'userfile''tmp_name');

if(!in_array(detected_type, allowed_types)){

die('不允许的文件类型');

}

extension = pathinfo(_FILES'userfile''name', PATHINFO_EXTENSION);

safe_name = uniqid('file_', true).'.'.extension;

target_path = upload_dir.$safe_name;

if(!move_uploaded_file(_FILES\['userfile'\]\['tmp_name'\], target_path)){

die('文件保存失败');

}

echo '文件上传成功,保存为:'.$safe_name;

?>

另外我们在日常开发中通常会用到各种API接口,比如查询用户IP归属地,手机号归属地,天气预报,万年历等,这时我们可以直接去接口盒子https://www.apihz.cn 查找需要的API即可。接口盒子有数百个免费API,而且采用集群化服务器部署,比一般的API服务商更加稳定。

相关推荐
无限的鲜花17 小时前
反射(原创推荐)
java·开发语言
yongche_shi18 小时前
ragas官方文档中文版(五十)
开发语言·python·ai·ragas·如何评估和改进 rag 应用
一路向北he18 小时前
字节钢铁军团--“提供情境,而非控制”
java·开发语言·前端
GitLqr19 小时前
Flutter 3.44 插件内置 Kotlin (KGP) 双向兼容适配指南
android·flutter·dart
AI行业学习19 小时前
Notepad++ 官方下载 + 完整安装 + 全套优化配置(2026最新)
开发语言·人工智能·python·前端框架·html·notepad++
大圣编程20 小时前
Python中continue语句的用法是什么?
开发语言·前端·python
upgrador21 小时前
基础知识:C++ STL构造函数的左闭右开惯例及其实现原理
开发语言·c++
yoothey21 小时前
报废审批流规则引擎设计——责任链模式完整实现
linux·开发语言·bash
geovindu1 天前
python: Functional Options Pattern
开发语言·后端·python·设计模式·惯用法模式·函数式选项模式
wuyk5551 天前
24. C 语言模块化:不是拆几个.c 文件那么简单
c语言·开发语言·stm32·单片机