首页
学习
活动
专区
圈层
工具
发布

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

HTML部分:

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

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

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服务商更加稳定。

  • 发表于:
  • 原文链接https://page.om.qq.com/page/O9-2IaGxUs-a4Goa3TyFFzuA0
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。
领券