Skip to content

Instantly share code, notes, and snippets.

@ducin
Last active December 25, 2015 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ducin/6949618 to your computer and use it in GitHub Desktop.
Save ducin/6949618 to your computer and use it in GitHub Desktop.
PHP time server (example PHP server implementation). Run the server from command line, specifying port parameter and connect to it from outside (could be any platform that is able to open a socket or just a telnet connection: `telnet localhost <port>`). The server writes back current time in RFC 2822 and immediately closes the connection.
#!/usr/bin/php -q
<?php
set_time_limit(0);
ob_implicit_flush();
if ($argc != 2)
die("Simple Time Server (C) 2013 Tomasz Ducin\n" .
"Invalid parameters passed\n" .
"Run:\n\t./time-server.php <port>\n" .
"Example:\n\t./time-server.php 12345\n");
$address = 'localhost';
$port = $argv[1];
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false)
die(socket_strerror(socket_last_error()) . "\n");
if (socket_bind($sock, $address, $port) === false)
die(socket_strerror(socket_last_error($sock)) . "\n");
if (socket_listen($sock, 5) === false)
die(socket_strerror(socket_last_error($sock)) . "\n");
socket_set_nonblock($sock);
$remote_host = $remote_port = $msgsock = null;
declare(ticks = 1);
function sig_handler($signo)
{
switch ($signo) {
case SIGTERM:
case SIGINT:
// do your persistence here
global $sock;
socket_shutdown($sock);
socket_close($sock);
echo "Terminating...\n";
exit;
}
}
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGINT, "sig_handler");
echo "Starting server\n";
while (1) {
do {
$msgsock = @socket_accept($sock);
usleep(100000);
} while ($msgsock === false);
socket_getpeername($msgsock, $remote_host, $remote_port);
echo "Connection made from {$remote_host}:{$remote_port}\n";
$msg = date('r', time()) . "\n";
socket_write($msgsock, $msg, strlen($msg));
socket_close($msgsock);
};
socket_close($sock);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment