我不知道這個方法叫什么:反向代理,隧道,繞過?
想象一下,我們有 3 個網站:
http://exampleapi.com - API or Service provider
http://example1.com - I bought the API for this Website from example.com
http://example2.com - My New website
1 . 我為example1.com購買了 API 或支付網關服務,該網站沒有任何內容、表單、資料。(只是為了獲取API)
2 . 現在,我想在example2.com |之間創建隧道 示例1.com | 示例api.com。我的意思是,從 example2.com 獲取所有請求,發送到 example1.com 并將資料傳遞給 exampleapi.com。
3 . 回應后,exampleapi.com.com 將資料發送到 example1.com,example2.com 將接收并顯示給用戶。
uj5u.com熱心網友回復:
這是一個如何撰寫代碼的示例。您可以像我一樣在單個站點上進行模擬。在我的網站上,我創建了 3 個檔案夾:
- 示例1
- 示例2
- 示例api
在它們下,我創建了一個 index.php 檔案。讓我們看看他們。
yoursite.com/exampleapi/index.php
<?php
header("Content-Type: application/text");
echo 'Titanic vs. Iceberg';
這個的輸出是明文
Titanic vs. Iceberg
我們將從 example1 呼叫此 API。
yoursite.com/example1/index.php
該站點的代碼將擁有自己的資料and,將從 exampleapi/index.php 中提取資料,如下所示:
<?php
// call exampleapi
$url = 'https://yoursite.com/exampleapi/index.php';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
$response = curl_exec($curl);
curl_close($curl);
// show data
header("Content-Type: application/json");
$data = [
'name' => 'John',
'age' => 25,
'data_from_exampleapi' => $response
];
echo json_encode($data);
此代碼的輸出將是
{"name":"John","age":25,"data_from_exampleapi":"Titanic vs. Iceberg"}
我們將從 example2 中呼叫它。
yoursite.com/example2/index.php
這將是您的網頁。我模擬了一個電話。當按鈕被按下時,PHP 會向 example1/index.php 發送一個請求。然后那個頁面會向exampleapi/index.php發送一個請求,獲取資料,將獲取的資料和它自己的資料結合起來,然后發回example2/index.php
<?php
function fetchInformation()
{
$url = 'https://yoursite.com/example1/index.php';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
?>
<!doctype html>
<body>
<form action="./" method="get">
<p>
When you press this button, PHP will try to get data from
example1/index.php and show information
below
</p>
<input type="submit" value="Get data from API" name="mybutton" id="mybutton">
</form>
<?php
// only if button is pressed, fetch information
if ($_SERVER['REQUEST_METHOD'] === 'GET')
{
if ( ! is_null($_REQUEST['mybutton']) )
{
echo '<h3>Information received</h3>';
$response = fetchInformation();
echo '<p>' . $response . '</p>';
}
}
?>
</body>
當您訪問 yoursite.com/example2/index.php 時,您會看到如下內容:

當您按下按鈕時,example2/index.php -> 呼叫 example1/index.php -> 呼叫 exampleapi/index.php。資料反向,你會看到這樣的輸出:

這向您展示了如何使用 PHP 單頁在另一頁上呼叫 API。如果您可以控制另一個頁面,則可以調整代碼以從另一個頁面呼叫 API。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/471951.html
上一篇:正則運算式匹配url的兩個部分
