一、使用GET方法
<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n"
)
);
$context = stream_context_create($opts);
$file = file_get_contents('http://www.yourhost.com/', false, $context);
?>
如果要提交参数,务必使用:http_build_query方法,如:
<?php
$data = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
$querystr = http_build_query($data);
?>
二、使用POST方法
<?php
$data = array ('foo' => 'bar', 'bar' => 'baz');
$data = http_build_query($data);
$context_options = array (
'http' => array (
'method' => 'POST',
'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
. "Content-Length: " . strlen($data) . "\r\n",
'content' => $data
)
);
$context = context_create_stream($context_options)
$fp = fopen('http://www.yourhost.com/', 'r', false, $context);
?>
三、重点提示
http_build_query会对参数值进行urlencode,接收端的$_GET或$_REQUEST会自动进行urldecode;
如果发送请求时没有进行或者只对部分参数进行urlencode,接收代码$_REQUEST可能不会进行自动urldecode解码。