PHP 模拟POST 数据

By | 2012 年 8 月 16 日

1.fsockopen方式,可post图片:
//例子:socket_post('http://site.com/', array('key1'=>'value1', 'key2'=>'value2'), array('filekey'=>'filepath'))

function socket_post($url, $postdata=array(), $files=array()) { 
	$boundary = '-------'.substr(md5(rand(0,32000)),0,10); 
	$encoded = ""; 
	if($postdata){ 
		while(list($k,$v) = each($postdata)){ 
			$encoded .= "--$boundary\r\nContent-Disposition: form-data; 
			name=\"".rawurlencode($k)."\"\r\n\r\n"; 
			$encoded .= rawurlencode($v)."\r\n"; 
		} 
	} 
	if($files){ 
		foreach($files as $name=>$file){ 
			$ext= strtolower(strrchr($file,".")); 
			switch($ext){ 
				case '.gif': $type = "image/gif"; break; 
				case '.jpg': $type = "image/jpeg"; break; 
				case '.png': $type = "image/png"; 
				break; default: $type = "image/jpeg"; 
			} 
			$encoded .= "--$boundary\r\nContent-Disposition: form-data; 
			name=\"".rawurlencode($name)."\"; 
			filename=\"$file\"\r\nContent-Type: $type\r\n\r\n"; 
			$encoded .= join("", file($file)); $encoded .= "\r\n"; 
		} 
	} 
	$encoded .= "--$boundary--\r\n"; 
	$length = strlen($encoded); 
	$uri = parse_url($url); 
	$fp = fsockopen($uri['host'], $uri['port'] ? $uri['port'] : 80); 
	if(!$fp) return "Failed to open socket to ".$uri['host']; 
	fputs($fp, sprintf("POST %s%s%s HTTP/1.0\r\n", $uri['path'], $uri['query'] ? "?" : "", $uri['query'])); 
	fputs($fp, "Host: ".$uri['host']."\r\n"); 
	fputs($fp, "Content-type: multipart/form-data; boundary=$boundary\r\n"); 
	fputs($fp, "Content-length: $length\r\n"); 
	fputs($fp, "Connection: close\r\n\r\n"); 
	fputs($fp, $encoded); 
	$results = ""; 
	while(!feof($fp)){ 
		$results .= fgets($fp,1024); 
		} 
	fclose($fp); 
	return preg_replace('/^HTTP(.*?)\r\n\r\n/s','',$results); 
}

2.file_get_contents方式,不能post文件: 

	function Post($url, $post = null) { 
		$context = array(); 
		if (is_array($post)) { 
			ksort($post); 
			$context['http'] = array ( 
				'method' => 'POST', 
				'header'=>'Content-type: application/x-www-form-urlencoded', 
				'content' => http_build_query($post, '', '&')
				); 
		} 
		return file_get_contents($url, false, stream_context_create($context)); 
	}

发表回复

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据