doulin2555 2015-12-07 22:44
浏览 77
已采纳

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

I have 2 PHP files, each one in separated server.

For example:

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

The first file code (index.php):

echo $_POST['file_name'];

The Second file code (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.

How to get the $data array to for instance to print an item ?

  • 写回答

1条回答 默认 最新

  • doupang4126 2015-12-07 23:43
    关注

    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. You can let php do the array to string conversion using http_build_query.

    $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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改