PHP 的file_get_contents是否安全,可以调用第三方 API


Is PHP's file_get_contents secure for calling third-party APIs?

我需要使用 PHP 调用第三方 API(file_get_contents),解码 json 响应 ( json_decode ),并将结果插入网页。

我想验证这些步骤都不允许受感染的 API 服务器在我的服务器上执行任意代码。

对于这个问题,如果它返回恶意的HTML/JS是可以的 - 我的问题严格来说是关于在服务器端执行任意PHP代码或系统命令。

谢谢。

编辑:这是一个代码示例。

<?php
$API_URL = 'https://HARDCODED.URL/SOMETHING';
$response = file_get_contents($API_URL);
$content = json_decode($response);
$server_address = $content->{'server_address'};
echo $server_address;
?>

根据 OP 的请求:

如何将file_get_contents()转换为 curl 请求:

<?php
// init the CURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // return response as a string
curl_setopt($ch, CURLOPT_URL, 'https://HARDCODED.URL/SOMETHING'); // the URL
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE); // verify SSL info
// You MIGHT need this step or else the CURLOPT_SSL_VERIFYPEER will cause issues
//
// Download https://curl.haxx.se/ca/cacert.pem and save as cacert.pem
//
// curl_setopt($ch, CURLOPT_CAINFO, '/path/to/cacert.pem');
//
// I say MIGHT because your webhost might have already set CURLOPT_CAINFO in the php.ini
// Get JSON
$result = curl_exec($ch);
// Basic error handling
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200)
{
    $content = json_decode($result, TRUE);
}
else
{
    echo 'Something went wrong :( please try again later.';
}
// Close connection
curl_close($ch);

只需使用像Guzzle这样的客户端。特别是如果您没有访问外部服务的经验。