PHP: Remote Function Call and returning the result?

前端 未结 3 1643
轻奢々
轻奢々 2020-12-03 22:58

I\'m not very expert to PHP. I want to know how to communicate between 2 web servers. For clearance, (from 1st Server) run a function (querying) on remote server. And return

3条回答
  •  一整个雨季
    2020-12-03 23:52

    Yes.

    A nice way I can think of doing would be to send a request to the 2nd server via a URL. In the GET (or POST) parameters, specify which method you'd like to call, and (for security) some sort of hash that changes with time. The hash in there to ensure no third-party can run the function arbitrarily on the 2nd server.

    To send the request, you could use cURL:

    function get_url($request_url) {
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $request_url);
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      $response = curl_exec($ch);
      curl_close($ch);
    
      return $response;
    }
    

    This sends a GET request. You can then use:

    $request_url = 'http://second-server-address/listening_page.php?function=somefunction&securityhash=HASH';
    $response = get_url($request_url);
    

    On your second server, set up the listening_page.php (with whatever filename you like, of course) that checks for GET requests and verifies the integrity of the request (i.e. the hash, correct & valid params).

提交回复
热议问题