stream_context_create() 模拟 POST、GET数据

来源:互联网 发布:淘宝评价了还能退款吗 编辑:程序博客网 时间:2024/06/03 14:08

利用 stream_context_create() 模拟 POST、GET数据,获取数据,CURL一样强大,

模拟post数据

$data = array(
    'foo'=>'bar',
    'baz'=>'boom',
    'site'=>'www.nowamagic.net',
    'name'=>'nowa magic');
    
$data = http_build_query($data);

//$postdata = http_build_query($data);
$options = array(
    'http' => array(
        'method' => 'POST',
        'header' => 'Content-type:application/x-www-form-urlencoded',
        'content' => $data
        //'timeout' => 60 * 60 // 超时时间(单位:s)
    )
);

$url = "http://www.nowamagic.net/test2.php";
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

echo $result;


1. 以上程序用到了 http_build_query() 函数,如果需要了解,可以参看PHP函数补完:http_build_query()构造URL字符串。

2. stream_context_create() 是用来创建打开文件的上下文件选项的,比如用POST访问,使用代理,发送header等。就是创建一个流,

3. stream_context_create创建的上下文选项即可用于流(stream),也可用于文件系统(file system)。对于像 file_get_contents、file_put_contents、readfile直接使用文件名操作而没有文件句柄的函数来说更有用。stream_context_create增加header头只是一部份功能,还可以定义代理、超时等。这使得访问web的功能不弱于curl。


模拟GET数据


$opts = array(
    'http'=>array(
    'method'=>"GET",
    'timeout'=>60,
  )
);
//创建数据流上下文
$context = stream_context_create($opts);

$html =file_get_contents('http://www.nowamagic.net', false, $context);

//fopen输出文件指针处的所有剩余数据:
//fpassthru($fp); //fclose()前使用



0 0