찾다

pthreads 확장이 필요합니다
실행하려면 PHP 명령줄 모드

급하게 작성해서 최적화할 시간이 없습니다. 시간이 나면 최적화하겠습니다

来自源地址: 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 런타임 환경은 멀티 스레드를 지원하지 않습니다.');
  5. exit(0);
  6. }
  7. if(!function_exists('mime_content_type')) {
  8. 로그('PHP 런타임 환경은 mime_content_type() 함수를 지원하지 않습니다.');
  9. exit(0);
  10. }
  11. class pthread 확장 스레드 {
  12. protected $ 소켓 = null;
  13. protected $arguments = null;
  14. protected $connections = 0;
  15. protected $octet_stream = false;
  16. 공용 함수 __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. 공용 함수 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('초' => $timeout, 'usec' => 0));
  31. $session = 1;
  32. while($session) {
  33. $buffer = '';
  34. while (( $buffer .= 소켓_read ($connfd, 1024, PHP_BINARY_READ) ))
  35. if(strpos($buffer, "rnrn") !== false) break;
  36. if($buffer == '') {
  37. 소켓_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, '날짜: '.gmtdate());
  46. array_push($headers, '서버: PHP-CLI/1.0');
  47. array_push($headers, 'Content-Type: text/html; charset=utf-8');
  48. array_push($headers, ' 연결: 닫음');
  49. if($this->arguments['ServerTokens'] == 'on')
  50. $headers[2] = '서버: PHP-CLI';
  51. $buffer = 폭발("rn", $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($ 패턴, '\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->인수['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] = "연결: 연결 유지";
  94. $headers[5] = '연결 유지: timeout='.$timeout.', max='.$maxRequests;
  95. }
  96. $headers[6] = '콘텐츠 길이: '. strlen($html);
  97. $response = array(
  98. 'header'=> implode("rn", $headers) . "rn",
  99. 'html'=> $html);
  100. socket_write($connfd, implode("rn", $response));
  101. if($availableRequests socket_close($connfd);
  102. $session = 0;
  103. }
  104. $length = strlen($html);
  105. 소켓_getpeername($connfd, $address, $port);
  106. 로그(sprintf('%s:%.0f -- " %s %s %s" %s %.0f "-" "%s"',
  107. $address,
  108. $port,
  109. $http_request_method,
  110. '/'.$http_request_file,
  111. $http_protocol,
  112. $code,
  113. $length,
  114. $http_user_agent));
  115. //logs('times '.intval($clients - 1), false);
  116. }
  117. }
  118. }
  119. 공개 함수 error_page($statusCode, $ServerTokens) {
  120. $httpStatus = array('403'=> '403 금지됨' , '404'=> '404 찾을 수 없음');
  121. $string = "
  122. %s
  123. %s

  124. %s< ;/center>
  125. ";
  126. if(!in_array($ServerTokens, array('on', 'off')))
  127. $ServerTokens = 'off';
  128. 반환(문자열) sprintf($string,
  129. $httpStatus[$statusCode],
  130. $httpStatus[$statusCode],
  131. $ServerTokens == '끄다' ? 'PHP-CLI/1.0' : 'PHP-CLI');
  132. }
  133. 공개 함수 HttpStatusCode($file, &$headers, &$html, &$code) {
  134. $code = '200';
  135. if(!file_exists($file)) {
  136. $headers[0] = 'HTTP/1.1 404 찾을 수 없음';
  137. $html = $this ->error_page('404', $this->arguments['ServerTokens']);
  138. $code = '404';
  139. return 0;
  140. }
  141. if( is_dir($file)){
  142. $find = false;
  143. $directoryIndex = $this->arguments['DirectoryIndex'];
  144. if(empty($directoryIndex)) {
  145. $headers [0] = 'HTTP/1.1 403 금지됨';
  146. $code = '403';
  147. }else{
  148. $list = 폭발(' ', $directoryIndex);
  149. foreach($list as $index) {
  150. if(file_exists($file .'/'. $index)) {
  151. $file .= '/'. $index;
  152. if(file_exists($file) && is_file($file))
  153. $extension = pathinfo($file, PATHINFO_EXTENSION);
  154. $array_key_exists = array_key_exists($extension, $this-> 인수['MimeTypes']);
  155. if($array_key_exists) {
  156. $mime_types = $this->arguments['MimeTypes'][$extension];
  157. }else{
  158. $this ->otect_stream = true;
  159. $headers[3] = sprintf('Content-Type: application/octet-stream');
  160. array_push($headers, 'Accept-Ranges: bytes');
  161. array_push($headers, 'Accept-Length: '.filesize($local_request_file));
  162. array_push($headers, 'Content-Disposition: attachment; filename='.basename($local_request_file));
  163. }
  164. $find = true;
  165. break;
  166. }
  167. }
  168. }
  169. if(!$find) {
  170. $html = $this->error_page ('403', $this->arguments['ServerTokens']);
  171. }else{
  172. if(!$this->octet_stream)
  173. $headers[3] = sprintf('Content -유형: %s; charset=%s', $mime_types, 'utf-8');
  174. $html = $this->get_local_handle_buffer($file);
  175. }
  176. 반환 -1;
  177. }else{
  178. $html = $this->get_local_handle_buffer($file);
  179. }
  180. return 1;
  181. }
  182. 공용 함수 get_local_handle_buffer($file) {
  183. $handle = fopen($file, 'rb');
  184. return $this->get_buffer($handle);
  185. }
  186. 공용 함수 get_buffer($handle) {
  187. $buffer = '';
  188. if(!is_resource($handle)) return null;
  189. while(!feof($handle) )
  190. $buffer .= fgets($handle, 1024);
  191. fclose($handle);
  192. return $buffer;
  193. }
  194. }
  195. 함수 gmtdate() {
  196. (문자열) date('D, d M Y H:i:s')를 반환합니다. ' GMT';
  197. }
  198. 함수 로그($string, $perfix = true) {
  199. ob_start();
  200. echo $perfix ?
  201. sprintf("[ %s ] %sn", date('d-M-Y H:i:s'), $string) :
  202. sprintf(" [ %s ]n", $string);
  203. ob_end_flush();
  204. }
  205. $mime_types = array(
  206. 'htm'=> 'text/html',
  207. 'html'=> 'text/html',
  208. 'jpg'=> 'image/jpeg',
  209. 'jpeg'=> 'image/jpeg',
  210. 'png'=> 'image/png',
  211. 'js'=> ,
  212. 'css'=> 'text/css',
  213. 'xml'=> 'text/xml');
  214. $conf = array(
  215. 'MimeTypes'= > $mime_types,
  216. 'ServerTokens'=> 'on',
  217. 'MaxRequests'=> 100,
  218. 'Timeout'=> ,
  219. 'DocumentRoot'=> '/home/www',
  220. 'DirectoryIndex'=> 'index.htm index.html');
  221. error_reporting(E_ALL);
  222. logs('운영 환경 초기화');
  223. sleep(1);
  224. set_time_limit(0);
  225. logs('PHP-CLI 실행 시간 초과 초기화');
  226. sleep(1 );
  227. $socket = 소켓_create(AF_INET, SOCK_STREAM, SOL_TCP);
  228. logs('소켓 초기화 중');
  229. sleep(1);
  230. logs('초기화 로컬 주소를 모든 IP 주소에 바인딩');
  231. sleep(1);
  232. $int = 소켓_bind($socket, '0.0.0.0', $conf['Listen']);
  233. logs ('초기화 바인드 로컬 포트 ​​'.$conf['Listen']);
  234. if(!$int){
  235. logs($conf['Listen'].' 포트가 다른 서비스에 의해 사용되고 있습니다.'" n");
  236. exit(0);
  237. }
  238. sleep(1);
  239. socket_listen($socket, 1024);
  240. logs('소켓 열기 듣기') ;
  241. sleep(1);
  242. logs('클라이언트 액세스 대기 중');
  243. echo "n";
  244. $i = 0;
  245. while( 1) {
  246. $pthread[$i] = new pthread($socket, $conf);
  247. $pthread[$i]->start();
  248. $pthread[$i]-> ;join();
  249. }
复代码

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
PHP와 Python : 다른 패러다임이 설명되었습니다PHP와 Python : 다른 패러다임이 설명되었습니다Apr 18, 2025 am 12:26 AM

PHP는 주로 절차 적 프로그래밍이지만 객체 지향 프로그래밍 (OOP)도 지원합니다. Python은 OOP, 기능 및 절차 프로그래밍을 포함한 다양한 패러다임을 지원합니다. PHP는 웹 개발에 적합하며 Python은 데이터 분석 및 기계 학습과 같은 다양한 응용 프로그램에 적합합니다.

PHP와 Python : 그들의 역사에 깊은 다이빙PHP와 Python : 그들의 역사에 깊은 다이빙Apr 18, 2025 am 12:25 AM

PHP는 1994 년에 시작되었으며 Rasmuslerdorf에 의해 개발되었습니다. 원래 웹 사이트 방문자를 추적하는 데 사용되었으며 점차 서버 측 스크립팅 언어로 진화했으며 웹 개발에 널리 사용되었습니다. Python은 1980 년대 후반 Guidovan Rossum에 의해 개발되었으며 1991 년에 처음 출시되었습니다. 코드 가독성과 단순성을 강조하며 과학 컴퓨팅, 데이터 분석 및 기타 분야에 적합합니다.

PHP와 Python 중에서 선택 : 가이드PHP와 Python 중에서 선택 : 가이드Apr 18, 2025 am 12:24 AM

PHP는 웹 개발 및 빠른 프로토 타이핑에 적합하며 Python은 데이터 과학 및 기계 학습에 적합합니다. 1.PHP는 간단한 구문과 함께 동적 웹 개발에 사용되며 빠른 개발에 적합합니다. 2. Python은 간결한 구문을 가지고 있으며 여러 분야에 적합하며 강력한 라이브러리 생태계가 있습니다.

PHP 및 프레임 워크 : 언어 현대화PHP 및 프레임 워크 : 언어 현대화Apr 18, 2025 am 12:14 AM

PHP는 현대화 프로세스에서 많은 웹 사이트 및 응용 프로그램을 지원하고 프레임 워크를 통해 개발 요구에 적응하기 때문에 여전히 중요합니다. 1.PHP7은 성능을 향상시키고 새로운 기능을 소개합니다. 2. Laravel, Symfony 및 Codeigniter와 같은 현대 프레임 워크는 개발을 단순화하고 코드 품질을 향상시킵니다. 3. 성능 최적화 및 모범 사례는 응용 프로그램 효율성을 더욱 향상시킵니다.

PHP의 영향 : 웹 개발 및 그 이상PHP의 영향 : 웹 개발 및 그 이상Apr 18, 2025 am 12:10 AM

phphassignificallyimpactedwebdevelopmentandextendsbeyondit

스칼라 유형, 반환 유형, 노조 유형 및 무효 유형을 포함한 PHP 유형의 힌트 작업은 어떻게 작동합니까?스칼라 유형, 반환 유형, 노조 유형 및 무효 유형을 포함한 PHP 유형의 힌트 작업은 어떻게 작동합니까?Apr 17, 2025 am 12:25 AM

PHP 유형은 코드 품질과 가독성을 향상시키기위한 프롬프트입니다. 1) 스칼라 유형 팁 : PHP7.0이므로 int, float 등과 같은 기능 매개 변수에 기본 데이터 유형을 지정할 수 있습니다. 2) 반환 유형 프롬프트 : 기능 반환 값 유형의 일관성을 확인하십시오. 3) Union 유형 프롬프트 : PHP8.0이므로 기능 매개 변수 또는 반환 값에 여러 유형을 지정할 수 있습니다. 4) Nullable 유형 프롬프트 : NULL 값을 포함하고 널 값을 반환 할 수있는 기능을 포함 할 수 있습니다.

PHP는 객체 클로닝 (클론 키워드) 및 __clone 마법 방법을 어떻게 처리합니까?PHP는 객체 클로닝 (클론 키워드) 및 __clone 마법 방법을 어떻게 처리합니까?Apr 17, 2025 am 12:24 AM

PHP에서는 클론 키워드를 사용하여 객체 사본을 만들고 \ _ \ _ Clone Magic 메소드를 통해 클로닝 동작을 사용자 정의하십시오. 1. 복제 키워드를 사용하여 얕은 사본을 만들어 객체의 속성을 복제하지만 객체의 속성은 아닙니다. 2. \ _ \ _ 클론 방법은 얕은 복사 문제를 피하기 위해 중첩 된 물체를 깊이 복사 할 수 있습니다. 3. 복제의 순환 참조 및 성능 문제를 피하고 클로닝 작업을 최적화하여 효율성을 향상시키기 위해주의를 기울이십시오.

PHP vs. Python : 사용 사례 및 응용 프로그램PHP vs. Python : 사용 사례 및 응용 프로그램Apr 17, 2025 am 12:23 AM

PHP는 웹 개발 및 컨텐츠 관리 시스템에 적합하며 Python은 데이터 과학, 기계 학습 및 자동화 스크립트에 적합합니다. 1.PHP는 빠르고 확장 가능한 웹 사이트 및 응용 프로그램을 구축하는 데 잘 작동하며 WordPress와 같은 CMS에서 일반적으로 사용됩니다. 2. Python은 Numpy 및 Tensorflow와 같은 풍부한 라이브러리를 통해 데이터 과학 및 기계 학습 분야에서 뛰어난 공연을했습니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.