Socket编程 之使用fsockopen()函数

时间:2023-03-08 23:02:37
Socket编程 之使用fsockopen()函数

fsockopen函数:初始化一个套接字连接到指定主机(hostname

get方式:

client.php

 <?php
//创建连接
$fp=fsockopen('localhost',80,$error,$errstr,10); //检测
if (!$fp){
echo $errstr;die;
} //拼接http请求报文
$http=''; //请求报文包括3部分 请求行 请求头 请求体
$http.="GET /phpStudy/http/server.php?username=huahua HTTP1.1\r\n"; //请求头信息
$http.="Host:localhost\r\n";
$http.="Connection:close\r\n\r\n"; //请求体:无 //发送请求
fwrite($fp,$http); //获取结果
$res='';
while(!feof($fp)){
$res.=fgets($fp);
} //输出内容
echo $res;

server.php

 <?php
//打印$_POST检测参数有没有过来
var_dump($_POST); //打印cookie内容
// var_dump($_COOKIE); //打印server的内容
// var_dump($_SERVER); //打印$_GET
// var_dump($_GET); //打印$GLOBALS
var_dump($GLOBALS);

post方式:

post.php

 <?php
//创建连接
$fp=fsockopen('localhost',80,$errno,$errstr,10); //检测
if (!$fp){
echo $errstr;die;
} //拼接http请求报文
$http=''; //请求报文包括3部分 请求行 请求头 请求体
$http.="POST /phpStudy/http/server.php HTTP/1.1\r\n"; //请求头信息
$http.="Host:localhost\r\n";
$http.="Connection:close\r\n";
$http.="Cookie:username=admin;uid=200\r\n";
$http.="User-agent:firefox-chrome-safari-ios-android\r\n";
$http.="Content-type:application/x-www-form-urlencoded\r\n";
$http.="Content-length:39\r\n\r\n"; //请求体
$http.="email=xiaohigh22@163.com&username=admin\r\n"; //发送请求
fwrite($fp,$http); //获取结果
$res='';
while(!feof($fp)){
$res.=fgets($fp);
} //输出内容
echo $res;

问题1:返回内容我们用什么?echo

问题2:请求体包括哪3部分? 行 头 体

问题3:使用post方式请求时,使用什么符号来连接参数?&