入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

file_get_contents模拟GET/POST请求

创建时间:2016-03-11 投稿人: 浏览次数:6464

模拟GET请求:

GET请求就是在访问URL的时候加上参数即可,我们首先使用http_build_query方法将数组转化为url参数,然后使用file_get_contents获取内容即可。

get.php

<?php

echo "GET responses are:<hr/>";
echo "<pre>";
var_dump($_GET);
echo "</pre>";

test.php

<?php
$data = array(
    "name"=>"zhezhao",
    "age"=>"23"
    );
$query = http_build_query($data);

$url = "http://localhost/get.php";//这里一定要写完整的服务页面地址,否则php程序不会运行

$result = file_get_contents($url."?".$query);

echo $result;

模拟POST请求:

post.php

<?php

echo "POST responses are:<hr/>";
echo "<pre>";
var_dump($_POST);
echo "</pre>";

test.php

<?php
$data = array(
    "name"=>"zhezhao",
    "age"=>23
    ); 

$query = http_build_query($data); 

$options["http"] = array(
     "timeout"=>60,
     "method" => "POST",
     "header" => "Content-type:application/x-www-form-urlencoded",
     "content" => $query
    );

$url = "http://localhost/post.php";
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

echo $result;
?>
阅读更多
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。