Archive for 2月 7th, 2012

  1. Hello, CGI World!

    Posted on 2月 7th, 2012 by cx20

    CGI

    CGI(Common Gateway Interface)は、Web サーバー上でプログラムを動作させる為の仕様の一つである。
    言語としては、C言語 や Perl が主に使われるが、他の言語でも HTTP ヘッダ “Content-Type: text/html¥n¥n” を出力することで、CGI プログラムとして動作させることが可能である。
    CGI 以外の実行方式としてはモジュール形式(Apache や IIS の拡張モジュールとして動作)や FastCGI 形式がある。

    ソースコード(C言語)

    #include <stdio.h>
     
    int main( int argc, char* argv[] )
    {
        printf( "Content-type: text/htmlnn" );
        printf( "<html>n" );
        printf( "  <head>n" );
        printf( "    <title>Hello, World</title>n" );
        printf( "  </head>n" );
        printf( "  <body>n" );
        printf( "    <p>Hello, CGI World!</p>n" );
        printf( "  </body>n" );
        printf( "</html>n" );
        return 0;
    }

    ソースコード(Perl)

    #!/usr/bin/perl
    print "Content-Type: text/htmlnn";
    print "<html>n";
    print "  <head>n";
    print "    <title>Hello, World!</title>n";
    print "  </head>n";
    print "  <body>n";
    print "    <p>Hello, CGI World!</p>n";
    print "  </body>n";
    print "</html>n";

    ソースコード(PHP)

    #!/usr/bin/php
    <html>
      <head>
        <title>Hello, World!</title>
      </head>
      <body>
        <p><?php echo "Hello, CGI World!"; ?></p>
      </body>
    </html>

    実行方法(C言語)

    1. コンパイル
       $ cc -o hello.cgi hello.c
    2. CGI用フォルダ(cgi-bin等)に配置
    3. 実行権限の付与
       $ chmod +x hello.cgi
    4. ブラウザで表示
       http://localhost/cgi-bin/hello.cgi

    実行方法(Perl)

    1. CGI用フォルダ(cgi-bin等)に配置
    2. 実行権限の付与
       $ chmod +x hello.pl
    3. ブラウザで表示
       http://localhost/cgi-bin/hello.pl

    実行方法(PHP)

    1. CGI用フォルダ(cgi-bin等)に配置
    2. 実行権限の付与
       $ chmod +x hello.php
    3. ブラウザで表示
       http://localhost/cgi-bin/hello.php

    実行結果

    Hello, CGI World!