构造post请求的几种方式分别为以下情景:
1. 使用file_get_contents()构造post请求
$postData = [
'content' => '1231445',
];
$postData = http_build_query($postData);
$opts = [
'http' => [
'method' => 'POST',
'header' => "Host:localhost\r\n" .
"Content-Type: application/x-www-form-urlencoded\r\n" .
'Content-length: '. strlen($postData) . "\r\n",
'content' => $postData,
]
];
$context = stream_context_create($opts);
file_get_contents('http://localhost/test.php', false, $context);
2. 使用fopen()构造post请求
$postData = [
'content' => 'fopen-----123123',
];
$postData = http_build_query($postData);
$opts = [
'http' => [
'method' => 'POST',
'header' => "Host:localhost\r\n" .
"Content-Type: application/x-www-form-urlencoded\r\n" .
'Content-length: '. strlen($postData) . "\r\n",
'content' => $postData,
]
];
$context = stream_context_create($opts);
$fp = fopen('http://localhost/test.php', 'r', false, $context);
fclose($fp);
3. 使用curl 构造post请求
$url = 'http://localhost/test.php';
$postData = [
'content' => 'curl-----123123',
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_exec($ch);
curl_close($ch);
4. 使用fsocket()构造post请求
$postData = [
'content' => 'socket-----123123',
];
$postData = http_build_query($postData);
$fp = fsockopen("localhost", 80, $errno, $errstr, 5);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "POST /test.php HTTP/1.1\r\n";
$out .= "Host:localhost\r\n";
$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
$out .= "Content-length: ". strlen($postData) . "\r\n\r\n";
$out .= $postData;
fwrite($fp, $out);
fclose($fp);
}