简体   繁体   English

如何使用CURL请求另一个服务器上的php页面,然后处理响应

[英]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. 我正在尝试连接到mysql数据库,但是从另一台服务器连接并处理该服务器上的所有查询,然后使用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. 当有人从服务器A访问页面时,请求将从服务器A发送到服务器B,然后服务器B连接到数据库。

  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. 一旦服务器B连接到数据库,它将从某些行和字段中获取信息,然后将其发送回服务器a。

  3. Once server A has received the info, it will then echo out and etc etc... 服务器A收到信息后,就会回显,依此类推等等。

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 在服务器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. $result现在包含您从服务器B请求的页面的HTML。

On server B 在服务器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. 显然,使用上述设置,信息仅echo显到服务器B上的页面。如果有人找到该页面,则他们将能够看到该信息。

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. 如果您需要防止这种情况,那么我建议从服务器A向服务器B发送令牌以验证正确的脚本正在尝试访问该信息。 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. 像API密钥之类的东西,您可以在curl请求中将其作为标头传递,然后从服务器B的$_SERVER取出并进行验证。

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

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