php异步简单实现

php使用异步的一种简单的方法就是使用fsockopen了, 它可以实现把耗时的任务丢给另外一个程序执行, 以至于不用浏览器一直在转圈圈(也就是一直在加载)

可以先把代码复制去执行一遍是什么效果吧, 代码如下:

注意: 下面的debug参数若为true则为用为调试,开启调试可以看到异步的执行情况,但是失去异步的效果

主php文件main.php:

<?php
function request_by_fsockopen($url,$post_data=array(),$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, 10);
    if(!$fp){
        echo "$errstr ($errno)";
        return false;
    }
    $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);
    //-----------------调试代码区间-----------------
    //注如果开启下面的注释,异步将不生效可是方便调试
    if($debug){
        $html = '';
        while (!feof($fp)) {
            $html.=fgets($fp);
        }
        echo $html;
    }
    //-----------------调试代码区间-----------------
    fclose($fp);
}
$data=array('name'=>'guoyu','pwd'=>'123456');
$url='http://localhost/test/other.php';
request_by_fsockopen($url,$data,true);

要异步执行的文件other.php:

<?php
header("content-type:text/html;charset=utf-8");
//error_reporting(0);
//ini_set('html_errors',false);
//ini_set('display_errors',false);
$name = isset($_POST['name'])?$_POST['name']:'';
$pwd = isset($_POST['pwd'])?$_POST['pwd']:'';
echo $name.$pwd;
echo 'success ok';
die;

若也想看到异步执行的效果, 可以的other.php内用文件来保存$name和$pwd信息, 如果想让效果更明显, 还可以再other.php文件内加个睡眠函数让它睡上几秒, 此时可以看到运行main.php秒结束, 但其实other.php还在运行(睡眠), 然后几秒后多了个文件, 则说明异步执行成功

作业:

希望各位能自己去修改main.php, 让其更简洁, 以及去掉所谓的debug参数, 只剩异步的代码

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值