欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  神坛PHP

异步执行文件

程序员文章站 2022-02-22 20:22:51
...

function asyncCurl($url, $data)

{

    if (is_array($data)) {

        $data = http_build_query($data, null, '&');

    }

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_POST, 1);

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    curl_setopt($ch, CURLOPT_TIMEOUT, 1);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $result['response'] = curl_exec($ch);

    $result['httpCode'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    return $result;

}


 

$url = "<http://127.0.0.1/exec.php>";

$data = [];

asyncCurl($url, $data);

echo "OK";



function sockPost($host, $url, $param)

{

    $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 = http_build_query($param);

    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 {

        stream_set_blocking($fp, 0);

        stream_set_timeout($fp, 10);

        $header = "GET $path" . "?" . "$query" . " HTTP/1.1\\r\\n";

        $header .= "Host: $host\\r\\n";

        $header .= "Connection: close\\r\\n\\r\\n";//长连接关闭

        fwrite($fp, $header);

        usleep(2000); // 延时,防止在nginx服务器上无法执行成功

        fclose($fp);

        return array('error_code' => 0);

    }

}

$host = "127.0.0.1";

$url = "/exec.php";

$param = [];

$result = sockPost($host, $url, $param);

var_dump($result);


相关标签: 异步 执行