繁体   English   中英

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;

?>

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

根据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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM