在php程序的开发中,传值和接收数据是最基础的功能。网站很多地方需要使用到表单数据的提交、URL参数的解析以及API站外数据的传递和接收等。本文主要介绍PHP对post和get这两种数据传递和接收方式的使用!
一、POST传值
在 PHP 中,有几种常用的方法可以发送 POST 数据。以下是几种常见的方法:
1. 使用curl库发送 POST 请求:
$data = array(
'param1' => 'value1',
'param2' => 'value2'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);
这种方法使用curl库发送 POST 请求,并可以在CURLOPT_POSTFIELDS中设置要发送的数据。
2. 使用file_get_contents()函数发送 POST 请求:
$data = array(
'param1' => 'value1',
'param2' => 'value2'
);
$options = array(
'http' => array(
'header' => 'Content-type: application/x-www-form-urlencoded',
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$response = file_get_contents('http://example.com', false, $context);
这种方法使用 stream_context_create()
函数创建一个上下文,并使用 file_get_contents()
函数发送 POST 请求。可以在上下文选项中设置请求头和发送的数据。