Making a connection in PHP using TLS

php, ssl

Solution

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.

Problem

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?

Original source

Related problems