php post到指定URL——fsockopen

<?php
function sendpost($url, $data){
	//先解析url
	$url = parse_url($url);
	$url_port = !isset($url['port']) ? (($url['scheme'] == 'http') ? 80 : 443) : $url['port'];
	if (!$url)
	{
		return "couldn't parse url";
	}
	//将参数拼成URL key1=value1&key2=value2 的形式
	$encoded = "";
	while (list($k, $v) = each($data))
	{
		$encoded .= ($encoded ? '&' : '');
		$encoded .= rawurlencode($k)."=".rawurlencode($v);
	}
	$len = strlen($encoded);
	//拼上http头
	$out = "POST ".$url['path'].(isset($url['query']) ? ('?'.$url['query']) : '')." HTTP/1.1\r\n";
	$out .= "Host:".$url['host']."\r\n";
	$out .= "Content-type: application/x-www-form-urlencoded\r\n";
	$out .= "Connection: Close\r\n";
	$out .= "Content-Length: $len\r\n";
	$out .= "\r\n";
	$out .= $encoded."\r\n";
	//打开一个sock
	$fp = @fsockopen($url['host'], $url_port);
	$line = "";
	if(!$fp){
		echo "$errstr($errno)\n";
	}else{
		fwrite($fp,$out);
		while (!feof($fp))
		{
			$line .= fgets($fp, 2048);
		}
	}
	//去掉头文件
	if ($line)
	{
		$body = stristr($line, "\r\n\r\n");
		$body =substr($body, 4, strlen($body));
		$line = $body;
	}
	fclose($fp);
	return $line;
}
	$arrVal["eee"] = "Hello";
	$arrVal["ee"] = "Sorry";
	echo sendpost("http://localhost/test.php",$arrVal);
?>

post.php 的内容
<?php
	while(list($k,$v) = each($HTTP_POST_VARS)){
	   echo "<h1>".$k."=".$v."<h1><br />";
	}
?>



function sendpost($url, $data,$sendType='POST'){
	//先解析url
	$url = parse_url($url);
	$url_port = !isset($url['port']) ? (($url['scheme'] == 'http') ? 80 : 443) : $url['port'];
	if (!$url)
	{
		return "couldn't parse url";
	}
	//将参数拼成URL key1=value1&key2=value2 的形式
	$encoded = "";
	while (list($k, $v) = each($data))
	{
		$encoded .= ($encoded ? '&' : '');
		$encoded .= rawurlencode($k)."=".rawurlencode($v);
	}
	$len = strlen($encoded);
	//拼上http头
	$out = "{$sendType} ".$url['path'].(isset($url['query']) ? ('?'.$url['query']) : '')." HTTP/1.1\r\n";
	$out .= "Host:".$url['host']."\r\n";
	$out .= "Content-type: application/x-www-form-urlencoded\r\n";
	$out .= "Connection: Close\r\n";
	$out .= "Content-Length: $len\r\n";
	$out .= "\r\n";
	$out .= $encoded."\r\n";
	//打开一个sock
	$fp = @fsockopen($url['host'], $url_port);
	$line = "";
	if(!$fp){
		echo "$errstr($errno)\n";
	}else{
		fwrite($fp,$out);
		while (!feof($fp))
		{
			$line .= fgets($fp, 2048);
		}
	}
	//去掉头文件
	if ($line)
	{
		$body = stristr($line, "\r\n\r\n");
		$body =substr($body, 4, strlen($body));
		$line = $body;
	}
	fclose($fp);
	return $line;
}



此文章来自网上,仅供参考

你可能感兴趣的:(PHP,url,get,post,fsockopen)