Current Location: Home> Latest Articles> socket_accept() + TLS implements encrypted data transmission (combined with OpenSSL extension)

socket_accept() + TLS implements encrypted data transmission (combined with OpenSSL extension)

M66 2025-06-01

In PHP, socket_accept() is used to accept client connections and implement TLS encrypted transmission in combination with OpenSSL extension, which is a common method to improve network communication security. This article will introduce how to use the native socket interface to cooperate with OpenSSL extensions to achieve encrypted TLS-based transmission.

1. Preparation

  1. Ensure PHP supports OpenSSL extensions <br> Check whether the openssl module is enabled via phpinfo() or the command line php -m .

  2. Prepare certificate and private key <br> You can use the OpenSSL command to generate a self-signed certificate, example:

     openssl req -newkey rsa:2048 -nodes -keyout server.key -x509 -days 365 -out server.crt
    
  3. Create a socket server <br> Use socket_create() and related functions to build a basic TCP server.

2. Sample code explanation

The following example demonstrates how to perform TLS handshake and encrypted communication through OpenSSL extension after accepting a client connection using socket_accept() .

 <?php

$host = '0.0.0.0';
$port = 8443;

// create TCP socket
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($sock, $host, $port);
socket_listen($sock);

echo "Server startup,monitor {$host}:{$port}\n";

// Loading certificate and private key path
$certFile = '/path/to/server.crt';
$keyFile = '/path/to/server.key';

// Waiting for client connection
while (true) {
    $clientSock = socket_accept($sock);
    if ($clientSock === false) {
        echo "Failed to accept connection\n";
        continue;
    }
    
    // create基于 socket of stream resource
    $clientStream = socket_export_stream($clientSock);
    
    // create SSL Context
    $context = stream_context_create([
        'ssl' => [
            'local_cert' => $certFile,
            'local_pk' => $keyFile,
            'allow_self_signed' => true,
            'verify_peer' => false,
        ]
    ]);
    
    // 将普通of TCP Connection upgrade to TLS Encrypted connection
    $sslStream = stream_socket_enable_crypto($clientStream, true, STREAM_CRYPTO_METHOD_TLS_SERVER);
    
    if (!$sslStream) {
        echo "TLS Handshake failed\n";
        fclose($clientStream);
        socket_close($clientSock);
        continue;
    }
    
    // Read client data
    $data = fread($clientStream, 8192);
    echo "Data received:$data\n";
    
    // Send a response
    fwrite($clientStream, "Hello from m66.net TLS server!\n");
    
    // Close the connection
    fclose($clientStream);
    socket_close($clientSock);
}

socket_close($sock);

3. Key points description

  1. socket_export_stream()
    This function converts socket resources into PHP stream resources, so that you can use stream_socket_enable_crypto() to perform TLS upgrade.

  2. stream_socket_enable_crypto()
    Responsible for TLS handshake and encryption startup. The third parameter selects the server mode ( STREAM_CRYPTO_METHOD_TLS_SERVER ) and enables encryption.

  3. Certificate configuration
    Pass the certificate and private key path in stream_context_create() . In the example, allow_self_signed and verify_peer settings are suitable for the test environment, and the formal environment should be validated.

  4. Data transmission <br> The subsequent data reading and writing are carried out through the encrypted stream, and the encryption and decryption are automatically completed.


4. Summary

Through socket_accept() and OpenSSL extension, PHP can flexibly implement TLS encrypted transmission to ensure data security. The key is to convert socket resources into stream, use stream_socket_enable_crypto() for encryption and upgrade, and combine it with effective certificate management to easily build a secure encrypted communication service.