본문 바로가기

Web Programings/PHP

[PHP] php끼리 post 송수신 하기

반응형
<?php

function post_request($url, $data) {
	// Convert the data array into URL Parameters like a=b&foo=bar etc.
	$data = http_build_query($data);

	// parse the given URL
	$url = parse_url($url);

	if ($url['scheme'] != 'http') {
		return "Error:Only HTTP request are supported!";
	}

	// extract host and path:
	$host = $url['host'];
	$path = $url['path'];
	$res = '';

	// open a socket connection on port 80 - timeout: 300 sec
	if ($fp = fsockopen($host, 80, $errno, $errstr, 300)) {
		$reqBody = $data;
		$reqHeader = "POST $path HTTP/1.1\r\n" . "Host: $host\r\n";
		$reqHeader .= "Content-type: application/x-www-form-urlencoded\r\n"
		. "Content-length: " . strlen($reqBody) . "\r\n"
		. "Connection: close\r\n\r\n";

		/* send request */
		fwrite($fp, $reqHeader);
		fwrite($fp, $reqBody);

		while(!feof($fp)) {
			$res .= fgets($fp, 1024);
		}

		fclose($fp);
	} else {
		return "Error:Cannot Connect!";
	}

	// split the result header from the content
	$result = explode("\r\n\r\n", $res, 2);

	$header = isset($result[0]) ? $result[0] : '';
	$content = isset($result[1]) ? $result[1] : '';

	return $content;
}

// usage
$url =  "http://www.example.com/receiver.php";
$data = array("key" => "value");
$res = post_request($url, $value);

?> 
반응형

'Web Programings > PHP' 카테고리의 다른 글

[PHP] HTML 작업시 PHP의 에러 출력하기  (0) 2013.06.10
[PHP] PHP로 URL의 결과 값 가져오기  (0) 2013.05.23
[php] URL 링크 제공하기  (0) 2013.01.10
[PHP] 함수 목록 및 기능  (0) 2013.01.10
[PHP] PHP에서 정규식  (0) 2012.09.06