2017-08-28 128 views
-2

我想從本地發送文件到遠程服務器,並將文件保存到服務器之後我想輸出響應。我正在使用cURL發送和上傳文件。當我在本地而不是遠程服務器上嘗試時,它正在工作。 我使用sftp協議和公共身份驗證密鑰進行連接。 我需要改變發送文件到服務器。php使用cURL將文件發送到遠程服務器

這是我的代碼。

$target_url = 'https://example.com/accept.php'; 
$file_name_with_full_path = realpath('ss.zip'); 
$post = array('file' => new CurlFile($file_name_with_full_path, 'application/zip' /* MIME-Type */, 'ss.zip')); 

    $ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL,$target_url); 
curl_setopt($ch, CURLOPT_POST,1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $post); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); 
$result=curl_exec ($ch); 
curl_close ($ch); 
echo $result; 
+0

以及最新的錯誤? – insider

+0

沒有任何錯誤。它只是顯示空白頁面。 – Snappy

+0

檢查日誌然後,空白頁是通常的錯誤500 – insider

回答

1

如果你想上傳圖片到客戶端上傳到你的網站的外部服務器上,你就在正確的教程中。

爲此提交,我們將使用2檔:

  • form.php的 - 頁面裏,我們將向客戶端的形式。該文件還將上傳的數據發送到外部服務器。

  • handle.php - 使用cURL從form.php接收上傳數據的外部服務器上的頁面。

我們不會將客戶端上傳的文件複製到我們的服務器,而是直接將文件發送到外部服務器。爲了發送,我們將使用base64加密文件。好的。開始吧。首先,我們創建FORM頁面:

<form enctype="multipart/form-data" encoding='multipart/form-data' method='post' action="form.php"> 
    <input name="uploadedfile" type="file" value="choose"> 
    <input type="submit" value="Upload"> 
</form> 
<? 
if (isset($_FILES['uploadedfile'])) { 
$filename = $_FILES['uploadedfile']['tmp_name']; 
$handle = fopen($filename, "r"); 
$data  = fread($handle, filesize($filename)); 
$POST_DATA = array(
    'file' => base64_encode($data) 
); 
$curl = curl_init(); 
curl_setopt($curl, CURLOPT_URL, 'http://extserver.com/handle.php'); 
curl_setopt($curl, CURLOPT_TIMEOUT, 30); 
curl_setopt($curl, CURLOPT_POST, 1); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $POST_DATA); 
$response = curl_exec($curl); 
curl_close ($curl); 
echo "<h2>File Uploaded</h2>"; 
} 
?> 
Now the code of the handle.php in external server where we sent the data using cURL : 

$encoded_file = $_POST['file']; 
$decoded_file = base64_decode($encoded_file); 
/* Now you can copy the uploaded file to your server. */ 
file_put_contents('subins', $decoded_file); 
The above code will receive the base64 encoded file and it will decode and put the image to its server folder. This might come in handy when you want to have your own user file storage system. This trick is used by ImgUr and other file hosting services like Google. 
+0

謝謝你o我試圖通過curl直接發送文件到存儲庫,它不工作。所以,我閱讀這篇文章並改變了我的策略,我發送到另一個php文件來處理圖像,然後保存文件,現在它正在工作o /// – heavyrick

相關問題