php使用cURL将文件发送到远程服务器

问题描述:

我想从本地发送文件到远程服务器,并将文件保存到服务器之后我想输出响应。我正在使用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

如果你想上传图片到客户端上传到你的网站的外部服务器上,你就在正确的教程中。

为此提交,我们将使用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