我想检查所有请求的 url,如果 url 中包含“video”文件夹,请将其重定向到 API 文件。然后 API 给了我一个 json 文件,它只包含“respond:true”或“respond:false”。如果 json 文件中有 respond:true 则必须显示 url,如果 json 文件包含 respond:false 则必须向用户显示预定义的简单 403 页面。
我知道第一部分可以通过 .htaccess 文件中的简单代码实现,如下所示:
RewriteRule ^your/special/folder/ /specified/url [R,L]
但我不知道如何做第二部分。我的意思是如何获取API的结果,它是一个json文件的形式并检查它。
最佳答案
你可以使用 CURL..
获取请求
$url = 'http://example.com/api/products';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response_json = curl_exec($ch);
curl_close($ch);
$response=json_decode($response_json, true);
发布请求
$postdata = array(
'name' => 'Arfan'
);
$url = "https://example.com/api/user/create";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
您也可以使用 file_get_content 来获取 API 数据。
$json = file_get_contents("$url")
关于php - 如何通过php调用api并从中获取json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46578460/