利用fsockopen模拟HTTP发送请求

首先检查PHP.ini 中 allow_url_fopen 选项是否开启,需要开启

GET 方式发送请求

$fp = fsockopen('localhost', 80, $errno, $errstr, 10);//host 端口 错误码 错误消息 超时时间

if(!$fp){
    echo $errstr;die;
}

$http = "";
//请求行
$http = "GET /http/server.php?use=111&name=oop HTTP/1.1\r\n";//以\r\n结尾 固定格式 连接地址为绝对路径

//请求头
$http .= "Host: localhost\r\n";
$http .= "Connection: close\r\n\r\n";//close:返回结果后关闭连接 请求头结束:结尾两个\r\n

//get 请求方式没有请求体
fwrite($fp, $http);

$result = "";

while(!feof($fp)){
    $result .= fgets($fp);//默认一次取1k字节数据
}

echo  $result;

POST方式

$fp = fsockopen('localhost', 80, $errno, $errstr, 10);

if(!$fp){
    echo $errstr;exit();
}

$http = "";
$body = "email=111@qq.com&username=admin";
//请求行
$http .= "POST /http/server.php HTTP/1.1 \r\n";
//请求头
$http .= "Host: localhost\r\n";
$http .= "Connection: close\r\n";
$http .= "Cookie: username=111;uid=2\r\n";
$http .= "User-agent: firefox\r\n";
$http .= "Content-type: application/x-www-form-urlencoded\r\n";//必须传
$http .= "Content-length: ".strlen(trim($body))."\r\n\r\n";//请求行和体中间两个\r\n 

//请求体
$http .= $body."\r\n";
//发送
fwrite($fp, $http);

$result = "";
while (!feof($fp)) {

    $result .= fgets($fp);

}

echo $result;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值