php如何實作腳本非同步執行的方法具體分析

黄舟
發布: 2023-03-14 19:44:02
原創
1753 人瀏覽過

本文實例講述了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[&#39;host&#39;];
  $port = isset($url_array[&#39;port&#39;])? $url_array[&#39;port&#39;] : 80;
  @$requestPath = $url_array[&#39;path&#39;] ."?". $url_array[&#39;query&#39;];
  $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(&#39;&&#39;, $_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 = &#39;&#39;;
  while (!feof($fp)) {
  $html.=fgets($fp);
  }
  echo $html;
  }
  //-----------------调试代码区间-----------------
  fclose($fp);
}
$data=array(&#39;name&#39;=>&#39;guoyu&#39;,&#39;pwd&#39;=>&#39;123456&#39;);
$url=&#39;http://localhost/test/other.php&#39;;
request_by_fsockopen($url,$data,true);//
登入後複製

other.php


<?php
header("content-type:text/html;charset=utf-8");
//error_reporting(0);
//ini_set(&#39;html_errors&#39;,false);
//ini_set(&#39;display_errors&#39;,false);
$name = isset($_POST[&#39;name&#39;])?$_POST[&#39;name&#39;]:&#39;&#39;;
$pwd = isset($_POST[&#39;pwd&#39;])?$_POST[&#39;pwd&#39;]:&#39;&#39;;
echo $name.$pwd;
echo &#39;success ok&#39;;
die;
?>
登入後複製

使用實例:

$data=array(&#39;name&#39;=>&#39;guoyu&#39;,&#39;pwd&#39;=>&#39;123456&#39;);
$url=&#39;http://localhost/test/other.php&#39;;
request_by_fsockopen($url,$data,true);//把应用B的用户表异步-同步数据
登入後複製

[導步執行檔other.php]

在other.php中便可以用$_POST接收main.php提交過來的參數,從而進行下一步操作

以上是php如何實作腳本非同步執行的方法具體分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!