开发者

Using CURL and JSON to parse variables from server A to server B

开发者 https://www.devze.com 2023-03-24 14:46 出处:网络
I\'m trying to run mysql queries from a remote server (server B) and then return the info from the DB back as variables to the original server (server A) using CURL and JSON.

I'm trying to run mysql queries from a remote server (server B) and then return the info from the DB back as variables to the original server (server A) using CURL and JSON.

This is what the end result will be:

  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 as variables such as $name $email etc etc.

  3. Onc开发者_StackOverflow中文版e server A has received the info, it will then echo out and etc etc...

Here is the code I've got so far...

Server A

<?

include ('../reference.php');


$post_fields = array(
    'unq__id' => $_reference,
    'gdi__username' => $sponsor_GDI_id,
);
$ch = curl_init('http://example.com/WP/d__access.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,  $post_fields);
curl_setopt($ch, CURLOPT_POST, 1);
$result = curl_exec($ch);



?>

Server B

<?

include ('config/wp__2135432135435135412312534.php');

mysql_connect($hostname,$username,$password) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());

$reference = $_POST['__id'];
$variable_name = $_POST['__username'];
$select = mysql_query("SELECT * FROM $usertable WHERE ". "username = '$variable_name' AND Unique_id = '$reference'");


?>

I haven't actually tested the above code yet because I'm trying to find a way to send all those variables from Server B to Server A (_email, $s, $tst etc etc)

So I'm not even sure if what I've got so far will even work....

Now from a previous question, I was told I could use JSON to send variables back to Server A... "Perhaps you could have server B return a JSON encoded string, which you could decode on Server A."

Could anyone tell me how I would go about doing something like that? Or any simpler alternatives would be great.


On your B server, you could construct a single array, that will contain all the data you need to send back to A :

$result = array(
    'sponsor_first_nme' => $sponsor_first_nme, 
    'sponsor_second_nme' => $sponsor_second_nme, 
);

Then, you can json_encode() that array and echo it :

echo json_encode($result);

This means you script on B will echo some valid JSON.


Then, on A, just get this result as a string, like you already do :

$result = curl_exec($ch);

And json_decode() that string, to get back some PHP data you can use (either array or object, depending on the parameters you used) :

$data = json_decode($result);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号