你可以使用http/ssl stream wrapper让php透明地处理ssl部分。
让我们从简单的开始:
$c = file_get_contents('file.txt');
没有指定包装器,因此默认使用 file://。 file:// wrapper 尝试打开本地文件 file.txt 并且 file_get_contents() 从该流中读取数据。
下一步:http 包装器
$c = file_get_contents('http://docs.php.net/fopen');
现在指定了一个包装器。 http-wrapper 请求 http://docs.php.net/fopen 并将结果作为流返回,其中 file_get_contents() 的所有数据。
如果启用了 ssl 支持,您也可以使用 https(另请参阅 http://docs.php.net/openssl)。
$c = file_get_contents('https://developer.mozilla.org/en/gecko_dom_reference');
可选:服务器/客户端身份验证
您可以附加 context to a php stream 允许您为所涉及的流包装器设置选项/参数。
例如。 http-wrapper 在向服务器发送 http 请求时会考虑 http.user_agent 参数。因此,如果您想让服务器“相信”特定版本的 firefox 请求文档,您可以执行类似的操作
$context = stream_context_create(
array(
'http'=>array('user-agent'=>'Mozilla/6.0 (Windows; U; Windows NT 7.0; en-US; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.9 (.NET CLR 3.5.30729)')
)
);
$c = file_get_contents('http://docs.php.net/fopen', 0, $context);
在发出 https 请求时,http 和 ssl 选项都被使用
$context = stream_context_create(
array(
'http'=>array( ...http-wrapper options here ),
'ssl'=>array( ...ssl-wrapper options here )
)
);
https 服务器可能要求您在允许访问资源之前进行身份验证。客户端证书必须与请求一起发送,服务器决定它是否可以接受。上下文参数 ssl.local_cert 允许您指定请求中使用的客户端证书。证书文件可能受密码保护。在这种情况下,您必须提供密码作为 ssl.passphrase
$context = stream_context_create(
array(
'ssl'=>array(
'local_cert'=>'xyz/VolkerCA/UserVolker.pem',
'passphrase'=>'my secret passphrase'
)
)
);
$c = file_get_contents('https://hermes..../ssl/test.php', 0, $context);
另一方面,您可能(也)希望确保服务器确实是它声称的那样。如何确定(服务器)证书是否可接受/有效/值得信赖有点超出这篇文章。 http://docs.php.net/book.openssl
设置 ssl.verify_peer=true 并将查找验证数据的信息作为 ssl.cafile 传递
$context = stream_context_create(
array(
'ssl'=>array(
'local_cert'=>'xyz/VolkerCA/UserVolker.pem',
'passphrase'=>'my secret passphrase',
'verify_peer'=>true,
'cafile'=>'xyz/VolkerCA/VolkerCA.pem'
)
)
);
$c = file_get_contents('https://hermes..../ssl/test.php', 0, $context);