簡體   English   中英

從外部域調用 php 變量的最佳方法是什么?

[英]What's the best way to call php variables from an external domain?

我有一個小的 php 腳本: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';
}

而且我需要在我的其他幾個站點(不同的域、服務器和 ips)上加載這個腳本的變量,這樣我就可以從一個文件中控制所有這些,例如:

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

並且“site.php”文件需要調用 script1.php 中的變量(但我不想在 25 個域中的每個域中復制該文件並每天編輯它們):site.php :

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

我不知道是否最好和最簡單的方法是通過此方法:通過 API、Cookie、Javascript、JSON 或嘗試將其作為包含甚至從 php 加載,在 php.ini 中授權域。 我不能在 url 中使用 get 變量,例如 ?variable1=abc。

我的領域是 php(但也不是很高級),其余的我非常外行,所以根據解決方案,我將不得不聘請開發人員,但我想了解要問開發人員什么,或者可能是最便宜的解決方案(即使不是最好的),因為它們是非營利網站。

謝謝你。

如果隱私不是問題,那么file_get_contents('https://example.com/file.php')就可以了。 將信息本身作為 JSON 文本傳遞,這是行業標准。

如果需要保護信息,假設您使用的是https協議,請使用一些密碼發出 POST 請求(使用 cURL 或 guzzle 庫)。

在 example.com 服務器上:

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

在客戶端服務器上:

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

為了完整起見,這是一個 POST 請求:

//
// 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM