웹 컨설팅의 동반자 PHP

양일등 / FBISKR@orgio.net

 

     

    안녕하세요. 계절의 여왕 5월입니다. 화사한 꽃들의 향기가 길거리를 걸을 때마다 어지러울 정도로 가득합니다. 이번 호에서는 우리의 웹 컨설팅의 동반자인 PHP에 대해서 좀더 자세히 알아볼까 합니다.

     

1. 폭넓은 함수군

    PHP는 시대의 첨단을 걷고 있습니다. 모든 인기 있는 것들을 모두 흡수하여 나날이 덩치가 커지고 있습니다. 물론 자기 자신이 그것을 모두 구현하는 것은 아니고 상호 연계된 함수군들을 제공한다는 것입니다.

    학생시절 유명했던 TURBO시리즈에서 빼놓을 수 없는 것이 바로 Turbo C와 Turbo Pascal입니다. 지금의 중견 프로그래머라면 이 제품을 한번씩은 다 사용해 보았을 정도로 유명합니다. 그중에 지금도 Turbo C 2.0 라이브러리 매뉴얼이라는 두꺼운 책이 책장 한구석을 차지하고 있습니다. 당시 책의 두께 자체만으로도 행복했습니다. 자기가 필요한 것을 라이브러리에서 찾아서 사용하면 되기 때문이었죠. 그래서 어떤 내용이 필요하면 그것을 지원하는 함수가 있나 찾아보며 고심하던 생각이 납니다. 언어적인 관점에서 PHP는 자신과 상관없는 함수들을 가지고 있지만(주로 데이터베이스 연결) 이것은 우리에게 아주 필요한 것임을 우리는 알 수 있습니다. 어쩌면 이러한 것 때문에 PHP가 날로 인기를 더해 가는지도 모르겠습니다.

    아래의 리스트를 보면 데이터베이스 제품별로 각각의 함수를 지원하는 것을 볼 수가 있습니다. 또 재미있는 것은 Compression functions과 Image functions과 같은 함수들입니다. 이것도 PHP용으로 개발된 것은 아니지만 컴파일할 때 같이 컴파일하면 아무런 생각없이(?)이 기능들을 이용할 수 있습니다. 일례로 우리는 C에서 사용한 것처럼 printf함수를 사용할 수 있고 그것도 싫으면 echo함수를 사용할 수 있습니다.

    자, 그럼 우리가 주로 사용하는 함수들을 살펴보겠습니다.

    Ⅰ.     Adabas D functions
    Ⅱ.     Apache-specific functions
    Ⅲ.     Array functions
    Ⅳ.     Aspell functions
    Ⅴ.     Arbitrary precision mathematics functions
    Ⅵ.     Calendar functions
    Ⅶ.     ClibPDF functions
    Ⅷ.     Date and Time functions
    Ⅸ.     Database(dbm-style) abstraction layer functions
    Ⅹ.      dBase functions
    XI .     dbm functions
    XII .    Directory functions
    XIII.    Dynamic Loading functions
    XIV.    Program Execution functions
    XV.     Forms Data Format functions
    XVI.    filePro functions
    XVII.   Filesystem functions
    XVIII.  Functions related to HTTP
    XIX.   Hyperwave functions
    XX.    Image functions
    XXI.   IMAP functions
    XXII.  PHP options & information
    XXIII. Informix functions
    XXIV. InterBase functions
    XXV.  LDAP functions
    XXVI . Mail functions
    XXVII . Mathematical functions
    XXVIII . Encryption functions
    XXIX . Hash functions
    XXX . Miscellaneous functions
    XXXI . mSQL functions
    XXXII . Microsoft SQL Server functions
    XXXIII . MySQL functions
    XXXIV. Sybase functions
    XXXV. Network functions
    XXXVI . NIS functions
    XXXVII . ODBC functions
    XXXVIII. Oracle 8 functions
    XXXIX . Oracle functions
    XL . Perl-compatible Regular Expression functions
    XLI . PDF functions
    XLII . PostgreSQL functions
    XLIII . Regular expression functions
    XLIV. Semaphore and shared memory functions
    XLV. Solid functions
    XLVI . SNMP functions
    XLVII . String functions
    XLVIII . URL functions
    XLIX . Variable functions
    L . Vmailmgr functions
    LI . WDDX functions
    LII . Compression functions
    LIII . XML parser functions

 

