通过curl将post请求从服务器发送到另一个服务器


Send post request from server to another by curl

我有两个PHP文件,每个文件都在单独的服务器中。

例如:

  1. mainServer/default/index.php
  2. externalServer/request.php

第一个文件代码(index.php):

echo $_POST['file_name'];

第二个文件代码(request.php):

$data = array(
    'file_name' => "file.zip",
    'file_size' => 5000
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://mainServer/default/index.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_TIMEOUT, 2);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);

我想要的是将$data数组从externalServer/request.php发送到mainServer/default/index.php,但出现错误Notice: Undefined index: file_name in default'index.php on line 13

如何获取$data数组以打印项目?

我在您的代码中发现了错误。直接发送关联数组(您所做的)不是一种正确的方式。您需要将数组作为字符串发送。

示例

This->
$data = array(
    'file_name' => "file.zip",
    'file_size' => 5000
);

应该是这个->

$data = "file_name=file.zip&file_zipe=500"

现在,当您发送数据时,就可以通过$_POST获取数据。您可以让php使用http_build_query执行array to string conversion

$data = array(
        'file_name' => "file.zip",
        'file_size' => 5000
    );
$string = http_build_query($data);
//output = file_name=file.zip&file_size=5000

阅读更多关于http_build_query的信息此处

相关文章: