PHP异步

php

浏览数:277

2019-1-7

AD:资源代下载服务
function asyncSock($url, $post=array()) {
    $host = parse_url($url, PHP_URL_HOST);
    $port = parse_url($url, PHP_URL_PORT);
    $port = $port ? $port : 80;
    $scheme = parse_url($url, PHP_URL_SCHEME);
    $path = parse_url($url, PHP_URL_PATH);
    $query = parse_url($url, PHP_URL_QUERY);
    if($query) {
        $path .= '?'.$query;
    }
    if($scheme == 'https') {
        $host = 'ssl://'.$host;
    }
    
    $fp = fsockopen($host, $port, $error_code, $error_msg, 1);
    if (!$fp) {
        return array('error_code' => $error_code, 'error_msg' => $error_msg);
    } else {
        if(empty($post)){//GET
            $header  = "GET $path HTTP/1.1\r\n";
            $header .= "Host: $host\r\n";
            $header .= "Connection: close\r\n\r\n";//长连接关闭
        }else{//POST
            $post_data = http_build_query($post);
            $header  = "POST $path HTTP/1.1\r\n";
            $header .= "Host: $host\r\n";
            $header .= "Content-type: application/x-www-form-urlencoded\r\n";
            $header .= "Content-length:".strlen($post_data)."\r\n";
            $header .= "Connection:close\r\n\r\n";
            $header .= "${post_data}";
        }
        fwrite($fp, $header);
        // usleep(1000);
        fclose($fp);
        return array('error_code' => 0);
    }
}