search
HomeBackend DevelopmentPHP TutorialPublish a HTTP download class written with PHP fsockopen_PHP Tutorial

Publish a HTTP download class written with PHP fsockopen_PHP Tutorial

Jul 21, 2016 pm 03:57 PM
fsockopenhttpphpdownloadcontentreleaseOpensupportuseofkindRemotelyOptions

If the option to open remote content is supported, PHP can actually obtain the content of a web page using fopen or file_get_contents. However, the default function has a shortcoming that it cannot obtain the HTTP header, which is very inconvenient in some special applications. For example, there is a link:

http://www.abc.com/showvd.asp?id=18

If it returns an image, it will be difficult to identify using the default function , but it is much simpler to judge by the HTTP response header. In addition, if the other party uses Refer to prevent hot links, it will not be obtained. Using the HTTP class can perfectly solve these problems, and the speed is almost the same.


Usage:

$hd = new DedeHttpDown();
$hd->OpenUrl("http://www.dedecms.com");
echo $hd->GetHtml();
//If saving as a file, use $hd->SaveBin("dede.html");
$hd->Close();

Get the http request header with
$hd->GetHead("key")
Set the request header
$hd->SetHead(key, value); (must be called after OpenUrl Previously set)


The code is as follows:


/* -------------------------- --------------------------------------------------
//Dream Weaving HTTP Download Class V1.0
//From: Dream Weaving Journey http://www.dedecms.com
//Author: IT Plato
//Time: 2005- 11-13 12:39
//Statement: First published on the Left Behind website, please retain the copyright information when reprinting
----------------------- ----------------------------------------------- */
class DedeHttpDown
{
var $m_url = "";
var $m_urlpath = "";
var $m_scheme = "http";
var $m_host = " ";
var $m_port = "80";
var $m_user = "";
var $m_pass = "";
var $m_path = "/";
var $m_query = "";
var $m_fp = "";
var $m_error = "";
var $m_httphead = "";
var $m_html = "";
var $m_puthead = "";
var $BaseUrlPath = "";
var $HomeUrl = "";
var $JumpCount = 0;//Prevent multiple redirects from falling into an infinite loop
// Initialization system
//
function PrivateInit($url)
{
if($url=="") return ;
$urls = "";
$urls = @parse_url( $url);
$this->m_url = $url;         $this->m_host = $urls["host"];
If(!empty($urls["scheme"])) $this->m_scheme = $urls["scheme"];

if(!empty($url s["user"] )){
                                                                                                                                                                                       

                          if(!empty($urls["pass"])){
                                        $this->m_pass = $urls["pass"];
                          }

                          if(!empty($urls["port"])){
                                        $this->m_port = $urls["port"];
                          }

                          if(!empty($urls["path"])) $this->m_path = $urls["path"];
                          $this->m_urlpath = $this->m_path;

                          if(!empty($urls["query"])){
                                        $this->m_query = $urls["query"];
                                        $this->m_urlpath .= "?".$this->m_query;
                          }
                          $this->HomeUrl = $urls["host"];
                          $this->BaseUrlPath = $this->HomeUrl.$urls["path"];
                          $this->BaseUrlPath = ereg_replace("/([^/]*).(.*)$","/",$this->BaseUrlPath);
                          $this->BaseUrlPath = ereg_replace("/$","",$this->BaseUrlPath);
                 }
        }
        //
        //打开指定网址
        //
        function OpenUrl($url)
        {
                //重设各参数
                $this->m_url = "";
                $this->m_urlpath = "";
                $this->m_scheme = "http";
                $this->m_host = "";
                $this->m_port = "80";
                $this->m_user = "";
                $this->m_pass = "";
                $this->m_path = "/";
                $this->m_query = "";
                $this->m_error = "";
                $this->JumpCount = 0;
                $this->m_httphead = Array() ;
                //$this->m_puthead = "";
                $this->m_html = "";
                $this->Close();
                //初始化系统
                $this->PrivateInit($url);
                $this->PrivateStartSession();
        }
        //
        //打开303重定向网址
        //
        function JumpOpenUrl($url)
        {
                //重设各参数
                $this->m_url = "";
                $this->m_urlpath = "";
                $this->m_scheme = "http";
                $this->m_host = "";
                $this->m_port = "80";
                $this->m_user = "";
                $this->m_pass = "";
                $this->m_path = "/";
                $this->m_query = "";
                $this->m_error = "";
                $this->JumpCount++;
                $this->m_httphead = Array() ;
                $this->m_html = "";
                $this->Close();
                //初始化系统
                $this->PrivateInit($url);
                $this->PrivateStartSession();
        }
        //
        //获得某操作错误的原因
        //
        function printError()
        {
                echo "错误信息:".$this->m_error;
                echo "具体返回头:
";
                foreach($this->m_httphead as $k=>$v)
                { echo "$k => $v 
rn"; }
        }
        //
        //判别用Get方法发送的头的应答结果是否正确
        //
        function IsGetOK()
        {
                if( ereg("^2",$this->GetHead("http-state")) )
                {        return true; }
                                                                                              Head("http-describe") ."
";
                                                                                                                           Whether it is text type
//
function IsText()
        {
                if(ereg("^2",$this->GetHead("http-state"))
                        && eregi("^text",$this->GetHead ("content-type")))
                                                                                                            $this->m_error .= "The content is non-text type or URL redirection
";
                         return false;                                        //                                                                        🎜> {
{ $ctype))
{ return true; }
else
{
$this- >m_error .= "Wrong type".$this->GetHead("content-type"). "
";
                                                                                                                                                      Download file
//
function SaveToBin($savefilename)
             { !"; return false; }
                                                                                                                                 fwrite($fp,fread($ this->m_fp,1024));                            return true; 🎜>                                                                                                              this->IsText()) $this- >SaveBinFile($savefilename);
function GetHtml()
             { if(!$this->m_fp||@feof($this->m_fp)) return ""; ;m_html .= fgets($this->m_fp,256);
                                                 m_html;
}
                                                                                                          !$this->PrivateOpenHost()){
$this->m_error .= "Error opening remote host!";
                                                                                                                                                                                                                                       

if($this->GetHead("http-edition")=="HTTP/1.1") $httpv = "HTTP/1.1";
else $httpv = "HTTP/1.0" ; > // Send a fixed start request head GET and HOST information
FPUTS ($ this- & gt; m_fp, "get". $ This- & gt; m_urlpath. "$ Httpvrn"); m_puthead["Accept"] = "*/*"; }
                                                                                                                { $this->m_puthead["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2)"; }
If(!isset($this->m_puthead["Refer" ])) { $this->m_puthead["Refer"] = "http://".$this->m_puthead["Host"]; }
foreach($this->m_puthead as $k =>$v){
                                                                                                 if($k!=""&&$v!="") {
                                                               fputs($this->m_fp,"$k: $vrn");                                    🎜>
//Send a fixed end request header
.1 The protocol must specify that the link should be closed after the document ends, otherwise feof cannot be used to determine the end when reading the document
if($httpv=="HTTP/1.1") fputs($this->m_fp,"Connection: Closernrn" );
            else fputs($this->m_fp,"rn"); ($this-> ;m_fp,256));
$this->m_httphead["http-edition"] = trim($httpstas[0]);
$this->m_httphead["http-state"] = trim($httpstas[1]);
               $this->m_httphead["http-describe"] =                                                                                      ){
                                                                                 $this->
                //获取详细应答头
                while(!feof($this->m_fp)){
                        $line = trim(fgets($this->m_fp,256));
                        if($line == "") break;
                        $hkey = "";
                        $hvalue = "";
                        $v = 0;
                        for($i=0;$i                                if($v==1) $hvalue .= $line[$i];
                                if($line[$i]==":") $v = 1;
                                if($v==0) $hkey .= $line[$i];
                        }
                        $hkey = trim($hkey);
                        if($hkey!="") $this->m_httphead[strtolower($hkey)] = trim($hvalue);
                }
                //判断是否是3xx开头的应答
                if(ereg("^3",$this->m_httphead["http-state"]))
                {
                        if($this->JumpCount > 3) return;
                        if(isset($this->m_httphead["location"])){
                                $newurl = $this->m_httphead["location"];
                                if(eregi("^http",$newurl)){
                                        $this->JumpOpenUrl($newurl);
                                }
                                                                                                                                                                                                                                                                                                                                                                                                            🎜> else
                                                                                                                                                                                                                                                                through"; }
                                                                                                                     name)
{
$headname = strtolower($headname);
if(isset($this->m_httphead[$headname]))
return $this->m_httphead[$headname];
          else
return "";
}
                                                                                                                                                                    🎜> $this- >m_puthead[$skey] = $svalue;
                                                                                          {
if($this ->m_host=="") return false;
                                                                                                                                                                                             🎜>                                                                                                                                                                                                      >                                                                                              @fclose($this->m_fp);
}
        //
        //补全相对网址
        //
        function FillUrl($surl)
  {
    $i = 0;
    $dstr = "";
    $pstr = "";
    $okurl = "";
    $pathStep = 0;
    $surl = trim($surl);
    if($surl=="") return "";
    $pos = strpos($surl,"#");
    if($pos>0) $surl = substr($surl,0,$pos);
    if($surl[0]=="/"){
            $okurl = "http://".$this->HomeUrl."/".$surl;
    }
    else if($surl[0]==".")
    {
      if(strlen($surl)      else if($surl[0]=="/")
      {
              $okurl = "http://".$this->BaseUrlPath."/".substr($surl,2,strlen($surl)-2);
            }
      else{
        $urls = explode("/",$surl);
        foreach($urls as $u){
          if($u=="..") $pathStep++;
          else if($i          else $dstr .= $urls[$i];
          $i++;
        }
        $urls = explode("/",$this->BaseUrlPath);
        if(count($urls)                 return "";
        else{
          $pstr = "http://";
          for($i=0;$i          { $pstr .= $urls[$i]."/"; }
          $okurl = $pstr.$dstr;
        }
      }
    }
    else
    {
      if(strlen($surl)        $okurl = "http://".$this->BaseUrlPath."/".$surl;
      else if(strtolower(substr($surl,0,7))=="http://")
        $okurl = $surl;
      else
        $okurl = "http://".$this->BaseUrlPath."/".$surl;
    }
    $okurl = eregi_replace("^(http://)","",$okurl);
    $okurl = eregi_replace("/{1,}","/",$okurl);
    return "http://".$okurl;
  }
}
?>

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/317890.htmlTechArticle如果支持打开远程内容的选项的话,实际上php用fopen或file_get_contents都能获得一个网页的内容,但是默认的函数有个不足的地方就是无法获取...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.