PHP7基于curl实现的上传图片功能
发布:smiling 来源: PHP粉丝网 添加日期:2018-10-11 14:16:14 浏览: 评论:0
本文实例讲述了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
- } //phpfensi.com
- 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示例:
- <?php
- file_put_contents(time().".json", json_encode($_FILES));
- $tmp_name = $_FILES['file']['tmp_name'];
- $name = $_FILES['file']['name'];
- move_uploaded_file($tmp_name,'audit/'.$name);
- ?>
Tags: 功能 图片
相关文章
- ·php实现文件下载功能的流程分析(2014-07-31)
- ·php中实现图片文件上传程序代码(2013-11-14)
- ·php上传图片失败原图(2013-11-28)
- ·PHP中Ckeditor+Ckfinder配置图片上传功能(2013-12-31)
- ·php上传文件与图片重命名方法总结(2014-01-06)
- ·多图片上传的php代码(2014-01-15)
- ·php简单文件图片批量上传程序代码(2014-03-26)
- ·php中上传图片文件的PHP函数(2014-06-08)
- ·PHP上传图片程序代码工作笔记(2014-06-15)
- ·php ckeditor上传图片文件名乱码解决方法(2014-07-05)
- ·php ckeditor上传图片文件大小限制修改(2014-07-05)
- ·PHP中上传图片到服务器中程序代码(2014-07-26)
- ·百度编辑器UEditor图片上传路径更改方法(2014-07-27)
- ·php中实现图片文件上传程序代码(2014-08-01)
- ·php下载css中图片代码(2014-08-02)
- ·php 图片上传代码例子(2014-08-18)
推荐文章
热门文章
最新评论文章
- 写给考虑创业的年轻程序员(10)
- PHP新手上路(一)(7)
- 惹恼程序员的十件事(5)
- PHP邮件发送例子,已测试成功(5)
- 致初学者:PHP比ASP优秀的七个理由(4)
- PHP会被淘汰吗?(4)
- PHP新手上路(四)(4)
- 如何去学习PHP?(2)
- 简单入门级php分页代码(2)
- php中邮箱email 电话等格式的验证(2)