Skip to content

Instantly share code, notes, and snippets.

@dam1r89
Created September 19, 2016 08:31
Show Gist options
  • Save dam1r89/345e7bba9d160095754760f2ec7c0847 to your computer and use it in GitHub Desktop.
Save dam1r89/345e7bba9d160095754760f2ec7c0847 to your computer and use it in GitHub Desktop.
#!/usr/local/bin/php -q
<?php
error_reporting(E_ALL);
session_start();
/* Allow the script to hang around waiting for connections. */
set_time_limit(0);
/* Turn on implicit output flushing so we see what we're getting
* as it comes in. */
ob_implicit_flush();
$address = 'localhost';
$port = 10020;
echo "Port http://$address:$port\n";
function handle($method, $path, $query, $headers)
{
}
function parse($req)
{
$headers = explode("\r\n", $req);
$requestLine = array_shift($headers);
$request = explode(' ', $requestLine);
$url = $request[1];
$queryString = parse_url($url, PHP_URL_QUERY);
$queryPath = parse_url($url, PHP_URL_PATH);
parse_str($queryString, $query);
return handle($request[0], $queryPath, $query, $headers);
}
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}
if (socket_bind($sock, $address, $port) === false) {
echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
if (socket_listen($sock, 5) === false) {
echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
do {
if (($msgsock = socket_accept($sock)) === false) {
echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
break;
}
// this method only handles GET requests
// (parse headers, not the body of the request)
$req = '';
do {
if (false === ($buf = @socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
break 2;
}
$req .= $buf;
if (substr($req, -4) == "\r\n\r\n") {
$talkback = parse($req);
socket_write($msgsock, $talkback, strlen($talkback));
echo $talkback . "\n";
break;
}
} while (true);
socket_close($msgsock);
} while (true);
socket_close($sock);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment