Current Location: Home> Function Categories> stream_socket_enable_crypto

stream_socket_enable_crypto

Turn on/off encryption on connected sockets
Name:stream_socket_enable_crypto
Category:Stream
Programming Language:php
One-line Description:Enable or disable encryption on an established socket connection

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:

  • $stream: Required, indicating the resource handle of the established socket connection.
  • $enable: Required, indicating whether encryption is enabled. If true, encryption is enabled; if false, encryption is disabled.
  • $crypto_type: Required, represents the encryption type, which can be one of the following constants:
    • STREAM_CRYPTO_METHOD_ANY: Default value, using any available encryption method.
    • STREAM_CRYPTO_METHOD_SSLv2_CLIENT: SSLv2 client encryption.
    • STREAM_CRYPTO_METHOD_SSLv3_CLIENT: SSLv3 client encryption.
    • STREAM_CRYPTO_METHOD_SSLv23_CLIENT: SSLv2, SSLv3 and TLSv1 client encryption.
    • STREAM_CRYPTO_METHOD_TLS_CLIENT: TLSv1 client encryption.
    • STREAM_CRYPTO_METHOD_SSLv2_SERVER: SSLv2 server encryption.
    • STREAM_CRYPTO_METHOD_SSLv3_SERVER: SSLv3 server encryption.
    • STREAM_CRYPTO_METHOD_SSLv23_SERVER: SSLv2, SSLv3 and TLSv1 server encryption.
    • STREAM_CRYPTO_METHOD_TLS_SERVER: TLSv1 server encryption.
  • $session_stream: optional, representing the resource handle used to encrypt the session.

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.

Similar Functions