PHP CURL图片上传背景与版本差异
本实例详细解析了基于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的处理逻辑示例如下:
<?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);
?>
希望上述关于PHP程序设计中文件上传部分的讲解,能对读者有所帮助。