欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

php fsockopen利用服务器进行异步请求

shiping1 的头像
多数情况下,可能需要进行异步请求,fsockopen是一个不错的选择

下面参数进行详解,看代码吧:

 

  1. <?php     
  2. set_time_limit(300);  
  3. function thread($count=1) {     
  4.     for($i=0;$i<$count;$i++){     
  5.         $fp=fsockopen($_SERVER['HTTP_HOST'],80);   // $timeout // 创建连接时的超时时间  
  6.         // stream_set_blocking($fp, 0); // 阻塞模式 0 非阻塞, 1 阻塞  
  7.         stream_set_timeout($fp, 2); // 读取流时的超时时间  
  8.         fwrite($fp,"GET http://localhost/testphp/thread/thread2.php\r\n\r\n");   
  9.         $r = fgets($fp,1024); // 如果stream_set_blocking没有设置 读取$fp 阻塞, 不读取$fp 非阻塞 (ps:前提是stream_set_blocking没有设置,设置了就按stream_set_blocking所设置的值)  
  10.         $m = stream_get_meta_data($fp); // 返回现有 stream 的信息 $fp  
  11.         var_dump($m);  
  12.         fclose($fp);  
  13.         soc_log('nosocket'date("Y-m-d H:i:s", time()));     
  14.     }     
  15. }     
  16.     
  17. function soc_log($script,$start_time)     
  18.     {     
  19.     $fp = fopen($script.".log"'a+');     
  20.     fputs($fp'start time is ' . date("Y-m-d H:i:s", time()) . "\n");     
  21.     fclose($fp);     
  22. }     
  23.     
  24. thread(2);  
  25. // for($j=0;$j<5;$j++){  
  26.   // soc_log('nosocket', date("Y-m-d H:i:s", time()));     
  27.   // }     
  28.     
  29. ?>    

来自 http://blog.csdn.net/swweb/article/details/8752052



Web服务器执行一个PHP脚本,有时耗时很长才能返回执行结果,后面的脚本需要等待很长一段时间才能继续执行。如果想实现只简单触发耗时脚本的执行而不等待执行结果就直接执行下一步操作,可以通过fscokopen函数来实现或者Geanman实现,php异步处理。

  PHP支持socket编程,fscokopen函数返回一个到远程主机连接的句柄,可以像使用fopen返回的句柄一样,对它进行 fwrite、fgets、fread等操作。使用fsockopen连接到本地服务器,触发脚本执行,然后立即返回,不等待脚本执行完成,即可实现异步 执行PHP的效果。

test.php 代码如下:

$domain = “localhost”; // 或者您的域名
$url = ‘/test4.php’; // 异步请求的页面
$header = “POST $url HTTP/1.0\r\n”;
$header .= “Content-Type:application/x-www-form-urlencoded\r\n”;

$par = “email=zhangzenglun@163.com”;

$header .=”Content-Length:”.strlen($par).”\r\n\r\n”;
$fp = @fsockopen($domain,80,$errno,$errstr,30);
fputs($fp, $header.$par);
fclose($fp);

echo ‘send ok!’;

test4.php 代码如下

set_time_limit ( 0 );
ignore_user_abort ( true );//浏览器关闭之后还执行
$i = 0;
while ( $i ++ < 50 ) {
file_put_contents ( $i . ‘.php’, $_REQUEST['email'].$i);
sleep ( 3 );
}

执行: 访问 test.php 很快就返回 send ok! 说明 异步成功。

来自 http://luhuang.sinaapp.com/php-fsockopen/


 

例子

test.php

 代码如下复制代码

<?php


$domain = "localhost";
$url = '/platform_php_sdk/test4.php';
$header = "POST $url HTTP/1.0\r\n";
$header .= "Content-Type:application/x-www-form-urlencoded\r\n";

$par = "email=zhangzenglun@163.com";

