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

时间:2017-08-28 08:02:34

标签: php

我想将文件从本地发送到远程服务器,在将文件保存到服务器之后,我想输出响应。我正在使用cURL发送和上传文件。当我在本地但不在远程服务器上尝试时,它正在工作。 我使用sftp协议和公共身份验证密钥进行连接。 我需要更改以将文件发送到服务器。

这是我的代码。

$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;

1 个答案:

答案 0 :(得分:2)

如果您想将图像上传到客户端上传到您网站的外部服务器,那么您就是正确的教程。

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