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

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

报告相同问题?

悬赏问题

  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统