简体   繁体   English

PHP客户端向服务器端发送请求并向远程服务器发送服务器端请求

[英]PHP client post request to Server side and server side post request to remote server

My scenario is as follows: 我的方案如下:

  1. when button clicked, client side will post request to server side 单击按钮时,客户端将向服务器端发送请求
  2. once server side receive the request, it will post another request to remote sever to get the result 一旦服务器端收到请求,它将向远程服务器发送另一个请求以获得结果
  3. once the response comes, server side should echo the response to client. 一旦响应到来,服务器端应该回应客户端的响应。

client 客户

$.post('login_server.php'{act:"post",phone:phone,passwords:passwords},function(e){
      alert(e);
    },'json');

server 服务器

$act = isset($_POST["act"]) ? $_POST["act"] : "default";
if($act == "default"){
    var_dump(123123);
}elseif($act == "post"){
    $phone = $_POST["phone"];
    $password = md5($_POST["passwords"]);
    $data_array = array('phone' => $phone,'password' =>$password );
    $jsonStr = json_encode($data_array);
    $url = "http://xx.xx.xx.xx/xxxx/userinfo/login";
    $data = http_post_json($url, $jsonStr); 
    echo json_encode(123);  
}

function http_post_json($url, $jsonStr)
{
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                      'Content-Type: application/json; charset=utf-8',
                      'Content-Length: ' . strlen($jsonStr)
                )
            );
  $response = curl_exec($ch);
  $abc = json_encode($response);
  $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  return array($httpCode, $response);
}

I checked the login_server. 我检查了login_server。 It can get the response from remote server. 它可以从远程服务器获取响应。 But if I add 但如果我补充一下

$response = curl_exec($ch);
the callback function doesn't work. 回调函数不起作用。

Is there anyone know this? 有没有人知道这个?

BRs Damon BRs达蒙

This doesn't work because you encode your array. 这不起作用,因为您编码您的数组。

$jsonStr = json_encode($data_array);

Try that 试试吧

curl_setopt($ch, CURLOPT_POSTFIELDS, $data_array);

or 要么

Here you need get the 'json' and decode on your page. 在这里你需要获得'json'并在你的页面上解码。

curl_setopt($ch, CURLOPT_POSTFIELDS, 'json='.$jsonStr);

http://php.net/manual/en/function.curl-setopt.php http://php.net/manual/en/function.curl-setopt.php

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

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