1 / 76

C G I (Common Gateway Interface)

C G I (Common Gateway Interface). 제 1 장 Introduction to the CGI 제 2 장 Input to the CGI 제 3 장 Output from the CGI 제 4 장 Form and the CGI 제 5 장 SSI(Server Side Include). 학습 목표. CGI 의 개념을 이해한다 . 관련된 환경 변수와 그 사용법을 이해한다 . CGI 에 자료 전달 방식 (GET 과 POST) 과 encoding 하는 규칙을 이해한다 .

wade-barton
Télécharger la présentation

C G I (Common Gateway Interface)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C G I(Common Gateway Interface) • 제 1장 Introduction to the CGI • 제 2장 Input to the CGI • 제 3장 Output from the CGI • 제 4장 Form and the CGI • 제 5장 SSI(Server Side Include)

  2. 학습 목표 • CGI의 개념을 이해한다. • 관련된 환경 변수와 그 사용법을 이해한다. • CGI에 자료 전달 방식(GET과 POST)과 encoding하는 규칙을 이해한다. • CGI에 전달된 자료를 decoding하는 방법을 이해한다. • CGI 프로그램에서 html 형식의 자료를 출력하는 방법을 이해한다. • Form tag의 사용법을 익힌다. • C언어로 CGI 프로그램을 구현하는 방법을 배우고 프로그래밍한다.

  3. 제 1장 Introduction to the CGI • CGI(Common Gateway Interface)의 정의 • 웹의 하이퍼미디어 시스템과 외부 응용 프로그램이 서로 연계되기 위한 인코딩, 디코딩 방법과 데이터 교환 방법을 표준화 • CGI 프로그램은 client의 요청에 따라 Web Server( HTTP Server)를 통하여 실행되며 C/C++, Java, Perl, Unix Shell 등으로 작성 가능 Submit (Form) Call CGI Program Form Client (Web Browser) CGI Program’s Response CGI Program’s Response Server Application (CGI)

  4. CGI 작동 순서 1 6 Web Browser (Netscape,Explorer) Web Server (HTTPD) 2 5 3 CGI Program DBMS 4

  5. CGI 응용 예 • Search engine • 정보검색을 위한 Query 처리 • Imagemap • Guest book • Order form • On-line 주문 • Clock, counter, web statistics • Bi-lingual dictionary • 한-영, 영-한, 일-영, 영-일 사전 등 • Intranet application

  6. 제 2장 Input to the CGI • CGI 프로그램이 얻을 수 있는 데이터의 종류 1) Server와 user에 관한 정보 • 웹 서버에서 설정하는 환경변수(environment variable)를 참조하여 얻을 수 있다. 2) User가 입력한 form data • GET 방법 : URL 뒤에 추가된 자료로 전달된다. • POST 방법 : 표준입력 데이터 stream(stdin)으로 전달된다. 3) Path name 정보 • 환경변수를 참조하여 얻을 수 있다.

  7. 서버에 관한 환경변수 • SERVER_NAME • Server의 Host Name(sungkyul.edu) • SERVER_PORT • HTTP 요청을 받은 서버의 port 번호 (표준 HTTP port 번호 : 80) • SERVER_SOFTWARE • Server Software의 이름과 버전 정보(Apache/0.6.4b) • SERVER_PROTOCOL • 서버의 프로토콜의 이름과 버전(HTTP/1.0) • GATEWAY_INTERFACE • Server가 사용하는 CGI의 Revision에 대한 정보(CGI/1.1)

  8. 사용자에 관한 환경변수 • REMOTE_HOST • CGI 수행을 요청한 client program이 있는 컴퓨터의 인터넷 주소 • REMOTE_ADDR • CGI 수행을 요청한 client program이 위치한 컴퓨터의 IP 주소 • HTTP_REFERER • CGI 수행을 요청하기 전의 클라이언트가 가리키던 문서의 URL • HTTP_FROM • CGI실행을 요청한 사용자의 e-mail address • HTTP_USER_AGENT • Client program의 이름과 버전 • HTTP_ACCEPT • Client program(Web Browser)가 받아 들일 수 있는 MIME Type List

  9. 요청에 따라 달라지는 환경변수 • DOCUMENT_ROOT • Web document가 제공되는 서버의 directory • PATH_INFO • CGI 프로그램에 넘겨지는 (추가의) path 정보 • PATH_TRANSLATED • PATH_INFO를 변환한 path 정보 • SCRIPT_NAME • 현재 실행되고 있는 CGI 프로그램의 path와 이름

  10. 요청에 따라 달라지는 환경변수 …. • REQUEST_METHOD • 데이터가 전달되는 방법(POST or GET) 지정 • QUERY_STRING • GET 방법에서 사용되며 URL에서 ? 다음에 저장되는 정보 (http://www.bearnet.com/cgi-bin/test.cgi?quick.brown.fox) • CONTENT_LENGTH • POST 방법에서 사용되며 표준입력 데이터 stream(stdin)으로 입력되어 CGI 프로그램에 넘겨진 데이타의 크기(byte 단위) • CONTENT_TYPE • POST 방법으로 전달된 데이터에 대해 type/subtype 형식의 MIME content-type • AUTH_TYPE • User validation을 위해 사용된 authentification method

  11. 환경 변수를 출력하는 C Program #include <stdio.h> #include <stdlib.h> void main(void) { char *safenv(const char *a); printf("Content-type:text/html\n\n"); printf("<HTML>\n"); printf("<HEAD><TITLE> Hello from the server </TITLE></HEAD>\n"); printf("<BODY>\n"); printf("Server Name : %s<BR>\n",safenv("SERVER_NAME")); printf("Port No : %s<BR>\n",safenv("SERVER_PORT")); printf("Server Software : %s<BR>\n", safenv("SERVER_SOFTWARE")); printf("Server Protocol : %s<BR>\n", safenv("SERVER_PROTOCOL")); printf("CGI Revision : %s<BR>\n", safenv("GATEWAY_INTERFACE")); printf("Remote Host : %s<BR>\n", safenv("REMOTE_HOST")); printf("Remote Addr : %s<BR>\n", safenv("REMOTE_ADDR")); printf("Referer : %s<BR>\n",safenv("HTTP_REFERER")); printf("User : %s<BR>\n",safenv("HTTP_FROM"));

  12. 환경 변수를 출력하는 C Program …. printf("HTTP User Agent : %s<BR>\n",safenv("HTTP_USER_AGENT")); printf("Accept Type : %s<BR>\n", safenv("HTTP_ACCEPT")); printf("Document Root : %s<BR>\n", safenv("DOCUMENT_ROOT")); printf("Path Info : %s<BR>\n", safenv("PATH_INFO")); printf("Path Translated : %s<BR>\n", safenv("PATH_TRANSLATED")); printf("Script Name : %s<BR>\n", safenv("SCRIPT_NAME")); printf("Request Method : %s<BR>\n", safenv("REQUEST_METHOD")); printf("Query String : %s<BR>\n",safenv("QUERY_STRING")); printf("Content Length : %s<BR>\n",safenv("CONTENT_LENGTH")); printf("Content Type : %s<BR>\n" ,safenv("CONTENT_TYPE")); printf("Authorization Method : %s<BR>\n",safenv("AUTH_TYPE")); printf("</BODY></HTML>\n"); } char *safenv(const char *a) { char *empty ="<empty>"; if (getenv(a)==NULL) return empty; else return getenv(a); }

  13. 환경 변수 알아 보기 예 <HTML> <HEAD><TITLE>Environment Variable</TITLE> </HEAD> <BODY> <H1>Environment Variable</H1><HR> <FORM Action="http://www.sungkyul.edu/~ywkeum/cgi/envar.cgi" Method="POST"> <FONT SIZE=5> Let's see what kinds of environment variables are available. <BR><BR> <Input Type="submit" Value="submit"> <Input Type="reset" Value="clear"> </FONT> </FORM> <HR> </BODY> </HTML>

  14. 환경 변수 리스트 Server Name : hana Port No : 80 Server Software : NCSA/1.4.2 Server Protocol : HTTP/1.0 CGI Revision : CGI/1.1 Remote Host : 203.230.16.120 Remote Addr : 203.230.16.120 Referer : file:///D|/MYDOCU~1/LECTURE/HTML/HTML/CGI/ENVAR~1.HTM User : HTTP User Agent : Mozilla/4.01 [en] (Win95; I) Accept Type : image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */* Document Root : /usr/local/etc/httpd/htdocs

  15. 환경 변수 리스트 …. Path Info : /a/b Path Translated : /usr/local/etc/httpd/htdocs/a/b Script Name : /home-cgi/envar.cgi Request Method : POST Query String : Content Length : 0 Content Type : application/x-www-form-urlencoded Authorization Method :

  16. CGI 프로그램 실습 문제 • 앞에 나온 C program을 작성한다. • 프로그램 소스를 자신의 학교 계정의 folder에 올려 놓는다. • ftp 사용(http://www.shareware.co.kr/에서 알ftp 다운받아 설치) • public_html 밑에 cgi folder 생성 • cgi 폴더에 C 프로그램 소스를 올린다. • C 프로그램 소스를 컴파일한다. • telnet으로 학교 시스템 lonon한다. • cgi 폴더로 이동(cd 명령 사용) • 컴파일 방법 /usr/local/bin/gcc -o envar.cgi envar.c envar.c : 소스 프로그램, envar.cgi : 목적 프로그램 • Html 파일을 만든다. • Form 태그 사용하여 envar.cgi가 수행되도록 한다. • Html 파일은 PC에 있어도 상관 없다.

  17. Query string • GET 방법을 사용할 때 데이터가 전달되는 방식이다. • URL뒤에 추가된 데이터 • 예) http://some.machine/cgi-bin/name.pl?fortune • 첫번째 ? 뒤의 모든 데이터를 query string이라 한다. • CGI 프로그램은 QUERY_STRING이라는 환경변수를 참조하여 query string을 얻을 수 있다.

  18. Query string 연습 문제 • 여러 Search engine에서 다음과 같은 단어로 웹 페이지를 찾아 보고 여기에 대응되는 query string을 적어 보시오. • CGI and JavaScript

  19. Rules of encoding • Form에서 입력하는 내용은 한 개의 문자열로 합하여져서 CGI 프로그램에 전달된다. • 규칙 • Name/Value pair : &로 구별된다. • Name에 Value 할당 : =을 사용한다. • Name1=Value1&Name2=Value2&…. • Space : ‘+’로 변환된다. (URL을 적는 규칙은 space를 허용하지 않는다.) • Special Characters : %two-digit hex equivalent to ASCII code 예 Name1에 First, Name2에 Second? That’s right. 일 때 => Name1=First&Name2=Second%3F+That%26s+right%21

  20. 실습 문제 : encoding의 예 • 아래와 같은 form을 작성하여 이 form에서 입력된 자료가 자신의 email로 전달되게 하고 email을 열어 자료를 확인하시오. • Data1은 영문으로, Data2는 한글로 자료 입력하여 보시오.

  21. 연습 문제 : encoding의 예(html 소스) <BODY> <H1> Two text fields </H1> <HR> <FORM Action="mailto:ywkeum@sungkyul.edu" Method="POST"> Data 1 <Input Type="text" Name="name1" Size=40> <BR> Data 2 <Input Type="text" Name="name2" Size=40> <BR><BR> <Input Type="submit" Value="Submit"> <Input Type="reset" Value="clear"> </FORM> <HR> </BODY>

  22. 제 3장 Output from the CGICGI Program의 Output • Simple document를 출력할 수 있다. • Plain text • HTML document • 그림 또는 그 외의 이진 데이터(영상, 소리, 등등)를 출력할 수 있다. • Client에게 HTTP status code를 보낼 수 있다. • Server에게 특정 document를 client에게 보내도록 지시할 수 있다.

  23. HTTP Header • Content-Type • Output Stream의 MIME Content Type • Content-Length • Output Stream의 크기 (byte 단위) • Location • Used to specify to the server that the script is returning a reference to a document rather than an actual document. 예) printf(“Location: /thanks.html\n\n”); • Expires/Pragma • Headers to instruct the client not to cache the document. • Status • Request의 status 정보

  24. HTTP Header 작성 요령 1) Header Line 정보를 적는 정해진 순서는 없다. 2) Header Block과 Body Block은 blank line으로 구별된다. Content-type: text/html <HTML> <HEAD><TITLE>Virtual HTML Document</TITLE> </HEAD> <BODY> ... </BODY> </HTML> Blank line

  25. Content-type & Content-length • Content-Type • CGI로 하여금 web Browser가 처리 가능한 data를 넘겨주도록 할 수 있다. • Web browser가 처리 가능한 data의 형태는 환경변수 HTTP_ACCEPT에 저장되어 있다. • CGI는 환경변수 HTTP_ACCEPT에 맞추어 Content-type을 넘겨준다. • Content-Length • HTML 문서가 아닌 GIF, JPEG Image, Audio Clip을 전송할 수도 있다. • 이 때에는 반드시 Content-length를 명시해 주어야 한다. • Content-type: image/gif • Content-length: 12000

  26. Status Codes • Client의 정보 request 처리결과 상태정보 (status/reason string) • 200 OK • 204 No Content • 301 Document Moved Permanently • 401 Unauthorized • 403 Forbidden • 404 Not Found • 500 Internal Server Error • 501 Not Implemented (참고 site) ftp://ftp.isi.edu/in-notes/rfc2616.txt

  27. An example of an output from CGI 예 #include <stdio.h> #include <stdlib.h> void main() { printf("Content-type: text/html\n\n"); printf("<HTML>\n"); printf("<HEAD><TITLE> HTML Document from CGI </TITLE></HEAD>\n"); printf("<BODY>\n"); printf("<H1> Welcome </H1>\n"); printf(“This is the output from a CGI program<BR>\n"); printf("</BODY></HTML> \n"); }

  28. 연습 문제 • 프로그램에서 html 문서를 생성하여 웹 브라우저에 출력하는 CGI 프로그램을 작성하고 호출하여 보시오. • Location을 사용하여 서버에 있는 html 문서를 출력하는 CGI 프로그램을 작성하고 호출하시오. • 환경 변수를 출력하는 프로그램을 작성하고 호출하시오.

  29. 제 4장 Forms and the CGI • Form의 사용 목적 • Data collection • Interactive communication • Form 사용의 이점 • Platform independent user interface • 다양한 gateway(database, information server)에 대한 front end • Form 사용의 문제점 • text 형 이외의 데이터 형에 대한 지원이 안 된다. • int, data, float, url 등의 데이터 형을 구별하여 지정하지 못한다. • User input을 client side에서 검증하지 못한다. • JavaScript와 CGI를 함께 사용하면 synergy 효과가 있음

  30. Form을 이용하여 Data를 처리하는 과정 User Requests a form User fills out the form Sends the form to client Forward to CGI application User submits form Output Received Output to Server Output to client Client (Web Browser) Server Application (CGI)

  31. FORM tag • Form을 구성하기 위해서는 <FORM> </FORM> tag를 사용한다. • 형식 : <FORM ACTION=“...” METHOD=“...” NAME=“…”> • ACTION : CGI program의 위치와 CGI program명을 지정한다. • ACTION을 지정하지 않으면 document의 URL을 사용 예) ACTION=“../cgi-bin/cgi-01.pl” • METHOD : POST 또는 GET을 지정한다. • POST를 사용하는 것을 권장함 • 값을 적지 않으면 GET이 default 값으로 사용됨. 예) METHOD=“POST” • NAME : FORM의 이름을 지정 예) NAME=“myForm”

  32. FORM tag 내의 다른 tag들 <FORM ...> <INPUT …> …. </INPUT> <SELECT ...> <OPTION>…. </SELECT> <TEXTAREA …> …. </TEXTAREA> </FORM>

  33. INPUT tag • <FORM> tag 내에서 <INPUT> tag로 입력 필드 지정 • <INPUT> tag의 TYPE attribute에 입력 필드 종류 지정 • Text field : Text, Password, Hidden • Button • Submit : form을 서버에 전송 • Reset : form을 초기 상태로 만듬 • Check Box & Radio Button • Other attributes(TYPE 외에) • Name : 입력 필드의 이름 지정 • Value : 입력 필드의 값 또는 button의 label 지정 • Checked : 선택 항목 중 어떤 항목을 기본으로 선택 • Size : 입력 필드의 크기 지정 • Maxlength : 실제 입력할 수 있는 최대 문자수 지정

  34. SELECT tag • <FORM> tag 내에서 Pull down menu, Scrolled menu 지정할 때 사용 • Attributes • Name attribute : 이름을 지정 • Size attribute : 항목 수를 지정 • Multiple : 다중 선택을 가능하게 한다. OPTION tag • SELECT tag 내에서 선택 사항을 지정 • Attributes • SELECTED : 기본으로 선택된 항목을 지정 • VALUE : 서버에 전송되는 데이터 값 정의

  35. Textarea tag • 여러 줄의 text를 입력 할 때 사용 • <FORM> tag 내에 정의 • Attributes • Name : 이름을 지정 • Rows : 세로의 길이를 나타냄 • Cols : 가로의 길이를 나타냄

  36. (1) Single Text Field <HTML> <HEAD><TITLE>Single Text Field</TITLE> </HEAD> <BODY> <H1> Single Text Field </H1> <HR> <FORM Action=“home-cgi/listform.cgi” Method=“POST”> Name <Input Type=“text” Name=“name” Size=10> <BR> <Input Type=“submit” Value=“Submit Query”> <Input Type=“reset” Value=“clear”> </FORM> <HR> </BODY></HTML>

  37. 환경변수와 입력을 출력하는 C program #include <stdio.h> #include <stdlib.h> // #include <string.h> void main() { int icl, nobj; char *qs; /*POST 방법으로 전달하는 자료를 넣는 장소 */ char *safenv(const char *a); printf("Content-type: text/html\n\n"); printf("<HTML>\n"); printf("<HEAD><TITLE> Form Input Test </TITLE></HEAD>\n"); printf("<BODY>\n"); printf("<HR noshade>\n"); printf("<H1 ALIGN=CENTER> <FONT COLOR=BLUE> Your Encoded Input Is </FONT></H1>\n"); printf("<HR noshade><FONT SIZE=5>\n");

  38. 환경변수와 입력을 출력하는 C program …. printf("<UL>\n"); printf("Request Method : %s<BR>\n", safenv("REQUEST_METHOD")); printf("Query String with GET : %s<BR>\n", safenv("QUERY_STRING"));//GET printf("Content Length : %s<BR>\n", safenv("CONTENT_LENGTH")); icl=atoi(safenv("CONTENT_LENGTH")); /* atoi : 문자열을 정수로 변환 */ if (icl !=0) { qs = malloc(icl+1); // icl=0이 아니면 POST 방법 // malloc : (icl+1) bytes의 메모리 할당 if ((nobj = fread(qs, icl, 1, stdin)) != 1 ) { printf("cannot read the input stream (%d)!\n",nobj); exit(1);} /* fread : stdin에서 자료를 1개 object에서 icl bytes를 읽어 qs에 넣는다. */

  39. 환경변수와 입력을 출력하는 C program …. printf("Input with POST : \n"); printf("%s", qs); } // POST 방법으로 읽은 자료 출력 printf("</UL><FONT>\n"); printf("</BODY></HTML>\n"); } char *safenv(const char *a) { char *empty ="<empty>"; if (getenv(a)==NULL) return empty; else return getenv(a); }

  40. 환경 변수와 입력 자료 (예) 입력 : Hongkil Dong • GET의 경우 • Query String with GET : name=Hongkil+Dong • Content Length : • Input with POST : • POST의 경우 • Query String with GET : • Content Length : 17 • Input with POST : name= Hongkil+Dong

  41. POST v.s. GET의 URL 비교 • GET 방법 사용 시 URL • http://www.sungkyul.ac.kr/home-cgi/listform.cgi? name=Hongkil+Dong • POST 방법 사용 시 URL • http://www.sungkyul.ac.kr/home-cgi/listform.cgi

  42. (2) Multiple Text Fields <HTML> <HEAD><TITLE> Multiple Text Fields </TITLE></HEAD> <BODY> <H1> Multiple Text Fields </H1> <HR> <FORM Action= “home-cgi/listform.cgi” Method=“POST”> 학번 <Input Type=“text” Name=“studentid” Size=20> <BR> 성명 <Input Type=“text” Name=“name” Size=20> <BR> <Input Type=“submit” Value=“Submit Query”> <Input Type=“reset” Value=“clear”> </FORM> <HR> </BODY></HTML>

  43. 환경 변수와 입력 자료 (예) 학번 : 88406-023 성명 : Hongkil Dong • GET의 경우 • Query String with GET : studentid=88406-023&name= Hongkil+Dong • Content Length : • Input with POST : • POST의 경우 • Query String with GET : • Content Length : 37 • Input with POST : studentid=88406-023&name= Hongkil+Dong

  44. POST v.s. GET의 URL 비교 • GET 방법 사용시 URL • http://www.sungkyul.ac.kr/ home-cgi/listform.cgi ?studentid=88406-406&name= Hongkil+Dong • POST 방법 사용시 URL • http:// www.sungkyul.ac.kr/ home-cgi/listform.cgi

  45. (3) CHECK BOX <HTML> <HEAD><TITLE>Check Box</TITLE> </HEAD> <BODY> <H1>Check Box</H1> <HR> <FORM Action=“home-cgi/listform.cgi” Method=“POST”> Which toppings would you like? <BR> <Input Type=“checkbox” Name=“Pepperoni ”> Pepperoni <Input Type=“checkbox” Name=“Sausage”> Sausage <Input Type=“checkbox” Name=“Ham”> Ham <Input Type=“checkbox” Name=“Pineapple”> Pineapple <BR> <Input Type=“submit” Value=“submit”> <Input Type=“reset” Value=“clear”> </FORM> <HR> </BODY> </HTML>

  46. 환경 변수와 입력 자료 (예) Sausage와 Ham을 Check한 경우 • GET의 경우 • Query String with GET : sausage=on&ham=on • Content Length : • Input with POST : • POST의 경우 • Query String with GET : • Content Length : 18 • Input with POST : sausage=on&ham=on

  47. (4) Radio Button <HTML> <HEAD><TITLE> Radio Button </TITLE></HEAD> <BODY> <H1> Radio Button </H1> <HR> <FORM Action=“home-cgi/listform.cgi” Method=“POST”> 당신이 가장 좋아하는 가수는? <BR> <Input Type=“radio” Name=“singer” Value=“ujh”> 엄정화 <Input Type=“radio” Name=“singer” Value=“khj”> 김현정 <Input Type=“radio” Name=“singer” Value=“sch”> 소찬휘 <Input Type=“radio” Name=“singer” Value=“lsr”> 이소라 <BR> <Input Type=“submit” Name=“submit”> <Input Type=“reset” Name=“clear”> </FORM> <HR></BODY> </HTML>

More Related