2. 날짜관련 함수들(VIII . Date and Time functions)

    checkdate     - validate a date/time
    date             - format a local time/date
    strftime         - format a local time/date according to locale settings
    gmstrftime    - format a GMT/CUT time/date according to locale settings
    getdate         - get date/time information
    gettimeofday - get current time
    gmdate        - format a GMT/CUT date/time
    mktime         - get UNIX timestamp for a date
    gmmktime    - get UNIX timestamp for a GMT date
    time             - return current UNIX timestamp
    microtime     - return current UNIX timestamp with microseconds

    2-1. date함수

    string date(string format, int [timestamp] );

    format 인자값

    a - “am” or “pm”
    A - “AM” or “PM”
    d - day of the month, 2 digits with leading zeros; i.e. “01” to “31”
    D - day of the week, textual, 3 letters; i.e. “Fri”
    F - month, textual, long; i.e. “January”
    h - hour, 12-hour format; i.e. “01” to “12”
    H - hour, 24-hour format; i.e. “00” to “23”
    g - hour, 12-hour format without leading zeros; i.e. “1” to “12”
    G - hour, 24-hour format without leading zeros; i.e. “0” to “23”
    i - minutes; i.e. “00” to “59”
    j - day of the month without leading zeros; i.e. “1” to “31”
    l (lowercase ‘L’) - day of the week, textual, long; i.e. “Friday”
    L - boolean for whether it is a leap year; i.e. “0” or “1”
    m - month; i.e. “01” to “12”
    n - month without leading zeros; i.e. “1” to “12”
    M - month, textual, 3 letters; i.e. “Jan”
    s - seconds; i.e. “00” to “59”
    S - English ordinal suffix, textual, 2 characters; i.e. “th”, “nd”
    t - number of days in the given month; i.e. “28” to “31”
    U - seconds since the epoch
    w - day of the week, numeric, i.e. “0” (Sunday) to “6” (Saturday)
    Y - year, 4 digits; i.e. “1999”
    y - year, 2 digits; i.e. “99”
    z - day of the year; i.e. “0” to “365”
    Z - timezone offset in seconds (i.e. “-43200” to “43200”)

    예제
    <HTML>
    <HEAD>
    <TITLE>Figure 1-1</TITLE>
    </HEAD>
    <BODY>
    Today’s Date: <? print(Date(“l F d, Y”)); ?>
    </BODY>
    </HTML>

    출력
    Today’s Date: Wednesday April 12, 2000

    날짜 관련 함수들을 적절히 조절하면 동양권의 날짜 형식으로 출력할 수 있습니다. 그리고 간단한 코드로 카운터(일명 D-day)도 만들 수 있습니다.
     

    D-<? echo date(“z”, mktime(0,0,0,4,29,2000)) - date(“z”,time()); ?>일

 

    결과는 “D-??일”이 출력됩니다. 먼저 mktime으로 지정된 시간의 UNIX timestamp을 설정하고 현재 시간을 설정합니다. 여기서 timestamp시간을 빼면 나머지 시간이 나오는데 이것을 date의 z인자로 넘겨주어서 365일 날짜를 계산합니다. 즉 1월 31일 다음 2월 1이면 32로 출력이 되는 것입니다.

     

