PHP反向代理类代码


Posted in PHP onAugust 15, 2014

改自PHP Reverse Proxy PRP,修改了原版中的一些错误,支持了文件上传以及上传文件类型识别,支持指定IP,自适应SAE环境。

使用方法

<?php
$proxy=new PhpReverseProxy();
$proxy->port="8080";
$proxy->host="3water.com";
//$proxy->ip="1.1.1.1";
$proxy->forward_path="";
$proxy->connect();
$proxy->output();
?>

源代码

<?php
//Source Code: http://www.xiumu.org/technology/php-reverse-proxy-class.shtml
class PhpReverseProxy{
 public $publicBaseURL;
 public $outsideHeaders;
 public $XRequestedWith;
 public $sendPost;
 public $port,$host,$ip,$content,$forward_path,$content_type,$user_agent,
  $XFF,$request_method,$IMS,$cacheTime,$cookie,$authorization;
 private $http_code,$lastModified,$version,$resultHeader;
 const chunkSize = 10000;
 function __construct(){
  $this->version="PHP Reverse Proxy (PRP) 1.0";
  $this->port="8080";
  $this->host="127.0.0.1";
  $this->ip="";
  $this->content="";
  $this->forward_path="";
  $this->path="";
  $this->content_type="";
  $this->user_agent="";
  $this->http_code="";
  $this->XFF="";
  $this->request_method="GET";
  $this->IMS=false;
  $this->cacheTime=72000;
  $this->lastModified=gmdate("D, d M Y H:i:s",time()-72000)." GMT";
  $this->cookie="";
  $this->XRequestedWith = "";
  $this->authorization = "";
 }
 function translateURL($serverName) {
  $this->path=$this->forward_path.$_SERVER['REQUEST_URI'];
  if(IS_SAE)
   return $this->translateServer($serverName).$this->path;
  if($_SERVER['QUERY_STRING']=="")
   return $this->translateServer($serverName).$this->path;
  else
  return $this->translateServer($serverName).$this->path."?".$_SERVER['QUERY_STRING'];
 }
 function translateServer($serverName) {
  $s = empty($_SERVER["HTTPS"]) ? ''
   : ($_SERVER["HTTPS"] == "on") ? "s"
   : "";
  $protocol = $this->left(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
  if($this->port=="") 
   return $protocol."://".$serverName;
  else
   return $protocol."://".$serverName.":".$this->port;
 }
 function left($s1, $s2) {
  return substr($s1, 0, strpos($s1, $s2));
 }
 function preConnect(){
  $this->user_agent=$_SERVER['HTTP_USER_AGENT'];
  $this->request_method=$_SERVER['REQUEST_METHOD'];
  $tempCookie="";
  foreach ($_COOKIE as $i => $value) {
   $tempCookie=$tempCookie." $i=$_COOKIE[$i];";
  }
  $this->cookie=$tempCookie;
  if(empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
   $this->XFF=$_SERVER['REMOTE_ADDR'];
  } else {
   $this->XFF=$_SERVER['HTTP_X_FORWARDED_FOR'].", ".$_SERVER['REMOTE_ADDR'];
  }
 
 }
 function connect(){
  if(empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
   $this->preConnect();
   $ch=curl_init();
   if($this->request_method=="POST"){
    curl_setopt($ch, CURLOPT_POST,1);
 
    $postData = array();
    $filePost = false;
    $uploadPath = 'uploads/';
    if (IS_SAE)
      $uploadPath = SAE_TMP_PATH;
 
    if(count($_FILES)>0){
      if(!is_writable($uploadPath)){
        die('You cannot upload to the specified directory, please CHMOD it to 777.');
      }
      foreach($_FILES as $key => $fileArray){ 
        copy($fileArray["tmp_name"], $uploadPath . $fileArray["name"]);
        $proxyLocation = "@" . $uploadPath . $fileArray["name"] . ";type=" . $fileArray["type"];
        $postData = array($key => $proxyLocation);
        $filePost = true;
      }
    }
 
    foreach($_POST as $key => $value){
      if(!is_array($value)){
     $postData[$key] = $value;
      }
      else{
     $postData[$key] = serialize($value);
      }
    }
 
    if(!$filePost){
      //$postData = http_build_query($postData);
      $postString = "";
      $firstLoop = true;
      foreach($postData as $key => $value){
      $parameterItem = urlencode($key)."=".urlencode($value);
      if($firstLoop){
     $postString .= $parameterItem;
      }
      else{
     $postString .= "&".$parameterItem;
      }
      $firstLoop = false; 
      }
      $postData = $postString;
    }
 
    //echo print_r($postData);
 
    //curl_setopt($ch, CURLOPT_VERBOSE, 0);
    //curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
    $this->sendPost = $postData;
    //var_dump(file_exists(str_replace('@','',$postData['imgfile'])));exit;
    curl_setopt($ch, CURLOPT_POSTFIELDS,$postData);
    //curl_setopt($ch, CURLOPT_POSTFIELDS,file_get_contents($proxyLocation));
    //curl_setopt($ch, CURLOPT_POSTFIELDS,file_get_contents("php://input"));
   }
 
   //gets rid of mulitple ? in URL
   $translateURL = $this->translateURL(($this->ip)?$this->ip:$this->host);
   if(substr_count($translateURL, "?")>1){
     $firstPos = strpos($translateURL, "?", 0);
     $secondPos = strpos($translateURL, "?", $firstPos + 1);
     $translateURL = substr($translateURL, 0, $secondPos);
   }
 
   curl_setopt($ch,CURLOPT_URL,$translateURL);
 
   $proxyHeaders = array(
     "X-Forwarded-For: ".$this->XFF,
     "User-Agent: ".$this->user_agent,
     "Host: ".$this->host
   );
 
   if(strlen($this->XRequestedWith)>1){
     $proxyHeaders[] = "X-Requested-With: ".$this->XRequestedWith;
     //echo print_r($proxyHeaders);
   }
 
   curl_setopt($ch,CURLOPT_HTTPHEADER, $proxyHeaders);
 
   if($this->cookie!=""){
    curl_setopt($ch,CURLOPT_COOKIE,$this->cookie);
   }
   curl_setopt($ch,CURLOPT_FOLLOWLOCATION,false); 
   curl_setopt($ch,CURLOPT_AUTOREFERER,true); 
   curl_setopt($ch,CURLOPT_HEADER,true);
   curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
 
   $output=curl_exec($ch);
   $info = curl_getinfo( $ch );
   curl_close($ch);
   $this->postConnect($info,$output);
  }else {
   $this->lastModified=$_SERVER['HTTP_IF_MODIFIED_SINCE'];
   $this->IMS=true;
  }
 }
 function postConnect($info,$output){
  $this->content_type=$info["content_type"];
  $this->http_code=$info['http_code'];
  //var_dump($info);exit;
  if(!empty($info['last_modified'])){
   $this->lastModified=$info['last_modified'];
  }
  $this->resultHeader=substr($output,0,$info['header_size']);
  $content = substr($output,$info['header_size']);
 
  if($this->http_code=='200'){
   $this->content=$content;
  }elseif( ($this->http_code=='302' || $this->http_code=='301') && isset($info['redirect_url'])){
   $redirect_url = str_replace($this->host,$_SERVER['HTTP_HOST'],$info['redirect_url']);
   if (IS_SAE)
     $redirect_url = str_replace('http://fetchurl.sae.sina.com.cn/','',$info['redirect_url']);
   header("Location: $redirect_url");
   exit;
  }elseif($this->http_code=='404'){
   header("HTTP/1.1 404 Not Found");
   exit("HTTP/1.1 404 Not Found");
  }elseif($this->http_code=='500'){
   header('HTTP/1.1 500 Internal Server Error');
   exit("HTTP/1.1 500 Internal Server Error");
  }else{
   exit("HTTP/1.1 ".$this->http_code." Internal Server Error");
  }
 }
 
 function output(){
  $currentTimeString=gmdate("D, d M Y H:i:s",time());
  $expiredTime=gmdate("D, d M Y H:i:s",(time()+$this->cacheTime));
 
  $doOriginalHeaders = true;
  if($doOriginalHeaders){
    if($this->IMS){
     header("HTTP/1.1 304 Not Modified");
     header("Date: Wed, $currentTimeString GMT");
     header("Last-Modified: $this->lastModified");
     header("Server: $this->version");
    }else{
 
     header("HTTP/1.1 200 OK");
     header("Date: Wed, $currentTimeString GMT");
     header("Content-Type: ".$this->content_type);
     header("Last-Modified: $this->lastModified");
     header("Cache-Control: max-age=$this->cacheTime");
     header("Expires: $expiredTime GMT");
     header("Server: $this->version");
     preg_match("/Set-Cookie:[^\n]*/i",$this->resultHeader,$result);
     foreach($result as $i=>$value){
      header($result[$i]);
     }
     preg_match("/Content-Encoding:[^\n]*/i",$this->resultHeader,$result);
     foreach($result as $i=>$value){
      //header($result[$i]);
     }
     preg_match("/Transfer-Encoding:[^\n]*/i",$this->resultHeader,$result);
     foreach($result as $i=>$value){
      //header($result[$i]);
     }
     echo($this->content);
     /*
     if(stristr($this->content, "error")){
    echo print_r($this->sendPost);
     }
     */
    }
  }
  else{
    $headerString = $this->resultHeader; //string 
    $headerArray = explode("\n", $headerString);
    foreach($headerArray as $privHeader){
   header($privHeader);
    }
 
    if(stristr($headerString, "Transfer-encoding: chunked")){
   flush();
   ob_flush();
   $i = 0;
   $maxLen = strlen($this->content);
 
   while($i < $maxLen){
     $endChar = $i + self::chunkSize;
     if($endChar >= $maxLen){
    $endChar = $maxLen - 1;
     }
     $chunk = substr($this->content, $i, $endChar);
     $this->dump_chunk($chunk);
     flush();
     ob_flush();
     $i = $i + $endChar;
   }
    }
    else{
    echo($this->content);
    }
 
    //echo "header: ".print_r($headerArray);
    //header($this->resultHeader);
  }
 
 }
 
 
 function dump_chunk($chunk) {
   echo sprintf("%x\r\n", strlen($chunk));
   echo $chunk;
   echo "\r\n";
 }
 
 
 function getOutsideHeaders(){
   $headers = array();
   foreach ($_SERVER as $name => $value){ 
  if (substr($name, 0, 5) == 'HTTP_') { 
    $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5))))); 
    $headers[$name] = $value; 
  }elseif ($name == "CONTENT_TYPE") { 
    $headers["Content-Type"] = $value; 
  }elseif ($name == "CONTENT_LENGTH") { 
    $headers["Content-Length"] = $value; 
  }elseif(stristr($name, "X-Requested-With")) { 
    $headers["X-Requested-With"] = $value;
    $this->XRequestedWith = $value;
  }
   } 
 
   //echo print_r($headers);
 
   $this->outsideHeaders = $headers;
   return $headers;
 } 
 
}
?>
PHP 相关文章推荐
PHP安全配置
Oct 09 PHP
如何对PHP程序中的常见漏洞进行攻击(下)
Oct 09 PHP
php 静态变量的初始化
Nov 15 PHP
一个基于PDO的数据库操作类
Mar 24 PHP
php设计模式 State (状态模式)
Jun 26 PHP
PHP empty函数报错解决办法
Mar 06 PHP
php实现mysql备份恢复分卷处理的方法
Dec 26 PHP
PHP中使用BigMap实例
Mar 30 PHP
PHP.vs.JAVA
Apr 29 PHP
win10环境PHP 7 安装配置【教程】
May 09 PHP
Laravel 5.3 学习笔记之 安装
Aug 28 PHP
PHP实现微信退款功能
Oct 02 PHP
ThinkPHP中自定义目录结构的设置方法
Aug 15 #PHP
win7 64位系统 配置php最新版开发环境(php+Apache+mysql)
Aug 15 #PHP
php获取apk包信息的方法
Aug 15 #PHP
phpmyadmin出现Cannot start session without errors问题解决方法
Aug 14 #PHP
PHP解码unicode编码的中文字符代码分享
Aug 13 #PHP
使用ob系列函数实现PHP网站页面静态化
Aug 13 #PHP
PHP语法自动检查的Vim插件
Aug 11 #PHP
You might like
php自动获取目录下的模板的代码
2010/08/08 PHP
PHP 显示客户端IP与服务器IP的代码
2010/10/12 PHP
部署PHP项目应该注意的几点事项分享
2013/12/20 PHP
php字符串分割函数用法实例
2015/03/17 PHP
js点击更换背景颜色或图片的实例代码
2013/06/25 Javascript
js复制到剪切板的实例方法
2013/06/28 Javascript
JS小数运算出现多为小数问题的解决方法
2016/06/02 Javascript
Bootstrap3 datetimepicker控件使用实例
2016/12/13 Javascript
javascript实现table单元格点击展开隐藏效果(实例代码)
2017/04/10 Javascript
Vue2几种常见开局方式详解
2017/09/09 Javascript
微信小程序 功能函数小结(手机号验证*、密码验证*、获取验证码*)
2017/12/08 Javascript
promise和co搭配生成器函数方式解决js代码异步流程的比较
2018/05/25 Javascript
angular1.x ui-route传参的三种写法小结
2018/08/31 Javascript
你或许不知道的一些npm实用技巧
2019/07/04 Javascript
JavaScript实现随机五位数验证码
2019/09/27 Javascript
JavaScript Window窗口对象属性和使用方法
2020/01/19 Javascript
Vue + element 实现多选框组并保存已选id集合的示例代码
2020/06/03 Javascript
JQuery实现折叠式菜单的详细代码
2020/06/03 jQuery
[02:22]2018DOTA2亚洲邀请赛VG赛前采访
2018/04/03 DOTA
Python正则表达式教程之二:捕获篇
2017/03/02 Python
pandas中的DataFrame按指定顺序输出所有列的方法
2018/04/10 Python
Python3.5基础之变量、数据结构、条件和循环语句、break与continue语句实例详解
2019/04/26 Python
pandas取出重复数据的方法
2019/07/04 Python
python按比例随机切分数据的实现
2019/07/11 Python
python绘制规则网络图形实例
2019/12/09 Python
详解Python 中的 defaultdict 数据类型
2021/02/22 Python
纯CSS3实现滚动的齿轮动画效果
2014/06/05 HTML / CSS
北京银河万佳Java面试题
2012/03/21 面试题
日语专业毕业生自荐信
2013/11/11 职场文书
《菜园里》教学反思
2014/04/17 职场文书
党的群众路线教育实践活动学习计划
2014/11/03 职场文书
2016年教师节贺卡寄语
2015/12/04 职场文书
网络研修心得体会
2016/01/08 职场文书
闭幕词的写作格式与范文!
2019/06/24 职场文书
致创业您:正能量激励人心句子(48条)
2019/08/15 职场文书
Elasticsearch6.2服务器升配后的bug(避坑指南)
2022/09/23 Servers