PHP file_get_contents函数详解

1.file_get_contents(path,include_path,context,start,max_length)

path 必需。规定要读取的文件。

include_path 可选。如果也想在 include_path 中搜寻文件的话,可以将该参数设为 “1”。

context 可选。规定文件句柄的环境。context 是一套可以修改流的行为的选项。若使用 null,则忽略。

start 可选。规定在文件中开始读取的位置。该参数是 PHP 5.1 新加的。

max_length 可选。规定读取的字节数。该参数是 PHP 5.1 新加的。   1,此函数可以用来打开一个网络地址 可以实现简单的网页抓取   2.此函数可以读取本地的文件   3.此函数可以模拟post请求  

网页抓取

  一般用file_get_contents或者fopen, file , readfile等函数读取url的时候 会创建一个$http_response_header变量保存HTTP响应的报头,使用fopen等函数打开的数据流信息可以用stream_get_meta_data获取

file_put_contents('./1.txt', var_export($_POST, true));//把接收的数据储存起来
$html = file_get_contents('http://www.baidu.com');
print_r($http_response_header);
$f = fopen('http://www.baidu.com', 'o');
print_r(stream_get_meta_data($f));
fclose($f);

  

post请求

$url = 'www.baidu.com';
$data = [
    'appkey'=> '1111',
    'text' => '2222',
];
$data = http_build_query($data);
$opts = [
    'http' => [
        'method' => 'POST',
        'header' => "Content-type:application/x-www-form-urlencoded\r\n".
                    "Content-Length: ".strlen($data)."\r\n".
                    "Cookie: PHPSESS."\r\n".
                    "User-Agent: Mozilla/5.0(Windows: U; Windows NT 6.1; zh-CH; rv: 1.9.2.13) Gecko/20101203 Firefox/3.6.13"."\r\n".
                    "Referer:http://aiyooyoo.com/index.php/archives/7/"."\r\n",
        'content' => $data,
    ],
];
$context = stream_context_create($opts);
$html = @file_get_contents($url, false, $context);