使用 TLS 在 PHP 中建立连接 [英] Making a connection in PHP using TLS

查看:47
本文介绍了使用 TLS 在 PHP 中建立连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为特殊目的编写了一个小型 SIP 客户端.基本上它使用函数 fsockopen()

I wrote a small SIP client for a special purpose. Basically it connects to port 5060 using function fsockopen()

$fp = fsockopen("10.0.0.1", 5060, $errno, $errstr, 30);

然后基本上使用fread()fwrite()读写SIP命令.

and then basically reads and writes SIP commands using fread() and fwrite().

现在我的 SIP 服务运营商希望我们的客户使用 SIPS基本上是基于 TLS 的 SIP.我花了几个小时寻找信息关于如何使用 PHP 连接到带有 TLS 的端口但没有任何成功.显然 fsockopen() 在一定程度上支持 TLS 但当我将上述内容替换为:

Now my SIP service operator wants us clients to use SIPS which is basically SIP over TLS. I've spent hours looking for information on how to connect to a port with TLS using PHP but without any success. Apparently the fsockopen() supports TLS to an extent but when I replaced the above with:

$fp = fsockopen("tls://10.0.0.1", 5061, $errno, $errstr, 10);

我一无所获.我可以使用 OpenSSL 客户端从我的 shell 连接到服务器:

I get nothing. I can connect to the server from my shell with with OpenSSL client:

$ openssl s_client -connect 10.0.0.1:5061

而且我可以通过该连接与 SIP 服务器进行通信而不会出现问题.OpenSSL 支持是在 PHP 中编译的.

And I can communicate with the SIP server through that connection without problems. OpenSSL support is compiled in the PHP.

我的问题是我无法在 PHP 中设置与服务器的 TLS 连接.我在一些论坛中注意到,在旧版本的 PHP 中,可以使用 fsockopen() 构建和使用 SSL 上下文,但显然不再适用,因为我收到关于参数过多的错误.

My problem is that I can't set up the TLS connection with the server in PHP. I noticed in some forums that in older versions of PHP it was possible to build and use the SSL context with fsockopen() but apparently not anymore, since I get an error about too many parameters.

我也尝试将 stream_context_create()stream_context_set_option() 一起使用,但我没有收到服务器的回复:

I also tried using stream_context_create() with stream_context_set_option() but I get no replies from the server:

$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 的推荐和工作方式是什么?

but I still can't get any replies or errors from the server. What is the recommended and working way of using TLS in PHP?

推荐答案

这足以打开一个 TLS 连接:

This is enough to open a TLS connection:

$context = stream_context_create();

$fp = stream_socket_client('tls://'.$host.':'.$port, $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context)

如果证书就位.如果不是,请按照 Filippos 链接的说明进行操作.

if the certificates are in their place. If they are not, follow the instructions linked by Filippos.

这篇关于使用 TLS 在 PHP 中建立连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