/* php使用fsockopen实现异步
*
* @parem $url 网页地址 host 主机地址 * @parem $port 网址端口 默认80 * @parem $t 脚本请求时间 默认30s
* @parem $post_data post 请求参数
* @parem $exetime 异步任务执行时间(单位秒)
* @parem $debug 是否开启调试模式
*
*
*/
function request_by_fsockopen($url,$post_data=array(),$exetime = 1, $debug=false){
$url_array = parse_url($url);
$hostname = $url_array['host'];
$port = isset($url_array['port'])? $url_array['port'] : 80;
@$requestPath = $url_array['path'] ."?". $url_array['query'];
$fp = fsockopen($hostname, $port, $errno, $errstr, $exetime);
if (!$fp) {
echo "$errstr ($errno)";
return false;
}
stream_set_blocking($fp,0); //开启非阻塞模式
stream_set_timeout($fp, 3); //设置超时时间(s)
$method = "GET";
if(!empty($post_data)){
$method = "POST";
}
$header = "$method $requestPath HTTP/1.1\r\n";
$header.="Host: $hostname\r\n";
if(!empty($post_data)){
$_post = strval(NULL);
foreach($post_data as $k => $v){
$_post[]= $k."=".urlencode($v);//必须做url转码以防模拟post提交的数据中有&符而导致post参数键值对紊乱
}
$_post = implode('&', $_post);
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";//POST数据
$header .= "Content-Length: ". strlen($_post) ."\r\n";//POST数据的长度
$header.="Connection: Close\r\n\r\n";//长连接关闭
$header .= $_post; //传递POST数据
}else{
$header.="Connection: Close\r\n\r\n";//长连接关闭
}
fwrite($fp, $header);
usleep(300000); //等待300ms
//-----------------调试代码区间-----------------
// 注如果开启下面的注释,异步将不生效可是方便调试
if($debug){
$html = '';
while (!feof($fp)) {
$html.=fgets($fp);
}
echo $html;
}
//-----------------调试代码区间-----------------
fclose($fp);
}
/**
* 判断是否是HTTPS
*
*/
function isHTTPS()
{
if (defined('HTTPS') && HTTPS) return true;
if (!isset($_SERVER)) return FALSE;
if (!isset($_SERVER['HTTPS'])) return FALSE;
if ($_SERVER['HTTPS'] === 1) { //Apache
return TRUE;
} elseif ($_SERVER['HTTPS'] === 'on') { //IIS
return TRUE;
} elseif ($_SERVER['SERVER_PORT'] == 443) { //其他
return TRUE;
}
return FALSE;
}
ignore_user_abort(true); // 忽略客户端断开
set_time_limit(0); // 设置执行不超时 0允许最大运行时间
$url = (isHTTPS() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'].'/modules/addons/consumeridcims/createserverorfloatingip.php'; //获取域名
$vars = [
'orderId' => 375,
'userId' => 30,
'invoiceId' => 385,
];
// 调用fsockopen实现异步
request_by_fsockopen($url,$vars);