Skip to content
PHP Logo

How can PHP sockets be utilized to monitor and record connection data effectively?

To monitor and record connection data effectively using PHP sockets, you can create a server script that listens for incoming connections, captures the data, and logs it to a file or database. This allows you to track and analyze connection information for further analysis or troubleshooting.

php
<?php
// Create a socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($socket, '127.0.0.1', 8888);
socket_listen($socket);

// Accept incoming connections
$client = socket_accept($socket);
$data = socket_read($client, 1024);

// Log the connection data
$logFile = 'connection_log.txt';
$logMessage = "Connection from: " . socket_getpeername($client) . " - Data: " . $data . PHP_EOL;
file_put_contents($logFile, $logMessage, FILE_APPEND);

// Close the socket
socket_close($client);
socket_close($socket);
?>