上下文(Context)选项和参数

PHP 提供了多种上下文选项和参数,可用于所有的文件系统或数据流封装协议。上下文(Context)由 stream_context_create() 创建。选项可通过stream_context_set_option() 设置,参数可通过 stream_context_set_params() 设置。

Example #1 获取一个页面并发送 POST 数据

<?php

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

?>

Example #2 忽略重定向并获取 header 和内容
 

<?php

$url = "http://www.example.org/header.php";

$opts = array('http' =>
    array(
        'method' => 'GET',
        'max_redirects' => '0',
        'ignore_errors' => '1'
    )
);

$context = stream_context_create($opts);
$stream = fopen($url, 'r', false, $context);

// header information as well as meta data
// about the stream
var_dump(stream_get_meta_data($stream));

// actual data at $url
var_dump(stream_get_contents($stream));
fclose($stream);
?>

猜你喜欢

转载自blog.csdn.net/huawuque004/article/details/84628229