1 <?php
2
3 //Accpet the http client request and generate response content.
4 //As a demo, this function just send "PHP HTTP Server" to client.
5 function handle_http_request($address, $port)
6 {
7 $max_backlog = 16;
8 $res_content = "HTTP/1.1 200 OK
9 Content-Length: 15
10 Content-Type: text/plain; charset=UTF-8
11
12 PHP HTTP Server";
13 $res_len = strlen($res_content);
14
15 //Create, bind and listen to socket
16 if(($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === FALSE)
17 {
18 echo "Create socket failed!\n";
19 exit;
20 }
21
22 if((socket_bind($socket, $address, $port)) === FALSE)
23 {
24 echo "Bind socket failed!\n";
25 exit;
26 }
27
28 if((socket_listen($socket, $max_backlog)) === FALSE)
29 {
30 echo "Listen to socket failed!\n";
31 exit;
32 }
33
34 //Loop
35 while(TRUE)
36 {
37 if(($accept_socket = socket_accept($socket)) === FALSE)
38 {
39 continue;
40 }
41 else
42 {
43 socket_write($accept_socket, $res_content, $res_len);
44 socket_close($accept_socket);
45 }
46 }
47 }
48
49 //Run as daemon process.
50 function run()
51 {
52 if(($pid1 = pcntl_fork()) === 0)
53 //First child process
54 {
55 posix_setsid(); //Set first child process as the session leader.
56
57 if(($pid2 = pcntl_fork()) === 0)
58 //Second child process, which run as daemon.
59 {
60 //Replaced with your own domain or address.
61 handle_http_request('www.codinglabs.org', 9999);
62 }
63 else
64 {
65 //First child process exit;
66 exit;
67 }
68 }
69 else
70 {
71 //Wait for first child process exit;
72 pcntl_wait($status);
73 }
74 }
75
76 //Entry point.
77 run();
78
79 ?>