A verry simple HTTP webserver written in PHP
Run it in the shell with php <name of file> and test in in the browser with <server address>:8080/test
<?php
error_reporting(E_ALL ^ E_NOTICE);
$host_socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if(!$host_socket) die("Failed to start event server. socket_create: ". socket_strerror(socket_last_error())."\n");
if(! socket_set_option($host_socket, SOL_SOCKET, SO_REUSEADDR, 1) )
die("Failed to start event server. socket_set_option: ". socket_strerror(socket_last_error())."\n");
if(! socket_bind($host_socket,"0.0.0.0",8080) )
die("Failed to start event server. socket_bind: ". socket_strerror(socket_last_error())."\n");
if(! socket_listen($host_socket,10) )
die("Failed to start event server. socket_listen: ".socket_strerror(socket_last_error())."\n");
while (true) {
$read = array($host_socket);
$ready=@socket_select($read, $write = NULL, $except = NULL,0);
if ($ready=== false)
die("Failed to listen for clients: ". socket_strerror(socket_last_error()));
elseif($ready>0){
$newsocket = socket_accept($host_socket);
$input = socket_read($newsocket, 1024);
if($input){
unset($client_header);
$line=explode("\n",preg_replace('/[^A-Za-z0-9\-+\n :;=%*?.,\/_]/','',substr($input,0,2000)));
list($client_header["method"],$client_header["url"],$client_header["protocol"])=explode(" ",$line[0]);
unset($line[0]);
foreach($line as $l){
list($key,$val)=explode(": ",$l);
if($key) $client_header[strtolower($key)]=$val;
}
socket_getpeername($newsocket, $client_header['ip']);
$client_header+=(array)parse_url($client_header['url']);
parse_str($client_header['query'],$client_header['arg']);
print_r($client_header);
if(strpos($client_header['path'],".html") && file_exists(__DIR__.$client_header['path'])){
echo "Sending a HTML page to client\n";
socket_write($newsocket,"$client_header[protocol] 200 OK\r\n");
socket_write($newsocket,"Content-type: text/html; charset=utf-8\r\n\r\n");
socket_write($newsocket,file_get_contents(__DIR__.$client_header['path'])."\r\n\r\n");
socket_close($newsocket);
}elseif($client_header['path']=="/test"){
echo "Sending test HTML page to client\n";
socket_write($newsocket,"<!DOCTYPE HTML><html><head><html><body><h1>Its working!</h1>Have fun\r\n");
socket_write($newsocket,"<pre>Request header: ". print_r($client_header,true) . "</pre>\r\n");
socket_write($newsocket,"</body></html>\r\n\r\n");
socket_close($newsocket);
}else{
echo "$client_header[protocol] 404 Not Found\r\n";
socket_write($newsocket,"$client_header[protocol] 404 Not Found\r\n\r\n");
socket_close($newsocket);
}
}
}
}
socket_close($host_socket);
?>