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服务商更加稳定。
评论前必须登录!
注册