PHP POSTDATA 函数(COOKIE保存)

 用post方式提交数据,记录cookie,同时第二次提交数据带上cookie,

能够进行模拟登陆,获取数据。

 

更好的方式可以用 zend库,但是比较冗余,不是很喜欢。

所以写个简单的用用。

 

<?
$url="http://xxx/login.cgi";
$data=array(
"xx"=>"xx",
"yy"=>"yy",
"zz"=>1,
"dd"=>"",
);

$httpRequest=new HttpRequest();

$res=array();
$res=$httpRequest->request($url,$data);
print_r($res);

$cookie=$httpRequest->getCookie();

var_dump($cookie);

$url="http://xxx/getmsg.cgi";
$data=array(
);

$res=array();
$res=$httpRequest->request($url,$data);

print_r($res);

$cookie=$httpRequest->getCookie();

var_dump($cookie);

Class HttpRequest
{
var $header=array();

function getHeader()
{
return $this->header;
}

function setCookie($cookie=false)
{
if(!empty($cookie))
{
$this->header[‘Set-Cookie’]=$cookie;
}
}
function getCookie()
{
return $this->header[‘Set-Cookie’];
}
function request($ourl, $data)
{
$url = parse_url($ourl);
if (!$url)
{
return array("FLAG"=>0,"MSG"=>"the url [ ${ourl} ] is not a valid httpUrl");
}

if (!isset($url[‘port’])) { $url[‘port’] = ""; }

if (!isset($url[‘query’])) { $url[‘query’] = ""; }

$encoded = "";

while (list($k,$v) = each($data))
{
$encoded .= ($encoded ? "&" : "");
$encoded .= rawurlencode($k)."=".rawurlencode($v);
}

$fp = fsockopen($url[‘host’], $url[‘port’] ? $url[‘port’] : 80);

if (!$fp)
{
return array("FLAG"=>0,"MSG"=>"fail to open the url ${ourl}");
}

$tmp="";
$tmp.=sprintf("POST %s%s%s HTTP/1.0\r\n", $url[‘path’], $url[‘query’] ? "?" : "", $url[‘query’]);
$tmp.="Host: $url[host]\r\n";
$tmp.="Content-type: application/x-www-form-urlencoded\r\n";
$tmp.="Content-Length: " . strlen($encoded) . "\r\n";

if(!empty($this->header[‘Set-Cookie’]))
{
$cookieStr="Cookie: ";
foreach($this->header[‘Set-Cookie’] as $key=>$val)
{
$cookieStr.=substr($val,0,strpos($val,";")+1) ;
}

$tmp.=$cookieStr."\r\n";

}

$tmp.="Connection: close\r\n\r\n";
$tmp.="$encoded\r\n";

fputs($fp,$tmp);

$line = fgets($fp,1024);

$status200=false;
$status302=false;

if(eregi("^HTTP/1\.. 200", $line))
{
$this->header[‘status’]=’200′;
$status200=true;
}

elseif(eregi("^HTTP/1\.. 302", $line))
{
$this->header[‘status’]=’302′;
$status302=true;
}
else
{
return array("FLAG"=>0,"MSG"=>$line);
}

$results = "";
$inheader = 1;
while(!feof($fp))
{
$line = fgets($fp,1024);
echo $line."\n";

if ($inheader && ($line == "\n" || $line == "\r\n"))
{
$inheader = 0;
}
elseif (!$inheader)
{
$results .= $line;
}
else
{
list($key,$val)=explode(":",$line);
$this->header[$key][]=trim($val);
}
}
fclose($fp);

return array("FLAG"=>1,"MSG"=>$results);

}
}

?>

发表评论

您的电子邮箱地址不会被公开。