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

时间:2016-02-29 21:30:41

标签: php api security

我需要使用PHP(file_get_contents)调用第三方API,解码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;

?>

2 个答案:

答案 0 :(得分:1)

只需使用Guzzle之类的客户端即可。 特别是如果您没有访问外部服务的经验。

答案 1 :(得分:1)

OP的每个请求:

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

<?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);
相关问题