温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在PHP项目中异步执行脚本

发布时间:2021-02-04 17:08:07 来源:亿速云 阅读:101 作者:Leah 栏目:开发技术

如何在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;
?>

使用实例:

[运行的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项目中异步执行脚本问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI