实例代码:
// 请求路径 $url='http://10.118.27.138/login?user=hello&age=20'; $data = parse_url($url); // 请求方法 $method='POST'; // 头部信息 $host=$data['host']; $port=isset($data['port'])?$data['port']:80; $path=$data['path']; $query=isset($data['query'])?$data['query']:''; $content_type='application/x-www-form-urlencoded; charset=UTF-8'; $referer='http://www.example.com'; $accept='text/html,application/xhtml+xml,application/xml'; $cookie='session_id=123456; Path=/; Expires='.gmdate("l, d F Y H:i:s",time()+60*60).' GMT'; // 超时时间,单位秒 $timeout=10; // 换行符,必须使用双引号才能识别 $CRLF="\r\n"; // 打开socket $fp = fsockopen ( $host,$port,$errno,$errstr,$timeout); if (!$fp) { echo 'errno:'.$errno.',errstr:'.$errstr; exit; } // 开始组装http报文 // get方式参数放在url上 if($method=='GET'){ $path=$path.'?'.$query; } $out = $method.' '.$path.' HTTP/1.1'.$CRLF; // 添加头部信息 $out.= 'Host: '.$host.$CRLF; $out.= 'Connection: Close'.$CRLF; $out.= 'Accept: '.$accept.$CRLF; $out.= 'Referer: '.$referer.$CRLF; // 设置cookie if($cookie){ $out.= 'Cookie: '.$cookie.$CRLF; } // 设置post参数 if($method=='POST'){ $out.= 'Content-Type: '.$content_type.$CRLF; $out.= 'Content-length: '.strlen($query).$CRLF; $out.=$CRLF; $out.=$query; } // 组装http报文结束 $out.=$CRLF; // 进行数据交互 fwrite($fp, $out); while (!feof($fp)) { // 打印响应报文 echo fgets($fp, 128); } fclose($fp);
后端可以通过$GLOBALS查看提交的内容
var_dump($GLOBALS);
更多设置请查看这里
Leave a Reply