PHP가 스크립트의 비동기 실행을 구현하는 방법에 대한 자세한 분석

黄舟
풀어 주다: 2023-03-14 19:44:02
원래의
1753명이 탐색했습니다.

이 문서의 예에서는 PHP 프로그래밍을 통해 스크립트의 비동기 실행을 구현하는 방법을 설명합니다. 참조용으로 모든 사람과 공유하세요. 세부 사항은 다음과 같습니다.

PHP 언어는 스크립트의 비동기 실행을 구현하기 위해 fsockopen() 함수를 사용해야 합니다. 코드는 다음과 같습니다.

비동기 요청 함수(디버그 매개변수가 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;
?>
로그인 후 복사

사용 예:

[main.php 메인 스크립트 파일 실행]


$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 학습자의 빠른 성장을 도와주세요!