简体   繁体   中英

how to use CURL to request a php page on another server and then process the response

I'm trying to connect to a mysql db, but from another server and process all queries on that server and then send all the data off to the original server, using CURL.

I've been researching for hours and cant seem to find the right way to go about it.

so this is what I'm trying to do overall:

  1. When somebody visits a page from server A, a request will then be sent out from server A to server B which will then connect to a db.

  2. Once server B has connected to the db, it will take information from certain rows and fields and then send it back to server a.

  3. Once server A has received the info, it will then echo out and etc etc...

Firstly, is this safe to do? It wont like open a door on both or even one server will it?

Secondly, I have no idea how to go about it.

An example code would be great!

On server A

$post_fields = array(
    'variable_name' => 'variable_value',
    'variable' => $variable,
);
$ch = curl_init('http://www.serverB.com/example.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,  $post_fields);
curl_setopt($ch, CURLOPT_POST, 1);
$result = curl_exec($ch);

$result now contains the HTML of the page you have requested from server B.

On server B

// pseudocode
$variable = $_POST['variable'];
$variable_name = $_POST['variable_name'];
$db_results = $db->getQuery('SELECT * FROM table WHERE `variable` = ?', array($variable))->toString();
echo $db_results;

Is it safe?

This depends. Does the information coming from the DB need to be protected from public view? Obviously with the setup above the information is just echo d out to a page on server B. Was someone to find that page then they would be able to see the information.

If that does not matter then its perfectly save and does not open any doors (you own both sites right?) particularly.

If you need to protect against that then I suggest sending a token from server A to server B to authenticate that the correct script is attempting to access the information. Something like an API key, which you could pass as a header in your curl request and then get out and verify from $_SERVER on server B.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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