PHP downloads remote webpage images and saves them to a local instance

Source: Internet
Author: User
Tags readfile trim


Fopen function instance

Ob_start: enable the output buffer.

Readfile: reads a file and writes it to the output buffer.
Returns the number of bytes read from the file. If an error is returned, FALSE is returned, and the error message is displayed unless called in the form of @ readfile.

Ob_get_contents: Return the contents of the output buffer (Return the content of the output buffer)
This will return the contents of the output buffer without clearing it or FALSE, if output buffering isn' t active. (if the output buffer has no activity (open), FALSE is returned)

Ob_end_clean (): Clean (erase) the output buffer and turn off output buffering (clear output buffer)

The code is as follows: Copy code


<? Php
// The URL is the complete remote image address and cannot be blank. $ filename is the name of the saved image.
// By default, images are stored in the same directory as the script.
Function GrabImage ($ url, $ filename = ""){
If ($ url = ""){
Return false;
        }
       
$ Ext = strrchr ($ url ,".");
       
If ($ ext! = ". Gif" & $ ext! = ". Jpg" & $ ext! = ". Bmp" & $ ext! = ". Png "){
Echo "format not supported! ";
Return false;
        }
       
If ($ filename = ""){
$ Filename = time (). "$ ext ";
        }
       
Ob_start ();
Readfile ($ url );
$ Img = ob_get_contents ();
Ob_end_clean ();
$ Size = strlen ($ img );
$ Fp2 = fopen ($ filename, "");
If (fwrite ($ fp2, $ img) === false ){
Echo "file cannot be written". $ filename;
Exit ();
} Else {
Echo "image saved! ";
        }
Fclose ($ fp2 );
Return $ filename;
       
    }
// Test
GrabImage ("/logo.png", "as.png ");
?>


Php remote image download function can be forged


$ Gurl: The Image address to download
$ Rfurl. If the target image has anti-Leech settings, you can bypass it.
$ Filename: the file name for downloading the image, relative path. Do not use realpath.
$ Gcookie: adjust cookie forgery
$ JumpCount jump count
$ Maxtime maximum times
Call method: DownImageKeep ("yun_qi_img/baidu_jgylogo2.gif", "http://baidu.com examples, example A.gif );

The code is as follows: Copy code

Function DownImageKeep ($ gurl, $ rfurl, $ filename, $ gcookie = "", $ JumpCount = 0, $ maxtime = 30)
{
$ Urlinfos = GetHostInfo ($ gurl );
$ Ghost = trim ($ urlinfos ['host']);
If ($ ghost = ")
{
Return FALSE;
}
$ Gquery = $ urlinfos ['query'];
If ($ gcookie = ""&&! Empty ($ rfurl ))
{
$ Gcookie = RefurlCookie ($ rfurl );
}
$ SessionQuery = "GET $ gquery HTTP/1.1rn ";
$ SessionQuery. = "Host: $ ghostrn ";
$ SessionQuery. = "Referer: $ rfurlrn ";
$ SessionQuery. = "Accept: */* rn ";
$ SessionQuery. = "User-Agent: Mozilla/4.0 (compatible; MSIE 5.00; Windows 98) rn ";
If ($ gcookie! = ""&&! Preg_match ("/[rn]/", $ gcookie ))
{
$ SessionQuery. = $ gcookie. "rn ";
}
$ SessionQuery. = "Connection: Keep-Alivernrn ";
$ Errno = "";
$ Errstr = "";
$ M_fp = fsockopen ($ ghost, 80, $ errno, $ errstr, 10 );
Fwrite ($ m_fp, $ sessionQuery );
$ Lnum = 0;

// Obtain the response header
$ M_httphead = Array ();
$ Httpstas = explode ("", fgets ($ m_fp, 256 ));
$ M_httphead ["http-edition"] = trim ($ httpstas [0]);
$ M_httphead ["http-state"] = trim ($ httpstas [1]);
While (! Feof ($ m_fp ))
{
$ Line = trim (fgets ($ m_fp, 256 ));
If ($ line = "" ||$ lnum> 100)
{
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! = "")
{
$ M_httphead [strtolower ($ hkey)] = trim ($ hvalue );
}
}

If (preg_match ("/^ 3/", $ m_httphead ["http-state"])
{
If (isset ($ m_httphead ["location"]) & $ JumpCount <3) {$ JumpCount ++; DownImageKeep ($ gurl, $ rfurl, $ filename, $ gcookie, $ JumpCount) ;}else {return FALSE ;}} if (! Preg_match ("/^ 2/", $ m_httphead ["http-state"]) {return FALSE;} if (! Isset ($ m_httphead) {return FALSE;} $ contentLength = $ m_httphead ['content-length']; // save the image $ fp = fopen ($ filename, "w ") or die ("writing File: {$ filename} failed! "); $ I = 0; $ okdata = ""; $ starttime = time (); while (! Feof ($ m_fp) {$ okdata. = fgetc ($ m_fp); $ I ++; // time-out exit if (time ()-$ starttime> $ maxtime)
{
Break;
}

// End with the specified size
If ($ I >=$ contentLength)
{
Break;
}
}
If ($ okdata! = "")
{
Fwrite ($ fp, $ okdata );
}
Fclose ($ fp );
If ($ okdata = "")
{
@ Unlink ($ filename );
Fclose ($ m_fp );
Return FALSE;
}
Fclose ($ m_fp );
Return TRUE;
}
// Obtain the host and query parts of the website
Function GetHostInfo ($ gurl)
{
$ Gurl = preg_replace ("/^ http: // I", "", trim ($ gurl ));
$ Garr ['host'] = preg_replace ("// (. *) $/I", "", $ gurl );
$ Garr ['query'] = "/". preg_replace ("/^ ([^/] *) // I", "", $ gurl );
Return $ garr;
}
// Obtain the Cookie information returned by the page
Function RefurlCookie ($ gurl)
{
Global $ gcookie, $ lastRfurl;
$ Gurl = trim ($ gurl );
If (! Empty ($ gcookie) & $ lastRfurl ==$ gurl)
{
Return $ gcookie;
}
Else
{
$ LastRfurl = $ gurl;
}
If (trim ($ gurl) = ")
{
Return ";
}
$ Urlinfos = GetHostInfo ($ gurl );
$ Ghost = $ urlinfos ['host'];
$ Gquery = $ urlinfos ['query'];
$ SessionQuery = "GET $ gquery HTTP/1.1rn ";
$ SessionQuery. = "Host: $ ghostrn ";
$ SessionQuery. = "Accept: */* rn ";
$ SessionQuery. = "User-Agent: Mozilla/4.0 (compatible; MSIE 5.00; Windows 98) rn ";
$ SessionQuery. = "Connection: Closernrn ";
$ Errno = "";
$ Errstr = "";
$ M_fp = fsockopen ($ ghost, 80, $ errno, $ errstr, 10) or die ($ ghost .'
');
Fwrite ($ m_fp, $ sessionQuery );
$ Lnum = 0;

// Obtain the detailed response header
$ Gcookie = "";
While (! Feof ($ m_fp ))
{
$ Line = trim (fgets ($ m_fp, 256 ));
If ($ line = "" ||$ lnum> 100)
{
Break;
}
Else
{
If (preg_match ("/^ cookie/I", $ line ))
{
$ Gcookie = $ line;
Break;
}
}
}
Fclose ($ m_fp );
Return $ gcookie;
}

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.