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

Send post request from server to another by curl

我有 2 个 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 Here