Unable to establish TLS connection in PHP via fsockopen

Markus Lanthaler picture Markus Lanthaler · Jul 15, 2011 · Viewed 12.8k times · Source

I'm trying since a couple of days to establish a TLS connection to a SMTP server in PHP via fsockopen() on my newly installed Ubuntu server. I#ve tried almost everything and googled for hours but still I didn't get it working.

The PHP code looks as follows:

$fp = fsockopen("tls://smtp.xxxx.com", 25, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
 // some other stuff
}  

The output is just (0), i.e., $errstr = null and $errno = 0.

OpenSSL is installed and enabled:

OpenSSL support: enabled
OpenSSL Library Version: OpenSSL 0.9.8o 01 Jun 2010
OpenSSL Header Version: OpenSSL 0.9.8o 01 Jun 2010

and the following stream socket transports are registered: tcp, udp, unix, udg, ssl, sslv3, sslv2, tls.

The port is open as a telnet from the console works.

Any ideas what's wrong or how I could at least get some more debug output?

Thanks, Markus

Answer

Marc B picture Marc B · Jul 15, 2011

Your connection doesn't make much sense. By using the TLS handler, you want TLS to be established BEFORE any data goes. But port 25 is standard SMTP, which can only establish TLS AFTER you've initially connected via an unencrypted regular connection. Once that initial connection is established, then you can enable TLS with the STARTTLS command to tell the SMTP server to switch over.

If you want TLS from the get-go, then use port 465, which is ssl/tls from the start.