構造post請求的幾種方式

 構造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);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章