Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Remote Function Call and returning the result?

Tags:

php

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?

like image 540
夏期劇場 Avatar asked Sep 18 '11 09:09

夏期劇場


1 Answers

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

like image 177
Alex Avatar answered Oct 01 '22 06:10

Alex