简体   繁体   English

通过curl将服务器的发帖请求发送到另一个

[英]Send post request from server to another by curl

I have 2 PHP files, each one in separated server. 我有2个PHP文件,每个文件位于单独的服务器中。

For example: 例如:

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

The first file code (index.php): 第一个文件代码(index.php):

echo $_POST['file_name'];

The Second file code (request.php): 第二个文件代码(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);

What I want is send the $data array from externalServer/request.php to mainServer/default/index.php , but there is an error Notice: Undefined index: file_name in default\\index.php on line 13 . 我想要的是将$data数组从externalServer/request.php发送到mainServer/default/index.php ,但是有一个错误Notice: Undefined index: file_name in default\\index.php on line 13

How to get the $data array to for instance to print an item ? 如何获取$data数组以例如打印项目?

I found the mistake in your code. 我在您的代码中发现了错误。 Sending an associative array directly (what you did) is not a correct way. 直接发送关联数组(您所做的)不是正确的方法。 You need to send the array as a string. 您需要将数组作为字符串发送。

Example

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

Should be This-> 应该是这个->

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

Now when you'd sent the data, you'd be able to fetch it via $_POST . 现在,当您发送数据后,就可以通过$_POST来获取数据了。 You can let php do the array to string conversion using http_build_query . 您可以让php使用http_build_queryarray 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

Read more about http_build_query Here 在此处阅读有关http_build_query更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM