1. 程式人生 > >PHP從一臺伺服器將圖片傳送到另一臺伺服器並儲存

PHP從一臺伺服器將圖片傳送到另一臺伺服器並儲存

由於我們的後臺和前臺是不同的php框架,而且後臺和前臺不在同一臺伺服器上,現在有一個問題,就是從後臺上傳圖片要儲存在前臺的框架中。

我們後臺用的是laravel框架

    public function laraveltest(Request $request) {
	$file = $request->file('file');
    	if($file -> isValid()){
	    	$clientName = $file -> getClientOriginalName();
	    	$tmpName = $file ->getFileName();
	    	$realPath = $file -> getRealPath();
	    	$entension = $file -> getClientOriginalExtension();
	    	$newName = md5($clientName).".".$entension;
	    	$url_path = 'upload/banner/';
	        $path = $file -> move($url_path,$newName);
	        $pathName = json_decode($path,TRUE);
	        $url1 = "http://47.101.54.26/test/testuploadpic";
	        $url2 = "http://47.101.54.27/test/testuploadpic";
	        $url3 = "http://47.101.54.28/test/testuploadpic";
	        $this->curl($path,$url1);
	        $this->curl($path,$url2);
	        $this->curl($path,$url3);
	        $returnPath = '/upload/banner/'.$newName;
	        return $this->json($returnPath);
    	}
    }
    public function curl($path,$url){
    	$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);
    }
通過上面兩個方法就可以將圖片傳送到另外一臺伺服器,我寫了3臺伺服器是因為我想說明可以傳送到無數臺伺服器

下面的程式碼是在另外一臺伺服器上接收到圖片資訊後儲存圖片

    public function testuploadpic(){
        $filename = $_FILES['file']['name'];
        $tmpname = $_FILES['file']['tmp_name'];
        $url = '/home/testuploadpic';
        if(move_uploaded_file($tmpname, $url.$filename))
        {
            echo json_encode('上傳成功');
        }
    }

這樣就可以儲存下來了!!!