用file_get_contents或者fopen、file、readfile、copy等函数读取url的时候,允许通过名为$http_response_header的变量来保存http响应的报头,自 PHP 4.3.0 起,还可以用 stream_get_meta_data()来获取http响应的报头。
以下是 PHP 内置用于文件系统函数 fopen()、copy()等URL风格协议列表。除了这些封装协议之外,从 PHP 4.3 起,还可以用 PHP 脚本和 stream_wrapper_register() 创建自己的封装协议。
HTTP 和 HTTPS
PHP 3,PHP 4。自 PHP 4.3.0 起支持
https://
http://example.com
http://user:password@example.com
https://example.com
https://user:password@example.com
允许通过 HTTP 1.0 使用 HTTP GET 方法对文件/资源进行只读访问。Host: 报头也会通过请求发送出去以支持基于域名的虚拟主机。如果你在 ini 文件或者流上下文配置了 user_agent 字符串,也会被包括在请求报头中。
自 PHP 4.0.5 起支持重定向。如果使用较早版本的 PHP 则需要在 URL 末尾包括一个斜线。如果一定要知道文档所在的资源的 url(在所有重定向被处理过之后),则需要处理从流返回的一系列响应报头信息。
<?php
$url = 'http://www.example.com/';
$fp = fopen($url, 'r');
foreach(stream_get_meta_data($fp) as $response)
{
if (substr(strtolower($response), 0, 10) == 'location: ')
{
$url = substr($response, 10);
}
}
?>
在php5中新增的stream_context_create函数,使模拟HTTP请求更加的灵活,如:
<?php
$data = array ('foo' => 'bar');
$data = http_build_query($data);
$opts = array (
'http' => array (
'method' => 'POST',
'header'=> "Content-type: application/x-www-form-urlencoded\r\n" .
"Content-Length: " . strlen($data) . "\r\n",
'content' => $data
),
);
$context = stream_context_create($opts);
$html = file_get_contents('http://www.example.com', false, $context);
echo $html;
以下是 PHP 内置用于文件系统函数 fopen()、copy()等URL风格协议列表。除了这些封装协议之外,从 PHP 4.3 起,还可以用 PHP 脚本和 stream_wrapper_register() 创建自己的封装协议。
HTTP 和 HTTPS
PHP 3,PHP 4。自 PHP 4.3.0 起支持
https://
http://example.com
http://user:password@example.com
https://example.com
https://user:password@example.com
允许通过 HTTP 1.0 使用 HTTP GET 方法对文件/资源进行只读访问。Host: 报头也会通过请求发送出去以支持基于域名的虚拟主机。如果你在 ini 文件或者流上下文配置了 user_agent 字符串,也会被包括在请求报头中。
自 PHP 4.0.5 起支持重定向。如果使用较早版本的 PHP 则需要在 URL 末尾包括一个斜线。如果一定要知道文档所在的资源的 url(在所有重定向被处理过之后),则需要处理从流返回的一系列响应报头信息。
<?php
$url = 'http://www.example.com/';
$fp = fopen($url, 'r');
foreach(stream_get_meta_data($fp) as $response)
{
if (substr(strtolower($response), 0, 10) == 'location: ')
{
$url = substr($response, 10);
}
}
?>
在php5中新增的stream_context_create函数,使模拟HTTP请求更加的灵活,如:
<?php
$data = array ('foo' => 'bar');
$data = http_build_query($data);
$opts = array (
'http' => array (
'method' => 'POST',
'header'=> "Content-type: application/x-www-form-urlencoded\r\n" .
"Content-Length: " . strlen($data) . "\r\n",
'content' => $data
),
);
$context = stream_context_create($opts);
$html = file_get_contents('http://www.example.com', false, $context);
echo $html;
?>
原文地址:http://hi.baidu.com/nathena/item/fc0ab39a391634df7b7f0193