夏期劇場
夏期劇場

Reputation: 18337

PHP: Remote Function Call and returning the result?

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 the result to 1st server.

Actually the theme will be:
Web Server (1) ----------------> Web Server (2) ---------------> Database Server
Web Server (1) <---------------- Web Server (2) <--------------- Database Server

Query Function() will be only located on Web Server (2). Then i need to run that query function() remotely from Web Server (1).

What is it call? And Is it possible?

Upvotes: 7

Views: 18457

Answers (3)

Alex
Alex

Reputation: 9471

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).

Upvotes: 12

arkleyjoe
arkleyjoe

Reputation: 131

What you are aiming to do is definitely possible. You will need to set up some sort of api in order for server one to make a request to server 2.

I suggest you read up on SOAP and REST api

http://www.netmagazine.com/tutorials/make-your-own-soap-api

Generally you will use something like CURL to contact server 2 from server 1.

Google curl and you should quickly get idea.

Its not going to be easy to give you a complete solution so I hope this nudge in the right direction is helpful.

Upvotes: 0

ahoura
ahoura

Reputation: 689

You can do so by using an API. create a page on second server that takes variables and communicates to the server using those vars (depending on what you need). and the standard reply from that page should be either JSON or XML. then read that from server 1 by requesting that file and getting the reply from the 2nd server.

*NOTE if its a private file, make sure you use an authentication method to prevent users from accessing the file

Upvotes: 0

Related Questions