3. 디렉토리 관련함수들(XII. Directory functions)

     

    chdir       - change directory
    dir          - directory class
    closedir   - close directory handle
    opendir   - open directory handle
    readdir    - read entry from directory handle
    rewinddir - rewind directory handle

 

    PHP를 사용하면서 느끼는 것은 통일성을 준다는 것입니다. 이것은 플랫폼에 상관없이 개발을 할 수 있다는 것인데, 언뜻 들으면 아무 것도 아닌 것 같지만 과서 ANSI C의 표준안을 따르지 않는 문법과 함수를 사용하면 다른 기종의 포팅이 어려웠습니다. 현재 Apache, PHP, mSQL, MySQL등 인기있는 제품들이 UNIX계열과 MS계열에서 모두 활발하게 개발되고 있습니다. 이것은 우리가 다른 기종에서의 포팅문제에 그리 큰 고민을 하지 않아도 된다는 이야기입니다. 자 잠깐 다른 방향으로 진행된 것 같은데, 디렉토리 함수 군을 살펴보면 6개 정도의 함수가 있습니다.
     

    <?php
        $handle=opendir(‘/.’);
        echo “Directory handle: $handle” . “<br>”;
        echo “Files:” . “<br>”;
        while ($file = readdir($handle)) {
            echo “$file” . “<br>”;
        }
        closedir($handle);

        $d = dir(“./”);
        echo “Handle: “.$d->handle.”<br>\n”;
        echo “Path: “.$d->path.”<br>\n”;
        while($entry=$d->read()) {
            echo $entry.”<br>\n”;
        }
        
        $d->close();
    ?>

    Directory handle: 1
    Files:
    BOOTLOG.TXT
    COMMAND.COM
    SUHDLOG.DAT
    FRUNLOG.TXT
    MSDOS.---
    SETUPLOG.TXT
    WINDOWS
    NETLOG.TXT
    AUTOEXEC.BAT
    WINGAME
    MSDOS.SYS
    CONFIG.SYS
    DETLOG.TXT
    BOOTLOG.PRV
    SYSTEM.1ST
    IO.SYS
    Program Files
    My Documents
    RECYCLED
    HNC
    WORK
    ffastun.ffl
    ffastun0.ffx
    ffastun.ffo
    ffastun.ffa
    cjgolf2
    usr
    access.txt
    tcpsp
    PDOXUSRS.NET
    Sierra
    N2pInst.log
    N2PActiveX.log
    My Music
    Cjgolf2.bak
    SCANDISK.LOG
    Handle: 2
    Path: ./
    .
    ..
    1.bak
    1.php3

    test
    my
    drv

 

    두 가지 방법으로 디렉토리를 탐색하는 예입니다. 하나는 opendir을 사용한 것이고 다른 것은 dir클래스를 사용한 것입니다. 소프트웨어 공학의 최고봉으로 군림했던 OOP(Object Oriented Programming)는 그 복잡성 때문에 실제 사용자들로부터 각광을 받지 못했습니다. 그래서 복잡한 클래스를 설계하는 것 보다는 간단한 함수들의 조합을 더 많이 사용하는 것 같습니다. 사용해 보시고 편한 것을 선택해서 사용하시면 됩니다.

 

4. 외부 실행 함수들(XIV. Program Execution functions)

    escapeshellcmd - escape shell metacharacters
    exec - Execute an external program
    system - Execute an external program and display output
    passthru - Execute an external program and display raw output

    과거 C에서 외부 쉘로 빠져 나갈 때 system(“command.com”)을 실행시키면 작동을 했습니다. 이것은 시스템명령어를 실행시키는 함수인데, 역시 PHP에서도 지원을 합니다.
     

    <pre>
    <%
            system($command);
    %>
    </pre>

    <form name=”form” method=”post” action=
    system.php3>

    <p><font face=”돋움체”>command : <input type=”text” name=”command” value=”<% echo $command; %>” size=”100” ></font></p>

    <p><input type=”submit” value=”run”></p>

    </form>

 

    위와 같이 하면 telnet으로 서버에 접속하는 절차를 거치지 않고 간단한 명령들을 실행시키고 결과를 확인할 수 있습니다.

 

