PHP-CLIWeb server-php Tutorial

Source: Internet
Author: User
PHP-CLIWeb server
Pthreads extension required
Php command line mode

Writing is urgent and there is no time to optimize it. I will take time to optimize it.

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, 1024, PHP_BINARY_READ )))
  35. If (strpos ($ buffer, "\ 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 200 OK ');
  45. Array_push ($ headers, 'date: '. gmtdate ());
  46. Array_push ($ headers, 'server: PHP-CLI/100 ');
  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 %. 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 ('20140901' => '20160901', '20160901' => '20160901' 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/123456': 'php-CLI ');
  133. }
  134. Public function HttpStatusCode ($ file, & $ headers, & $ html, & $ code ){
  135. $ Code = '000000 ';
  136. If (! File_exists ($ file )){
  137. $ Headers [0] = 'http/1.1 404 Not Found ';
  138. $ Html = $ this-> error_page ('20140901', $ this-> arguments ['servertokens']);
  139. $ Code = '000000 ';
  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 = '000000 ';
  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 ('20140901', $ 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. 'Metypes '=> $ mime_types,
  217. 'Servertokens' => 'on ',
  218. 'Maxrequests' => 100,
  219. 'Timeout' => 15,
  220. 'Listen' = & gt; 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. }

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.