A Tiny Webserver in PHP

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php
set_time_limit(0);
	
//$dir = realpath(dirname(__FILE__) . '/../../') . '/samples/site/';
//$host = '127.0.0.1';
$host = '0.0.0.0';
$port = 8080;

$header_html = "HTTP/1.0 200 OK\r\nContent-type: text/html\r\nServer: MyWebServer 0.1 \r\n\r\n";
$header_plain = "HTTP/1.0 200 OK\r\nContent-type: text/plain\r\nServer: MyWebServer 0.1\r\n\r\n";
$header_css = "HTTP/1.0 200 OK\r\nContent-type: text/css\r\n\r\n";
$header_jpeg = "HTTP/1.0 200 OK\r\nContent-type: image/jpeg\r\n\r\n";
$header_png = "HTTP/1.0 200 OK\r\nContent-type: image/png\r\n\r\n";

$sock = socket_create(AF_INET, SOCK_STREAM, 0);
socket_bind($sock, $host, $port) or die("could not bind to address");
socket_listen($sock);

while(true)
{
	print "\MyWebServer v0.1 has started...\n Listening on... \n port: {$port} \n host: {$host}\n\nUse Control C (^C) To cancel MyWebServer\n";
		
		
	$client = socket_accept($sock);
	
	ob_start();
		phpinfo(); //If you want to server your php page, change this to require('path/to/your/file.php')
	$output = ob_get_clean();
		
	$fromClient = socket_read($client, 1024);
	
	socket_write($client, "MyWebServer Webserver Testing \n" . $output);
}

socket_close($sock);
?>