file_get_contents的深入

来源:互联网 发布:2016淘宝分销刷信誉 编辑:程序博客网 时间:2024/05/18 03:56

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的内容写入$strecho $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);//获取内容
0 0
原创粉丝点击