5. 파일 관련 함수들(XVII. Filesystem functions)

    basename - return filename component of path
    chgrp - change file group
    chmod - change file mode
    chown - change file owner
    clearstatcache - clear file stat cache
    copy - copy file
    delete - a dummy manual entry
    dirname - return directory name component of path
    diskfreespace - return available space in directory
    fclose - close an open file pointer
    feof - test for end-of-file on a file pointer
    fgetc - get character from file pointer
    fgetcsv - get line from file pointer and parse for CSV fields
    fgets - get line from file pointer
    fgetss - get line from file pointer and strip HTML tags
    file - read entire file into an array
    file_exists - Check whether a file exists.
    fileatime - get last access time of file
    filectime - get inode change time of file
    filegroup - get file group
    fileinode - get file inode
    filemtime - get file modification time
    fileowner - get file owner
    fileperms - get file permissions
    filesize - get file size
    filetype - get file type
    flock - portable advisory file locking
    fopen - open file or URL
    fpassthru - output all remaining data on a file pointer
    fputs - write to a file pointer
    fread - Binary-safe file read
    fseek - seek on a file pointer
    ftell - tell file pointer read/write position
    fwrite - Binary-safe file write
    set_file_buffer - Sets file buffering on the given file pointer
    is_dir - tells whether the filename is a directory
    is_executable - tells whether the filename is executable
    is_file - tells whether the filename is a regular file
    is_link - tells whether the filename is a symbolic link
    is_readable - tells whether the filename is readable
    is_writeable - tells whether the filename is writeable
    link - Create a hard link
    linkinfo - Get information about a link
    mkdir - make directory
    pclose - close process file pointer
    popen - open process file pointer
    readfile - output a file
    readlink - Return the target of a symbolic link
    rename - rename a file
    rewind - rewind the position of a file pointer
    rmdir - remove directory
    stat - give information about a file
    lstat - give information about a file or symbolic link
    symlink - Create a symbolic link
    tempnam - create unique file name
    touch - set modification time of file
    umask - changes the current umask
    unlink - Delete a file

    우리가 프로그래밍을 하면서 많이 다루는 것이 파일입니다. 데이터의 최종보존을 위해서 파일에 저장하기 때문입니다. 요즘 웹에서는 데이터 베이스를 사용하기 때문에 파일에 직접 데이터를 기록하는 경우는 드물지만 조그만 양의 데이터를 기록하는 것은 데이터 베이스 보다 효과적입니다.
     

    <HTML>
    <HEAD>
    <TITLE>fopen</TITLE>
    </HEAD>
    <BODY>
    <?
            print(“<H1>HTTP</H1>\n”);

            // open a file using http protocol
            if(!($myFile = fopen(“http://www.clearink.com/”, “r”)))
            {
                    print(“file could not be opened”);
                    exit;
            }

            while(!feof($myFile))
            {
                    // read a line from the file
                    $myLine = fgetss($myFile, 255);
                    print(“$myLine <BR>\n”);
            }

            // close the file
            fclose($myFile);

            print(“<H1>FTP</H1>\n”);
            print(“<HR>\n”);

            // open a file using ftp protocol
            if(!($myFile = fopen(“ftp://ftp.php.net/welcome.msg”, “r”)))
            {
                    print(“file could not be opened”);
                    exit;
            }

            while(!feof($myFile))
            {
                    // read a line from the file
                    $myLine = fgetss($myFile, 255);
                    print(“$myLine <BR>\n”);
            }

            // close the file
            fclose($myFile);

            print(“<H1>Local</H1>\n”);
            print(“<HR>\n”);

            // open a local file
            if(!($myFile = fopen(“data.txt”, “r”)))
            {
                    print(“file could not be opened”);
                    exit;
            }

            while(!feof($myFile))
            {
                    // read a line from the file
                    $myLine = fgetss($myFile, 255);
                    print(“$myLine <BR>\n”);
            }

            // close the file
            fclose($myFile);
     ?>
    </BODY>
    </HTML>

 

    fopen함수는 local파일 및 인터넷의 파일을 직접 열 수가 있습니다. 여기에 HTML테그를 스킵해서 읽어오는 fgetss를 사용해서 읽고 그것을 출력합니다. 사용자 입장에서 보면 로컬파일을 읽는것과 동일하게 생각할 수 있습니다.

 

6. 문자열 처리 함수들(String functions)

    AddSlashes - quote string with slashes
    bin2hex - convert binary data into hexadecimal representation
    Chop - remove trailing whitespace
    Chr - return a specific character
    chunk_split - Split a string into smaller chunks
    convert_cyr_string - Convert from one Cyrillic character set to another
    crypt - DES-encrypt a string
    echo - output one or more strings
    explode - split a string by string
    flush - flush the output buffer
    get_meta_tags - Extracts all meta tag content attributes from a file and returns an array
    htmlspecialchars - Convert special characters to HTML entities.
    htmlentities - Convert all applicable characters to HTML entities.
    implode - join array elements with a string
    join - join array elements with a string
    ltrim - Strip whitespace from the beginning of a string.
    md5 - calculate the md5 hash of a string
    nl2br - Converts newlines to HTML line breaks.
    Ord - return ASCII value of character
    parse_str - parses the string into variables
    print - output a string
    printf - output a formatted string
    quoted_printable_decode - Convert a quoted-printable string to an 8 bit string
    QuoteMeta - quote meta characters
    rawurldecode - decode URL-encoded strings
    rawurlencode - URL-encode according to RFC1738
    setlocale - set locale information
    similar_text - calculate the similarity between two strings
    soundex - calculate the soundex key of a string
    sprintf - return a formatted string
    strchr - Find the first occurrence of a character.
    strcmp - binary safe string comparison
    strcspn - find length of initial segment not matching mask
    strip_tags - Strip HTML and PHP tags from a string
    StripSlashes - un-quote string quoted with addslashes
    strlen - get string length
    strrpos - Find position of last occurrence of a char in a string.
    strpos - Find position of first occurrence of a string.
    strrchr - Find the last occurrence of a character in a string.
    strrev - Reverse a string.
    strspn - find length of initial segment matching mask
    strstr - Find first occurrence of a string.
    strtok - tokenize string
    strtolower - Make a string lowercase.
    strtoupper - Make a string uppercase.
    str_replace - Replace all occurrences of needle in haystack with str
    strtr - Translate certain characters.
    substr - Return part of a string.
    trim - Strip whitespace from the beginning and end of a string.
    ucfirst - Make a string’s first character uppercase
    ucwords - Uppercase the first character of each word in a string

    우리에게 Norton 유틸리티로 유명한 피터 노턴씨는 “훌륭한 프로그래머가 되기 위해서는 스트링을 자유자제로 다루어야 한다”라고 말씀하셨습니다. 스트링은 자료처리의 기초가 됩니다. 그래서 언어적인 관점에서 그 언어가 얼마나 스트링 처리에 강력한가 하는 것도 언어를 평가하는 기준에 속합니다. PHP는 우리가 일반적으로 사용하는 스트링외에 좋은 것들은 모두 가지고 있습니다. 예로 Visual Basic에서 쓰이는 trim도 있고 웹상에서 유용하게 쓰이는 nl2br와 같은 함수도 있습니다. 물론 구현하기에 어렵지는 않지만 버그테스트를 마친 함수들을 사용하는 것이 더 낳습니다.
     

    strtok예제

    <HTML>
    <HEAD>
    <TITLE>strtok</TITLE>
    </HEAD>
    <BODY>
    <?
            // create a demo string
            $line = “leon\tatkinson\tleon@clearink.com”;

            // loop while there are still tokens
            for($token = strtok($line, “\t”);
                    $token != “”;
                    $token = strtok(“\t”))
            {
                    print(“token: $token<BR>\n”);
            }
            
    ?>
    </BODY>
    </HTML>

    explode예제

    <HTML>
    <HEAD>
    <TITLE>explode</TITLE>
    </HEAD>
    <BODY>
    <?
            /*
            ** convert tab-delimited list into an array
            */
            $data = “red\tgreen\tblue”;
            $colors = explode(“\t”, $data);

            // print out the values
            for($index=0; $index < count($colors); $index++)
            {
                    print(“$index : $colors[$index] <BR>\n”);
            }
    ?>
    </BODY>
    </HTML>

 

    위 두 예제 모두 스트링을 형식에 맞게 나누어서 처리하는 예입니다. 기존의 ANSI C에 있는 strtok는 스트링을 토큰별로 나누는 기능이 있지만 사용자가 부가적인 처리를 해야 합니다. 여기에 PHP는 explode함수를 추가하였는데 PHP의 강력한 변수형 변환기능을 합쳐서 바로 배열로 토큰을 반환합니다. 하지만 어느 것을 사용하는가는 여러분의 선택입니다.

     

7. zlib 함수들(LII. Compression functions)

    gzclose - close an open gz-file pointer
    gzeof - test for end-of-file on a gz-file pointer
    gzfile - read entire gz-file into an array
    gzgetc - get character from gz-file pointer
    gzgets - get line from file pointer
    gzgetss - get line from gz-file pointer and strip HTML tags
    gzopen - open gz-file
    gzpassthru - output all remaining data on a gz-file pointer
    gzputs - write to a gz-file pointer
    gzread - Binary-safe gz-file read
    gzrewind - rewind the position of a gz-file pointer
    gzseek - seek on a gz-file pointer
    gztell - tell gz-file pointer read/write position
    readgzfile - output a gz-file
    gzwrite - Binary-safe gz-file write

     // get contents of a gz-file into a string
    $filename = “/usr/local/something.txt.gz”;
    $zd = gzopen( $filename, “r” );
    $contents = gzread( $zd, 10000 );
    gzclose( $zd );

    zlib는 우리가 일반적으로 .gz 으로 압축된 파일을 변환과정없이 바로 다룰 수 있도록 하는 라이브러리입니다. 이것 또한 여러 기종과 언어로 포팅 되었습니다.

 

8. 마치며

    그 외 PHP의 함수들은 데이터 베이스 함수와 크게 GD 라이브러리 함수들로 구성되어 있습니다. PHP를 사용하면서 “어떤 데이터 베이스를 사용할까?” 하는 행복한 고민에 빠지게 합니다. 자 이렇게 PHP의 함수들을 살펴보았습니다.

    그런데 PHP에 대한 도움을 얻고자 하려면 어떻게 해야 할까요? PC통신 동호회 각종 PHP관련 사이트(우리나라)에서 정보를 얻으시려고 노력할 것입니다. 하지만 조금만 노력을 하면 하나의 트릭을 찾기 위해 몇 날 몇일 인터넷을 헤매실 필요가 없고 버그 아닌 버그와 사투를 벌일 필요가 없습니다.. 그것은 바로 메일링 리스트 가입과 소스에 포함되어 있는 도큐멘트를 보는 것입니다. 이 글 쓰면서도 php 3.0.12의 도큐먼트와 core php의 예제들 그리고 PHP 메일링 리스트를 참조하였습니다. 이것은 양질의 정보를 얻을 수 있는 곳이기 때문입니다.
    예를 들어 메일을 보내면서 파일을 첨부하는 홈페이지를 만들고 싶을 경우에 도큐먼트에 친절히 설명을 해 주고 있습니다.

    이것으로 PHP에 대해 자세히 알아보았습니다. 소개를 못해 드린 것들은 독자 여러분의 몫으로 남겨 놓겠습니다.
    다음호에서는 실제 프로그래밍을 하면서 살펴보겠습니다.




▲ top

home으로...