首页 > IT职业 > IT职场 > PHP 发送GET 和 POST数据的方法分析
一、使用GET方法
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: enrn"
)
);
$context = stream_context_create($opts);
$file = file_get_contents('http://www.yourhost.com/', false, $context);
?>
如果要提交参数,务必使用:http_build_query方法,如:
$data = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
$querystr = http_build_query($data);
?>
二、使用POST方法
$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-urlencodedrn"
. "Content-Length: " . strlen($data) . "rn",
'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解码。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4422/viewspace-2809093/ ,如需转载,请注明出处,否则将追究法律责任。