hi,欢迎访问本站!
当前位置: 首页编程开发正文

php使用 file_get_contents 发送post或get请求的方法

墨初 编程开发 513阅读

php中请求一个远程的数据时一般都是使用CURL工具,curl工具不仅仅使用GET提交数据协议,也能使用POST提交数据协议。除了curl工具以外,php还内置了一个远程请求的函数 file_get_contents.此函数同样也在使用GET或POST请求数据,下面是使用方法。

php file_get_contents() 发送GET请求的方法

例:

$data = array( 'username'=>'zhezhao','userpass'=>'123');
$query = http_build_query($data);
//请求的地址
$url = 'http://localhost/get.php';
$result = file_get_contents($url.'?'.$query);

php file_get_contents() 发送POST请求的方法

例:

# 73so.com
$data = array( 'username'=>'zhezhao','userpass'=>'123');
$requestBody = http_build_query($data);
$context = stream_context_create(['http' => ['method' => 'POST', 'header' => "Content-Type: application/x-www-form-urlencoded\r\n"."Content-Length: " . mb_strlen($requestBody), 'content' => $requestBody]]);
$response = file_get_contents('http://localhost/get.php', false, $context);
声明:无特别说明,转载请标明本文来源!
相关推荐