您的位置:首页 > 理论基础 > 计算机网络

PHP 发送HTTP post请求发送和获取

2013-03-13 15:55 232 查看
 

发送POST请求

和GET方法一样,POST方法也是HTTP协议中的一个重要组成部分。POST方法一般用来向目的服务器发出请求,并附有请求实体。
POST被设计成用统一的方法实现下列功能:
     o 对现有资源的注释(Annotation of existing resources);
     o 向电子公告栏、新闻组,邮件列表或类似讨论组发送消息;
     o 提交数据块,如将表格(form)的结果提交给数据处理过程;
     o 通过附加操作来扩展数据库。
     o 也可用来上传文件。
在所有的HTTP的POST请求中,必须指定合法的内容长度(Content-Length)。
如果HTTP/1.0服务器在接收到请求消息内容时无法确定其长度,就会返回400(非法请求)代码。
应用程序不能缓存对POST请求的回应,因为做为应用程序来说,它们没有办法知道服务器在未来的请求中将如何回应。
POST方式和GET方法的最大区别就是把发送的数据和URI地址分离。请求参数是在http标题的一个不同部分(名为entity body)传输的,这一部分用来传输表单信息,因此必须将Content-type设置为:application/x-www-form- urlencoded
Post请求格式如下:
POST /login.asp HTTP/1.1
Accept: */*
Referer: http://www.wantsoft.com
Accept-Language: zh-cn,en-us;q=0.5
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; .NET CLR 1.0.3705; .NET CLR 1.1.4322)
Host: www.wantsoft.com
Content-Length: 35
Pragma: no-cache
Cache-Control: no-cache
username=wantsoft&password=password   //post的数据

[code] <;?php


$srv_ip = '127.0.0.1';//你的目标服务地址或频道.


$srv_port = 80;


$url = '/helloworld/?r=helloworld'; //接收你post的URL具体地址


$fp = '';


$resp_str = '';


$errno = 0;


$errstr = '';


$timeout = 10;


$post_str = "username=demo&str=aaaa";//要提交的内容.




//echo $url_str;


if ($srv_ip == ''){


 echo('ip or dest url empty<;br>');


}


//echo($srv_ip);


$fp = fsockopen($srv_ip,$srv_port,$errno,$errstr,$timeout);


if (!$fp){


 echo('fp fail');


}


$content_length = strlen($post_str);


$post_header = "POST $url HTTP/1.1\r\n";


$post_header .= "Content-Type: application/x-www-form-urlencoded\r\n";


$post_header .= "User-Agent: MSIE\r\n";


$post_header .= "Host: ".$srv_ip."\r\n";


$post_header .= "Content-Length: ".$content_length."\r\n";


$post_header .= "Connection: close\r\n\r\n";


$post_header .= $post_str."\r\n\r\n";


fwrite($fp,$post_header);


while(!feof($fp)){


 $resp_str .= fgets($fp,512);//返回值放入$resp_str


}


fclose($fp);


echo($resp_str);//处理返回值.


//unset ($resp_str);


?>

[/code]

[code] echo "<br> Post Data is :<br>";


foreach($_POST as $key=>$val)


{


 echo "key:$key,val:$val<br>";


}




$data = file_get_contents("php://input");


echo $data.'<br>';


echo $GLOBALS['HTTP_RAW_POST_DATA'];

[/code]
[/code]

结果如下:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: