<?php /** * 異步 執行程序 * @param string $path 異步url 地址 * @param array $postData 傳遞的參數 * @param string $method 請求方式 * @param string $url 請求地址 * @return bool */ function request_asynchronous($path, $method = "POST", $postData = array(), $url = ''){ set_time_limit(0); //設置不限執行時間 ignore_user_abort(true); //忽略客戶端中斷 if(empty($path)){ return false; } if(!$url){ $host = $_SERVER['HTTP_HOST']; }else{ $arr = parse_url($url); $host = $arr['host']; } $port = 443;//80 $host = $port == 443 ? 'ssl://'.$host : $host; $errNo = 0; $errStr = ''; $timeout = 120; $fp = ''; if(function_exists('fsockopen')) { $fp = fsockopen($host, $port, $errNo, $errStr, $timeout); } elseif(function_exists('pfsockopen')) { $fp = pfsockopen($host, $port, $errNo, $errStr, $timeout); } elseif(function_exists('stream_socket_client')) { $fp = stream_socket_client($host.':'.$port, $errNo, $errStr, $timeout); } if (!$fp) { return false; } stream_set_blocking($fp, 0); //開啟非阻塞模式 stream_set_timeout($fp, 3); //設置超時時間(s) $date = []; if($postData) { //處理參數 foreach ($postData as $key => $value) { if(is_array($value)){ $date[$key] = serialize($value); }else{ $date[$key] = $value; } } } $query = $date ? http_build_query($date) : ''; if ($method == "GET") { $path .= "?".$query; } //http消息頭 $out = $method." ".$path." HTTP/1.1\r\n"; $out .= "HOST: ".$host."\r\n"; if ($method == "POST") { $out .= "Content-Length:".strlen($query)."\r\n"; } $out .= "Content-Type: application/x-www-form-urlencoded\r\n"; $out .= "Connection: Close\r\n\r\n"; //$out .= "Cookie: ".$cookie."\r\n\r\n"; if ($method == "POST") { $out .= $query; } fputs($fp, $out); //忽略執行結果 /*while (!feof($fp)) { echo fgets($fp, 128); }*/ usleep(5000); fclose($fp); return true; } //調用方式
request_asynchronous("/api/files/index",'GET');
?>