본문 바로가기

C-Language/CGI, QUERY_STRING

CGI, QUERY_STRING

Apache 2.2 와 C언어를 이용한 CGI 프로그램 예

실행환경

OS : Windows Vista, IDE : Visual Studio 2008 Express Edition, Web-Server : Apache 2.2.16(Win32), Language : C


Apache 2.2 다운로드


Apache 2.2 설치

Apache 2.2 를 기본설정으로 설치한다.


Apache 2.2 의 cgi-bin 디렉토리 확인

[Apache ROOT]/conf/httpd.conf 파일을 열고 다음과 같은 내용을 찾는다.
ScriptAlias /cgi-bin/ "C:/Program Files/Apache Software Foundation/Apache2.2/cgi-bin/"
Apache 2.2.16은 325번 라인에서 위의 내용이 발견된다.
cgi-bin 경로는 CGI 프로그램을 작성한 후에 이 디렉토리에 두면 Apache가 그 CGI 프로그램을 실행할 수 있는 장소이다.


CGI 소스작성 및 실행파일 생성

Visual Studio 2008 Express Edition 에서 Win32 Console Application > Empty Project 를 선택하여 빈 프로젝트를 생성한 후에 다음과 같은 소스를 코딩하고 빌드 > 솔루션 빌드, 이 결과 *.exe 파일이 생성되었으면 그 실행파일을 위에서 확인한 Apache 2.2 의 cgi-bin 디렉토리에 복사한다. 확장자는 꼭 exe 일 필요는 없다. 웹브라우저에서 요청할 때와 서버에 저장된 CGI 프로그램의 확장자가 동일하기만 하면 된다.


웹브라우저에서 요청

Apache 2.2를 실행하고 웹브라우저의 주소창에 다음과 같이 요청한다.
http://localhost/cgi-bin/test.exe?m=4&n=9<enter>
요청 URL중의 test.exe는 작성해서 Apache 2.2의 cgi-bin디렉토리에 복사한 CGI 프로그램의 파일이름이다.


실행결과

실행된 결과 웹브라우저는 이 소스 하단에 보이는 바와 같다.


사용된 CGI 소스코드  ( GET방식의 요청에 응답하는 내용 )

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void) {
 char *data;
 long m,n;

 printf("Content-Type:text/html;charset=euc-kr\n\n";

 printf("<html><head><title> 곱셈결과 </title></head>\n");
 printf("<body><center>\n");
 printf("<h3>곱셈결과</h3>\n");

 data = getenv("QUERY_STRING");

 printf("전달된 파라미터 : %s <br>\n 문자수 : %d \n", data, strlen(data));

 if(data==NULL) {
  printf("<p>웹브라우저에서 전달된 파라미터 문자열이 없습니다.<br>\n");
  printf("<p>웹브라우저 주소창에 ?m=5&n=3 를 추가해보세요.<br>\n");
 }
 else if(sscanf(data, "m=%ld&n=%ld", &m, &n)!=2)
  printf("<p>파라미터의 값은 정수이어야 합니다<br>.\n");
 else
  printf("<p>계산 결과: %ld * %ld = %ld.\n", m,n,m*n);

 printf("</center></body>\n");

 return 0;

}