네이버 api작업하다 필요해서만든 소켓통신함수...
호스팅 환경이 php4다보니 이것저것 함수에 제한이 좀 있어서 검색한거에
내가 쓸만하게끔 변경함..
- GET,POST,다른포트, ssl도 그냥 되도록 만듬. http1.0이용
- http1.1에선 추가할헤더나 데이터에 이상한값문제로 보류함.
- http_build_query 가지원안되는 버젼에서는 함수를 생성하도록함.
[사용]
$_url = "http://openapi.naver.com/search";
$_send_data = array(
'key'=> API_KEY
,'target' => "recmd"
,'query' => iconv("euc-kr","utf-8",$sch_key)
);
$_return_data = get_socket($_url, $_send_data,"GET");
결과값은 배열로 리턴
return array(
'status' => 'ok' //실행결과
,'header' => $header //받은헤더
,'content' => $content // 받은데이터
,'urls' => $path //접속url
);
#######################################
[2014-04 추가] agent, cookie 부분추가.
사용 - 로그인이 필요한 경우나 cookie가 필요한경우 최초 접속시 생성된 쿠키를 변수에 담아두고 이후 재사용 - AGENT 는 필요한 경우에 셋팅 --------------------------------------------------------------------- 1. 로그인시 또는 최초접속
$_url = "로그인url"; $_set = array( 'return_type'=> 'json' ,'userid'=> $_uid ,'userpasswd'=> $_pw ); $_res = get_socket($_url,$_set,'POST','',AGENT ); $_result = $_res['status']; if( $_result == 'ok'){ preg_match_all("/Set-Cookie: [^\n]+/", $_res['header'], $_cook); $_cookies = array(); foreach($_cook[0] AS $_V){ $_tmp = explode(";",$_V); $_tmp1 = explode("=",str_replace('Set-Cookie: ','',$_tmp[0])); $_cookies[$_tmp1[0]] = $_tmp1[1]; } } ------------------------------------------------------------------------- 2. 이후 계속 쿠키를 재사용 $_url = "작업url"; $_set = array( 'return_type'=> 'json' ); $_res = get_socket($_url,$_set,'GET','',AGENT,$_cookies ); $_result = $_res['status']; if( $_result == 'ok'){ blah blah~~~ }else{ blah blah~~~ }
더보기(개정판) 접기(개정판)
function get_socket($url, $data,$method='GET', $referer='',$_agent='',$_cookie="") { $data = http_build_query($data); $url = parse_url($url); $host = $url['host']; $path = $url['path']; $port = $url['port']; if(!$port){$port=80;} // open a socket connection on port 80 - timeout: 30 sec switch($url['scheme']){ case "http": $fp = @fsockopen($host, $port, $errno, $errstr, 10); break; case "https": $fp = @fsockopen("ssl://".$host, $port, $errno, $errstr, 10); break; default : return array( 'status' => 'Error', 'error' => "https or http protocol required" ); exit; } if ($fp){ if($method == "GET"){ $path .= "?".$data; } @fputs($fp, $method." $path HTTP/1.0\r\n"); @fputs($fp, "Host: $host\r\n"); if($_agent !=""){ @fputs($fp, "User-Agent: $_agent\r\n"); } if($referer !=""){ @fputs($fp, "Referer: $referer\r\n"); } if(is_array($_cookie)){ $_cook_val = ""; foreach($_cookie AS $_K=>$_V){ $_cook_val .= "{$_K}={$_V}; "; } @fputs($fp, "Cookie: ".$_cook_val."\r\n"); } @fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); @fputs($fp, "Content-length: ". strlen($data) ."\r\n"); @fputs($fp, "Connection: close\r\n\r\n"); @fputs($fp, $data); $result = ''; while(!feof($fp)) { // receive the results of the request $result .= fgets($fp, 128); } }else { return array( 'status' => 'err', 'error' => "$errstr ($errno)" ); } @fclose($fp); //die($result); // split the result header from the content $result_post = explode("\r\n\r\n", $result, 2); $header = isset($result_post[0]) ? $result_post[0] : ''; $content = isset($result_post[1]) ? $result_post[1] : ''; //$content = str_replace("\n","",$content); //$content = str_replace("\r","",$content); // return as structured array: return array( 'status' => 'ok', 'header' => $header, 'content' => $content ,'urls' => $path ); }
접기(개정판)
더보기(이전버전) 접기(이전버전)
############################################
## 소켓통신용 함수
if (!function_exists('http_build_query')) {
function http_build_query($data, $prefix = '', $sep = '', $key = '') {
$ret = array();
foreach ((array)$data as $k => $v) {
if (is_int($k) && $prefix != null) {
$k = urlencode($prefix . $k);
}
if ((!empty($key)) || ($key === 0)) {
$k = $key . '[' . urlencode($k) . ']';
}
if (is_array($v) || is_object($v)) {
array_push($ret, http_build_query($v, '', $sep, $k));
} else {
array_push($ret, $k . '=' . urlencode($v));
}
}
if (empty($sep)) {
$sep = ini_get('arg_separator.output');
}
return implode($sep, $ret);
}
}
function get_socket($url, $data,$method='GET', $referer='') {
$data = http_build_query($data);
$url = parse_url($url);
$host = $url['host'];
$path = $url['path'];
$port = $url['port'];
if(!$port){$port=80;}
//print_r($url);
//echo "DATA [ $data ]\n\n";
//exit;
// open a socket connection on port 80 - timeout: 30 sec
switch($url['scheme']){
case "http":
$fp = @fsockopen($host, $port, $errno, $errstr, 30);
break;
case "https":
$fp = @fsockopen("ssl://".$host, $port, $errno, $errstr, 30);
break;
default :
return array(
'status' => 'Error',
'error' => "https or http protocol required"
);
exit;
}
if ($fp){
if($method == "GET"){
$path .= "?".$data;
}
// send the request headers:
// GET /search?key=x&target=kin&start=1&display=10&sort=sim&query=검색어 HTTP/1.1
// Host: openapi.naver.com
// User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1
// Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
// Accept-Language: ko
// Accept-Encoding: gzip, deflate
// Accept-Charset: EUC-KR,utf-8;q=0.7,*;q=0.7
// Connection: keep-alive
// Cookie: NB=GM4TSNRTGA4TONRZ; NNB=LNDCIFZVXTZE4; npic=Io1URjA1BdOJJe5XvX2cQOktCX6CjilwzS5bvqejBH6kzX/OqNAAHJgj5ERll3/OCA==
// Cache-Control: max-age=0
//fputs($fp, $method." $path HTTP/1.1\r\n");
@fputs($fp, $method." $path HTTP/1.0\r\n");
@fputs($fp, "Host: $host\r\n");
//fputs($fp, "Referer: $referer\r\n");
@fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
@fputs($fp, "Content-length: ". strlen($data) ."\r\n");
@fputs($fp, "Connection: close\r\n\r\n");
@fputs($fp, $data);
$result = '';
while(!feof($fp)) {
// receive the results of the request
$result .= fgets($fp, 128);
}
}else {
return array(
'status' => 'err',
'error' => "$errstr ($errno)"
);
}
@fclose($fp);
//die($result);
// split the result header from the content
$result_post = explode("\r\n\r\n", $result, 2);
$header = isset($result_post[0]) ? $result_post[0] : '';
$content = isset($result_post[1]) ? $result_post[1] : '';
//$content = str_replace("\n","",$content);
//$content = str_replace("\r","",$content);
// return as structured array:
return array(
'status' => 'ok',
'header' => $header,
'content' => $content
,'urls' => $path
);
}
## 소켓통신용함수끝
############################################
############################################
접기(이전버전)
첨부파일있음 (j2h crontab auto module , 암호는 맨날쓰던 n*****25**)
댓글