我經常在 PHP 文件中看到使用者沒有檢查 PHP 函式的回傳值,在 socket_write 的情況下,我沒有在這裡的評論中看到任何人費心去讀取伺服器在 socket 上的回覆。
然後有一位使用者認為在 SMTP 連線上的 socket_write 之後使用 usleep 會是一個好主意。
實際上,如果您檢查伺服器的回覆,不僅可以在您再次寫入 socket 之前給伺服器時間回覆,這也是一個檢查伺服器回覆內容的好機會。
例如,對於 SMTP 連線
在此範例中,MAIL_SERVER、MAIL_PORT 和 DEBUG 是我定義的常數。
<?php
function sendmail( $param )
{
$from = &$param[ 'from' ];
$to = &$param[ 'to' ];
$message = &$param[ 'data' ];
$isError = function( $string )
{
if( preg_match( '/^((\d)(\d{2}))/', $string, $matches ) )
{
if( $matches[ 2 ] == 4 || $matches[ 2 ] == 5 ) return( $matches[ 1 ] );
}
else
{
return( false );
}
};
try
{
$socket = null;
if( ( $socket = socket_create( AF_INET, SOCK_STREAM, SOL_TCP ) ) == false )
{
throw new Exception( sprintf( "Unable to create a socket: %s", socket_strerror( socket_last_error() ) ) );
}
if( !socket_connect( $socket, MAIL_SERVER, MAIL_PORT ) )
{
throw new Exception( sprintf( "Unable to connect to server %s: %s", MAIL_SERVER, socket_strerror( socket_last_error() ) ) );
}
$read = socket_read( $socket, 1024 );
if( $read == false )
{
throw new Exception( sprintf( "Unable to read from socket: %s", socket_strerror( socket_last_error() ) ) );
}
if( socket_write( $socket, sprintf( "HELO %s\r\n", gethostname() ) ) === false )
{
throw new Exception( sprintf( "Unable to write to socket: %s", socket_strerror( socket_last_error() ) ) );
}
$read = socket_read( $socket, 1024 );
if( $read == false )
{
throw new Exception( sprintf( "Unable to read from socket: %s", socket_strerror( socket_last_error() ) ) );
}
else
{
if( ( $errCode = $isError( $read ) ) ) throw new Exception( "Server responded with an error code $errCode" );
}
if( socket_write( $socket, sprintf( "MAIL FROM: %s\r\n", $from ) ) === false )
{
throw new Exception( sprintf( "Unable to write to socket: %s", socket_strerror( socket_last_error() ) ) );
}
$read = socket_read( $socket, 1024 );
if( $read == false )
{
throw new Exception( sprintf( "Unable to read from socket: %s", socket_strerror( socket_last_error() ) ) );
}
else
{
if( ( $errCode = $isError( $read ) ) ) throw new Exception( "Server responded with an error code $errCode" );
}
return( $totalWriten );
}
catch( Exception $e )
{
$ERROR = sprintf( "Error sending mail message at line %d. ", $e->getLine() ) . $e->getMessage();
return( false );
}
}