Several methods to open the URL address in PHP _ PHP Tutorial

Source: Internet
Author: User
Summary of several methods to open the URL address in PHP. 1: Use file_get_contents to get the content and copy the code as follows :? Php $ urlwww.baidu.com; $ htmlfile_get_contents ($ url); print_r ($ http_response_header); ec 1: get content using file_get_contents in get mode

The code is as follows:


$ Url = 'http: // www.baidu.com /';
$ Html = file_get_contents ($ url );
// Print_r ($ http_response_header );
Ec ($ html );
Printhr ();
Printarr ($ http_response_header );
Printhr ();
?>


Example code 2: Use fopen to open a url and get the content

The code is as follows:


$ Fp = fopen ($ url, 'r ');
Printarr (stream_get_meta_data ($ fp ));
Printhr ();
While (! Feof ($ fp )){
$ Result. = fgets ($ fp, 1024 );
}
Echo "url body: $ result ";
Printhr ();
Fclose ($ fp );
?>


Sample Code 3: Use the file_get_contents function to obtain the url in post mode.

The code is as follows:


$ Data = array ('foo' => 'bar ');
$ Data = http_build_query ($ data );
$ Opts = array (
'Http' => array (
'Method' => 'post ',
'Header' => "Content-type: application/x-www-form-urlencoded ".
"Content-Length:". strlen ($ data )."",
'Content' => $ data
),
);
$ Context = stream_context_create ($ opts );
$ Html = file_get_contents ('http: // localhost/e/admin/test.html ', false, $ context );
Echo $ html;
?>


Example code 4: Use the fsockopen function to open a url and get complete data, including header and body

The code is as follows:


Function get_url ($ url, $ cookie = false ){
$ Url = parse_url ($ url );
$ Query = $ url [path]. "? ". $ Url [query];
Ec ("Query:". $ query );
$ Fp = fsockopen ($ url [host], $ url [port]? $ Url [port]: 80, $ errno, $ errstr, 30 );
If (! $ Fp ){
Return false;
} Else {
$ Request = "GET $ query HTTP/1.1 ";
$ Request. = "Host: $ url [host]";
$ Request. = "Connection: Close ";
If ($ cookie) $ request. = "Cookie: $ cookie \ n ";
$ Request. = "";
Fwrite ($ fp, $ request );
While (! @ Feof ($ fp )){
$ Result. = @ fgets ($ fp, 1024 );
}
Fclose ($ fp );
Return $ result;
}
}
// Obtain the html part of the url and remove the header
Function GetUrlHTML ($ url, $ cookie = false ){
$ Rowdata = get_url ($ url, $ cookie );
If ($ rowdata)
{
$ Body = stristr ($ rowdata ,"");
$ Body = substr ($ body, 4, strlen ($ body ));
Return $ body;
}
Return false;
}

?>


Example code 5: Use the fsockopen function to open the url and obtain the complete data in POST mode, including the header and body

The code is as follows:


Function HTTP_Post ($ URL, $ data, $ cookie, $ referrer = ""){
// Parsing the given URL
$ URL_Info = parse_url ($ URL );
// Building referrer
If ($ referrer = "") // if not given use this script as referrer
$ Referrer = "111 ";
// Making string from $ data
Foreach ($ data as $ key => $ value)
$ Values [] = "$ key =". urlencode ($ value );
$ Data_string = implode ("&", $ values );
// Find out which port is needed-if not given use standard (= 80)
If (! Isset ($ URL_Info ["port"])
$ URL_Info ["port"] = 80;
// Building POST-request:
$ Request. = "POST". $ URL_Info ["path"]. "HTTP/1.1 \ n ";
$ Request. = "Host:". $ URL_Info ["host"]. "\ n ";
$ Request. = "Referer: $ referer \ n ";
$ Request. = "Content-type: application/x-www-form-urlencoded \ n ";
$ Request. = "Content-length:". strlen ($ data_string). "\ n ";
$ Request. = "Connection: close \ n ";
$ Request. = "Cookie: $ cookie \ n ";
$ Request. = "\ n ";
$ Request. = $ data_string. "\ n ";
$ Fp = fsockopen ($ URL_Info ["host"], $ URL_Info ["port"]);
Fputs ($ fp, $ request );
While (! Feof ($ fp )){
$ Result. = fgets ($ fp, 1024 );
}
Fclose ($ fp );
Return $ result;
}
Printhr ();
?>


Example code 6: Use the curl Library. before using the curl library, you may need to check php. ini to see if the curl extension has been enabled.

The code is as follows:


$ Ch = curl_init ();
$ Timeout = 5;
Curl_setopt ($ ch, CURLOPT_URL, 'http: // www.baidu.com /');
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, $ timeout );
$ File_contents = curl_exec ($ ch );
Curl_close ($ ch );
Echo $ file_contents;
?>


About curl Library:
Http://curl.haxx.se/
Curl is a FILE transfer tool using URL syntax. it supports FTP, FTPS, http htpps scp sftp tftp telnet dict file and LDAP. Curl supports SSL certificates, http post, http put, and FTP uploads, kerberos, HTT-based Upload, proxy, cookie, user + password proof, file transfer recovery, http proxy channel and a large number of other useful techniques

The code is as follows:


Function printarr (array $ arr)
{
Echo"
Row field count: ". count ($ arr )."
";
Foreach ($ arr as $ key => $ value)
{
Echo "$ key = $ value
";
}
}
?>


7.
Some host service providers disable php's allow_url_fopen option, that is, they cannot directly use file_get_contents to obtain the content of the remote web page. That is, you can use another function curl.
Below are two different expressions of the same function of file_get_contents and curl:
Example of using the file_get_contents function:

The code is as follows:


<? Php
$ File_contents = file_get_contents ('http: // www.ccvita.com /');
Echo $ file_contents;
?>


Example of curl function replacement:

The code is as follows:


<? Php
$ Ch = curl_init ();
$ Timeout = 5;
Curl_setopt ($ ch, CURLOPT_URL, 'http: // www.ccvita.com ');
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, $ timeout );
$ File_contents = curl_exec ($ ch );
Curl_close ($ ch );
Echo $ file_contents;
?>


Use the function_exists function to determine whether php supports a function. you can easily write the following function.

The code is as follows:


<? Php
Function vita_get_url_content ($ url ){
If (function_exists ('File _ get_contents ')){
$ File_contents = file_get_contents ($ url );
} Else {
$ Ch = curl_init ();
$ Timeout = 5;
Curl_setopt ($ ch, CURLOPT_URL, $ url );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, $ timeout );
$ File_contents = curl_exec ($ ch );
Curl_close ($ ch );
}
Return $ file_contents;
}
?>


In fact, the above function remains to be discussed. if your host service provider closes file_get_contents and curl, the above function will encounter an error.

Using file_get_contents to get content in the get method, the code is as follows :? Php $ url = 'http: // www.baidu.com/'; $ html = file_get_contents ($ url); // print_r ($ http_response_header); ec...

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.