Function name: stream_socket_enable_crypto()
Applicable version: PHP 5 >= 5.1.0, PHP 7
Function Description: The stream_socket_enable_crypto() function is used to enable or disable encryption on an established socket connection.
Syntax: bool stream_socket_enable_crypto ( resource $stream , bool $enable , int $crypto_type [, resource $session_stream ] )
parameter:
Return value: Return true if encryption is enabled or disabled successfully; otherwise return false.
Example:
// 创建一个socket连接$socket = stream_socket_client('tcp://www.example.com:443', $errno, $errstr, 30); // 启用加密if (stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) { echo "加密已成功启用!\n"; } else { echo "无法启用加密!\n"; } // 发送加密的数据fwrite($socket, "Hello, encrypted world!"); // 关闭加密stream_socket_enable_crypto($socket, false); // 发送非加密的数据fwrite($socket, "Hello, world!"); // 关闭socket连接fclose($socket);
In the example above, we first use the stream_socket_client() function to create a TCP connection to port 443 of www.example.com. We then enable encryption using the stream_socket_enable_crypto() function and specify the encryption type to TLS client encryption. If encryption is enabled successfully, the output is "encrypted successfully enabled!", otherwise the output is "encrypted cannot be enabled!". Next, we use the fwrite() function to send the encrypted data. Then, we use the stream_socket_enable_crypto() function to disable encryption. Finally, we use the fwrite() function to send non-encrypted data and close the socket connection.