Home >Backend Development >PHP Tutorial >Four ways to access url in php

Four ways to access url in php

angryTom
angryTomforward
2019-10-15 15:27:4012606browse

Four ways to access url in php

1.fopen method

//访问指定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;  
}

Recommended learning: PHP video tutorial

2.file_get_contents method (opening a remote file will cause the CPU to surge. file_get_contents can actually be posted)

$content = file_get_contents("http://www.google.com");

3.curl method

function curl_file_get_contents($durl){  
    $ch = curl_init();  
    curl_setopt($ch, CURLOPT_URL, $durl);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回    
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回    
    $r = curl_exec($ch);  
    curl_close($ch);  
    return $r;  
}

4.fsockopen method (only the homepage information of the website can be obtained, not other pages)

$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);     
if (!$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);     
}

The above is the detailed content of Four ways to access url in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete