Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a connection in PHP using TLS

Tags:

php

ssl

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

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

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

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

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

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.

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

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?

like image 995
James Brown Avatar asked Jul 12 '26 12:07

James Brown


1 Answers

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)

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

like image 186
James Brown Avatar answered Jul 14 '26 01:07

James Brown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!