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

yipeiwu_com6年前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程序设计有所帮助。

相关文章

PHP 强制性文件下载功能的函数代码(任意文件格式)

复制代码 代码如下: /******************** *@file - path to file */ function force_download($file) { if...

PHP的简单跳转提示的实现详解

PHP的简单跳转提示的实现详解

在PHP开发中,尤其是MVC框架或者项目中,会碰到很多跳转情况,比如:登录成功或失败后的跳转等等。 以下以MVC框架开发中为基础,示例讲解: 在基础控制器类中:Conrtoller.cl...

php读取文件内容到数组的方法

本文实例讲述了php读取文件内容到数组的方法。分享给大家供大家参考。具体分析如下: php中可以通过file()函数将文件读取到数组中,数组中的元素即为文件的每行,file()函数通过"...

编写Smarty插件在模板中直接加载数据的详细介绍

之前使用smarty的时候,通常是在php程序端读取数据(一般从数据库),然后assign给模板的变量,才可以在前端使用这个变量。这样不是不好,只是数据多的时候php端的代码维护起来有点...

给apache2.2加上mod_encoding模块後 php5.2.0 处理url出现bug

这个问题是mod_encoding已经先一步处理了url ,而PHP又解了一次 例如 x.php?s=%252B%2F%2B%2F 那么$_GET['s']得到的是 +/&nb...