본문 바로가기

PHP/Example

[PHP] fsockopen을 이용해 php코드로 POST 요청 보내기


가끔가다 php단에서 POST요청을 보내주어야 하는 상황이 생긴다.

그럴 때 소켓통신을 이용해서 POST요청을 만들어 보내는 코드


<?php
    //보낼 데이터
    $data = array(
        'im' =--> 'bunkering',
        'kong' => 222,    
        'tak' => 'heater'
    );
    
    //POST요청을 위하여 im=bunkering&kong=2&... 형태로 변경
    while(list($n,$v) = each($data)){
        $send_data[] = "$n=$v";
    }    
    $send_data = implode('&', $send_data);
    
    //url 파싱    
    $url = "http://yourDomain/test.php";
    $url = parse_url($url);
    
    $host = $url['host'];
    $path = $url['path'];
    
    //소켓 오픈
    $fp = fsockopen($host, 80, $errno, $errstr, 10.0);
    if (!is_resource($fp)) {
        echo "not connect host : errno=$errno,errstr=$errstr";
        exit;
    } 
 
    fputs($fp, "POST $path HTTP/1.1\r\n");
    fputs($fp, "Host: $host\r\n");
    fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
    fputs($fp, "Content-length: " . strlen($send_data) . "\r\n");
    fputs($fp, "Connection:close" . "\r\n\r\n");
    fputs($fp, $send_data);
 
    //반환값 받기
    $result = ''; 
    while(!feof($fp)) {
        $result .= fgets($fp, 128);
    }    
    fclose($fp);
    
    //헤더와 컨텐츠(웹페이지에 표시되는 내용) 구분
    $result = explode("\r\n\r\n", $result, 2);
 
    $header = isset($result[0]) ? $result[0] : '';
    $content = isset($result[1]) ? $result[1] : '';
    
    //결과 출력
    echo $header;
    echo $content;

?>

$header를 출력하면 response  헤더의 내용이 나오고

$content를 출력하면 POST요청을 보낸 페이지(http://yourDomain/test.php)의 응답이 출력된다.



'PHP > Example' 카테고리의 다른 글

[PHP] PHP로 짜본 게시판 페이지 알고리즘  (1) 2013.03.29