file_get_contents() 函數把整個文件讀入一個字符串中,和 file() 一樣,不同的是 file_get_contents() 把文件讀入一個字符串.
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 新加的.
php實例代碼如下:
- <?php
- function post($url, $post = null)
- {
- $context = array();
- if (is_array($post))
- {
- ksort($post);
- $context['http'] = array
- (
- 'method' => 'post',
- 'content' => http_build_query($post, '', '&'),
- );
- }
- return file_get_contents($url, false, stream_context_create($context));
- }
- $data = array
- (
- 'name' => 'test',
- 'email' => 'test@gmail.com',
- 'submit' => 'submit',
- );
- echo post('http://localhost/5-5/request_post_result.php', $data);
- ?>
接收數據,request_post_result.php 接收經過post的數據,php代碼如下:
- <?php
- echo $_post['name'];
- echo $_post['email'];
- echo $_post['submit'];
- echo "fdfd";
- ?>
實例二,代碼如下:
- /**
- * 其它版本
- * 使用方法:
- * $post_string = "app=request&version=beta";
- * request_by_other('http://facebook.cn/restserver.php',$post_string);
- */
- function request_by_other($remote_server,$post_string){
- $context = array(
- 'http'=>array(
- 'method'=>'post',
- 'header'=>'content-type: application/x-www-form-urlencoded'."rn".
- 'user-agent : jimmy's post example beta'."rn".
- 'content-length: '.strlen($post_string)+8,
- 'content'=>'mypost='.$post_string)
- );
- $stream_context = stream_context_create($context);
- $data = file_get_contents($remote_server,false,$stream_context);
- return $data;
- }
新聞熱點
疑難解答