当前位置:Gxlcms > PHP教程 > PHP实现脚本异步执行的方法

PHP实现脚本异步执行的方法

时间:2021-07-01 10:21:17 帮助过:17人阅读

这篇文章主要介绍了PHP编程实现脚本异步执行的方法,结合实例形式分析了php使用fsockopen()实现的脚本异步调用与执行操作技巧,需要的朋友可以参考下

具体如下:

php语言得用fsockopen()函数,实现脚本异步运行,代码如下

异步请求函数(用debug参数若为true则为用为调试,开启调试可以看到异步的执行情况,但是失去异步的效果)

main.php

  1. <?php
  2. function request_by_fsockopen($url,$post_data=array(),$debug=false){
  3. $url_array = parse_url($url);
  4. $hostname = $url_array['host'];
  5. $port = isset($url_array['port'])? $url_array['port'] : 80;
  6. @$requestPath = $url_array['path'] ."?". $url_array['query'];
  7. $fp = fsockopen($hostname, $port, $errno, $errstr, 10);
  8. if (!$fp) {
  9. echo "$errstr ($errno)";
  10. return false;
  11. }
  12. $method = "GET";
  13. if(!empty($post_data)){
  14. $method = "POST";
  15. }
  16. $header = "$method $requestPath HTTP/1.1\r\n";
  17. $header.="Host: $hostname\r\n";
  18. if(!empty($post_data)){
  19. $_post = strval(NULL);
  20. foreach($post_data as $k => $v){
  21. $_post[]= $k."=".urlencode($v);//必须做url转码以防模拟post提交的数据中有&符而导致post参数键值对紊乱
  22. }
  23. $_post = implode('&', $_post);
  24. $header .= "Content-Type: application/x-www-form-urlencoded\r\n";//POST数据
  25. $header .= "Content-Length: ". strlen($_post) ."\r\n";//POST数据的长度
  26. $header.="Connection: Close\r\n\r\n";//长连接关闭
  27. $header .= $_post; //传递POST数据
  28. }else{
  29. $header.="Connection: Close\r\n\r\n";//长连接关闭
  30. }
  31. fwrite($fp, $header);
  32. //-----------------调试代码区间-----------------
  33. //注如果开启下面的注释,异步将不生效可是方便调试
  34. if($debug){
  35. $html = '';
  36. while (!feof($fp)) {
  37. $html.=fgets($fp);
  38. }
  39. echo $html;
  40. }
  41. //-----------------调试代码区间-----------------
  42. fclose($fp);
  43. }
  44. $data=array('name'=>'guoyu','pwd'=>'123456');
  45. $url='http://localhost/test/other.php';
  46. request_by_fsockopen($url,$data,true);//

other.php

  1. <?php
  2. header("content-type:text/html;charset=utf-8");
  3. //error_reporting(0);
  4. //ini_set('html_errors',false);
  5. //ini_set('display_errors',false);
  6. $name = isset($_POST['name'])?$_POST['name']:'';
  7. $pwd = isset($_POST['pwd'])?$_POST['pwd']:'';
  8. echo $name.$pwd;
  9. echo 'success ok';
  10. die;
  11. ?>

使用实例:

[运行的main.php主脚本文件]

  1. $data=array('name'=>'guoyu','pwd'=>'123456');
  2. $url='http://localhost/test/other.php';
  3. request_by_fsockopen($url,$data,true);//把应用B的用户表异步-同步数据

[导步执行文件other.php]

在other.php中便可以用$_POST接收main.php提交过来的参数,从而进行下一步操作

相关推荐:

php如何实现脚本异步执行的方法具体分析

PHP语言实现脚本异步执行

PHP语言实现脚本异步执行_PHP教程

以上就是PHP实现脚本异步执行的方法的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行