title: Making a connection in PHP using TLS
body: <p>I wrote a small SIP client for a special purpose.
  Basically it connects to port 5060 using function <code>fsockopen()</code></p>
  
  <pre><code>$fp = fsockopen("10.0.0.1", 5060, $errno, $errstr, 30);
  </code></pre>
  
  <p>and then basically reads and writes SIP commands using <code>fread()</code> and <code>fwrite()</code>.</p>
  
  <p>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 <code>fsockopen()</code> supports TLS to an extent but 
  when I replaced the above with:</p>
  
  <pre><code>$fp = fsockopen("tls://10.0.0.1", 5061, $errno, $errstr, 10);
  </code></pre>
  
  <p>I get nothing.  I can connect to the server from my shell with with OpenSSL client:</p>
  
  <pre><code>$ openssl s_client -connect 10.0.0.1:5061
  </code></pre>
  
  <p>And I can communicate with the SIP server through that connection without problems. OpenSSL support is compiled in the PHP. </p>
  
  <p>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 <code>fsockopen()</code> but apparently not anymore, since I get an error about too many parameters.</p>
  
  <p>I also tried using <code>stream_context_create()</code> with <code>stream_context_set_option()</code> but I get no replies from the server:</p>
  
  <pre><code>$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);
  </code></pre>
  
  <p>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?</p>