构造post请求的几种方式

2 篇文章 0 订阅

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值