$header .="Content-Length:".strlen($par)."\r\n\r\n";
$fp = @fsockopen($domain,80,$errno,$errstr,30);
fputs($fp, $header.$par);
fclose($fp);

echo 'send ok!';

?>

test4.php

 代码如下复制代码

<?php

set_time_limit ( 0 );
ignore_user_abort ( true );//浏览器关闭之后还执行
$i = 0;
while ( $i ++ < 50 ) {
file_put_contents ( $i . '.php', $_REQUEST['email'].$i);
sleep ( 3 );
}

?>

来自 http://www.111cn.net/phper/php-cy/63439.htm

php fsockopen 异步 post

发表于4年前(2012-05-09 10:21)   阅读(1041) | 评论(1) 2人收藏此文章, 我要收藏
0

yibu.php

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
$data["channel"]=1;
$data["mobile"]=2;
$data["gateway"]=3;
$data["isp"]=4;
$data["linkid"]=5;
$data["msg"]=6;
 
$post = http_build_query($data);
$len = strlen($post);
//发送
$host = "localhost";
$path = "/yibu2.php";
$fp = fsockopen( $host , 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)\n";
} else {
    
    $out = "POST $path HTTP/1.1\r\n";
    $out .= "Host: $host\r\n";
    $out .= "Content-type: application/x-www-form-urlencoded\r\n";
    $out .= "Connection: Close\r\n";
    $out .= "Content-Length: $len\r\n";
    $out .= "\r\n";
    $out .= $post."\r\n";
    // echo($out);
    fwrite($fp, $out);
    
    //实现异步把下面去掉
    // $receive = '';
    // while (!feof($fp)) {
        // $receive .= fgets($fp, 128);
    // }
    // echo "<br />".$receive;
    //实现异步把上面去掉
    
    fclose($fp);
}

 

yibu2.php

 

 

1
2
<?php
var_dump($_POST);


来自 http://my.oschina.net/zhuzhu0129/blog/56722



使用fsockopen发送post请求,实现邮件异步提醒,常用

 
浏览:1479 发布日期:2014/03/26 分类:技术分享
A在评论B的博客,B收到提醒,如果在留言入库的时候,再做一个邮件发送的操作,这会让B去等待很久,所以这里应该是异步的。想必大家对这个场景也不比较熟悉!
下面不多说,直接以邮件发送为例子,上代码。轻喷。
  1. function request_by_fsockopen($url,$post_data=array()){
  2.     $url_array = parse_url($url);
  3.     $hostname = $url_array['host'];
  4.     $port = isset($url_array['port'])? $url_array['port'] : 80; 
  5.     $requestPath = $url_array['path'] ."?". $url_array['query'];
  6.     $fp = fsockopen($hostname, $port, $errno, $errstr, 10);
  7.     if (!$fp) {
  8.         echo "$errstr ($errno)";
  9.         return false;
  10.     }
  11.     $method = "GET";
  12.     if(!empty($post_data)){
  13.         $method = "POST";
  14.     }
  15.     $header = "$method $requestPath HTTP/1.1\r\n";
  16.     $header.="Host: $hostname\r\n";
  17.     if(!empty($post_data)){
  18.         $_post = strval(NULL);
  19.         foreach($post_data as $k => $v){
  20.                 $_post[]= $k."=".urlencode($v);//必须做url转码以防模拟post提交的数据中有&符而导致post参数键值对紊乱
  21.         }
  22.         $_post = implode('&', $_post);
  23.         $header .= "Content-Type: application/x-www-form-urlencoded\r\n";//POST数据
  24.         $header .= "Content-Length: ". strlen($_post) ."\r\n";//POST数据的长度
  25.         $header.="Connection: Close\r\n\r\n";//长连接关闭
  26.         $header .= $_post; //传递POST数据
  27.     }else{
  28.         $header.="Connection: Close\r\n\r\n";//长连接关闭
  29.     }
  30.     fwrite($fp, $header);
  31.     //-----------------调试代码区间-----------------
  32.     /*$html = '';
  33.     while (!feof($fp)) {
  34.         $html.=fgets($fp);
  35.     }
  36.     echo $html;*/
  37.     //-----------------调试代码区间-----------------
  38.     fclose($fp);
  39.  }
  40.  
  41. $data = array(
  42.     'authId'=>'authcode',
  43.     'email'=>'mengkang@php.net',
  44.     'nickname'=>'周梦康',
  45.     'mailBody'=>'<h3>康哥 <span style="padding:15px">某某文章</span> 有新的留言</span></h3><p>周某人 < mengkang@php.net >在评论中说:</p><div style="border-radius: 4px;margin: 10px 0 10px;border: 1px dashed #BEB0B0;padding: 8px;background: #F0F0F0;">测试回复的内容</div><p><a href="http://m.cn/github/zhoumengkang/index.php?m=Blog&a=blog&id=21#floor26">点击链接查看</a></p>'
  46.     );
  47. echo microtime(),"\r\n";
  48. request_by_fsockopen('http://m.cn/github/zhoumengkang/index.php?m=Comment&a=sendEmail',$data);
  49. echo microtime();
复制代码
 
下面是邮件发送的代码,使用的是phpmail,添加了下请求时的验证,防止恶意请求
  1. class CommentAction{
  2.     //发送邮件之前的验证码
  3.     protected $authId = 'baf09ebd312758607e0b8601598eea74';
  4.     //简单的加密演示
  5.     protected function auth_encode($data){
  6.         return md5($data.'zmk');
  7.     }
  8.     public function sendEmail(){
  9.         //解码已编码的URL字符串
  10.         $data = array_map('urldecode',$_POST);
  11.         //安全处理做
  12.         //验证是不是我自己发送的,而非别人模拟发送的
  13.         if($this->auth_encode($data['authId']) != $this->authId){
  14.             return fasle;
  15.         }
  16.         $this->snyc_send($data);
  17.     }
  18.     protected function snyc_send($data){
  19.         new MailModel($data['email'],$data['nickname'],$data['mailBody'],$data['title']);
  20.     }
  21.  }
  22.  class MailModel {
  23.     protected $mail;
  24.     public function __construct($address,$nickname,$boby,$title=null) {
  25.         require_once(dirname(__FILE__).'/../library/phpmailer/class.phpmailer.php');
  26.         $this->mail = new PHPMailer(); //实例化
  27.         $this->mail->IsSMTP(); // 启用SMTP
  28.         $this->mail->Host = "smtp.exmail.qq.com"; //SMTP服务器
  29.         $this->mail->Port = 25;  //邮件发送端口
  30.         $this->mail->SMTPAuth   = true;  //启用SMTP认证
  31.         $this->mail->CharSet  = "UTF-8"; //字符集
  32.         $this->mail->Encoding = "base64"; //编码方式
  33.         $this->mail->Username = "i@mengkang.net";  //你的邮箱
  34.         $this->mail->Password = "xxx";  //你的密码
  35.         $this->mail->Subject = $title ? $title : '主人,北剅轩有人造访'; //邮件标题
  36.         $this->mail->From = "i@mengkang.net";  //发件人地址(也就是你的邮箱)
  37.         $this->mail->FromName = "周梦康";  //发件人姓名
  38.         $this->mail->AddAddress($address,$nickname);//添加收件人(地址,昵称)
  39.         $this->mail->IsHTML(true);
  40.         $this->mail->Body = $boby;//内容里面必须带博客的id链接
  41.         if(!$this->mail->Send()) {
  42.             echo "发送失败: " .$this->mail->ErrorInfo;
  43.         }
  44.     }
  45.  }
复制代码
 
我的博客原地址:http://mengkang.net/33.html
希望结交更多的phper~

来自 http://www.thinkphp.cn/topic/12402.html

 

普通分类: