我为特殊目的编写了一个小型 SIP 客户端。
基本上它使用函数 fsockopen()
连接到端口 5060
$fp = fsockopen("10.0.0.1", 5060, $errno, $errstr, 30);
然后基本上使用
fread()
和 fwrite()
读取和写入 SIP 命令。现在我的 SIP 服务运营商希望我们的客户使用 SIPS
基本上是基于 TLS 的 SIP。我花了几个小时寻找信息
关于如何使用 PHP 连接到带有 TLS 的端口但没有任何
成功。显然
fsockopen()
在一定程度上支持 TLS 但当我将上述内容替换为:
$fp = fsockopen("tls://10.0.0.1", 5061, $errno, $errstr, 10);
我什么也得不到。我可以使用 OpenSSL 客户端从我的 shell 连接到服务器:
$ openssl s_client -connect 10.0.0.1:5061
我可以通过该连接与 SIP 服务器进行通信,而不会出现问题。 OpenSSL 支持是在 PHP 中编译的。
我的问题是我无法在 PHP 中设置与服务器的 TLS 连接。我在一些论坛中注意到,在旧版本的 PHP 中,可以使用
fsockopen()
构建和使用 SSL 上下文,但显然不再适用,因为我收到关于参数太多的错误。我还尝试将
stream_context_create()
与 stream_context_set_option()
一起使用,但没有收到服务器的回复:$context = stream_context_create();
$result=stream_context_set_option($context, 'ssl', 'verify_peer', 'TRUE');
$result=stream_context_set_option($context, 'ssl', 'cafile', 'cert.cer');
$result=stream_context_set_option($context, 'ssl', 'verify_depth', '5');
$fp = stream_socket_client('tls://'.$host.':'.$port, $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context);
但我仍然无法从服务器获得任何回复或错误。在 PHP 中使用 TLS 的推荐和工作方式是什么?
最佳答案
我认为您的某些选项对于验证自签名证书是错误的;以下应该足以使其工作:
$context = stream_context_create([
'ssl' => [
'verify_peer' => true,
'allow_self_signed' => true,
'local_cert' => 'cert.cer',
],
]);
关于php - 使用 TLS 在 PHP 中建立连接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21431977/