有时候,我们需要在服务器端模拟 post/get 等请求,也就是在 php 程序中去实现模拟,改怎么做到呢?或者说,在 php 程序里,给你一个数组,如何将这个数组 post/get 到另外一个地址呢?当然,使用 curl 很容易办到,那么如果不使用 curl 库,又该怎么办呢?其实,在 php 里已经有相关的函数实现了,这个函数就是接下来要讲的 stream_context_create()。
直接 show you the code,这是最好的方法
立即学习“PHP免费学习笔记(深入)”;
<?php$data = array( 'foo'=>'bar', 'baz'=>'boom', 'site'=>'www.example.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://127.0.0.1/test2.php";$context = stream_context_create($options);$result = file_get_contents($url, false, $context);echo $result;?>
立即学习“PHP免费学习笔记(深入)”;
立即学习“PHP免费学习笔记(深入)”;
<?php $data = $_POST;echo '<pre class="brush:php;toolbar:false;">';print_r( $data );echo '
立即学习“PHP免费学习笔记(深入)”;
Array
(
[foo] => bar
[baz] => boom
[site] => www.example.net
[name] => nowa magic
)
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号