最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
PHP7基于curl实现的上传图片功能
时间:2022-06-24 16:34:38 编辑:袖梨 来源:一聚教程网
本文实例讲述了PHP7基于curl实现的上传图片功能。分享给大家供大家参考,具体如下:
根据php版本不同,curl模拟表单上传的方法不同
php5.5之前
$curl = curl_init(); if (defined('CURLOPT_SAFE_UPLOAD')) { curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false); } $data = array('file' => '@' . realpath($path));//‘@' 符号告诉服务器为上传资源 curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, 1 ); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_USERAGENT,"TEST"); $result = curl_exec($curl); $error = curl_error($curl);
php5.5之后,到php7
$curl = curl_init(); curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true); $data = array('file' => new CURLFile(realpath($path))); url_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, 1 ); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_USERAGENT,"TEST"); $result = curl_exec($curl); $error = curl_error($curl);
下面提供一个兼容的方法:
$curl = curl_init(); if (class_exists('CURLFile')) { curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true); $data = array('file' => new CURLFile(realpath($path)));//>=5.5 } else { if (defined('CURLOPT_SAFE_UPLOAD')) { curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false); } $data = array('file' => '@' . realpath($path));//<=5.5 } curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, 1 ); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_USERAGENT,"TEST"); $result = curl_exec($curl); $error = curl_error($curl);
其中:
$path:为待上传的图片地址
$url:目标服务器地址
例如
$url="http://localhost/upload.php"; $path = "/bg_right.jpg"
upload.php示例:
相关文章
- 2024金摇杆奖年度游戏名单 11-22
- 用针在纸上绣画是哪种非遗技艺 蚂蚁新村11月21日答案最新 11-22
- 重返未来1999纸信圈儿什么时候up 为什么故事集卡池活动介绍 11-22
- 重返未来1999雾中盛会怎么玩 UTTU聚光专栏雾中盛会活动介绍 11-22
- 光遇姆明季后续版本怎么玩 光遇音乐节宴会节活动介绍 11-22
- 无期迷途四星装束是谁 无期迷途首个四星装束剪影介绍 11-22