历史潮流浩浩荡荡,顺之则昌,逆之则亡。——孙中山

PHP使用fsockopen函数实现伪异步

编程语言 徐承恩 1982℃

WEB服务器端开发异步场景非常之多,比如说异步发送短信、邮件、处理根式各样的耗时任务等等,但PHP语言先天不足无法多线程。本篇文章徐叔主要介绍使用fsockopen函数来实现伪异步。

贴代码

/**
 * 异步POST请求
 * @param $url url地址
 * @param array $params 参数
 */
function async_post($url, $params = [])
{
    $url_arr = parse_url($url);
    $host = $url_arr['host'];
    $port = isset($url_arr['port']) ? $url_arr['port'] : 80;
    $path = $url_arr['path'];
    $query = isset($params) ? http_build_query($params) : '';
    $errno = 0;
    $errstr = '';
    $timeout = 60;
    $fp = fsockopen($host, $port, $errno, $errstr, $timeout);
    $out = "POST " . $path . " HTTP/1.1\r\n";
    $out .= "host:" . $host . "\r\n";
    $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 .= $query;
    fputs($fp, $out);
    fclose($fp);
}

使用案例

public function index()
    {

        $domains = [
            'zooo.cc',
            'dowerly.com',
            'razzleton.com',
            'd-dollar.cc',
            'pokeradv.com',
            'cryptostrategy.biz',
            'in-delhi.in',
            'hourdeposit.com',
            'asset-finance.com',
            'earntech.cc',
            'nvestyoutime.com',
            'safeumoney.com',
            'instaadpays.com',
            'profitbank.org',
            'cool-deposit.com',
            'cloudminingpool.com',
            'rmc-bank.com',
            'rubix-cube.cc',
            'bitpayingads.com',
            '3daypayout.net',
            'trustbitdeposit.com',
            'payhour.biz',
            'bitwallet.biz',
            'perfectbtc.com',
            'forexparadise.biz',
            'depositclub.biz',
            'coininvest.biz',
            'earndollar.biz',
            'rmc-bank.com',
            'us-income.com',
            'fxtrade.io',
            'bitz2u.com',
            'allerainvest.com',
            'cool-deposit.com',
            'hourfxprofit.co',
            'astoriaforex.com',
            'bluechiplab.com',
            'gradlux.com'
        ];

        $url = url('/admin/test/task',null,null,true);

        foreach ($domains as $domain){
            echo "爬取" . $domain. "监控图片...<br>";
            async_post($url,['domain' => $domain]);
        }

    }

 

转载请注明:思码老徐 » PHP使用fsockopen函数实现伪异步

喜欢 (3)