Skip to content

Instantly share code, notes, and snippets.

@rmpel
Created May 20, 2025 05:38
Show Gist options
  • Save rmpel/7f13c3141adf2c9aa3491d441a545892 to your computer and use it in GitHub Desktop.
Save rmpel/7f13c3141adf2c9aa3491d441a545892 to your computer and use it in GitHub Desktop.
Test SSL on email (IMAP) servers.
<?php
// This tool is 80% ChatGPT code. Just so you know.
error_reporting( -1 );
ini_set('display_errors', 'on');
// === CONFIGURATION ===
$config = [
'servers' => [ 'srv1.mail.example.com', 'srv2.mail.example.com', ],
'timeout' => 10, // seconds
];
// === FUNCTIONS ===
function check_imap_ssl($host, $timeout) {
$context = stream_context_create([
'ssl' => [
'verify_peer' => true,
'verify_peer_name' => true,
'allow_self_signed' => false,
'capture_peer_cert' => true,
]
]);
$fp = @stream_socket_client("ssl://$host:993", $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $context);
if ($fp === false) return false;
fclose($fp);
return true;
}
function check_imap_tls($host, $timeout) {
$fp = @stream_socket_client("tcp://$host:143", $errno, $errstr, $timeout);
if ($fp === false) return false;
// Read initial banner
$banner = fgets($fp, 512);
if ($banner === false || stripos($banner, '* OK') === false) {
fclose($fp);
return false;
}
// Send STARTTLS command
fwrite($fp, "a001 STARTTLS\r\n");
$response = fgets($fp, 512);
if (stripos($response, 'OK') === false) {
fclose($fp);
return false;
}
try {
ob_start();
$cryptoEnabled = stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
$m = ob_get_clean();
if ($m && preg_match('/stream_socket_enable_crypto\(\): (.+) in </', $m, $m2)) {
check_imap_set_error( $m2[1]);
}
} catch (Exception $e) {
check_imap_set_error( $e->error_message );
return false;
}
// Upgrade to TLS
fclose($fp);
return $cryptoEnabled === true;
}
function check_imap_set_error( $msg = null ) {
static $m = null;
if ($msg) {
$m = $msg;
}
return $m;
}
function render_status($server, $label, $result) {
$color = $result ? 'green' : 'red';
$status = $result ? '✅ SUCCESS' : '❌ FAILED ' . check_imap_set_error();
echo "<tr><th>$server</th><td>$label</td><td style='color:$color;font-weight:bold;'>$status</td></tr>\n";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>IMAP Connection Check</title>
<style>
body { font-family: sans-serif; margin: 2em; }
table { border-collapse: collapse; width: 50%; }
th, td { padding: 8px 12px; border: 1px solid #ccc; }
th { background-color: #f4f4f4; }
</style>
</head>
<body>
<h1>IMAP Connection Status</h1>
<table>
<tr><th>Server</th><th>Connection Type</th><th>Status</th></tr>
<?php
foreach ($config['servers'] as $server) {
$sslOk = check_imap_ssl($server, $config['timeout']);
$tlsOk = check_imap_tls($server, $config['timeout']);
render_status($server, "IMAP over SSL (port 993)", $sslOk);
render_status($server, "IMAP with STARTTLS (port 143)", $tlsOk);
}
?>
</table>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment