PHP反向代理类代码

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

使用方法

<?php
$proxy=new PhpReverseProxy();
$proxy->port="8080";
$proxy->host="www.jb51.net";
//$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;
 } 

}
?>
(0)

相关推荐

  • php curl抓取网页的介绍和推广及使用CURL抓取淘宝页面集成方法

    php的curl可以用来实现抓取网页,分析网页数据用, 简洁易用, 这里介绍其函数等就不详细描述, 放上代码看看: 只保留了其中几个主要的函数. 实现模拟登陆, 其中可能涉及到session捕获, 然后前后页面涉及参数提供形式. libcurl主要功能就是用不同的协议连接和沟通不同的服务器~也就是相当封装了的sock PHP 支持libcurl(允许你用不同的协议连接和沟通不同的服务器)., libcurl当前支持http, https, ftp, gopher, telnet, dict, f

  • PHP 反射机制实现动态代理的代码

    演示用代码如下所示:  复制代码 代码如下: <?php class ClassOne { function callClassOne() { print "In Class One"; } } class ClassOneDelegator { private $targets; function __construct() { $this->target[] = new ClassOne(); } function __call($name, $args) { fore

  • php采集中国代理服务器网的方法

    本文实例讲述了php采集中国代理服务器网的方法.分享给大家供大家参考.具体如下: <?php /** * 采集中国代理服务器网 最新列表 */ class proxy { /* 需采集列表 */ public $list; /* 代理列表 保存路径 */ public $save_path = 'proxy.txt'; /* 获取采集列表 */ function get_list($page) { $url = 'http://www.cnproxy.com/proxy(*).html'; //

  • PHP Curl模拟登录微信公众平台、新浪微博实例代码

    使用curl之前先打开curl配置,具体方式百度一下就知道,开启curl扩展.密码用md5加密,这是经过测试成功的,把用户跟密码改成你的就行了. 下面一段代码给大家介绍php使用curl模拟登录微信公众平台,具体代码如下所示: <?php //模拟微信登入 $cookie_file = tempnam('./temp','cookie'); $login_url = 'https://mp.weixin.qq.com/cgi-bin/login'; $pwd = md5("********

  • php在线代理转向代码

    复制代码 代码如下: <?php if ($_REQUEST['url']) { header('Location:http://bcd.allowed.org/0/?url='.base64_encode(strrev($_REQUEST['url']))); } else { echo "<form method='POST' action='proxy.php'> url:<input name='url' type='text' value=\"\&qu

  • php使用curl并发减少后端访问时间的方法分析

    本文实例讲述了php使用curl并发减少后端访问时间的方法.分享给大家供大家参考,具体如下: 在我们平时的程序中难免出现同时访问几个接口的情况,平时我们用curl进行访问的时候,一般都是单个.顺序访问,假如有3个接口,每个接口耗时500毫 秒那么我们三个接口就要花费1500毫秒了,这个问题太头疼了严重影响了页面访问速度,有没有可能并发访问来提高速度呢?今天就简单的说一下,利用 curl并发来提高页面访问速度, 1.老的curl访问方式以及耗时统计 <?php function curl_fetc

  • php使用curl通过代理获取数据的实现方法

    本文实例讲述了php使用curl通过代理获取数据的实现方法.分享给大家供大家参考,具体如下: $curl=curl_init(); curl_setopt($curl, CURLOPT_URL, "http://www.baidu.com/"); curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:20.0) Gecko/20100101 Firefox/20.0'); curl

  • php设计模式 Proxy (代理模式)

    代理,指的就是一个角色代表另一个角色采取行动,就象生活中,一个红酒厂商,是不会直接把红酒零售客户的,都是通过代理来完成他的销售业务.而客户,也不用为了喝红酒而到处找工厂,他只要找到厂商在当地的代理就行了,具体红酒工厂在那里,客户不用关心,代理会帮他处理. 代理模式,就是给某一对象提供代理对象,并由代理对象控制具体对象的引用. 代理模式涉及的角色: 抽象主题角色,声明了代理主题和真实主题的公共接口,使任何需要真实主题的地方都能用代理主题代替. 代理主题角色,含有真实主题的引用,从而可以在任何时候操

  • php中通过虚代理实现延迟加载的实现代码

    这货是从 Martin 大神的<企业应用架构模式>中学到的,辅助 PHP 动态语言的特性,可以比 Java 轻松很多的实现延迟加载(LazyLoad).基本原理是通过一个虚代理(Virtual Proxy)做占位符,一旦访问代理对象的某成员(方法或属性),加载就被触发. 不过我实现的这个版本有局限性: 只适用于对象,无法代理数组等基本数据类型(需要用 ArrayObject 一类的内置对象封装) 被代理之后,一些带有操作符重载性质的接口实现就失效了,例如 ArrayAccess 的索引器.It

  • PHP使用curl模拟post上传及接收文件的方法

    本文实例讲述了PHP使用curl模拟post上传及接收文件的方法.分享给大家供大家参考,具体如下: public function Action_Upload(){ $this->path_config(); exit(); $furl="@d:\develop\JMFrameworkWithDemo.rar"; $url= "http://localhost/DemoIndex/curl_pos/"; $this->upload_file_to_cdn

随机推荐