Home > Software engineering >  What's the best way to call php variables from an external domain?
What's the best way to call php variables from an external domain?

Time:07-17

I have a small php script: domain1.com/script1.php

//my database connections, check functions and values, then, load:

$variable1 = 'value1';
$variable2 = 'value2';

if ($variable1 > 5) {
    $variable3 = 'ok';
} else {
    $variable3 = 'no';
}

And I need to load the variables of this script on several other sites of mine (different domains, servers and ips), so I can control all of them from a single file, for example:

domain2.com/site.php
domain3.com/site.php
domain4.com/site.php

And the "site.php" file needs to call the variable that is in script1.php (but I didn't want to have to copy this file in each of the 25 domains and edit each of them every day): site.php:

echo $variable1 . $variable2 . $variable3; //loaded by script.php another domain

I don't know if the best and easiest way is to pass this: via API, Cookie, Javascript, JSON or try to load it as an include even from php, authorizing the domain in php.ini. I can't use get variables in the url, like ?variable1=abc.

My area would be php (but not very advanced either), and the rest I am extremely layman, so depending on the solution, I will have to hire a developer, but I wanted to understand what to ask the developer, or maybe the cheapest solution for this (even if not the best), as they are non-profit sites.

Thank you.

CodePudding user response:

If privacy is not a concern, then file_get_contents('https://example.com/file.php') will do. Have the information itself be passed as JSON text it's the industry standard.

If need to protect the information, make a POST request (using cURL or guzzle library) with some password assuming you're using https protocol.

On example.com server:

$param = $_REQUEST("param");
$result = [
  'param' => $param,
  'hello' => "world"
];
echo json_encode($data);

On client server:

$content = file_get_contents('https://example.com/file.php');
$result = json_decode($content, true);
print_r ($result);

For completeness, here's a POST request:

//
// A very simple PHP example that sends a HTTP POST to a remote site
//

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://www.example.com/file.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
            "postvar1=value1&postvar2=value2&postvar3=value3");

// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS, 
//          http_build_query(array('postvar1' => 'value1')));

// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec($ch);
curl_close ($ch);

$result = json_decode($server_output , true);

  • Related