PHP编程实现脚本异步执行的方法
发布时间:2022-11-16 19:03:46 所属栏目:PHP教程 来源:互联网
导读: 本文实例讲述了php编程实现脚本异步执行的方法。分享给大家供大家参考php编程教程,具体如下:
php语言得用fsockopen()函数,实现脚本异步运行,代码如下
异步请求函数(用debug参数若为true则
php语言得用fsockopen()函数,实现脚本异步运行,代码如下
异步请求函数(用debug参数若为true则
本文实例讲述了php编程实现脚本异步执行的方法。分享给大家供大家参考php编程教程,具体如下: php语言得用fsockopen()函数,实现脚本异步运行,代码如下 异步请求函数(用debug参数若为true则为用为调试,开启调试可以看到异步的执行情况,但是失去异步的效果) 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; ?> 使用实例: [运行的main.php主脚本文件] $data=array('name'=>'guoyu','pwd'=>'123456'); $url='http://localhost/test/other.php'; request_by_fsockopen($url,$data,true);//把应用b的用户表异步-同步数据 [导步执行文件other.php] 在other.php中便可以用$_post接收main.php提交过来的参数,从而进行下一步操作 更多关于php相关内容感兴趣的读者可查看本站专题:《php socket用法总结》、《php网络编程技巧总结》、《php curl用法总结》、《php数组(array)操作技巧大全》、《php数据结构与算法教程》、《php程序设计算法总结》及《php字符串(string)用法总结》 希望本文所述对大家php程序设计有所帮助。 (编辑:重庆站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
站长推荐