PHP fsockopen模拟POST/GET方法

fsockopen除了像上面实例模拟生成 HTTP 连接之外,还能实现很多功能,比如模拟post 和 get 传送数据的方法。
get :

<?php
$url = "http://localhost/test2.php?site=www.tbrer.com";
print_r(parse_url($url));// 解析 URL,返回其组成部分

/* get提交 */
sock_get($url,'user=gonn');

// fsocket模拟get提交
function sock_get($url,$query){
$data = array(
'foo' => 'bar',
'baz' => 'boom',
'site' => 'www.tbrer.com',
'name' => 'nowa magic'
);

$query_str = http_build_query($data);// http_build_query()函数的作用是使用给出的关联(或下标)数组生成一个经过 URL-encode 的请求字符串

$info = parse_url($url);
$fp = fsockopen($info["host"],80,$errno,$errstr,30);
$head = "GET " . $info['path'] . '?' . $query_str . " HTTP/1.0\r\n";
$head .= "Host: " . $info['host'] . "\r\n";
$head .= "\r\n";
$write = fputs($fp,$head);
while(!feof($fp)){
$line = fread($fp,4096);
echo $line;
}
}
?>

<?php
$url = "http://localhost/test2.php?site=www.tbrer.com";
print_r(parse_url($url));// 解析 URL,返回其组成部分

/* post提交 */
sock_post($url,'user=gonn');

// fsocket模拟post提交
function sock_post($url,$query){
$info = parse_url($url);
$fp = fsockopen($info["host"],80,$errno,$errstr,30);
$head = "POST " . $info['path'] . "?" . $info["query"] . " HTTP/1.0\r\n";
$head .= "Host: " . $info['host'] . "\r\n";
$head .= "Referer: http://" . $info['host'] . $info['path'] . "\r\n";
$head .= "Content-type: application/x-www-form-urlencoded\r\n";
$head .= "Content-Length: ". strlen(trim($query)) . "\r\n";
$head .= "\r\n";
$head .= trim($query);
$write = fputs($fp,$head);
while(!feof($fp)){
$line = fread($fp,4096);
echo $line;
}
}
?>

接收页面 test2.php 的代码为:

<?php
$data = $_REQUEST;

echo '<pre>';
print_r($data);
echo '</pre>';
?>
————————————————
原文链接:https://blog.csdn.net/zjsfdx/article/details/89376176

posted @   旅行者无声  阅读(179)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示