개발 꿀팁/PHP

PHP 손글씨 HTTP 프로토콜

Jammie 2022. 9. 13. 11:52
반응형

HTTP GET 요청 형식:

GET /path HTTP/1.1
Header1: Value1
Header2: Value2
Header3: Value3

주의: 각 Header의 행은 하나이고, 줄바꿈은 \r\n이고, 마지막 Header는 두 개의 연속된 \r\n,php\r\n을 따옴표로 묶어야 합니다.

다음은 php socket이 구현한 http 액세스이며 실측값은 ok입니다

//연결할 도메인 이름
        $host="127.0.0.1";
        $port="80";
        //php socket 만들기
        $socket=socket_create(AF_INET,SOCK_STREAM,getprotobyname("tcp"));
        //링크 서버
        $req=socket_connect($socket,$host,$port);
        if ($req){
            //HTTP GET를 시뮬레이션으로 구현하는데, 여기서 문자열 스플릿은 이중 따옴표로 번역해야 한다
            $http="GET /index.php HTTP/1.1\r\n";
            $http.="Host: $host\r\n";
            $http.="Accept-Language: zh-cn\r\n";
            $http.="Connection: Keep-Alive\r\n";
            $http.="Cookie: session_id=fweiweiBFDGPERII2JHsd;username=test\r\n";
            $http.="\r\n";//header 결말
            //HTTP 요청 모의 전송
            socket_write($socket,$http,strlen($http));
            //한 번에 다 읽을 수 있는 반환 데이터 읽기
            $input = socket_read($socket, 1024*1024);
            socket_close($socket);
            echo($input);
        }

같은 POST의 포맷은 다음과 같습니다

POST /path HTTP/1.1
Header1: Value1
Header2: Value2
Header3: Value3
 
name=test&age=18

주의: 두 개의 연속된 \r\n을 만나면 Header 부분은 끝납니다. 뒤에 있는 데이터는 모두 Body입니다. body는 Content-length Header 헤더를 추가해야 합니다. body 데이터 길이는 반드시 그것과 일치해야 합니다. Content-Type을 통해 데이터 형식을 표시합니다.
eg

//연결할 도메인 이름
        $host="127.0.0.1";
        $port="80";
        //php socket 만들기t
        $socket=socket_create(AF_INET,SOCK_STREAM,getprotobyname("tcp"));
        //링크 서버
        $req=socket_connect($socket,$host,$port);
        if ($req){
            $data="age=111&name=0505";
            //HTTP GET 시뮬레이션
            $http="POST /index.php HTTP/1.1\r\n";
            $http.="Host: $host\r\n";
            $http.="Accept-Language: zh-cn\r\n";
            $http.="Accept: */*\r\n";
            $http.="Connection: Keep-Alive\r\n";
            $http.="Cookie: session_id=fweiweiBFDGPERII2JHsd;username=test\r\n";
            $http.="Content-Type: application/x-www-form-urlencoded\r\n";
            $http.="Content-length: ".strlen($data)."\r\n";//데이터를 휴대해야 하며, 반드시 내용 길이를 선언해야 한다
            $http.="\r\n";

            //퍼즐 body
            $http=$http.$data;
            //HTTP 요청 모의 전송
            socket_write($socket,$http,strlen($http));
            //한 번에 다 읽을 수 있는 반환 데이터 읽기
            $input = socket_read($socket, 1024*1024);
            socket_close($socket);
            echo($input);
        }

HTTP 응답도 body를 포함하면 \r\n\r\n에 의해 분리된다.

Body의 데이터 유형은 Content-Type 헤더에 의해 정해지며 웹페이지의 경우Body는 텍스트, Body는 그림의 이진 데이터이다.

resporn 예제

HTTP/1.1 200 OK 
Server: nginx Date: Tue, 18 May 2021 08:10:37 GMT 
Content-Type: text/html; charset=UTF-8 Transfer-Encoding: chunked Connection: keep-alive Vary: Accept-Encoding 1b 
{"age":"111","name":"0505"} 
0

 

반응형