How does PHP access URLs? PHP Access URL method Summary (code)

Source: Internet
Author: User
This article introduces you to how PHP accesses URLs? PHP Access URL method Summary (code), there is a certain reference value, the need for friends can refer to, I hope to help you.

1, Fopen Way

Accesses the specified URL function access_url ($url) {        if ($url = = ") return false;       $fp = fopen ($url, ' r ') or exit (' Open URL faild! ');        if ($fp) {while       (!feof ($fp)) {            $file. = Fgets ($fp). "";        }        Fclose ($FP);         }       return $file;    }

2, file_get_contents mode (open remote files will cause the CPU to soar. File_get_contents can actually post)

Get Url$data = Array (' foo ' = ' bar ') by post, $data = Http_build_query ($data), $opts [' http '] = Array (  ' method ' => ; ' POST ',  ' header ' = ' content-type:application/x-www-form-urlencodedrn '.  " Content-length: ". Strlen ($data). "RN",  ' content ' = $data); $context = Stream_context_create ($opts); $html = file_get_contents (' http://localhost /test.html ', false, $context); Echo $html;

3. Curl Mode

function Curl_file_get_contents ($durl) {      $ch = Curl_init ();      curl_setopt ($ch, Curlopt_url, $durl);      curl_setopt ($ch, Curlopt_returntransfer, true); Get Data return        curl_setopt ($ch, Curlopt_binarytransfer, true);//Get Data back when Curlopt_returntransfer is enabled        $data = Curl_ EXEC ($ch);      Curl_close ($ch);      return $data;  }

4, Fsockopen Way (can only obtain the website homepage information, other pages can not)

 $fp = Fsockopen ("www.example.com", $errno, $errstr, 30); (! $fp)     {echo "$errstr ($errno) <br/>\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, 128);     } fclose ($FP); }
Related Article

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.