Code Sharing for PHP download files

Source: Internet
Author: User
Tags ereg php download ftp protocol
This article introduces, in PHP, to implement some of the methods and code to download files, including system function calls, wget, and socket connection mode download files. If you need a friend, make a reference.

In PHP to implement the download file, the method is mostly the following two kinds: one is to use the system, exec, and so on, the function calls the systems come with download tools, such as wget to download files. The other is to use the PHP itself to use the socket to download files.

I like to use the second way.

Using the socket to download files, if it is an HTTP protocol file, you must understand the HTTP protocol running process, if the FTP protocol is to understand the FTP protocol running process. For example, the HTTP protocol accesses a file:

 
      \ n ";} else {    $out = "get/http/1.1\r\n";    $out. = "host:www.example.com\r\n";    $out. = "connection:close\r\n\r\n";    Fwrite ($fp, $out);        while (!feof ($fp)) {            echo fgets ($fp, +);        }    Fclose ($FP);}? >

Use fopen to access remote files directly for the purpose, while also accessing HTTP and FTP. Of course, if you follow the above ideas, you can also use the FTP function library to implement.

Examples of using the fopen function:

#! /usr/bin/php
     

Save the above code as a download.php file, plus the executable attribute: chmod +x download.php

Execute, note that the path to the script is correct: #! /usr/local/php/bin/php

Use the script above to download the file: download.php Remote File Save path

If you download the Google Talk program to our/tmp directory: download.php http://dl.google.com/googletalk/googletalk-setup.exe/tmp/

If there is no error, wait a while to see the Googletalk-setup.exe file in the/tmp/directory.

Here to share a stronger HTTP download class:

     M_url = $url;        if (Is_array ($urls)) {$this->m_host = $urls ["Host"];             if (!empty ($urls ["scheme"]) $this->m_scheme = $urls ["scheme"];        if (!empty ($urls ["User"])) {$this->m_user = $urls ["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;     }}}////opens the specified URL//function OpenUrl ($url) {//resets each parameter $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->m_httphead = "";     $this->m_html = "";     $this->close ();     Initialize the system $this->privateinit ($url); $this->privatestartsession ();}     Get the cause of an operation error//function Printerror () {echo "error message:". $this->m_error; echo "Specific return header:
"; foreach ($this->m_httphead as $k = + $v) {echo "$k + $v
\ r \ n "; }}////determine if the answer to the header sent with the Get method is correct//function Isgetok () {if (Ereg ("^2", $this->gethead ("Http-state")) {return true;} else {$this->m_error. = $this->gethead ("Http-state"). "-". $this->gethead ("Http-describe"). "
"; return false; }}////See if the page returned is text type//function Istext () {if (Ereg ("^2", $this->gethead ("Http-state")) && eregi ("^text" , $this->gethead ("Content-type")) {return true;} else {$this->m_error. = "Content is non-text type
"; return false; }}////determines whether the returned Web page is of a specific type//function Iscontenttype ($ctype) {if (Ereg ("^2", $this->gethead ("Http-state")) && $ This->gethead ("Content-type") ==strtolower ($ctype)) {return true;} else {$this->m_error. = "wrong type". $this->gethead ("Content-type"). "
"; return false; }}////download file with HTTP protocol//function Savetobin ($savefilename) {if (! $this->isgetok ()) return false; if (@feof ($this->m_fp)) {$this->m_error = "The connection is closed! "; return false; } $fp = fopen ($savefilename, "w") or Die ("Write File $savefilename failed! "); while (!feof ($this->m_fp)) {@fwrite ($fp, fgets ($this->m_fp,256)); } @fclose ($this->m_fp); return true;} Save the page content as text file//function Savetotext ($savefilename) {if ($this->istext ()) $this->savebinfile ($savefilename ); else return "";} Get the content of a Web page using the HTTP protocol//function gethtml () {if (! $this->istext ()) return ""; if ($this->m_html!= "") return $this->m_html; if (! $this->m_fp| | @feof ($this->m_fp)) return ""; while (!feof ($this->m_fp)) {$this->m_html. = fgets ($this->m_fp,256); } @fclose ($this->m_fp); return $this->m_html;} Start HTTP session//function Privatestartsession () {if (! $this->privateopenhost ()) {$this->m_error. = "Error opening remote host! "; return false; if ($this->gethead ("http-edition") = = "http/1.1") $HTTPV = "http/1.1"; else $HTTPV = "http/1.0"; Fputs ($this->m_fp, "GET". $this->m_urlpath. "$HTTPV \ r \ n"); Fputs ($this->m_fp, "Host:". $this->m_host. " \ r \ n "); Fputs ($this->m_fp, "Accept: */*\r\n"); Fputs ($this->m_fp, "user-agent:mozilla/4.0+ (compatible;+msie+6.0;+windows+nt+5.2) \ r \ n"); The HTTP1.1 protocol must specify closing the link after the document is finished, otherwise you cannot use feof to determine the end if ($HTTPV = = "http/1.1") fputs ($this->m_fp, "connection:close\r\n\r") when reading the document \ n "); else fputs ($this->m_fp, "\ r \ n"); $httpstas = fgets ($this->m_fp,256); $httpstas = Split ("", $httpstas); $this->m_httphead["http-edition") = Trim ($httpstas [0]); $this->m_httphead["http-state") = Trim ($httpstas [1]); $this->m_httphead["http-describe"] = ""; for ($i =2; $i m_httphead["Http-describe". ". Trim ($httpstas [$i]); } while (!feof ($this->m_fp)) {$line = Str_replace ("\" "," ", Trim (fgets ($this->m_fp,256))); if ($line = = "") break; if (Ereg (":", $line)) {$lines = Split (":", $line); $this->m_httphead[strtolower (Trim ($lines [0])] = Trim ($lines [1]); }}////gets the value of an HTTP header//function GetHead ($headname) {$headname = Strtolower ($headname); if (Isset ($this->m_httphead[$headname])) return $this->m_httphead[$headname]; else return "";} Open Connection//function Privateopenhost () {if ($this->m_host== "") return false; $this->m_fp = @fsockopen ($this->m_host, $this->m_port, & $errno, & $errstr, 10); if (! $this->m_fp) {$this->m_error = $errstr; return false; } else{return true; }}////Close Connection//function Close () {@fclose ($this->m_fp);}}? >

Call Example: 1, download Web page

 
      OPENURL ("http://bbs.it-home.org"); Echo $httpdown->gethtml (); $httpdown->close ();? >

2. Download the picture and save it

 
      OPENURL ("Http://img.jbxue.com/images/1.jpg"), Echo $httpdown->savebin ("test.jpg"); $httpdown->close (); echo " ";? >
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.