PHP-CLI Web Server

Source: Internet
Author: User
Tags ranges
Requires pthreads extension
PHP command line mode run

Write more urgent, no time to optimize, there is time I will take a moment to optimize

From Source Address: http://www.haowei.me/archives/1009.html
  1. Ini_set (' display_errors ', false);
  2. error_reporting (0);
  3. if (!class_exists (' thread ')) {
  4. Logs (' PHP Runtime Environment not support multi thread ');
  5. Exit (0);
  6. }
  7. if (!function_exists (' Mime_content_type ')) {
  8. Logs (' PHP runtime Environment not support function Mime_content_type () ');
  9. Exit (0);
  10. }
  11. Class Pthread extends Thread {
  12. protected $socket = null;
  13. protected $arguments = null;
  14. protected $connections = 0;
  15. Protected $octet _stream = false;
  16. Public function __construct ($socket, $arguments = Array ()) {
  17. $this->socket = $socket;
  18. $this->arguments = $arguments;
  19. if (!isset ($this->arguments[' Servertokens '))
  20. $this->arguments[' servertokens '] = ' off ';
  21. }
  22. Public Function run () {
  23. Date_default_timezone_set (' UTC ');
  24. $clients = 1;
  25. $maxRequests =!isset ($this->arguments[' maxrequests ')?
  26. Intval ($this->arguments[' maxrequests '):
  27. 100;
  28. $timeout = 5;
  29. $CONNFD = socket_accept ($this->socket);
  30. Socket_set_option ($CONNFD, Sol_socket, So_rcvtimeo, Array (' sec ' = $timeout, ' usec ' = 0));
  31. $session = 1;
  32. while ($session) {
  33. $buffer = ";
  34. while ($buffer. = Socket_read ($CONNFD, 1024x768, Php_binary_read)))
  35. if (Strpos ($buffer, "\r\n\r\n")!== false) break;
  36. if ($buffer = = ") {
  37. Socket_close ($CONNFD);
  38. $session = 0;
  39. }else{
  40. $availableRequests = $maxRequests-$clients;
  41. $clients + +;
  42. $i = 0;
  43. $headers = Array ();
  44. Array_push ($headers, ' http/1.1 OK ');
  45. Array_push ($headers, ' Date: '. gmtdate ());
  46. Array_push ($headers, ' server:php-cli/1.0 ');
  47. Array_push ($headers, ' content-type:text/html; Charset=utf-8 ');
  48. Array_push ($headers, ' connection:close ');
  49. if ($this->arguments[' servertokens '] = = ' on ')
  50. $headers [2] = ' server:php-cli ';
  51. $buffer = Explode ("\ r \ n", $buffer);
  52. $http _user_agent = ";
  53. $http _request_method = ";
  54. $http _request_file = ";
  55. $http _protocol = ";
  56. $extension = ";
  57. $mime _types = ";
  58. $this->octet_stream = false;
  59. foreach ($buffer as $line) {
  60. $pattern = '/(get| POST) \s\/(. *) \s (http\/1\.[ 0-1]) $/';
  61. if (Preg_match ($pattern, $line)) {
  62. $http _request_method = preg_replace ($pattern, ' \\1 ', $line);
  63. $http _request_file = preg_replace ($pattern, ' \\2 ', $line);
  64. $http _protocol = preg_replace ($pattern, ' \\3 ', $line);
  65. }
  66. $pattern = '/^user\-agent: (. +) $/';
  67. if (Preg_match ($pattern, $line)) {
  68. $http _user_agent = preg_replace ($pattern, ' \\1 ', $line);
  69. }
  70. }
  71. $local _request_file = $this->arguments[' documentroot '). ' /'. $http _request_file;
  72. if (file_exists ($local _request_file) && is_file ($local _request_file))
  73. $extension = PathInfo ($local _request_file, pathinfo_extension);
  74. if (file_exists ($local _request_file)) {
  75. $array _key_exists = array_key_exists ($extension, $this->arguments[' mimetypes ');
  76. if (Is_file ($local _request_file)) {
  77. if ($array _key_exists) {
  78. $mime _types = $this->arguments[' mimetypes ' [$extension];
  79. $headers [3] = sprintf (' content-type:%s; charset=%s ', $mime _types, ' utf-8 ');
  80. }else{
  81. $this->octet_stream = true;
  82. $headers [3] = sprintf (' Content-type:application/octet-stream ');
  83. Array_push ($headers, ' accept-ranges:bytes ');
  84. Array_push ($headers, ' accept-length: '. FileSize ($local _request_file));
  85. Array_push ($headers, ' content-disposition:attachment; Filename= '. basename ($local _request_file));
  86. }
  87. }
  88. }
  89. $html = ";
  90. $code = ";
  91. $this->httpstatuscode ($local _request_file, $headers, $html, $code);
  92. if ($availableRequests > 0) {
  93. $headers [4] = "connection:keep-alive";
  94. $headers [5] = ' keep-alive:timeout= '. $timeout. ', max= '. $maxRequests;
  95. }
  96. $headers [6] = ' content-length: '. Strlen ($html);
  97. $response = Array (
  98. ' Header ' = Implode ("\ r \ n", $headers). "\ r \ n",
  99. ' html ' = $html);
  100. Socket_write ($CONNFD, implode ("\ r \ n", $response));
  101. if ($availableRequests <= 0) {
  102. Socket_close ($CONNFD);
  103. $session = 0;
  104. }
  105. $length = strlen ($html);
  106. Socket_getpeername ($CONNFD, $address, $port);
  107. Logs (sprintf ('%s:%.0f--"%s%s"%s%.0f "-" "%s" ',
  108. $address,
  109. $port,
  110. $http _request_method,
  111. '/'. $http _request_file,
  112. $http _protocol,
  113. $code,
  114. $length,
  115. $http _user_agent));
  116. Logs (' Times '. Intval ($clients-1), false);
  117. }
  118. }
  119. }
  120. Public Function Error_page ($statusCode, $ServerTokens) {
  121. $httpStatus = Array (' 403 ' = ' 403 Forbidden ', ' 404 ' = ' 404 Not Found ');
  122. $string = "
  123. %s
  124. %s

  125. %s
  126. ";
  127. if (!in_array ($ServerTokens, Array (' on ', ' Off ')))
  128. $ServerTokens = ' off ';
  129. Return (String) sprintf ($string,
  130. $httpStatus [$statusCode],
  131. $httpStatus [$statusCode],
  132. $ServerTokens = = ' off '? ' php-cli/1.0 ': ' php-cli ');
  133. }
  134. Public Function HttpStatusCode ($file, & $headers, & $html, & $code) {
  135. $code = ' 200 ';
  136. if (!file_exists ($file)) {
  137. $headers [0] = ' http/1.1 404 Not Found ';
  138. $html = $this->error_page (' 404 ', $this->arguments[' Servertokens ']);
  139. $code = ' 404 ';
  140. return 0;
  141. }
  142. if (Is_dir ($file)) {
  143. $find = false;
  144. $directoryIndex = $this->arguments[' DirectoryIndex ');
  145. if (empty ($directoryIndex)) {
  146. $headers [0] = ' http/1.1 403 Forbidden ';
  147. $code = ' 403 ';
  148. }else{
  149. $list = Explode (' ', $directoryIndex);
  150. foreach ($list as $index) {
  151. if (file_exists ($file. ' /'. $index)) {
  152. $file. = '/'. $index;
  153. if (file_exists ($file) && is_file ($file))
  154. $extension = PathInfo ($file, pathinfo_extension);
  155. $array _key_exists = array_key_exists ($extension, $this->arguments[' mimetypes ');
  156. if ($array _key_exists) {
  157. $mime _types = $this->arguments[' mimetypes ' [$extension];
  158. }else{
  159. $this->otect_stream = true;
  160. $headers [3] = sprintf (' Content-type:application/octet-stream ');
  161. Array_push ($headers, ' accept-ranges:bytes ');
  162. Array_push ($headers, ' accept-length: '. FileSize ($local _request_file));
  163. Array_push ($headers, ' content-disposition:attachment; Filename= '. basename ($local _request_file));
  164. }
  165. $find = true;
  166. Break
  167. }
  168. }
  169. }
  170. if (! $find) {
  171. $html = $this->error_page (' 403 ', $this->arguments[' Servertokens ']);
  172. }else{
  173. if (! $this->octet_stream)
  174. $headers [3] = sprintf (' content-type:%s; charset=%s ', $mime _types, ' utf-8 ');
  175. $html = $this->get_local_handle_buffer ($file);
  176. }
  177. return-1;
  178. }else{
  179. $html = $this->get_local_handle_buffer ($file);
  180. }
  181. return 1;
  182. }
  183. Public Function Get_local_handle_buffer ($file) {
  184. $handle = fopen ($file, ' RB ');
  185. return $this->get_buffer ($handle);
  186. }
  187. Public Function Get_buffer ($handle) {
  188. $buffer = ";
  189. if (!is_resource ($handle)) return null;
  190. while (!feof ($handle))
  191. $buffer. = Fgets ($handle, 1024);
  192. Fclose ($handle);
  193. return $buffer;
  194. }
  195. }
  196. function Gmtdate () {
  197. return (string) date (' d, D M Y h:i:s '). ' GMT ';
  198. }
  199. function logs ($string, $perfix = True) {
  200. Ob_start ();
  201. Echo $perfix?
  202. sprintf ("[%s]%s\n", date (' D-m-y h:i:s '), $string):
  203. sprintf ("\0\0[%s]\n", $string);
  204. Ob_end_flush ();
  205. }
  206. $mime _types = Array (
  207. ' htm ' = ' text/html ',
  208. ' html ' = ' text/html ',
  209. ' jpg ' = ' image/jpeg ',
  210. ' jpeg ' = ' image/jpeg ',
  211. ' png ' = ' image/png ',
  212. ' js ' = ' text/javascript ',
  213. ' CSS ' = ' text/css ',
  214. ' xml ' = ' text/xml ');
  215. $conf = Array (
  216. ' Mimetypes ' = $mime _types,
  217. ' Servertokens ' = ' on ',
  218. ' maxrequests ' = 100,
  219. ' Timeout ' = 15,
  220. ' Listen ' = 8080,
  221. ' DocumentRoot ' = '/home/www ',
  222. ' DirectoryIndex ' = ' index.htm index.html ');
  223. Error_reporting (E_all);
  224. Logs (' Initializing the Operating Environment ');
  225. Sleep (1);
  226. Set_time_limit (0);
  227. Logs (' Initializing php-cli execution timeout ');
  228. Sleep (1);
  229. $socket = Socket_create (Af_inet, Sock_stream, sol_tcp);
  230. Logs (' Initializing the socket ');
  231. Sleep (1);
  232. Logs (' initialization bind local address any IP address ');
  233. Sleep (1);
  234. $int = Socket_bind ($socket, ' 0.0.0.0 ', $conf [' Listen ']);
  235. Logs (' Initialization bind local port '. $conf [' Listen ']);
  236. if (! $int) {
  237. Logs ($conf [' Listen ']. ' Port is occupied by other services '. " \ n ");
  238. Exit (0);
  239. }
  240. Sleep (1);
  241. Socket_listen ($socket, 1024);
  242. Logs (' Opening a socket listening ');
  243. Sleep (1);
  244. Logs (' Waiting for clients to access ');
  245. echo "\ n";
  246. $i = 0;
  247. while (1) {
  248. $pthread [$i] = new Pthread ($socket, $conf);
  249. $pthread [$i]->start ();
  250. $pthread [$i]->join ();
  251. }
Copy Code
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.