PHP file_get_contents函数详解

一. 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获取

$html = file_get_contents('http://www.baidu.com');
print_r($http_response_header);
$fp = fopen('http://www.baidu.com', 'r');
print_r(stream_get_meta_data($fp));
fclose($fp);
1
2
3
4
5
模拟post请求

test.php   
```php
$url = 'http://192.168.31.63/2.php';
$data = array(
'item' => 'test data',
);
$content = http_build_query($data);
$content_length = strlen($content);
$options = array(
'http' => array(
'method' => 'POST',
'header' =>
"Content-type: application/x-www-form-urlencoded\r\n" .
"Content-length: $content_length\r\n",
'content' => $content
)
);
echo file_get_contents($url, false, stream_context_create($options));


2.php

<?php
/**
* @Author: anchen
* @Date: 2017-03-23 13:51:46
* @Last Modified by: anchen
* @Last Modified time: 2017-03-23 13:53:46
*/
file_put_contents('./1.txt', var_export($_POST, true));//把接收的数据储存起来
下面写一个贴近一点的例子

$data = [
'author' => '白菜打下',
'mail' => 'info@aiyooyoo.com',
'text' => '博主很给力',
];
$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: PHPSESSID=13ROTEGFGJDFDFDOGDFGD"."\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('http://aiyooyoo.com/index.php/archives/7/comment', false, $context);

原文链接:https://blog.csdn.net/estaaa/article/details/82291292

 
posted @ 2020-03-21 09:28  HelpYourself!  阅读(1614)  评论(0编辑  收藏  举报