当使用单独的服务器来存储图片的时候最大的问题就是如何把上传的图片从主服务器保存到图片服务器。而php中curl扩展可以实现向别的服务器发起请求和传送数据,今天要分享的实现远程上传图片到另一台服务器页正是利用curl扩展的这一特性来实现。
为了更好的理解下面通过代码示例来讲解。
主服务器程序:
(为了方便阅读和理解,这里把前端代码和后端处理代码放到了一起,在实际项目中运用的时候可以把前后端的代码分离出来)
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <div style="width: 60%;margin: 0 auto;max-height: 100px;padding-top: 50px;"> <!--图片上传,因为只是讲解实现远程上传和保存文件,这里没有严格限制上传文件类型--> <form action="" method="post" enctype="multipart/form-data"> <input type="file" name="img"> <input type="submit" name="dosubmit" value="提交"> </form> <!--图片上传处理--> <?php echo "<pre>"; if(!empty($_FILES['img'])){ $tmp_name = $_FILES['img']['tmp_name']; $url = "http://www.a.com/index.php";//这里是图片服务器的上传图片处理接口 img_curl($url, $tmp_name); } //把主服务器上传的图片通过curl传送给图片服务器 function img_curl($url, $path){ $curl = curl_init(); if (class_exists('\CURLFile')) { curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true); $data = array('file' => new \CURLFile(realpath($path)));//php版本>=5.5 } else { if (defined('CURLOPT_SAFE_UPLOAD')) { curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false); } $data = array('file' => '@' . realpath($path));//php版本<=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); var_dump($result); } ?> </div> </body> </html>
图片服务器对主服务器传送过来的图片进行处理:
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <div style="width: 100%;margin: 0 auto;min-height: 300px;"> <?php //主服务器通过curl传递过来的图片数据存储在$_FILES, $filename = date('YmdHis',time()).'.jpg'; $tmpname = $_FILES['file']['tmp_name']; $url = 'image/';//图片服务器图片存储目录 var_dump(scandir($url));//scardir:浏览制定目录下的文件 var_dump(move_uploaded_file($tmpname, $url.$filename));//move_uploaded_file :将接受到的图片进行重命名保存 var_dump(scandir($url)); ?> </div> </body> </html>
实际远程上传图片的效果:
通过截图可以发现,在www.test.com上传的图片最终成功保存了www.a.com站点中。