Connection could not be established with host

最近重灌了工作用的筆電,把開發環境的 PHP 升級到 5.6.10,然後就各種狀況…..

其中一個問題是從本機連不上公司 mail server,所以寄信功能就掛掉了。Laravel log 的訊息如下

local.ERROR: 500 – Connection could not be established with host xxx.com.tw [ #0] @ /
exception ‘Swift_TransportException’ with message ‘Connection could not be established with host xxx.com.tw [ #0]’ in laravel/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php:270

原來是因為從 PHP 5.6 開始,變更了 SSL 認證的預設值,verify_peer 與 verify_peer_name 這兩項安全檢查都被改為預設,然後很多 SSL verification 就過不了。雖然提高安全性是好事,但開發環境卻造成一些困擾。

以上述的 swiftmailer 套件為例,它的 SSL 連線是用 stream_socket_client 實現的,其參數設置是透過 stream_context_create 傳入,所以設定方式如下:

$contextOptions = [
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false
    ]
];
$context = stream_context_create($contextOptions);
stream_socket_client(
    $host.':'.$port,
    $errno,
    $errstr,
    $timeout,
    STREAM_CLIENT_CONNECT,
    $context
);

如此一來就可以關閉檢查,終於可以連上 mail server 了。收工。


Posted

in

,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *