您好,欢迎访问一九零五行业门户网

可兼容php5与php7的cURL文件上传功能实例分析php技巧

这篇文章主要介绍了可兼容php5与php7的curl文件上传功能,结合实例形式分析了针对php5与php7版本在使用curl进行文件上传时的相关判定与具体操作技巧,需要的朋友可以参考下
本文实例讲述了可兼容php5与php7的curl文件上传功能。分享给大家供大家参考,具体如下:
为啥要写这个示例
最近修改一个项目,需要通过curl上传文件。
记得之前做过类似实现的,于是翻出来之前的代码,使用的是“@”前缀方式。
但同样的方法现在不行了!后来发现,是版本兼容问题。
奔着开源分享的精神,同时避免自己遗忘,于是写了下面的示例程序。
示例程序
特别说明:
共3个文件,都放在web根目录的test目录下,同时保证该目录可写。上传的图片也会保存在该目录。
如果要将程序文件放在其他目录运行,必须更改php代码中的相关url,否则示例可能无法运行。
<html><head> <title>上传示例</title></head><body> <p>下面上传文件到中间脚本:</p> <br /> <form action="upload.php" method="post" enctype="multipart/form-data"> 选择文件: <input type="file" name="file" /> <input type="submit" value="上传" /> </form></body></html>
<?php/** * 接收通过浏览器上传的文件 * * @author straiway<straiway@qq.com> * @site http://straiway.sinaapp.com */if (empty($_files['file'])) { exit('没有上传指定名称的文件');}// 先保存到本地,再上传$file = $_files['file'];$file_name = __dir__ . "/{$file['name']}";move_uploaded_file($_files['file']['tmp_name'], $file_name);// 本地测试时,可能需要更改下面的url$ch = curl_init('http://localhost/test/upload_via_curl.php');// 从php5.5开始,反对使用"@"前缀方式上传,可以使用curlfile替代;// 据说php5.6开始移除了"@"前缀上传的方式if (class_exists('curlfile')) { $file = new curlfile($file_name); // 禁用"@"上传方法,这样就可以安全的传输"@"开头的参数值 curl_setopt($ch, curlopt_safe_upload, true);} else { $file = "@{$file_name}";}// 从php5.2开始,要上传文件,必须给curlopt_postfields传递数组,而不是字符串。// 也只有传递数组,http头部的"content-type"才会设置成"multipart/form-data"curl_setopt($ch, curlopt_postfields, array('file_via_curl' => $file));// 将传输结果作为curl_exec的返回值,而不是直接输出curl_setopt($ch, curlopt_returntransfer, true);$result = curl_exec($ch);$error = curl_error($ch);if ($result) { $result_array = json_decode($result, true); if ($result_array) { if ($result_array['status']) { exit("上传成功!curl返回图片地址:{$result_array['data']['url']}<br /><img src='{$result_array['data']['url']}' />"); } else { exit("curl上传失败!错误信息:{$result['info']}"); } } else { exit("发生错误,curl返回结果:{$result}"); }} else { exit('curl请求发生错误' . var_export($error, true));}
<?php/** * 接受通过curl上传的文件。 * * @author straiway<straiway@qq.com> * @site http://straiway.sinaapp.com */if (empty($_files['file_via_curl'])) { $return = array('status' => 0, 'info' => '没有上传指定名称的文件');} else { // 保存文件 $file = $_files['file_via_curl']; // 重命名文件,便于识别 $base_name = explode('.', $file['name']); $base_name[0] .= '_upload_var_curl'; $base_name = implode('.', $base_name); $file_name = __dir__ . "/{$base_name}"; if (move_uploaded_file($file['tmp_name'], $file_name)) { // 本地测试时,可能需要更改下面的url $url = "http://localhost/test/{$base_name}"; $return = array('status' => 1, 'info' => '上传成功', 'data' => array('url' => $url)); } else { $return = array('status' => 0, 'info' => '上传失败'); }}exit(json_encode($return));
参考资料
http://php.net/manual/en/function.curl-setopt.php
//www.jb51.net/article/139950.htm
您可能感兴趣的文章:php区块查询实现方法分析php技巧
php折半查找算法实例分析php技巧
php折半(二分)查找算法实例分析php技巧
以上就是可兼容php5与php7的curl文件上传功能实例分析php技巧的详细内容。
其它类似信息

推荐信息