file_get_contents的深入

file_get_contents()用法:

string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )

参数详解:
第一个参数:文件路径或者远程主机资源的URL
第二个参数:是否使用php.ini中定义的include_path,如果设为true,将去php.ini中定义的include_path中寻找
第三个参数:资源流上下文(十分重要),用stream_content_create()创建
第四个参数:起始位置
第五个参数:长度

用处:
1. 获取本地文件内容
  将一个文件内容读入一个字符串中,一般是将文件里的全部内容读入内存中,所以比较大的文件一般要用这个函数

$str = file_get_contents(01.txt);//将01.txt的内容写入$str
echo $str;

2.用获取某个url的内容

$str = file_get_content('http://www.baidu.com');//获取www.baidu.com页面的内容
echo $str;

3.利用file_get_content模拟http的GET和POST请求

/*
@function:用file_get_contents发送GET请求
*/
$url     = 'http://localhost/01.php';//定义请求URL
$method  = 'GET';//定义请求方法
$header  = 'Cookie: name=testname;';//定义请求头信息
$options = array(
    'http' => array(
        'method' => $method,
        'header' => $header,
        )
    );
$content = stream_context_create($options);//生成资源上下文
echo file_get_contents($url,false,$content);

注意:设置COOKIE是应该COOKIE的字符串拼接在header最后,以免对其他的header信息造成影响

/*
@function:用file_get_contents发送POST请求
*/
$url = 'http://localhost/inertview/01.php';//定义请求URL
$method = 'POST';//定义请求方法
$content = array(
    'username' => 'root',
    'password' => '123456'
    );
$content = http_build_query($content);//定义请求的主体信息
$header = "Content-Type: application/x-www-form-urlencoded\r\n"."Content-Length: ".strlen($content)."\r\n".'Cookie: name=testname;';//定义请求头信息
$options = array(
    'http' => array(
        'method' => $method,
        'header' => $header,
        'content' => $content
        )
    );
$content = stream_context_create($options);
echo file_get_contents($url,false,$content);//获取内容
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值