Stig Sæther Bakken
Egon Schmid
황원희 (Home Page: http://php.morosolution.com
E-Mail: regina@morosolution.com)
(이 글은 황원희 개인이 번역한 내용입니다. 글의 오역에 따른 책임을 지지 않습니다. 글의 잘못된 부분은 연락해 주시면
감사하겠습니다.)
Copyright ⓒ 1997, 1998, 1999, 2000 by the PHP Documentation Group
Copyright (역자주 : 원문의 법적인 효력문제로 번역하지 않습니다. 내용은 GPL을 따르고 있다는 내용입니다.)
This manual is © Copyright 1997, 1998, 1999, 2000 by the PHP Documentation Group. The members of this group are listed on the front page of this manual.
This manual can be redistributed under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
PHP Version 3.0은 HTML에 내장되어 동작하는 스크립트 언어이다.(HTML-embedded scripting language) PHP는 C와 Java, Perl등으로부터 많은 문장 형식을 빌려쓰고 있고, 몇가지는 고유한 것도 있다. 이 언어의 목적은 웹개발자들이 동적인 웹문서를 빠르고 쉽게 작성할 수 있도록 하는 것이다.
원래 영문 매뉴얼은 DocBook DTD을 사용한 SGML로 작성되어 있고, formatting을 위해서는 DSSSL (Document Style and Semantics Specification Language)을 사용하고 있다. 또한 Tex와 RTF버젼도 있으나, 한글 문서는 역자의 편의를 위해 일단 HTML만을 사용하도록 하겠다.
PHP는 server-side HTML-embedded scripting language입니다.
간단한 답이지만, 무엇을 의미할까? 다음 예를 보자. :
Example 1-1. An introductory example <html><head><title>Example</title> <body> <?php echo "Hi, I'm a PHP script!"; ?> </body></html> |
Perl이나 C와같은 다른 언어와 다르게 HTML을 출력하는데 많은 명령어가 필요없다. 여러분은 HTML내에 여러분이 하고자 하는 일(위의 경우는 한줄의 문자열 출력)에 대한 스크립트를 적어주면 된다. PHP 코드는 특정한 시작/끝 태크사이에 들어가게 되는데 이 태그는 "PHP 모드"로 들어가거나 나오게 하는 것이다.
PHP가 client-side Javascript 같은 것과 구별되는 것은 이 코드가 서버에서 실행된다는 것이다.
가장 기본적인 레벨에서, PHP는 CGI 프로그램에서 할 수 있는 모든 것을 할 수 있다. form data를 가져오고, 동적인 웹페이지를 만들거나, Cookie를 보내고 받을 수도 있다.
아마 PHP의 가장 강력하고 관심가는 부분은 database와의 연동부분일 것이다. PHP를 사용하면 여러분은 Database의 Data를 사용한 Web page를 놀랍도록 간단히 만들 수 있다. 다음에 나오는 DB server들을 현재 사용할 수 있다. :
Adabas D
InterBase
Solid
dBase
mSQL
Sybase
Empress
MySQL
Velocis
FilePro
Oracle
Unix dbm
Informix
PostgreSQL
PHP는 IMAP나 SNMP, NNTP, POP3, HTTP등의 프로토콜들을 사용해서 다른 서비스들에 대해 접근하여 데이터를 교환할 수 있다. 심지어는 raw network 소켓을 사용하면, 그외의 프로토콜들을 사용할 수도 있다.
PHP는 1994년 가을 Rasmus Lerdorf가 처음 고안하였다. 처음 비공개판은 그의 홈페이지에 사용되었고, 외부에 사용된 것은 1995년 초부터 사용되어 Personal Home Page Tools라고 불리게 되었다. 이것은 몇 개의 특별한 매크로를 사용할 수 있는 단순한 파서(명령 해석기) 엔진과 방명록이나 카운터 같이 홈페이지의 뒤에서 공통적으로 사용할 수 있는 몇 개의 간단한 유틸리티로 구성되었다. 이 파서가 1995년 중반에 재작성되어 PHP/FI Version 2라고 명명되었다. FI는 Rasmus가 작성한 html 형식의 데이터를 해석할 수 있는 별도의 패키지다. 그는 이 두가지를 합치고 mSQL을 지원하도록하여 PHP/FI를 탄생시켰다. PHP/FI는 빠른 속도로 발전하였고, 많은 사람들이 이에 공헌하였다.
정확한 통계는 없지만 1996년 후반 PHP/FI는 전세계적으로 최소한 15,000개 이상의 웹사이트에서 사용되는 것으로 추정되었고, 1997년 중반에 그수는 50,000으로 늘어났다. 1997년 중반 PHP는 또다른 중요한 변화를 가져왔다. 이때부터 PHP는 Rasmus의 개인이 아닌 팀에 의해 개발되고 있다. 새 파서는 Zeev Suraski와 Andi Gutmans가 재 작성되었고, PHP Version 3라는 이름으로 나타났다. 많은 PHP/FI의 기능들이 옮겨왔고, 그외에도 많은 기능들이 새로 작성되었다.
1998년 중반인 현재 PHP/FI나 PHP3는 C2의 StrongHold web server나 RedHat Linux같은 여러 상업적인 제품과 함께 제공되고 있으며, 전세계적으로 최소한 150,000개의 웹사이트가 사용하고 있다. 이 수는 인터넷에서 Netscape's flagship Enterprise server의 사용수보다 많다.
이 글이 쓰여지고 있는 가운데, PHP의 차기 버전이 제작되고 있다. 새로운 PHP는 Zend 같은 효율적인 스크립트 엔진과 Apache이외의 웹서버에서도 모듈로 실행될 수 있도록 제작되고 있다.
여러분은 최신버전의 소스와 (윈도우즈를 포함한)여러 플랫폼의 배포판을 http://www.php.net에서 내려 받을 수 있다.
이 장은 PHP를 설치하고 설정하는 방법에 대해 설명하고 있다. 필요한 지식과 소프트웨어 :
기본적인 UNIX 사용법 ("make"와 C 컴파일러의 사용)
ANSI C 컴파일러
web 서버
1 2 1. gunzip apache_1.3.x.tar.gz 3 2. tar xvf apache_1.3.x.tar 4 3. gunzip php-3.0.x.tar.gz 5 4. tar xvf php-3.0.x.tar 6 5. cd apache_1.3.x 7 6. ./configure --prefix=/www 8 7. cd ../php-3.0.x 9 8. ./configure --with-mysql --with-apache=../apache_1.3.x --enable-track-vars 10 9. make 11 10. make install 12 11. cd ../apache_1.3.x 13 12. ./configure --prefix=/www --activate-module=src/modules/php3/libphp3.a 14 13. make 15 14. make install 16 17 이 단계 대신 httpd 이진 파일을 기존의 파일에 덮어 쓸 수도 있다. 18 이 작업을 하려면 우선 httpd 서버를 끄는 것을 잊지 말도록 하자. 19 20 21 15. cd ../php-3.0.x 22 16. cp php3.ini-dist /usr/local/lib/php3.ini 23 24 여러분은 이제 PHP의 설정을 고치기위해 /usr/local/lib/php3.ini를 수정하면 된다. 25 만약 이 파일의 위치를 옮기고 싶다면 위의 8단계에서 --with-config-file=/path 옵션을 준다. 26 27 28 17. Edit your httpd.conf or srm.conf file and add: 29 30 AddType application/x-httpd-php3 .php3 31 32 여기서 여러분은 .php3외에 다른 확장자를 사용할 수도 있다. 33 하지만 많은 사람들이 사용하는대로 그냥 .php3를 사용할 것을 권한다. 34 35 18. 일반적인 방식대로 Apache 서버를 시작한다. 36 (반드시 stop과 start하여 재시동하여야한다. 37 HUP이나 USR1같은 signal을 주는 등의 reload만 해서는 소용이 없다.) 38 |
PHP를 설정하는 방법에는 크게 두가지가 있다.
다음은 여러 가지 설정 옵션들의 자세한 내용이다.
PHP를 아파치 모듈로 만들려면, "Build as an Apache module?"의 질문에 "yes"로 답하고, Apache 배포본의 base 디렉토리를 명시해 주면 된다. (configure에서는 --with-apache=DIR 옵션을 주면 된다.) 만약 여러분의 Apache 소스의 배포본을 /usr/local/src/apache_1.3.3에 풀어 놓았다면, 이 디렉토리가 Apache 배포본의 base 디렉토리가 된다. 기본 디렉토리는 /usr/local/etc/httpd이다.
PHP를 fhttpd 모듈로 만들려면, "Build as an fhttpd module?"의 질문에 "yes"로 답하고, fhttpd 소스의 base 디렉토리를 명시해 주면 된다. (configure에서는 --with-fhttpd=DIR 옵션을 주면 된다.) 기본 디렉토리는 /usr/local/src/fhttpd이다. 여러분이 fhttpd를 운영중에 있다면, 이 모듈로 만들어 실행하는 것이 더 좋은 성능을 제공하며, 또한 제어와 원격 실행 능력도 향상된다.
PHP는 기본적으로 CGI 프로그램으로 만들어 진다. 만약 여러분이 PHP가 모듈로 제공되는 웹 서버를 운영중이라면, 해당 모듈로 사용하는 것이 일반적으로 좋은 성능을 낼 수 있다. 하지만, CGI 버전은 아파치 사용자들에게 다른 user-id를 사용하여 별도의 PHP-enabled 페이지를 실행할 수 있도록 해 준다. 만약 PHP를 CGI로 실행하고 싶다면 Security chapter를 반드시 읽어보기 바란다.
PHP는 다음의 database들에 대한 고유의 지원을 제공한다. (ODBC도 제공한다.)
--with-adabas=DIR
Adabas D 지원으로 컴파일한다. DIR은 Adabas D가 설치된 Directory이고, 기본값은 /usr/local/adabasd이다.
--with-dbase
DBase지원으로 컴파일 한다. 별도의 라이브러리는 필요 없다.
--with-filepro
번들된 읽기 전용 filePro(bundled read-only filePro)를 지원하도록 해 준다. 별도의 라이브러리는 필요 없다.
--with-msql=DIR
mSQL을 지원하도록 한다. DIR은 mSQL이 설치된 디렉토리이고 기본값은 /usr/local/Hughes이다. 이 디렉토리는 mSQL 2.0 배포본의 기본 디렉토리이다. configure는 현재 작동중인 mSQL의 버전을 자동으로 탐지하여 1.0과 2.0중 하나를 지원하도록 한다. 만약 PHP가 mSQL 1.0지원으로 컴파일되었다면, 여러분은 mSQL 2.0 database는 사용하지 못한다. 마찬가지로 2.0으로 컴파일 되었다면 1.0 database는 사용할 수 없다.
See also mSQL Configuration Directives in the configuration file.
--with-mysql=DIR
MySQL을 지원하도록 한다. DIR은 MySQL이 설치된 디렉토리이고, 기본값은 /usr/local이다. 이 디렉토리는 MySQL 배포본의 기본 디렉토리 이다.
See also MySQL Configuration Directives in the configuration file.
--with-iodbc=DIR
iODBC지원을 포함하도록 한다. 이 기능은 iODBC 드라이버 관리자를 위해 맨 먼저 개발되었는데, 이 iODBC 드라이버 관리자 많은 UNIX하에서 돌아가는 무료 배포가 가능한 ODBC 드라이버 관리자이다. DIR은 iODBC가 설치된 디렉토리이고, 기본값은 /usr/local이다.
FreeODBC home page or iODBC home page--with-openlink=DIR
OpenLink ODBC 지원을 포함하도록 한다. DIR은 OpenLink ODBC가 설치된 디렉토리이고, 기본값은 /usr/local/openlink이다.
--with-oracle=DIR
오라클 지원을 포함하도록 한다. 오라클 버전 7.0에서 7.3까지는 동작을 테스트하여 문제가 없었다. DIR은 ORACLE_HOME 디렉토리이다. 오라클 환경이 이미 설정되어 있다면, DIR을 반드시 정해줄 필요는 없다.
--with-pgsql=DIR
IPostgreSQL지원을 포함하도록 한다. DIR은 PostgreSQL이 설치된 base 디렉토리이고, 기본값은 /usr/local/pgsql이다.
See also Postgres Configuration Directives in the configuration file.
--with-solid=DIR
Solid지원을 포함하도록 한다. =DIR은 Solid가 설치된 디렉토리이고, 기본값은 /usr/local/solid이다.
--with-sybase=DIR
Sybase지원을 포함하도록 한다. DIR은 Sybase가 설치된 디렉토리이고, 기본값은 /home/sybase이다.
See also Sybase Configuration Directives in the configuration file.
--with-sybase-ct=DIR
Sybase-CT지원을 포함하도록 한다. DIR은 Sybase-CT가 설치된 디렉토리이고, 기본값은 /home/sybase이다.
See also Sybase-CT Configuration Directives in the configuration file.
--with-velocis=DIR
Velocis지원을 포함하도록 한다. DIR은 Velocis가 설치된 디렉토리이고, 기본값은 /usr/local/velocis이다.
--with-custom-odbc=DIR
사용자 지정의 ODBC 라이브러리 지원을 포함하도록 한다. DIR은 base 디렉토리이고, 기본값은 /usr/local이다.
이 옵션을 사용하려면 여러분은 configure 스크립트를 실행할 때 CUSTOM_ODBC_LIBS를 이미 정의해 주었어야 한다. 또한, 여러분의 include path에는 적합한 odbc.h라는 헤더 파일이 반드시 있어야 한다. 만약 없다면, 여러분이 만들어서 포함시켜야 한다. 헤더에는 좀 특별한 정의들이 필요하게 되는데, 특히 그것이 multiplatform일 경우는 상세히 적어주어야 한다. 그 정의는CFLAGS 옵션에 적어준다.
예를들어 다음과 같은 옵션으로 QNX 하에서 Sybase SQL Anywhere를 사용할수 있다. : CFLAGS=-DODBC_QNX LDFLAGS=-lunix CUSTOM_ODBC_LIBS="-ldblib -lodbc" ./configure --with-custom-odbc=/usr/lib/sqlany50
--disable-unified-odbc
Unified ODBC 모듈을 사용하지 않도록한다. 이 Unified ODBC 모듈은 Solid나 Adabas D같은 ODBC기 반의 인터페이스(ODBC-based interface)를 가지고 있는 모든 database의 공통의 interface이다. 또한 이 모듈은 보통의 ODBC 라이브러리를 위해 동작한다. 이 옵션은 iODBC와 Solid, Adabas D, Sybase SQL Anywhere에서 시험을 거쳤다. 이 옵션을 사용하려 면 위의 모듈들 중 하나(반드시 하나만)거나, vELOCIS 모듈이 enabled되어 있거나 custom ODBC library가 설정되어 있어야 한다. 즉, 이 옵션은 다음과 같은 옵션중 하나가 사용되었을 경우만 사용이 가능하다. : --with-iodbc, --with-solid, --with-adabas, --with-velocis, --with-custom-odbc.
See also Unified ODBC Configuration Directives in the configuration file.
--with-ldap=DIR
LDAP (Lightweight Directory Access Protocol) 지원을 포함한다. DIR은 LDAP가 설치된 base 디렉토리이고, 기본값은 /usr/local/ldap이다.
LDAP에 대한 자세한 설명은 RFC1777 과 RFC1778에서 찾을 수 있다.
--with-mcrypt
mcrypt 라이브러리를 포함한다. 자세한 내용은 mcrypt documentation을 보자. DIR 옵션을 주게되면 PHP는 DIR/include에서 mcrypt.h를 찾는다.
--enable-sysvsem
대부분의 UNIX에서 지원하는 Sys V 세마포어의 지원을 포함한다. 자세한 정보는 Semaphore and Shared Memory documentation을 읽어 보도록 한다.
--enable-sysvshm
대부분의 UNIX에서 지원하는 Sys V 의 공유 메모리(shared memory) 지원을 포함한다. 자세한 정보는 Semaphore and Shared Memory documentation을 읽어 보도록 한다.
--with-xml
James Clark의 expat library를 사용한, 아직 공인받지 못한 XML parser를 사용하도록 한다. 자세한 내용은 XML function reference을 보자.
--enable-maintainer-mode
PHP개발자들을 위한 컴파일러 주의 메시지나, extra dependencie 메시지등을 출력하게 한다.
--with-system-regex
정규 표현식(regular expression) 라이브러리를 PHP와 같이 제공된 것이 아닌, 시스템의 것을 사용하도록 한다. 만약 여러분이 PHP를 서버 모듈로 만든다면, 여러분은 서버를 만들 때와 같은 라이브러리를 PHP를 만들 때도 사용하여야 한다. 만약 시스템의 라이브러리가 여러분이 원하는 특별한 기능을 가지고 있다면 이 옵션을 Enable시키도록 하자. 그러나, 가능하면 PHP와 같이 제공된 라이브러리를 사용하는 것이 권장된다.
--with-config-file-path=DIR
PHP가 시작될 때 사용할 configuration file(php3.ini)을 찾을 디렉토리를 정해준다.
--with-exec-dir=DIR
안전 모드(safe mode)일 때, 여기서 지정해 준 =DIR안의 실행 파일만 실행이 가능하다. 기본값은 /usr/local/bin이다. 이 옵션은 단지 Default값을 지정해 주는 것 뿐이고, configuration file의 safe_mode_exec_dir 지시자에 의해서 나중에 바뀔 수 있다.
--disable-debug
라이브러리나 실행 파일에 디버그 정보를 포함시키지 않는다. 디버그 정보는 버그의 위치를 정확하게 나타내는데 도움을 준다. 따라서, PHP가 alpha나 beta상태일 경우에는 디버그 정보를 포함시키는 것이 좋다.
--enable-safe-mode
기본값으로 "안전 모드"(safe mode)를 지정한다. 안전 모드는 문서의 root에 있는 파일만을 열수 있게 하는 등, PHP가 할 수 있는 작업에 여러 가지 제약을 가한다. 더 자세한 정보는 Security chapter를 읽어보기 바란다. CGI사용자들은 언제나 secure mode에서 사용하여야 한다. 이 옵션은 단지 Default 값을 정하는 것 뿐이고, 후에 configuration file의 safe_mode 지시자에 의해 Enable/Disable 될 수 있다.
--enable-track-vars
HTTP_GET_VARS, HTTP_POST_VARS, HTTP_COOKIE_VARS 배열에 들어있는 GET / POST / cookie 변수들이 어디서 왔는지 기억하고 있게 만든다. 이 옵션은 단지 Default 값을 정하는 것 뿐이고, 후에 configuration file의 track_vars 지시자에 의해 Enable/Disable 될 수 있다.
--enable-magic-quotes
magic quotes의 기본값을 Enable로 한다. 이 옵션은 단지 Default 값을 정하는 것 뿐이고, 후에 configuration file의 magic_quotes_runtime지시자에 의해 Enable/Disable 될 수 있다.
magic_quotes_gpc 와 magic_quotes_sybase 지시자를 참조하여 보기 바란다.
--enable-debugger
내장된 PHP 디버거 지원을 가능하게 한다. 이 기능은 아직 실험적인 상태이다.
configuration file의 Debugger Configuration 지시자를 살펴보자.
--enable-discard-path
만약 이것이 Enabled되면, PHP CGI 실행파일이 웹 트리 밖에 안전하게 위치할 수 있게 되어 사용자들이 .htaccess security를 피할 수 없게 된다. 자세한 사항은 section in the security chapter를 읽어보기 바란다.
--enable-bcmath
bc 형식의 수의 정밀도(precision)를 마음대로 조정할 수 있는 수학 함수를 사용할 수 있게 해 준다.
See also the bcmath.scale option in the configuration file.
--enable-force-cgi-redirect
내부적인 서버 리디렉트(internal server redirects) 시에 보안 검사(security check)를 하도록 한다. 여러분이 Apache와 함께 CGI 버전을 사용한다면 반드시 이 옵션을 사용하여야 한다.
GI binary형태로 PHP를 사용할 때, PHP는 기본적으로 그것이 리디렉션으로 사용되었는가를 우선 검사한다(예를 들어, Apache에서 Action directives를 사용한 경우이다). 이 옵션을 사용하면 http://my.host/cgi-bin/php/secret/doc.html과 같은 방법으로 PHP binary를 직접 호출하여 표준 web server authentication 절차를 회피하는 방법을 사용할 수 없게 된다. 이 예는 http://my.host/secret/doc.html에 접근할 수 있지만, httpd가 /secret디렉토리에 설정한 어떠한 보안 설정에도 영향을 받지 않게 된다.
이 옵션을 Enable하지 않으면 httpdd의 보안과 인증 설정을 체크하지 않고, 회피가 가능하게 된다. 이 옵션은 서버 소프트웨어가 안전한 리디렉션이 되어 있다는 것을 나타내는 것이 불가능하고, document root와 사용자 디렉토리 아래의 모든 파일이 누구에게나 개방되어 있을 때만 사용하자.
이 옵션에 대한 자세한 설명은 section in the security chapter을 읽어보기 바란다
--disable-short-tags
short form <? ?> PHP 태그의 사용을 불가능하게 한다. 여러분은 PHP와 XML을 함께 사용할 경우 short form의 사용을 불가능하게 하여야 한다. 짧은 태그의 사용이 불가능하다면, PHP의 코드는 태그는 <?php ?> 뿐이다. 이 옵션은 단지 Default 값을 정하는 것 뿐이고, 후에 configuration file의 short_open_tag 지시자에 의해 Enable/Disable 될 수 있다.
--enable-url-includes
include()함수를 사용하여 PHP에서 직접 다른 HTTP나 FTP서버에 있는 코드를 실행시킬수 있도록 한다.
See also the include_path option in the configuration file.
--disable-syntax-hl
syntax highlighting 기능을 끈다.
PHP를 설치할 때 다른 디렉토리에 있는 헤더나 라이브러리를 찾아서 만들려면, CPPFLAGS 와 LDFLAGS 환경변수를 각각 수정해 주어야 한다. 여러분이 일반적인 쉘을 사용하고 있다면 다음과 같이 사용하는 것이 가능할 것이다. LDFLAGS=-L/my/lib/dir CPPFLAGS=-I/my/include/dir ./configure
PHP의 설정이 완료되면 여러분은 PHP 라이브러리나 CGI 실행 파일을 생성할 준비가 끝난 것이다. make 명령으로 여러분은 그것을 만들 수 있다. 만약 만들 수 없고 그 이유를 모를 경우에는 Problems section을 살펴보기 바란다.
( 역자주 : PHP를 Apache 모듈로 만들었다면 restart가 아닌 stop후 start하여야 합니다.)
PHP를 CGI 프로그램 형태로 만들었다면, 여러분은 make test라고 입력하여 테스트해 볼 수 있다. 이 방법은 결과물을 테스트하는 언제나 좋은 방법이다. 이 방법은 여러분의 시스템 환경에서 나중에 문제로 골치 썩이지 않고 미리 PHP의 문제를 발견할 수 있게 해 준다.
PHP를 CGI 프로그램 형태로 만들었다면, 여러분은 make bench라고 입력하여 벤치마크 테스트를 할 수 있다. 안전 모드(safe mode)의 기본값이 on 되어 있을 때는, 작업이 허용된 30초 보다 많이 걸리게 되면 벤치마크를 끝낼 수 없다. 이것은 안전 모드에서는 set_time_limit() 함수를 사용할 수 없기 때문이다. 스크립트에서 max_execution_time을 조절하여 이 시간 간격을 조절한다. make bench는 configuration file을 무시한다.
이 설치 안내서는 여러분에게 PHP를 Windows 9x/NT 웹서버에서 설치하고 설정하는데 도움을 줄 것입니다. 이 안내서는 Bob Silva에 의해 작성되었습니다. 따라서 가장 최신의 개정판은 http://www.umesd.k12.or.us/php/win32install.html에서 찾을 수 있을 것입니다.
이 안내서는 다음과 같은 웹서버를 대상으로 합니다.
Personal Web Server (Newest version recommended)
Internet Information Server 3 or 4
Apache 1.3.x
Omni HTTPd 2.0b1
웹 서버의 종류와 관계없이 다음의 설치 과정들이 완료되어야 한다.
c:\windows for Windows 95/98 |
c:\winnt or c:\winnt40 for NT servers |
PHP 확장을 위한 DLL들은 'php3_'로 시작한다. 이것은 PHP 확장을 위한 DLL들과 자체적인 지원을 위한 DLL들간의 혼란을 방지하기 위해서이다.
이 서버들에서의 설정은 배포판의 INF 파일(php_iis_reg.inf)을 사용하는 것을 권한다. 여러분은 이 파일을 수정하여 여러분이 원하는 PHP 설치 디렉토리와 확장 내용들을 설정할 수 있다. 만약 수동으로 설정하고 싶다면 다음과 같이 합니다.
주의 : 이 과정은 윈도우의 resistry를 직접 다룹니다. 하나의 실수가 여러분의 시스템 전체를 불안한 상태로 만들 수 있습니다. 우리는 여러분이 registry를 편집하기 전에 반드시 편집 전의 registry를 백업해 놓을 것. PHP 개발팀은 어떠한 registry의 파손도 책임지지 않습니다. 만약 registry에 손상이 갈 경우 OS를 새로 깔기 전에는 부팅되지 않을 수도 있습니다.
PWS와 IIS 3 사용자들은 현재 완전한 운영중인 시스템을 갖고 있습니다. IIS 3 사용자들은 Steven Genusa가 작성한 스크립트 맵을 설정하는 매력적인 tool을 사용할 수 있습니다.
PHP를 IIS 4가 운영중인 NT Server에 설치하려면 다음 과정을 따른다.
Apache를 PHP CGI binary와 함께 실행하도록 설정하려면 srm.conf이나 httpd.conf를 다음과 같이 수정하여야 한다.
비록 Apache하에서 PHP의 설정이 약간 차이가 있을지 모르지만, 이 설정은 초보자도 할 수 있을 정도로 쉽다. 여기에 나온 것 이상의 설정 지시자는 Apache Docs를 참조하도록 하자.
소스 코드 하이라이팅 기능(소스에 색깔을 넣어서 보기 좋게 출력해 주는 기능)을 사용하기 위해서는 다음과 같은 내용을 가지는 스크립트를 만들어주면 된다. : <?php show_source ("original_php_script.php3"); ?>. 여기서 original_php_script.php3를 여러분이 원하는 소스 코드의 이름으로 바꿔주면 된다.
Note: Win-Apache에서 "c:\directory\file.ext"와 같이 path에 사용되는 모든 백슬래시(\)는 일반 슬래시(/)로 바꿔야 합니다.
이 설정은 매우 쉬운 편이다.
Step 1: Omni server를 설치한다. |
Step 2: system tray의 푸른색 OmniHTTPd 아이콘에서 오른쪽 버튼을 클릭하여 Properties(등록정보)를 선택한다. |
Step 3: Web Server Global Settings을 클릭한다. |
Step 4: 'External' 탭에서 다음을 입력한다. : virtual = .php3 | actual = c:\path-to-php-dir\php.exe |
Step 5: Mime 탭에서 다음을 입력한다. : virtual = wwwserver/stdcgi | actual = .php3 |
Step 6: OK를 클릭한다. |
PHP의 모든 확장자에 대해 steps 2 - 6을 반복한다.
Table 2-1. PHP Modules
php3_calendar.dll |
Calendar conversion functions |
php3_crypt.dll |
Crypt functions |
php3_dbase.dll |
DBase functions |
php3_dbm.dll |
GDBM emulation via Berkely DB2 library |
php3_filepro.dll |
READ ONLY access to filepro databases |
php3_gd.dll |
GD Library functions for gif manipulation |
php3_hyperwave.dll |
HyperWave functions |
php3_imap4r2.dll |
IMAP 4 functions |
php3_ldap.dll |
LDAP functions |
php3_msql1.dll |
mSQL 1 client |
php3_msql2.dll |
mSQL 2 client |
php3_mssql.dll |
MSSQL client (requires MSSQL DB-Libraries) |
php3_mysql.dll |
MySQL functions |
php3_nsmail.dll |
Netscape mail functions |
php3_oci73.dll |
Oracle functions |
php3_snmp.dll |
SNMP get and walk functions (NT only!) |
php3_zlib.dll |
ZLib functions |
일부 질문들은 공통적인 것이 많다. PHP FAQ에 이 공통적인 질문들이 모여있으니 찾아보자. 이 문서는 http://www.php.net/FAQ.php3에서 찾을 수 있다.
(역자주 : FAQ의 번역본은 http://w3.to/regina/FAQ.htm에 번역되어 있으나 최신판은 아니다.)
만약 여러분이 Bug라고 생각되는 것이 발견될 경우 이것을 반드시 보고해 주기 바란다. PHP의 개발자들은 아마 그 버그에 대해 여러분이 알려주기 전에는 모르고 있을 것이다. 여러분의 버그 레포트로 그 버그들을 잡을 수 있다. 버그 보고용 폼이 PHP 사이트에 있다. 주요 양식은 http://ca.php.net/bugs.php3에서 찾을 수 있을 것이다. (역자주: 버그 레포트는 영어로 써야 겠지요. Hi)
만약 여러분이 아직도 고생하고 있다면, PHP의 메일링 리스트(mailing list)가 도움을 줄 수 있을 것이다. 여러분이 만약 어떤 질문을 하기 전에 우선 보관 문서(archive)를 찾아보아 같은 문제에 대한 해답이 있는지 찾아보는 것을 잊지 말도록 하자. 보관 문서는 http://www.php.net/에서 찾아 볼 수 있다. PHP 메일링 리스트에 참가하려면 php3-subscribe@lists.php.net으로 빈 편지를 하나 보내면 된다. mailing list 주소는 php3@lists.php.net이다.
만약 여러분이 mailing list를 통해서 어떤 도움을 받고 싶다면, 질문시에 자세하고 명확한 질문과 함께, 여러분의 운영 환경에 대한 세부항목을 첨부하는 것이 좋다 (운영체계, PHP 버전, 웹서버의 종류와 버전, PHP를 CGI로 쓰고 있는지 모듈로 쓰고 있는지 등). 또한 여러분이 당면한 문제를 재현할 수 있는 코드를 포함시키면 더욱 좋다. (역자주: 이것도 당연히 영어로 써야 겠지요. Hi)
설정 파일(configuration file)은 (PHP 3.0에서는 php3.ini 이고, PHP 4.0에서는 php.ini 이다.) PHP가 시작될 때 읽혀진다. 서버 모듈 형태의 PHP는 이 작업을 서버가 실행 될 때 한번만 하게 된다. CGI형태의 경우는 불려질 때마다 매번 일어난다.
PHP를 아파치 모듈로 사용할 때는, PHP의 설정을 Apache configuration 파일과 .htaccess 파일에서 지정하여 설정할 수도 있다.
PHP 3.0에서는, PHP의 지시자(directive)들과 일치하는 Apache httpd.conf 지시자가 있다. httpd.conf에서의 지시자 이름은 php3.ini의 지시자 이름 앞에 "php3_"를 붙인 것이다.
PHP 4.0에서는 다음과 같은 몇 개의 Apache 지시자만으로 PHP 설정을 바꿀 수 있다.
( 역자주 : PHP를 아파치 모듈로 사용할 경우 httpd.conf에 적어준 옵션만 작동한다고 한다. )
( 역자주 : httpd.conf에 옵션을 적는 방법은 조금 다르다. "="을 사용하지말고 그냥 한칸을 띄고 적어주면 된다.
include_path 옵션을 설정하는 예는 다음과 같다. php3_include_path .:/home/httpd/php-lib )
현재 설정된 설정값은 phpinfo()함수를 사용하여 확인해 볼 수 있다. 또한 개개의 설정 내용을 확인하기 위해서는 get_cfg_var()함수를 사용하면 된다.
Note: ASP-style tags 지원은 3.0.4 버전에서 추가되었다.
none 값을 주게 되면 auto-appending이 disable된다.
NOTE: 만약 스크립트가 exit()로 종료되게 되면 auto-append는 일어나지 않는다.
none 값을 주게 되면 auto-prepending이 disable된다.
Table 3-1. Error Reporting Levels
bit value |
enabled reporting |
---|---|
1 |
normal errors |
2 |
normal warnings |
4 |
parser errors |
8 |
non-critical style-related warnings |
기본값은 7 이다(normal errors와 normal warnings, parser errors가 레포트 된다).
예를 들어 어떤 스크립트가 fopen이나 gzopen으로 파일을 열려고 할 때 그 파일이 지정된 위치에 있는가 검사한다. 만약 파일이 지정된 디렉티리밖에 있다면, PHP는 이 열기 동작을 거부한다. 모든 symbolic link들은 원래의 이름으로 바뀌어 해석된다. 따라서 이 제한을 피하기 위해 symbolic link를 사용하는 것을 방지할 수 있다.
.이라는 지정된 값을 주면 스크립트 파일이 있는 디렉토리가 base-directory로 지정된다.
Windows에서는 세미콜론(;)을 사용하고, 다른 OS에서는 콜론(:)으로 구분한다. As an Apache module, open_basedir paths from parent directories are now automatically inherited
NOTE: PHP 3.0.7 부터, 한 개 이상의 디렉토리를 지정할 수 있도록 되었다.
기본값은 모든 파일을 열 수 있는 것이다.
See also ignore_user_abort().
Example 3-1. UNIX include_path
|
Example 3-2. Windows include_path
|
기본값은 .이다. (현재 디렉토리만)
sendmail을 사용하지 않는 시스템의 경우 현재 제공되고 있는 다른 메일 시스템의 sendmail 호환 명령(wrapper/replacement)으로 설정해 주어야 한다. 예를들어 Qmail 사용자는 보통 /var/qmail/bin/sendmail로 설정해 주면 된다.
dynamic loading을 불가능하게 하는 첫 번 째 이유는 보안상의 이유이다. dynamic loading에서는 모든 safe_mode 설정과 open_basedir 설정이 무시될 수 있기 때문이다.
기본값은 모든 dynamic loading을 허용하는 것이다. 단, safe-mode를 사용하는 중에는 항상 dl()의 사용이 불가능해 진다.
PHP는 강력한 언어이디. 그 인터프리터는 웹서버의 모듈로 되어 있건 CGI binary로 되어 있건 간에, 파일을 사용할 수 있고, 다른 명령이나 프로그램을 실행할 수 있고, 서버로 네트웍 연결을 할 수도 있다. 이런 특성들은 기본적으로 어떤 프로그램이든 실행시켜 웹서버를 불안한 상태로 만들 수 있다. PHP는 분명히 Perl이나 C보다 좀더 안전한 CGI 프로그램을 만들 수 있다. 컴파일시나 실행시 설정 옵션들을 적절히 선택함으로, 여러분은 원하는 정도의 자유로움과 보안상의 제약을 조화시킬 수 있다.
PHP는 수많은 방법으로 이용이 가능하고, 이에 따른 여러 가지 설정 옵션이 있을 수 있다. 많은 옵션 선택 사항들은 PHP를 보다 많은 목적으로 사용할 수 있도록 하지만, 이 옵션들의 조합과 서버의 설정에 따라 보안상의 허점을 노출시킬 수도 있다. 이 장은 다른 옵션의 조합 방법과 이것을 안전하게 사용하는 상황을 설명한다.
CGI binary 형태의 PHP는 어떤 이유로 서버 소프트웨어(아파치 같은)의 모듈로 사용되기를 원하지 않는 경우에 사용할 수 있고, PHP를 다른 종류의 CGI wrapper와 함께 안전한 chroot와 setuid 환경을 만들어 내는 곳에 때에 사용할 수 있다. 이 설정은 보통 실행할 PHP binary를 웹서버의 cgi-bin디렉토리에 설치해야 한다. CERT 권고사항 CA-96.11에 따르면 모든 인터프리터들은 cgi-bin에 설치하도록 권고된다. 비록 PHP binary가 독립적인 인터프리터로 사용된다 할지라도, PHP는 이 설정이 만들어낼 가능한 공격을 다음과 같이 막아내도록 설계되어 있다. :
이 url내의 물음표(?)이후에 있는 요청은 CGI 인터페이스에 의해 command line argument로 인터프리터에게 전달된다. 보통 인터프리터는 커맨드 라인의 첫 번째 argument의 파일을 읽어서 실행 한다.
CGI binary로 실행 된 PHP는 모든 command line argument들을 모두 무시한다.
이 url의 PHP binary 이후의 path 정보(/secret/doc.html)는 일반적으로 CGI 프로그램에 의해 읽고 해석되어 지는 파일 이름으로 사용된다. 보통 어떤 웹서버 설정 지시자(Apache의 경우 Action)가 http://my.host/secret/script.php3와 같은 문서 요청을 PHP 인터프리로 리디렉트 하는데 사용된다. 이렇게 설정하면, 웹서버는 우선 /secret 디렉토리의 접근 권한을 검사한 후에 http://my.host/cgi-bin/php/secret/script.php3의 리디렉트 요청을 하게 된다. 불행히도, 이 요청이 원래의 form에서 주어진 것이라면, 웹서버는 /secret/script.php3 파일에 대한 접근 권한 검사를 하지 않고, /cgi-bin/php 파일에 대한 검사만을 행한다. 이 방법을 사용하면 /cgi-bin/php에 접근 가능한 사용자는 웹서버상의 모든 보호된 문서들도 접근할 수 있다.
PHP에서는 서버 문서 tree가 접근 제약이 있는 디렉토리를 가지고 있다면, 컴파일시에 --enable-force-cgi-redirect 설정 옵션을 주고, 실행시에 doc_root와 user_dir 지시자를 사용하여서 이 공격을 막아낼 수 있다. 아래에 여러 가지 다른 조합 방법에 대한 자세한 설명이 나와 있다.
만약 여러분의 서버가 password 나 ip 기준의 접근 통제에 관한 어떠한 사항도 없다면, 이러한 설정 옵션들은 필요 없다. 만약 여러분의 웹서버가 리디렉트를 허용하지 않거나, 서버가 해당 요구가 안전하게 리디렉트된 요구인지 대해 PHP binary와 통신할 수 있는 방법이 없을 경우, 여러분은 스크립트를 설정하기 위해 --disable-force-cgi-redirect 옵션을 명시할 수 있다. 여러분은 여전히 여러분의 PHP 스크립트가, http://my.host/cgi-bin/php/dir/script.php3처럼 직접 접근하는 것도 아니고 http://my.host/dir/script.php3같이 리디렉션에 의해서도 아닌, 다른 믿지 못할 방법에 의해 불려 질 때를 대비하여 대책을 강구해 두어야 합니다.
리디렉션은 예를들어 Apache에서는 AddHandle과 Action 지시자를 사용하여 설정할 수 있습니다. (아래를 보세요.)
이 컴파일시의 옵션은 사용자가 http://my.host/cgi-bin/php/secretdir/script.php3와 같이 PHP를 직접 호출하는 것을 막아준다. 대신, 이 모드에서 PHP는 그것이 웹서버의 리디렉트 규칙을 통과한 경우에만 parse 작업을 할 것이다.
일반적으로 아파치 설정에서 리디렉트 설정은 다음과 같이 지시자를 사용하여 한다. :
Action php3-script /cgi-bin/php AddHandler php3-script .php3
이 옵션은 아파치 웹서버에서 시험을 거쳤고, 아파치는 리디렉트된 요구에 대해서는 REDIRECT_STATUS 라는 비 표준 CGI 환경 변수를 설정한다. 만약 당신의 웹서버가 문서 요구가 직접(direct)인지 리디렉트(redirect)인지 구별할 수 있는 방법을 제공하지 않는다면 여러분은 이 옵션을 사용할 수 없다. 따라서, 여러분은 이 문서에 씌여져 있는 CGI 버전의 다른 실행 방법을 사용해야 할 것이다.
웹서버 문서 디렉토리에 script나 실행파일 같은 Active content를 포함하는 것은 종종 불안하다고 생각되어 진다. 만약 약간의 설정 오류로 스크립트가 실행되지 않고 HTML 문서처럼 그대로 출력 된다면, 각종 지적 재산이나 Password같은 보안상의 정보가 누설되는 결과가 초래될 지도 모른다. 그러므로 많은 시스템 관리자들은 스크립트를 위한 별도의 디렉토리를 만들어 놓고, 이 디렉토리는 PHP CGI를 통해서만 접근이 가능하도록 만들어 놓아 실행은 가능하지만 보여지지는 않도록 한다.
또한, 전장에서 기술한 바와 같이, 요구가 리디렉트된 것이 아니라고 확인해주는 방법이 없다면, 웹 문서의 root와는 다른 스크립트의 doc_root를 설정해 주는 것이 반드시 필요하다.
여러분은 php3.ini의 doc_root 지시자를 설정하거나, PHP_DOCUMENT_ROOT라는 환경변수 값에 설정해 주어, PHP 스크립트 문서의 root를 설정할 수 있다. 만약 이것이 설정되어 있다면, CGI 버전의 PHP는 언제나 이 doc_root와 request에 있는 경로 정보를 가지고 접근하려는 파일의 이름을 만든다. 따라서 여러분은 이 디렉토리 밖에서는 어떠한 스크립트도 실행될 수 없도록 만들게 된다. (아래에 있는 user_dir 만은 예외이다)
이곳에서 또 하나 사용할 수 있는 옵션은 user_dir이다. user_dir이 설정되어 있지 않으면 접근 가능한 파일을 doc_root에 있는 것 뿐이다. http://my.host/~user/doc.php3같은 url로는 user home directory에 있는 파일을 열 수 없다. 단지 doc_root아래의 ~user/doc.php3 파일을 부를 뿐이다. (물론 틸데[~]로 시작하는 "~user"라는 디렉토리이다.)
만약 user_dir이 예를 들어 public_php로 설정되어 있다면, http://my.host/~user/doc.php3와 같은 요구는 user의 home 디렉토리 밑의 public_php라는 디렉토리 밑의 doc.php3라는 파일을 호출 할 것이다. 만약 사용자의 home이 /home/user라면, 실행되는 파일은 /home/user/public_php/doc.php3이 된다.
user_dir 확장은 doc_root 설정과 관련없이 발생하므로, 여러분은 document root와 user directory 접근 통제를 별도로 할 수 있다.
매우 신뢰할수 있는 옵션으로 PHP parser binary를 웹 트리 밖에다 두는 방법이다. 예를 들어 /usr/local/bin 같은 곳에 둔다. 이 옵션의 실질적인 단점은, 모든 PHP 택을 포함하고 있는 파일의 첫번째 라인에 다음과 비슷하게 적어주는 것 뿐이다. :
#!/usr/local/bin/php
또한 파일을 실행 가능으로 만들어 주어야 한다. 즉, 자신의 실행을 위해서 #! shell-escape 메카니즘을 사용하는 Perl이나 sh 혹은 다른 스크립트 언어와 같은 방식으로 다루는 것이다.
이 설정에서 PHP가 PATH_INFO와 PATH_TRANSLATED정보를 올바르게 다루려면, php parser가 --enable-discard-path 설정 옵션으로 컴파일 되어야 한다.
PHP가 아파치의 모듈로 사용될 때는 아파치의 사용자 permission을 계승받는다. (일반적으로 "nobody"로 설정되어 있다.)
HTML로부터 빠져나와 "PHP code mode"로 들어가는 방법은 다음 4가지가 있다 :
Example 5-1. Ways of escaping from HTML
|
첫 번째 방법은 short tags가 enable되어 있어야 사용가능하다. short_tags()를 호출하거나, short_tags run-time 설정에서 가능하고, 컴파일시에 --enable-short-tags 옵션을 주어 컴파일하여 enable할 수도 있다.
네 번째 방법은 ASP-style tags가 enable되어 있어야 사용가능하다. asp_tags run-time 설정에서 가능하고, 컴파일시에 --enable-asp_tags 옵션을 주어 컴파일하여 enable할 수도 있다.
Note: ASP-style tags는 3.0.4부터 지원된다.
닫는 괄호는 newline을 포함한다.
각각의 명령은 C나 Perl과 마찬가지로 구분된다. 각 문장은 ;(세미콜론)으로 종료된다.
PHP의 종료택인 ?>는 문장의 끝이라는 의미도 함께 가지고 있다. 따라서 다음 두 개의 문장은 동일하다.
1 2 <?php 3 echo "This is a test"; 4 ?> 5 6 <?php echo "This is a test" ?> 7 |
PHP는 'C'와 'C++', Unix shell 형태의 주석문을 제공한다. 예를 들어 :
1 2 <?php 3 echo "This is a test"; // This is a one-line c++ style comment 4 /* This is a multi line comment 5 yet another line of comment */ 6 echo "This is yet another test"; 7 echo "One Final Test"; # This is shell-style style comment 8 ?> 9 |
"one-line" 주석문은 라인의 끝이나, 현 php 코드 블록의 끝에서 끝난다.
1 2 <h1>This is an <?# echo "simple";?> example.</h1> 3 <p>The header above will say 'This is an example'. 4 |
'C' 형태의 주석문은 중복해서 사용하지 말아야 한다.
1 2 <?php 3 /* 4 echo "This is a test"; /* 이 주석문은 문제가 된다. */ 5 */ 6 ?> 7 |
PHP는 다음 형태의 type을 지원한다. :
( 역자주 : 내부적으로는 함수와 클래스도 변수로 정의되기는 하지만 이것들은 일반적인 변수로 체크되지 않는다. )
변수타입은 보통 프로그래머가 선택할 필요가 없다. 대신, PHP가 실행중에 변수의 값의 내용에 따라 자동적으로 바꾸어 준다.
만약 여러분이 특정한 변수 타입으로 지정하고 싶다면 변수를 cast 하거나, settype() 함수를 사용한다.
종종 변수들은 실행시 어떤 타입으로 되어 있느냐에 따라 특정한 상황에서 원하는 대로 동작하지 않을 때가 있다. Type Juggling 편을 보면 자세히 알 수 있다.
정수형은 다음과 같은 형태의 문장으로 지정할 수 있다.
1 2 $a = 1234; # decimal number 3 $a = -123; # a negative number 4 $a = 0123; # octal number (equivalent to 83 decimal) 5 $a = 0x12; # hexadecimal number (equivalent to 18 decimal) 6 |
실수형("doubles")은 다음과 같은 형태의 문장으로 지정할 수 있다.
1 2 $a = 1.234; $a = 1.2e3; 3 |
문자열은 두 개의 delimiters를 사용해 나타낸다.
문자열이 큰 따옴표(")로 둘러싸이게 표시되면, 다음과 같이 특수 문자들을 포함할 수 있다. C나 Perl에서처럼 백슬래시(\)를 사용하여 특수 기호를 표시하게 된다.
Table 6-1. Escaped characters
sequence |
meaning |
---|---|
\n |
newline |
\r |
carriage |
\t |
horizontal tab |
\\ |
backslash |
\$ |
dollar sign |
\" |
double-quote |
때로는 다른 escape를 사용할 수 있지만, worning이 발생하게 된다.
문자열을 표현하는 또 다른 방법은 큰 따옴표(") 대신 작은 따옴표(')를 사용하는 것이다. 이것은 \\과 \'의 두 개만을 백슬래시 처리하고 나머지는 그냥 둔다. 작은 따옴표를 사용하는 문자열 내에서는 변수를 사용하여 그 값을 출력하는 기능을 사용할 수 없다.
문자열을 선언하는 다른 방법은 here doc 구문("<<<")을 사용하는 것이다. <<< 뒤에 적당한 identifier를 적어주고, 원하는 문자열의 내용을 적은 후에, 앞에 적은 identifier로 문자열을 끝맷으면 된다. 끝맷는 identifier는 해당 라인의 첫번째 칸에서 시작해야 한다.
Example 6-1. Here doc string quoting example
|
Note: Here doc은 PHP 4에서부터 지원된다.
문자열은 '.' (점) 연산자로 연결할 수 있다. '+' (더하기) 연산자는 사용할 수 없다. 자세한 정보는 String operators 부분을 참조하기 바란다.
문자열내의 개개의 문자는, C 언어에서의 문자의 배열로된 문자열처럼 배열에 숫자 인덱스를 통해 접근이 가능하다. 아래 그 예가 있다.
Example 6-2. Some string examples
|
문자열이 숫자로 다루어질 때, 결과 값과 type은 다음과 같이 결정된다.
만약 문자열 안에 '.' 이나 'e', 'E'의 문자가 있을 경우 그 type은 double이 된다. 그렇지 않다면 정수 값이다
그 값은 문자열의 가능한 부분까지만 사용된다. 문자열이 올바른 숫자 데이터로 시작하지 않으면 그 값은 0이다. 올바른 숫자 데이터는 '+'/'-', '0'-'9','.'과 숫자 뒤의 'e'나 'E' 표시이다.
첫 번째 표현식이 string인 경우, 변수의 type은 첫 번째가 아닌 두 번째 표현식에 의해 결정된다.
1 2 $foo = 1 + "10.5"; // $foo is double (11.5) 3 $foo = 1 + "-1.3e3"; // $foo is double (-1299) 4 $foo = 1 + "bob-1.3e3"; // $foo is integer (1) 5 $foo = 1 + "bob3"; // $foo is integer (1) 6 $foo = 1 + "10 Small Pigs"; // $foo is integer (11) 7 $foo = 1 + "10 Little Piggies"; // $foo is integer (11) 8 $foo = "10.0 pigs " + 1; // $foo is integer (11) 9 $foo = "10.0 pigs " + 1.0; // $foo is double (11) 10 |
이 변환에 대한 자세한 설명은Unix manual page의 strtod(3)을 보아라.
만약 여러분이 위의 예제를 실제 실험하고자 한다면, 위의 예제를 잘라 붙인 후에, 어떤 일이 일어났는 가를 알기 위해 아래의 줄을 삽입한다.
1 2 echo "\$foo==$foo; type is " . gettype( $foo ) . "<br>\n"; 3 |
배열을 실제로 hash tables (associative arrays) 과 indexed arrays (vectors)의 두가지로 동시에 사용된다.
PHP는 scalar 배열과 associative 배열의 두 가지를 지원한다. 사실 두 가지의 차이는 없다. 여러분은 list()나 array() 함수를 사용하여 배열을 만들거나, 각 원소의 값을 정해 주어 배열을 만들 수 있다.
1 2 $a[0] = "abc"; 3 $a[1] = "def"; 4 $b["foo"] = 13; 5 |
또한 다음과 같이 변수에 값을 더해주는 것만으로 배열을 만들 수도 있다.
1 2 $a[] = "hello"; // $a[2] == "hello" 3 $a[] = "world"; // $a[3] == "world" 4 |
배열은 정렬을 원하는 형식에 따라 asort(), arsort(), ksort(), rsort(), sort(), uasort(), usort(), uksort() 함수들을 이용해 순서대로 정렬할 수 있다.
count() 함수를 사용하면 배열의 원소 개수를 셀 수 있다.
next()와 prev() 함수를 이용하여 배열의 내용을 탐색할 수 있다. 배열의 내용을 탐색하는 방법으로 each() 함수를 사용할 수도 있다.
다차원 배열이라 하더라도 실제로 매우 간단한다. 배열의 각 차원에 대하여 단지 [key]값을 뒤어 붙여주면 된다.
1 2 $a[1] = $f; # one dimensional examples 3 $a["foo"] = $f; 4 5 $a[1][0] = $f; # two dimensional 6 $a["foo"][2] = $f; # (you can mix numeric and associative indices) 7 $a[3]["bar"] = $f; # (you can mix numeric and associative indices) 8 9 $a["foo"][4]["bar"][0] = $f; # four dimensional! 10 |
PHP3에서, 문자열 내에서 다차원 배열의 값을 직접 접근하는 것은 불가능하다. 예를들어 다음과 같은 문장은 원하는 결과를 얻지 못할 것이다.
1 2 $a[3]['bar'] = 'Bob'; 3 echo "This won't work: $a[3][bar]"; 4 |
PHP3에서 위의 출력은 won't work: Array[bar] 일 것이다. 원하는 결과를 얻으려면 문자열 연결 연산자(.)를 사용하여야 할 것이다.
1 2 $a[3]['bar'] = 'Bob'; 3 echo "This will work: " . $a[3][bar]; 4 |
PHP4에서는 접근하려는 배열식을 중괄호({})로 둘러쌈으로써 이것을 가능하게 할 수도 있다.
1 2 $a[3]['bar'] = 'Bob'; 3 echo "This will work: {$a[3][bar]}"; 4 |
여러 가지 방법으로 이 다차원 배열에 값을 넣을 수 있으나, associative 배열에 값을 저장하는 간단한 방법으로 array() 명령을 사용하는 방법이 있다. 우선 다음의 두가지 코드는 일차원 배열에 값을 저장하는 방법으로 결과는 동일하다.
1 2 # Example 1: 3 4 $a["color"] = "red"; 5 $a["taste"] = "sweet"; 6 $a["shape"] = "round"; 7 $a["name"] = "apple"; 8 $a[3] = 4; 9 10 # Example 2: 11 $a = array( 12 "color" => "red", 13 "taste" => "sweet", 14 "shape" => "round", 15 "name" => "apple", 16 3 => 4 17 ); 18 |
array() 함수는 다차원 배열에 대해서도 다음과 같이 사용할 수 있다. :
1 2 <? 3 $a = array( 4 "apple" => array( 5 "color" => "red", 6 "taste" => "sweet", 7 "shape" => "round" 8 ), 9 "orange" => array( 10 "color" => "orange", 11 "taste" => "tart", 12 "shape" => "round" 13 ), 14 "banana" => array( 15 "color" => "yellow", 16 "taste" => "paste-y", 17 "shape" => "banana-shaped" 18 ) 19 ); 20 21 echo $a["apple"]["taste"]; # will output "sweet" 22 ?> 23 |
객체(Object)를 초기화하는 방법은 new 명령을 사용하여 object를 변수에 인스턴스 시키는 것이다.
1 2 class foo { 3 function do_foo () { 4 echo "Doing foo."; 5 } 6 } 7 8 $bar = new foo; 9 $bar->do_foo(); 10 |
PHP는 변수 선언에 있어서 명확한 정의를 할 필요도 없고 지원하지도 않는다. 변수의 형식은 변수가 사용되는 문장 속에서 결정된다. 다른 말로 하면, 만약 여러분이 var이라는 변수에 문자열 값을 할당하면 var는 문자열 변수가 되는 것이고, 정수 값을 할당하면 정수 변수가 되는 것이다.
PHP의 자동 형 변환 예는 '+' 연산에서 찾을 수 있다. 어떤 한 피 연산자가 double이면 나머지 모든 피연산자의 형도 double로 바뀌어 결과도 double형이 된다. 만약 피연산자들이 정수형이면 결과도 정수형이다. 여기서 중요한 것은 피연산자 자신의 형은 바뀌지 않는다는 것이다.
1 2 $foo = "0"; // $foo is string (ASCII 48) 3 $foo++; // $foo is the string "1" (ASCII 49) 4 $foo += 1; // $foo is now an integer (2) 5 $foo = $foo + 1.3; // $foo is now a double (3.3) 6 $foo = 5 + "10 Little Piggies"; // $foo is integer (15) 7 $foo = 5 + "10 Small Pigs"; // $foo is integer (15) 8 |
마지막 두 개의 예가 의아한 사람은 String conversion을 보기 바란다.
만약 변수를 어떤 특정한 type으로 지정하여 계산되게 하고 싶다면, Type casting 편을 보기 바란다. 만약 여러분이 변수의 type을 바꾸고 싶다면 settype().을 보기 바란다.
만약 여러분이 위의 예제를 실제 실험하고자 한다면, 위의 예제를 잘라 붙인 후에, 어떤 일이 일어났는 가를 알기 위해 아래의 줄을 삽입한다.
1 2 echo "\$foo==$foo; type is " . gettype( $foo ) . "<br>\n"; 3 |
Note: 배열로의 자동 변환은 현재 정의되어 있지 않다.
1 2 $a = 1; // $a is an integer 3 $a[0] = "f"; // $a becomes an array, with $a[0] holding "f" 4위의 예에서는 $a의 결과가 첫 번째 요소로 'f'를 가지는 배열이 될 것이라고 알 수 있다. 하지만 다음을 보자. :
1 2 $a = "1"; // $a is a string 3 $a[0] = "f"; // What about string offsets? What happens? 4PHP가 문자열내의 문자를 indexing해서 접근하는 것이 가능하므로 위의 예제는 $a의 문자열의 첫 번째 문자를 "f"로 하라는 것인지, $a를 "f"라는 문자열을 첫 번째 원소로 가진 배열로 만들라는 것인지 알 수 없다.
이런 이유에서 PHP 3.0.12 와 PHP 4.0b3-RC4에서는 이 부분에서의 자동 변환은 정의되어 있지 않다. 이 문제의 해결은 현재 논의중이다.
PHP의 Type casting은 C에서와 같은 방법으로 한다 : 변환하려는 변수 앞에 원하는 type 이름을 괄호 안에 써주면 된다.
1 2 $foo = 10; // $foo is an integer 3 $bar = (double) $foo; // $bar is a double 4 |
다음과 같은 변환이 가능하다. :
탭과 공백은 괄호안에서는 무시된다. 즉 다음 두 개의 문장은 동일하다. :
1 2 $foo = (int) $bar; 3 $foo = ( int ) $bar; 4 |
특정 타입간의 형변환은 그 결과를 명확하게 알 수 없는 경우가 있다. 다음과 같은 내용들을 알아두도록 하자.
스칼라값이나 문자열을 배열로 형 변환하면, 그 값은 해당 배열의 첫 번째 원소의 값이 된다.
1 2 $var = 'ciao'; 3 $arr = (array) $var; 4 echo $arr[0]; // outputs 'ciao' 5 |
스칼라값이나 문자열을 객체로 형 변환하면, 그 값은 해당 객체의 'scalar'라는 속성의 값이 된다.
1 2 $var = 'ciao'; 3 $obj = (object) $var; 4 echo $obj->scalar; // outputs 'ciao' 5 |
PHP는 모든 스크립트에 그것이 실행 될 때 다수의 미리 정의된 변수들을 제공한다. 이 변수들중 서버의 종류나 버전, 기타 다른 요인으로인해 달라지는 많은 변수들이 이곳에 문서화 되지 않았다. 또한 이 변수들중 많은 것이 PHP가 command-line으로 동작할 때는 사용할 수 없다.
이런 여러 요인들이 있지만 이곳에서는 가장 일반적인 환경인 Apache (1.3.6)에서 모듈로 PHP3를 설치한 환경에서의 미리 정의된 변수들을 살펴보도록 하자.
여러분이 사용하는 시스템의 모든 미리 정의된 변수들을 보려면 phpinfo() 함수를 사용하도록하자. (이 함수는 다른 여러 유용한 정보도 알려준다.)
Note: 이 목록은 완전하지 않다. (완벽할 생각도 없다.) 이 목록은 단순히 여러분의 스크립트에서 어떤 종류의 미리 정의된 변수들이 사용될 수 있는가의 예시일 뿐이다.
이 변수들은 Apache 웹서버로부터 생성된 것이다. 만약 여러분이 다른 웹서버를 사용하고 있다면 이와 동일한 변수들이 생성된다고 보장할 수 없다. 아마도 일부는 없어지고, 여기에 있는 변수들이 새로 생길 것이다. 여기에 있는 변수중 다수는 CGI 1.1 specification에서 나온 것이고, 그 내용대로 사용된다.
이곳의 변수중 PHP가 command line으로 동작할 경우 사용될 수 있는 변수는 거의 없다.
Contents of the Accept: header from the current request, if there is one.
Contents of the Accept-Charset: header from the current request, if there is one. Example: 'iso-8859-1,*,utf-8'.
Contents of the Accept-Encoding: header from the current request, if there is one. Example: 'gzip'.
Contents of the Accept-Language: header from the current request, if there is one. Example: 'en'.
Contents of the Connection: header from the current request, if there is one. Example: 'Keep-Alive'.
Contents of the Host: header from the current request, if there is one.
The address of the page (if any) which referred the browser to the current page. This is set by the user's browser; not all browsers will set this.
Contents of the User_Agent: header from the current request, if there is one. This is a string denoting the browser software being used to view the current page; i.e. Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Among other things, you can use this value with get_browser() to tailor your page's functionality to the capabilities of the user's browser.
The IP address from which the user is viewing the current page.
The port being used on the user's machine to communicate with the web server.
The absolute pathname of the currently executing script.
The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host.
The port on the server machine being used by the web server for communication. For default setups, this will be '80'; using SSL, for instance, will change this to whatever your defined secure HTTP port is.
String containing the server version and virtual host name which are added to server-generated pages, if enabled.
Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping.
Contains the current script's path. This is useful for pages which need to point to themselves.
The URI which was given in order to access this page; for instance, '/index.html'.
These variables are imported into PHP's global namespace from the environment under which the PHP parser is running. Many are provided by the shell under which PHP is running and different systems are likely running different kinds of shells, a definitive list is impossible. Please see your shell's documentation for a list of defined environment variables.
Other environment variables include the CGI variables, placed there regardless of whether PHP is running as a server module or CGI processor.
These variables are created by PHP itself.
Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string.
Contains the number of command line parameters passed to the script (if run on the command line).
The filename of the currently executing script, relative to the document root. If PHP is running as a command-line processor, this variable is not available.
An associative array of variables passed to the current script via HTTP cookies. Only available if variable tracking has been turned on via either the track_vars configuration directive or the <?php_track_vars?> directive.
An associative array of variables passed to the current script via the HTTP GET method. Only available if variable tracking has been turned on via either the track_vars configuration directive or the <?php_track_vars?> directive.
An associative array of variables passed to the current script via the HTTP POST method. Only available if variable tracking has been turned on via either the track_vars configuration directive or the <?php_track_vars?> directive.
변수가 사용가능한 곳은 그 변수가 선언된 곳 안에서 만이다. PHP 변수의 대부분은 한 개의 범위(single scope)만을 가지고 있다. 이 범위는 include나 require 파일에도 동일하게 적용된다. 예를들어 :
1 2 $a = 1; 3 include "b.inc"; 4 |
위에서 $a변수는 b,inc 스크립트에서도 사용할 수 있다.
기본적으로 함수 안에서 선언된 것은 함수 안에서만 사용되는 지역 변수이다. 또한 함수 안에서 사용되는 함수들은 기본적으로 지역 변수라고 가정하고 찾게 된다. 예를 들어:
1 2 $a = 1; /* global scope */ 3 4 Function Test () { 5 echo $a; /* reference to local scope variable */ 6 } 7 8 Test (); 9 |
이 스크립트는 함수 안의 $a 변수를 지역변수로 가정하였고, 지역변수 $a에는 아무 값도 대입되지 않았기 때문에 아무런 출력도 나타나지 않는다. 이것은 C와는 약간 차이가 나는 부분이다. PHP에서 전역변수를 사용하려면 사용하고 싶은 전역 변수를 함수 안에 global 선언을 해 주어야 한다. 예를 들어 :
1 2 $a = 1; 3 $b = 2; 4 5 Function Sum () { 6 global $a, $b; 7 8 $b = $a + $b; 9 } 10 11 Sum (); 12 echo $b; 13 |
위의 스크립트는 "3"을 출력할 것이다. 함수 내에서 $a and $b를 global로 선언했으므로, 이 함수내의 $a, $b는 전역 변수를 참조하게 된다. 함수 내에서 다룰 수 있는 전역변수의 개수에는 제한이 없다.
전역 변수를 참조하는 두 번째 방법은 PHP에서 특별히 정의하고 있는 $GLOBALS라는 배열을 사용하는 것이다. 위의 예를 다음과 같이 바꿔 쓸 수 있다. :
1 2 $a = 1; 3 $b = 2; 4 5 Function Sum () { 6 global $a, $b; 7 8 $b = $a + $b; 9 } 10 11 Sum (); 12 echo $b; 13 |
$GLOBALS 배열은 변수이름이 Key가 되고, 그 변수의 내용이 값이 되는 원소를 가진 associative 배열이다.
변수 범위에서 또 다른 중요한 것은 정적 변수(static variable)이다. 정적 변수는 지역 함수 내에서만 존재하지만 지역 함수가 종료되어도 그 값을 읽어버리지 않고 가지고 있다. 다음 예를 보자 :
1 2 Function Test () { 3 $a = 0; 4 echo $a; 5 $a++; 6 } 7 |
위의 함수는 Test()를 부를 때 마다 $a가 0으로 대입되므로 0을 출력한다.
1 2 Function Test () { 3 static $a = 0; 4 echo $a; 5 $a++; 6 } 7 |
위의 함수는 Test()를 부를 때마다 처음에는 0, 다음에는 1, 그 다음에는 2하는 식으로 하나씩 증가된 수를 출력해 준다. 즉, $a의 값이 보존되는 것이다.
또한 정적 변수는 다음과 같이 recursion에서 반드시 필요하다. 재귀적인 함수는 자기 자신의 함수를 호출하는 것을 말한다. 재귀적인 함수를 사용할 때는 무한 루프에 빠질 수 있기 때문에 매우 주의를 요한다. 따라서 여러분은 재귀 호출을 끝내는 적절한 방법을 마련해 두어야 한다. 다음의 간단한 예제는 10번의 재귀적 호출을 한다. :
1 2 Function Test () { 3 static $a = 0; 4 echo $a; 5 $a++; 6 } 7 |
가끔 변수의 이름을 변경할 수 있다면 편리하다고 느낄 때가 있다. 이곳에서는 변수의 이름을 바꾸어 사용하는 방법을 알아보자. 보통의 변수 선언은 다음과 같다. :
1 2 $a = "hello"; 3 |
여기서 이 가변 변수은 변수의 값을 가질 수도 있고, 또한 이 값을 변수의 이름으로 다룰 수도 있다. 위의 예에서 hello는 $$를 앞에 붙이면 변수 이름으로 사용할 수 있는 것이다. 예 :
1 2 $$a = "world"; 3 |
이렇게 하면 PHP의 symbol tree에는 "hello"라는 값을 가지는 $a와 "world"라는 값을 가지는 $hello의 두 개의 변수가 생기게 된다. 그러므로 다음과 같은 문장은 :
1 2 echo "$a ${$a}"; 3 |
다음 문장과 똑 같은 출력을 나타내게 된다.:
1 2 echo "$a $hello"; 3 |
ie. 둘의 출력: hello world.
가변 변수를 배열과 함께 사용하려면, 한가지 모호성 문제를 해결해야 한다. 그것은, 만약 여러분이 $$a[1]이라고 썼으면, $a[1]을 하나의 변수로 볼 것인지, 아니면 $$a를 변수로 보고 그 변수에 [1]의 인덱스를 해 줄 것인가 하는 문제이다. 다음과 같이 하여 모호성을 해결하자. 전자의 경우 ${$a[1]}라고 쓰고, 후자의 경우는 ${$a}[1]라고 쓰면 된다. ( 역자주: 가변 변수를 나타낼 때는 항상 { }로 둘러 싸는 것이 보기 좋고 오류도 없앨 수 있다.)
폼이 PHP 스크립트로 submit되면 폼에 있는 모든 내용들이 자동적으로 만들어진 PHP 변수로 들어온다. 다음의 폼을 보자 :
Example 7-1. Simple form variable
|
위의 폼이 submit되면 PHP는 $name변수를 만들고, 이 변수에 폼의 Name: 필드에 입력된 모든 내용을 저장한다.
PHP는 폼에 1차원 배열 변수도 사용할 수 있다. 예를들어, 여러분은 여러 변수를 함께 사용하는 그룹 관련 변수(group related variables)나 multi select 변수의 내용들을 검색할 수 있다. :
Example 7-2. More complex form variables
|
만약 track_vars 설정이 on 되어 있거나, <?php_track_vars?> 지시자가 설정되어 있다면, POST나 GET으로 전송되는 모든 변수들과 그 내용은 전역 배열 변수인 $HTTP_POST_VARS과 $HTTP_GET_VARS에서 찾을 수 있다.
폼은 submit할 때 일반적으로 사용하는 submit 버튼대신 다음과 같이 그림을 사용할 수도 있다. :
1 2 <input type=image src="image.gif" name="sub"> |
사용자가 image를 클릭하면, 폼은 sub_x와 sub_y의 두 개의 변수가 추가되어 서버에 전송된다. 이 두 변수는 이미지에서 사용자가 click한 위치 정보를 담고 있다. 일부 브라우저에서는 밑줄(_)대신 마침표(.)를 사용하는 경우도 있는데, PHP는 이런 경우 자동적을 마침표(.)를 밑줄(_)로 바꿔준다.
PHP는 HTTP 쿠키를 Netscape's Spec의 정의에 따라 제공한다. Cookie 메카니즘은 트래킹이나 사용자 식별 등을 위해 원격 browser에 저장된 데이터를 돌려 받는 과정을 말한다. 여러분은 cookie를 설정하기 위해 SetCookie() 함수를 사용할 수 있다. Cookie는 HTTP 헤더의 한 부분이므로, SetCookie() 함수는 브라우저로 보내는 어떤 데이터보다도 앞에 사용해야 한다. 이 제약은 Header() 함수와 같은 제약으로 보면 된다. 당신이 보내준 모든 cookie는 자동적으로 GET이나 POST 방식 데이터와 같은 PHP 변수로 변환된다.
만약 여러분이 동일한 cookie에 여러 값을 저장하고 싶다면 Cookie이름에 []를 더하면 된다. 예를 들어 :
1 2 SetCookie ("MyCookie[]", "Testing", time()+3600); 3 |
쿠키는 새로 설정하면 path나 도메인이 다르지 않는 한 이전의 쿠키를 덮어쓰게 된다. 그러므로 쇼핑 카트 같은 응용 프로그램에서는 카운터를 유지하고, 이것을 기준으로 Cookie를 사용하는 것이 좋다. 예 :
Example 7-3. SetCookie Example
|
PHP는 자동적으로 환경 변수들을 일반적인 PHP 변수로 만든다.
1 2 echo $HOME; /* Shows the HOME environment variable, if set. */ 3 |
GET, POST and Cookie 메카니즘을 통해서 정보가 들어 온 정보로부터 자동적으로 PHP 변수가 생기므로, 이 방법은 때때로 올바른 버전을 확인하기 위해 환경으로부터 변수를 읽어 들이기에 가장 좋다. 이를 위해 getenv() 함수를 사용할 수도 있다. 여러분은 환경 변수를 설정하기 위해 putenv() 함수를 사용할 수도 있다.
일반적으로 PHP는 변수를 스크립트로 가져올 때 변수명을 바꾸지 않는다. 그러나, PHP의 변수명에는 '.' (점)을 사용할 수 없다. 다음과 같은 경우를 보자. :
1 2 $varname.ext; /* invalid variable name */ 3 |
위의 경우 파서는 $varname이라는 변수와, 연결 연산자, 'ext'(따옴표가 없는 경우 그것이 어떤 알려진 키나 예약어가 아니면 문자열로 취급된다.)로 해석한다. 따라서 이것은 우리가 원하는 결과가 아니다.
위와 같은 이유로 PHP는 외부에서 불러들인 변수의 이름에 '.'이 있으면 '_'(밑줄)로 바꾸어 읽어들인다.
PHP가 변수의 type을 정하고 (일반적으로) 필요한 경우에는 그 type을 바꾸므로, 특정 시점에 그 변수 어떤 type인지는 쉽게 알 수 없다. PHP는 변수의 type을 알아보기 위해 여러개의 함수를 가지고 있다. gettype(), is_long(), is_double(), is_string(), is_array(), and is_object()가 그것들이다.
PHP는 약간의 기본적인 상수들을 제공하고, 실행시 상수를 설정할 수 있는 메카니즘을 지원한다. 상수는 변수와 비슷하다. 그러나 define()함수를 사용하여 선언한다는 것과 나중에 다른 값으로 바꿀 수 없다는 점이 차이가 있다.
미리 지정된 상수는 다음과 같다.
E_* 상수는 대개 error_reporting() 함수를 사용하여 reporting 레벨을 정할 때 흔히 사용된다.
또한 여러분은 define()함수를 사용하여 추가적인 상수를 정의할 수 있다.
주의할 점은 상수는 C에서의 macro 값은 것이 아니다. 단지 scalar 값을 가질 수 있을 뿐이다.
Example 8-1. Defining Constants
|
Example 8-2. Using __FILE__ and __LINE__
|
표현식은 PHP에서 매우 중요한 내용이다. PHP에서 여러분이 작성하는 거의 모든 것은 표현식이다. 간단히 표현식의 정의를 엄밀하게 말한다면 "값을 가지고 있는 모든 것"("anything that has a value")이다.
간단한 예제로 "$a = 5"와 같은 것이 있다. 이것은 5라는 값을 $a라는 변수에 대입하는 문장이다. 여기서 5라는 표현식은 5의 값이라는 의미가 된다. 위의 문장 다음에 "$b = $a"라는 문장이 있다면 여기서 $a라는 표현식은 그 변수가 가진 5라는 값을 표현한다.
조금 복잡한 경우는 함수이다. 다음 함수를 보자. :
1 2 function foo () { 3 return 5; 4 } 5 |
$c = 5라는 문장에서 foo()는 5를 돌려줄 것이기 때문에 'foo()'라는 표현식은 5를 표현한다고 말할 수 있다.
PHP는 정수값(integer values), 실수값(floating point values), 문자열(string values)의 3가지 스칼라 type을 가지고 있다. (스칼라 값이란 더 이상 작은 값으로 쪼개질 수 없는 값을 말한다.) 또한 PHP는 배열(array)과 객체(object)의 2가지 혼합(composite, non-scalar) type을 지원한다. 이 type들은 변수에 값을 할당할 수 있고, 함수에 의해 값을 돌려줄 수 있다.
여기까지는 PHP/FI 2 사용자들은 아무것도 바뀌지 않았다고 느낄 것이다. PHP는 거의 모든 것이 표현식으로 표현된다는 점에서, 표현 중심 언어 (expression-oriented language)라고 불릴 수 있다. 표현 중심의 좋은 예는 대입문이다. PHP에서는 C와 같이 대입문도 하나의 표현식으로 본다. 따라서 '$a=5; $b=5;'는 '$a = ($b=5);' 혹은 '$a = $b = 5;'로 표현 가능하다.
표현 중심의 다른 좋은 예로는 ++와 --이다. In PHP/FI 2에서는 '$a++'와 같은 문장은 아무 값도 가지지 않았다. 즉, 표현식이 아니었다. 따라서 이 값을 다른 곳에 대입하는 것은 불가능했다. 그러나 PHP 3에서는 이것이 가능해졌다. C에서와 같이 ++/--를 사용하는 방법에는 앞에 붙이는 것과 뒤에 붙이는 것 두가지가 있다. 둘 모두 변수의 값이 증가된다는 점은 같으나, '++$variable'은 그 변수의 증가된 값이 표현식의 값이 되고, '$variable++'는 변수의 증가되기 전의 값이 표현식의 값이 된다.
비교 표현식은 0이나 1의 값을 가진다. 0은 부정(FALSE)을 1은 긍정(TRUE)를 나타낸다. PHP는 > (bigger than), >= (bigger than or equal to), == (equal),< (smaller than), <= (smaller than or equal to)를 지원한다.
마지막 예는 결합된 연산-대입 표현식(combined operator-assignment expression)이다. 뭐 복잡한 얘기는 아니고 '$a = $a + 3'은 표현식을 '$a += 3'으로 표현할 수 있는 것이다. -=, *=, /=, .= 등도 사용할 수 있다.
다음예를 보면 도움이 될 것이다. :
1 2 function double($i) { 3 return $i*2; 4 } 5 $b = $a = 5; /* $a와 $b 에 5 대입 */ 6 $c = $a++; /* post-increment, $c 에는 $a의 원래 값인 5가 대입되고 $a는 6이 된다 */ 7 $e = $d = ++$b; /* pre-increment, $d와 $e는 증가된 $b의 값 6이 대입된다. */ 8 9 /* 여기부터 $d와 $e의 값은 6이다. */ 10 $f = double($d++); /* $f는 $d가 증가되기 전의 값인 6을 두 배한 값을 가진다. 2*6 = 12 */ 11 $g = double($++e); /* $g는 $e가 증가된 후의 값인 7을 두배한값을 가진다. 2*7 = 14 */ 12 $h = $g += 10; /* $g는 14에 10을 더해 24의 값을 가진 후 그 값을 $h에 대입한다. 둘다 24 */ 13 |
그러나, 하나의 표현식이 하나의 문장은 아니다. 표현식이 세미콜론 ';'으로 끝나야 하나의 문장이 되는 것이다. 즉 '$b=$a=5;'에서 $a=5는 표현식이지만 문장은 아니다.
PHP에서 참/거짓의 판단은 Perl과 비슷하다. 0이 아닌 숫자는 모두 TRUE이고, 0은 FALSE이다. 빈 문자열이나 문자열 "0"은 FALSE이다. 다른 모든 문자열은 TRUE이다. 배열이나 객체는 원소가 하나도 없다면 FALSE를 의미하고, 나머지의 경우는 TRUE이다.
앞으로 이 매뉴얼에서 'expr'이라고 쓰여진 부분은 PHP의 올바른 표현식이라는 의미이다.
학교에서 배운 산술 연산(가감승제)을 기억하는가? 이 산술 연산자는 그것들처럼 동작한다.
Table 10-1. Arithmetic Operators
예 |
이름 |
결과 |
---|---|---|
$a + $b |
덧셈(Addition) |
$a와 $b의 합. |
$a - $b |
뺄셈(Subtraction) |
$a에서 $b를 뺀 값. |
$a * $b |
곱셈(Multiplication) |
$a와 $b의 곱. |
$a / $b |
나눗셈(Division) |
$a에서 $b를 나눈 값(혹 은 몫). |
$a % $b |
나머지(Modulus) |
$a에서 $b를 나눈 나머지. |
기본 대입 연산자는 "="이다. 이 연산자를 처음 보았을 때는 "같다"라는 연산자로 생각하기 쉽지만 전혀 아니다. 이것의 의미는 오른쪽의 표현식을 계산하여 그 값을 왼쪽에 있는 피연산자의 값으로 설정한다는 의미이다. (이것을 "gets set to"라고 한다.)
대입 연산자의 값은 왼쪽으로 대입된 값이다. 즉, "$a = 3"의 값은 3이 된다. 이것은 여러분에게 약간의 트릭이 가능하도록한다.
1 2 $a = ($b = 4) + 5; // $a는 9, $b는 4의 값을 가진다. 3 |
기본적인 대입 연산자 외에 모든 Bit 단위 연산자, 산술 연산자와 결합한 복합 대입 연산자도 있다. 결합된 연산자는 표현식에서 해당 연산으로 사용되고, 그 연산 값을 왼쪽에 있는 피연산자에 대입한다. 예를 들어 :
1 2 $a = 3; 3 $a += 5; // $a는 8이다. $a = $a + 5; 와 동일하다. 4 $b = "Hello "; 5 $b .= "There!"; // $b는 "Hello There!"가 된다. $b = $b . "There!";와 같다. 6 |
비트 단위 연산자는 정수의 개별 비트의 값을 on, off 할 수 있다.
Table 10-2. Bitwise Operators
example |
name |
result |
---|---|---|
$a & $b |
And |
$a와 $b가 모두 1인 비트만 1이 된다. |
$a | $b |
Or |
$a와 $b중 하나라도 1인 비트는 1이 된다. |
$a ^ $b |
Xor |
$a와 $b중 하나는 1이고, 다른 하나는 0인 비트만 1이되고, 나머지는 0이 된다. |
~ $a |
Not |
$a에서 1인 비트는 0으로, 0인 비트는 1로 된다. |
$a << $b |
Shift left |
$a의 비트들을 $b step 만큼 왼쪽으로 shift 한다. (한 step은 2를 한 번 곱하는 만큼의 효과가 있다.) |
$a >> $b |
Shift right |
$a의 비트들을 $b step 만큼 오른으로 shift 한다. (한 step은 2를 한 번 나누는 만큼의 효과가 있다.) |
비교 연산자는 이름에서 알 수 있듯이 두 개의 값을 비교하는 연산자이다.
Table 10-4. Comparson Operators
example |
name |
result |
---|---|---|
$a == $b |
Equal |
$a와 $b가 같으면 true. |
$a === $b |
Identical |
$a와 $b가 같으면 true. $a와 $b의 type까지 동일해야 한다. (PHP4 only) |
$a != $b |
Not equal |
$a와 $b가 다르면 true. |
$a < $b |
Less than |
$a가 $b보다 작으면 true. |
$a > $b |
Greater than |
$a가 $b보다 크면 true. |
$a <= $b |
Less than or equal to |
$a가 $b보다 작거나 같으면 true. |
$a >= $b |
Greater than or equal to |
$a가 $b보다 크거나 같으면 true. |
또다른 조건 연산자로 C나 다른 언어에 있는 "?:" 연산자가 있다.
1 2 (expr1) ? (expr2) : (expr3); 3 |
이 표현식은 expr1의 결과가 참여면 expr2를 반환하고, 거짓이면 expr3를 반환한다.
PHP는 @(at 표시)이라는 한 개의 오류 제어 연산자를 제공한다. PHP의 표현식 앞에 이 표시가 붙으면, 해당 표현식에서 발생한 모든 에러 메시지가 무시된다.
만약 track_errors 기능이 활성화 되어 있다면, 해당 표현식에서 발생한 모든 에러 메시지는 $php_errormsg 라는 전역 변수에 저장될 것이다. 이 변수의 값은 매번 에러가 발생할 때마다 새로 설정된다. 따라서 만약 여러분이 이 변수를 사용하려면 에러가 발생한 직후에 최대한 빨리 사용하여야 한다.
1 2 <?php 3 /* Intentional SQL error (extra quote): */ 4 $res = @mysql_query( "select name, code from 'namelist" ) or 5 die( "Query failed: error was '$php_errormsg'" ); 6 ?> 7 |
See also error_reporting().
PHP는 한 개의 실행 연산자를 제공한다. (``) 일반 작은 따옴표가 아님을 주의하자! PHP는 이 사이에 있는 명령을 shell 명령어로 실행하고 그 결과를 반환한다. (실행 결과를 단순히 출력하는 것이 아니고, 변환하여 변수에 저장할 수도 있다.)
1 2 $output = `ls -al`; 3 echo "<pre>$output</pre>"; 4 |
See also system(), passthru(), exec(), popen(), and escapeshellcmd().
PHP는 C 형태의 앞, 뒤에 붙는 증가나 감소 연산자를 제공한다.
Table 10-4. Increment/decrement Operators
example | name | effect |
---|---|---|
++$a | Pre-increment | $a 를 1 증가시킨 후, $a를 반환한다. |
$a++ | Post-increment | $a를 반환한 후,$a 를 1 증가시킨다. |
--$a | Pre-decrement | $a 를 1 감가시킨 후, $a를 반환한다. |
$a-- | Post-decrement | $a를 반환한 후,$a 를 1 감소시킨다. |
여기 간단한 예제가 있다. :
1 2 <?php 3 echo "<h3>Postincrement</h3>"; 4 $a = 5; 5 echo "Should be 5: " . $a++ . "<br>\n"; 6 echo "Should be 6: " . $a . "<br>\n"; 7 8 echo "<h3>Preincrement</h3>"; 9 $a = 5; 10 echo "Should be 6: " . ++$a . "<br>\n"; 11 echo "Should be 6: " . $a . "<br>\n"; 12 13 echo "<h3>Postdecrement</h3>"; 14 $a = 5; 15 echo "Should be 5: " . $a-- . "<br>\n"; 16 echo "Should be 4: " . $a . "<br>\n"; 17 18 echo "<h3>Predecrement</h3>"; 19 $a = 5; 20 echo "Should be 4: " . --$a . "<br>\n"; 21 echo "Should be 4: " . $a . "<br>\n"; 22 ?> 23 |
Table 10-3. Logical Operators
example |
name |
result |
---|---|---|
$a and $b |
And |
$a와 $b가 모두 true 이면 true |
$a or $b |
Or |
$a와 $b중 하나라도 true이면 true |
$a xor $b |
Xor |
$a와 $b중 하나만 true이어야 true |
! $a |
Not |
$a가 true가 아니면 true |
$a && $b |
And |
$a와 $b가 모두 true 이면 true |
$a || $b |
Or |
$a와 $b중 하나라도 true이면 true |
"and"와 "or" 연산자가 두가지의 다른 형태를 가지고 있는 이유는 이 연산자들이 서로 다른 우선순위를 가지고 있기 때문이다. (아래를 보라.)
연산자들의 우선순위는 두 개의 표현식중 어느것이 더 단단히 묶여 있는가를 명기한다. 예를들어 1 + 5 * 3은 16을 반환하지 18을 반환하지 않는다. 왜냐하면 곱하기("*")연산자가 더하기("+")연산자보다 우선순위가 높기 때문이다.
다음 표는 연산자의 우선순위를 나타낸다 가장 위에 있는 연산자의 우선순위가 가장 낮다.
Table 10-6. Operator Precedence
Associativity | Operators |
---|---|
left | , |
left | or |
left | xor |
left | and |
right | |
left | = += -= *= /= .= %= &= |= ^= ~= <<= >>= |
left | ? : |
left | || |
left | && |
left | | |
left | ^ |
left | & |
non-associative | == != === |
non-associative | < <= > >= |
left | << >> |
left | + - . |
left | * / % |
right | ! ~ ++ -- (int) (double) (string) (array) (object) @ |
right | [ |
non-associative | new |
문자열 연산자에는 두개가 있다. 첫 번째는 오니쪽과 오른쪽의 두 문자열을 연결하는 연결(concatenation) 연산자 (".") 가 있다. 두 번쨰로는 연결 대입 연산자 (".=") 가 있다. 이에 대해서는 대입연산자(Assugnment Operator) 부분을 읽어보자.
1 2 $a = "Hello "; 3 $b = $a . "World!"; // now $b contains "Hello World!" 4 5 $a = "Hello "; 6 $a .= "World!"; // now $a contains "Hello World!" 7 |
$a = "Hello "; $b = $a . "World!"; // now $b = "Hello World!"
모든 PHP 스크립트는 일련의 구문으로 이루어 진다. 하나의 구문은 대입문이 될 수도 있고, 함수 호출, 반복문, 조건문이 될 수도 있으며 심지어는 아무 내용이 없는 빈 문장일 수도 있다. 한 구문은 일반적으로 세미콜론(;)으로 끝난다. 또한 여러개의 구문을 중괄호({,})를 사용하여 하나의 그룹으로 만들어 사용할 수도 있다. 이 구문-그룹은 그 그룹의 모든 구문들이 하나의 구문인 것처럼 인식된다. 여기서는 여러 가지 구문형태에 대해 알아본다.
PHP의 IF문은 C와 비슷하다.
1 2 if (expr) 3 statement 4 |
expr을 평가하여 TRUE이면 statement를 실행한다. FALSE이면 무시한다.
다음 예제는 $a가 $b보다 크면 "a is bigger than b"를 출력한다.
1 2 if ($a > $b) 3 print "a is bigger than b"; 4 |
여러 문장을 실행시키려면 중괄호( { } )를 사용하여 복문으로 만들면된다. :
1 2 if ($a > $b) { 3 print "a is bigger than b"; 4 $b = $a; 5 } 6 |
ELSE는 IF문의 평가식이 FALSE일 경우 실행하는 문장을 지정한다. :
1 2 if ($a > $b) { 3 print "a is bigger than b"; 4 } else { 5 print "a is NOT bigger than b"; 6 } 7 |
ELSEIF는 ELSE와 IF를 합쳐놓은 것과 같다. :
1 2 if ($a > $b) { 3 print "a is bigger than b"; 4 } elseif ($a == $b) { 5 print "a is equal to b"; 6 } else { 7 print "a is smaller than b"; 8 } 9 |
한 IF문에는 여러개의 ELSEIF문이 있을 수 있다. ELSEIF문은 순서대로 평가하여 TRUE인 곳을 실행한다. 즉, 어떤 ELSEIF문이 실행 되려면 IF문의 평가식과 그 앞의 모든 ELSEIF문의 평가식이 FALSE이어야 한다. 이것은 'else if'라고 두 개의 문장으로 써도 된다(문법적인 의미는 약간 다르지만).
PHP 3는 중괄호({ })를 쓰는 대신 IF(expr)뒤에 콜론( : )을 찍고, 하나 이상의 문장을 나열한 후에 ENDIF;로 끝내는 방법을 제공한다. 이 방법은 특히 IF문 안에 HTML 블럭을 삽입하는데 유용하게 사용될 수 있다. 다음 예를 보자. :
1 2 <?php if ($a == 5): ?> 3 A is equal to 5 4 <?php endif; ?> 5 |
위의 예에서 "A = 5"라는 HTML 블록이 IF문 안에 사용되고 있다. 위의 HTML 블록은 $a가 5일 경우에만 표시된다.
다음과 같이 ELSE와 ELSEIF (expr)도 사용할 수 있다. :
1 2 if ($a == 5): 3 print "a equals 5"; 4 print "..."; 5 elseif ($a == 6): 6 print "a equals 6"; 7 print "!!!"; 8 else: 9 print "a is neither 5 nor 6"; 10 endif; 11 |
WHILE 루프는 PHP 3의 가장 간단한 형태이다. 이것은 C와 동일하게 작동한다. 기본 형태는 다음과 같다. :
1 2 while (expr) statement 3 |
IF문과 마찬가지로 다음과 같은 문장 형태로 중괄호( { } )를 사용하지 않는 방법도 있다. :.
1 2 while (expr): statement ... endwhile; 3 |
다음두개의 예제는 동일한 예제이다. 1부터 10까지 출력한다.:
1 2 /* example 1 */ 3 4 $i = 1; 5 while ($i <= 10) { 6 print $i++; /* the printed value would be 7 $i before the increment 8 (post-increment) */ 9 } 10 11 /* example 2 */ 12 13 $i = 1; 14 while ($i <= 10): 15 print $i; 16 $i++; 17 endwhile; 18 |
DO..WHILE 루프는 비교식이 앞이 아닌 맨 뒤에 있다는 점을 제외하면 WHILE 루프와 비슷하다. 따라서 WHILE 조건절은 DO 문장이 실행된 후에 평가되므로, DO 이후의 문장은 무조건 한번은 실행된다.
다음과 같은 DO..WHILE 루프에서도 한번은 출력이 된다. :
1 2 $i = 0; 3 do { 4 print $i; 5 } while ($i>0); 6 |
FOR는 PHP의 가장 복잡한 루프이다. 이것은 C와 유사하다. FOR 루프의 형태는 다음과 같다. :
1 2 for (expr1; expr2; expr3) statement 3 |
첫 번째 표현식(expr1)은 루프를 시작할 때 무조건 한번 평가(실행)된다.
매 반복의 시작 때마다 expr2가 평가된다. 만약 이것이 TRUE면 루프는 계속되고 statement가 실행된다. expr2가 FALSE이면 루프는 종료된다.
매 반복이 끝날 때 expr3가 평가(실행)된다.
각 평가식은 비워둘 수 있다.expr2가 비어있으면 무한 루프를 뜻한다. (PHP는 C와 같이 비어있으면 TRUE로 인식한다.) 이건 별로 좋은 방법이 아니지만, 종종 BREAK를 사용하여 종료하는 방법도 있다.
다음 예는 1에서 10까지 출력하는 예이다. :
1 2 /* example 1 */ 3 4 for ($i = 1; $i <= 10; $i++) { 5 print $i; 6 } 7 8 /* example 2 */ 9 10 for ($i = 1;;$i++) { 11 if ($i > 10) { 12 break; 13 } 14 print $i; 15 } 16 17 /* example 3 */ 18 19 $i = 1; 20 for (;;) { 21 if ($i > 10) { 22 break; 23 } 24 print $i; 25 $i++; 26 } 27 28 /* example 4 */ 29 30 for ($i = 1; $i <= 10; print $i, $i++) ; 31 |
물론 처음것이 가장 좋아보인다. 그러나 나머지도 가능하다는 것을 알아야 한다.
PHP는 FOR 루프에 대해서도 다음과 같은 "colon syntax"를 지원한다.
1 2 for (expr1; expr2; expr3): statement; ...; endfor; 3 |
일부 다른 언어들은 배열을 탐색하기 위하여 foreach 문장을 제공하기도 한다. 그러나 PHP는 이를 위해 list()와 each() 함수를 사용하여 while 루프로 해결한다. 이 함수들에 대해서는 예제를 참조하자.
PHP4(PHP3는 아니다)는 perl 등의 다른 언어가 제공하는 foreach 구조를 제공한다. 이 구조는 배열에 있어서 반복적인 작업을 하는데 유용하다. 이것에는 두가지 문법이 있는데, 두 번째 것은 첫 번째 것의 부분 확장이나 매우 유용하게 사용된다.
1 2 foreach(array_expression as $value) statement 3 foreach(array_expression as $key => $value) statement 4 |
첫 번째 모양은 array_expression 으로 주어진 배열에 대해 순환작업(loop)을 수행한다. 개개의 순환작업에서, 배열의 원소는 $value에 저장되고 내부 배열 포인터(internal array pointer)는 하나 전진하여 다음 작업시에 새로운 원소를ㄹ 가져오도록 한다.
두 번째 모양은 첫 번째와 동일한 작업을 하지만, $key에 해당 원소의 키값을 저장하게 된다.
foreach 문이 처음 수행될 때, 내부 배열 포인터(internal array pointer)는 자동적으로 배열의 첫번째 원소로 설정된다. 이말의 의미는 여러분이 foreach 문을 사용할 때 reset()을 미리 호출할 필요는 없다는 것이다.
따라서 아래의 두 개의 문장은 동일한 결과를 만든다는 것을 알 수 있을 것이다. :
1 2 reset ($arr); 3 while (list(, $value) = each ($arr)) { 4 echo "Value: $value<br>\n"; 5 } 6 7 foreach ($arr as $value) { 8 echo "Value: $value<br>\n"; 9 } 10 |
다음 두 개의 문장은 기능적으로 동일한 문장이다. :
1 2 reset ($arr); 3 while (list($key, $value) = each ($arr)) { 4 echo "Key: $key; Value: $value<br>\n"; 5 } 6 7 foreach ($arr as $key => $value) { 8 echo "Key: $key; Value: $value<br>\n"; 9 } 10 |
추가적으로 몇 개의 예제를 보자. :
1 2 /* foreach example 1: value only */ 3 4 $a = array (1, 2, 3, 17); 5 6 foreach ($a as $v) { 7 print "Current value of \$a: $v.\n"; 8 } 9 10 /* foreach example 2: value (with key printed for illustration) */ 11 12 $a = array (1, 2, 3, 17); 13 14 $i = 0; /* for illustrative purposes only */ 15 16 foreach($a as $v) { 17 print "\$a[$i] => $k.\n"; 18 } 19 20 /* foreach example 3: key and value */ 21 22 $a = array ( 23 "one" => 1, 24 "two" => 2, 25 "three" => 3, 26 "seventeen" => 17 27 ); 28 29 foreach($a as $k => $v) { 30 print "\$a[$k] => $v.\n"; 31 } 32 |
break는 현재 루프에서 빠져 나가는 명령이다.
break에는 숫자 옵션을 줄 수 있는데, 이것은 한번에 빠져 나갈 제어 구조의 수를 의미한다.
1 2 $i = 0; 3 while ($i < 10) { 4 if ($arr[$i] == "stop") { 5 break; /* You could also write 'break 1;' here. */ 6 } 7 $i++; 8 } 9 10 /* Using the optional argument. */ 11 12 $i = 0; 13 while ( ++$i ) { 14 switch ( $i ) { 15 case 5: 16 echo "At 5<br>\n"; 17 break 1; /* Exit only the switch. */ 18 case 10: 19 echo "At 10; quitting<br>\n"; 20 break 2; /* Exit the switch and the while. */ 21 default: 22 break; 23 } 24 } 25 |
CONTINUE 는 현재 루프의 처음으로 가도록 하는 명령이다.
continue도 숫자 옵션을 줄 수 있는데, 이것은 한번에 처음으로 갈 제어 구조의 수를 의미한다.
1 2 while (list ($key, $value) = each ($arr)) { 3 if (!($key % 2)) { // skip odd members 4 continue; 5 } 6 do_something_odd ($value); 7 } 8 9 $i = 0; 10 while ($i++ < 5) { 11 echo "Outer<br>\n"; 12 while (1) { 13 echo " Middle<br>\n"; 14 while (1) { 15 echo " Inner<br>\n"; 16 continue 3; 17 } 18 echo "This never gets output.<br>\n"; 19 } 20 echo "Neither does this.<br>\n"; 21 } 22 |
SWITCH문은 동일한 표현식의 IF문의 나열과 비슷하다. 다음 예는 동일한 것은 IF문과 SWITCH문으로 표현한 것이다. :
1 2 if ($i == 0) { 3 print "i equals 0"; 4 } 5 if ($i == 1) { 6 print "i equals 1"; 7 } 8 if ($i == 2) { 9 print "i equals 2"; 10 } 11 12 switch ($i) { 13 case 0: 14 print "i equals 0"; 15 break; 16 case 1: 17 print "i equals 1"; 18 break; 19 case 2: 20 print "i equals 2"; 21 break; 22 } 23 |
SWITCH문은 문장 단위로 실행된다. SWITCH에 있는 평가식과 일치하는 CASE문을 찾아 그 이후 SWITCH블럭이 끝날 때 까지 실행한다. 따라서 원하는 경우 BREAK로 실행을 중지시킬 필요가 있다. 다음 예를 보자. :
1 2 switch ($i) { 3 case 0: 4 print "i equals 0"; 5 case 1: 6 print "i equals 1"; 7 case 2: 8 print "i equals 2"; 9 } 10 |
여기서 $i가 0이면 모든 print문을 실행할 것이다. 만약 $i가 1이면 마지막 두개의 print문을 실행한다. 따라서 여러분이 원하는 결과를 얻으려면 BREAK문을 잊지 않는 것이 중요한다.
특별한 case로 default case가 있다. 이 것은 다른 어떤 case에도 맞지 않는 경우를 의미한다. 예를 들어 :
1 2 switch ($i) { 3 case 0: 4 print "i equals 0"; 5 break; 6 case 1: 7 print "i equals 1"; 8 break; 9 case 2: 10 print "i equals 2"; 11 break; 12 default: 13 print "i is not equal to 0, 1 or 2"; 14 } 15 |
다른 중요한 점은 CASE 표현식에는 정수, 실수, 문자열의 스칼리 타입으로 평가되는 어떤 표현식이와도 된다는 것이다. 배열이나 객체도 문제를 일으키지는 않는다. 그러나 그것은 문장에서 의미가 없다.
switch 문에 대해서도 Alternative syntax가 지원된다. 자세한 내용은 Alternative syntax for control structures 를 살펴보자
1 2 switch ($i): 3 case 0: 4 print "i equals 0"; 5 break; 6 case 1: 7 print "i equals 1"; 8 break; 9 case 2: 10 print "i equals 2"; 11 break; 12 default: 13 print "i is not equal to 0, 1 or 2"; 14 endswitch; 15 |
require() 문은 C preprocessor의 #include와 비슷하게, 자신을 지정된 파일로 대체한다.
include() 되거나 require() 되어 읽혀지는 파일은 포함된 파일의 처음에 PHP모드에서 빠져나와 HTML모드로 들어가고, 마지막에 PHP모드로 복귀한다. 따라서 포함될 파일의 PHP 코드는 적절한 PHP 시작, 종료 택에 둘러싸여 있어야 한다.
이것은 require()문을 루프 구조 안에 두어, 매번 다른 파일을 읽어들일 수 없다는 것을 의미한다. 이런 동작을 위해서는 INCLUDE 문을 사용하라.
require('header.inc');
require()는 사실 함수가 아니라 제어구조이다. 따라서 이것은 함수와는 다른 규칙을 따른다. 이를테면 require()는 다른 어떤 제어구조와도 사용할 수 없다. 또한, 이것은 반환값이 없다. (반환값을 돌려받으려하면 파싱 에러가 난다.)
include()와 다르게, require()는 언제나 해당 파일을 읽어온다. 심지어 해당 라인이 전혀 실행되지 않아도 읽어온다. 만약 여러분이 조건에 따라 파일을 포함시키고 싶다면 include()문을 사용하여야 한다. 조건절은 require()에 아무 영향을 미치지 못한다. 그러나, require()문이 있는 줄이 실행되지 않는다면 해당 파일의 어떤 코드도 실행되지 않는다.
비슷하게, 순환문 또한 require()에 영향을 주지 못한다. 해당 파일에 있는 내용이 루프의 내용이라 하더러도 require()문은 단지 한번만 나타나는 것으로 된다.
이것은 require() 문을 순환문 안에 사용할 수 없다는 것을 의미하고, 매 순환시마다 다른 파일을 읽어오려면 include()문을 사용하여야 한다는 것이다.
1 2 require ('header.inc'); 3 |
include()와 require() 모두 호출한 스크립트안으로 원하는 파일의 내용 자체를 끌어들이는(pull) 것이지, HTTP나 그와 비슷한 방식으로 해당 타겟을 call하는 것은 아니다. 따라서 현재 범위안에 선언된 모든 변수들은 포함할 파일 안에서도 그대로 사용된다.
1 2 require ("file.inc?varone=1&vartwo=2"); /* Won't work. */ 3 4 $varone = 1; 5 $vartwo = 2; 6 require ("file.inc"); /* $varone and $vartwo will be available in file.inc */ 7 |
여러분은 remote files 기능을 사용하여 HTTP를 통한 원격 파일을 include하거나 require할 때 위의 내용을 명확히 알아둘 필요가 있다.
PHP3에서는 require()로 포함된 파일안에서 return 문을 사용할 수 있었다. 단, return 문이 포함된 파일의 global scope에서 나타나는 경우만 가능하고, 어떠한 블록내({} 내부)에서도 사용할 수 없다. 그러나, PHP4에서는 이런 기능 자체가 없어져 버렸다. 만약 여러분이 이런 기능을 사용하고 싶다면 include() 문을 사용하기 바란다.
INCLUDE문은 지정한 파일을 읽고 실행한다.
include() 되거나 require() 되어 읽혀지는 파일은 포함된 파일의 처음에 PHP모드에서 빠져나와 HTML모드로 들어가고, 마지막에 PHP모드로 복귀한다. 따라서 포함될 파일의 PHP 코드는 적절한 PHP 시작, 종료 택에 둘러싸여 있어야 한다.
이 동작은 실행중 include() 문을 만날 때 만다 일어난다. 따라서 여러분은 include() 문을 루프 구조 안에 두어 매번 다른 파일을 읽어 들이도록 할 수 있다.
1 2 $files = array ('first.inc', 'second.inc', 'third.inc'); 3 for ($i = 0; $i < count($files); $i++) { 4 include $files[$i]; 5 } 6 |
include()는 이 문장을 만날 때 마다 매번 재평가되어 재실행된다는 점에서 require()와 다르다. 반면에 require()문은 지정된 파일의 내용이 실행되는가에 관계없이(예를들어 if 문 안에 들어있고 상태가 거짓인 경우에도), 이 문장을 처음 만날을 때 지정된 파일로 대체된다.
include()는 특별한 구조이므로, 만약 이것이 조전절 안에 놓여있다면 반드시 {}(statement block)으로 둘러싸야 한다.
1 2 /* This is WRONG and will not work as desired. */ 3 4 if ($condition) 5 include($file); 6 else 7 include($other); 8 9 /* This is CORRECT. */ 10 11 if ($condition) { 12 include($file); 13 } else { 14 include($other); 15 } 16 |
PHP3, PHP4 모두 include() 된 파일 내에서, 이 파일의 수행을 종료하고, 이 파일을 부른 스크립트로 복귀하기 위해 return 문을 사용할 수 있다. 약간 다른점이 있기는하다. 우선, PHP3에서는 해당 블록이 함수의 블록이 아닌한 return 문이 블록안에 올 수 없다. (함수의 블록 안에 있는 경우는 해당 함수에서 return 하는 것이지 현재 파일에서 return 하는 것은 아니다.) 그러나, PHP4에서는 이 제한이 없다. ㄸ또한 PHP4에서는 include() 파일의 return시에 리턴값을 사용할 수 있다. 여러분은 include() 문을 일반 함수처럼 반환값을 받을 수 있다. (이것은 PHP3에서는 구문에러를 발생시킨다.)
Example 11-1. include() in PHP3 and PHP4 다음의 test.inc 라는 파일이 메인 파일과 동일한 디렉토리에 있다고 가정한다. :
main.html 이라는 메인파일의 내용은 다음과 같다. :
main.html 이 PHP3에서 불려지면, 이 파일은 두 번째 줄에서 "you can't take the value of an include()" 라는 구문 에러를 발생시킨다. 그러나, PHP4에서는 다음돠 같은 결과를 출력한다. :
이제 main.html 을 다음과 같은 내용으로 고쳐서 실행해 보자. :
PHP4에서는 다음과 같은 결과가 출력된다. :
그러나 PHP3에서는 다음과 같은 결과가 나온다. :
위의 구문 에러는 test.inc에서 return 문이 함수블록이외의 블록안에 사용되었기 때문에 생긴다. return 을 블록 밖으로 꺼내면 다음과 같은 경과가 출력된다. :
위의 '27'이 출력된 것은 PHP3가 include파일로 부터의 값의 반환을 지원하지 않기 때문이다. |
include()와 require() 모두 호출한 스크립트안으로 원하는 파일의 내용 자체를 끌어들이는(pull) 것이지, HTTP나 그와 비슷한 방식으로 해당 타겟을 call하는 것은 아니다. 따라서 현재 범위안에 선언된 모든 변수들은 포함할 파일 안에서도 그대로 사용된다.
1 2 include ("file.inc?varone=1&vartwo=2"); /* Won't work. */ 3 4 $varone = 1; 5 $vartwo = 2; 6 include ("file.inc"); /* $varone and $vartwo will be available in file.inc */ 7 |
여러분은 remote files 기능을 사용하여 HTTP를 통한 원격 파일을 include하거나 require할 때 위의 내용을 명확히 알아둘 필요가 있다.
See also readfile(), require(), virtual().
함수는 다음과 같이 정의한다. :
1 2 function foo ($arg_1, $arg_2, ..., $arg_n) { 3 echo "Example function.\n"; 4 return $retval; 5 } 6 |
함수 안에는 다른 함수나 class의 선언 등을 포함한 모든 가능한 PHP 코드가 사용될 수 있다.
PHP3에서는 함수는 그 함수가 사용되기 이전에 선언되어 있어야 하였으나 PHP4에서는 이런 제약이 없어졌다.
PHP는 function overloading을 지원하지 않고, 이미 정의된 함수를 재정의하거나 없애지 못한다.
PHP3에서는 함수 파라메터의 기본값을 설정해주는 것(default argument values를 보자.)은 가능해도, 파라메터의 개수를 가변으로 설정하는 것은 불가능했지만, PHP4는 두가지 모두 가능하다. 자세한 내용은 Variable-length argument lists 와 func_num_args(), func_get_arg(), func_get_args() 의 함수 설명을 보기 바란다.
argument list를 통해 함수에 어떤 정보를 넘겨줄 수 있다. 이 argument list는 쉼표(,)로 나위어진 변수나 상수의 list이다.
PHP는 passing by value(기본적으로 이것을 사용)와 passing by reference, default argument values의 3가지 방법을 제공한다. 가변 길이(Variable-length) argument list는 PHP4이후에서만 제공된다. 자세한 내용은 Variable-length argument lists 와 func_num_args(), func_get_arg(), func_get_args() 의 함수 설명을 보기 바란다. 그러나 PHP3에서도 배열을 통한 전달을 사용한다면 비슷한 효과를 낼 수 있다.
1 2 function takes_array($input) { 3 echo "$input[0] + $input[1] = ", $input[0]+$input[1]; 4 } 5 |
기본적으로 함수의 인수(argument)들은 값으로 전달된다(passed by value). 함수내에서 변화시킨 값을 그대로 유지하려면 pass by reference로 인수를 넘겨야 한다.
여러분이 어떤 함수의 인수를 항상 pass by reference로 넘기려 한다면, 여러분은 함수를 선언할 때 ampersand(&)를 인수의 앞에 붙여주면 된다. :
1 2 function add_some_extra(&$string) { 3 $string .= 'and something extra.'; 4 } 5 $str = 'This is a string, '; 6 add_some_extra($str); 7 echo $str; // outputs 'This is a string, and something extra.' 8 |
만약 기본은 by value 로 하지만 필요에 따라 by reference로 호출하고 싶다면 함수 호출 시에 인수의 앞에 &를 붙이면 된다. :
1 2 function foo ($bar) { 3 $bar .= ' and something extra.'; 4 } 5 $str = 'This is a string, '; 6 foo ($str); 7 echo $str; // outputs 'This is a string, ' 8 foo (&$str); 9 echo $str; // outputs 'This is a string, and something extra.' 10 |
스칼라 인수는 다음과 같이 C++ 과 비슷하게 기본값을 정해줄 수 있다. :
1 2 function makecoffee ($type = "cappucino") { 3 return "Making a cup of $type.\n"; 4 } 5 echo makecoffee (); 6 echo makecoffee ("espresso"); 7 |
위의 코드의 실행 결과는 다음과 같다 :
Making a cup of cappucino. Making a cup of espresso. |
default 값은 반드시 상수이어야 한다. (예를들어) 변수나 class의 멤버를 사용해서는 안된다.
PHP 4.0에서는 default argument로 unset을 지정할 수 있다. 이것은 해당 argument에 값이 제공되지 않으면, 절대로 값을 설정하지 않는 것을 의미한다.
default argument를 사용할 때, default가 되는 인수들은 non-default인 인수들보다 오른쪽에 위치해야 한다. 그렇지 않으면 원하는 결과가 나오지 않는다. 다음을 보자. :
1 2 function makeyogurt ($type = "acidophilus", $flavour) { 3 return "Making a bowl of $type $flavour.\n"; 4 } 5 6 echo makeyogurt ("raspberry"); // won't work as expected 7 |
위 코드의 실행 결과는 다음과 같다 :
Warning: Missing argument 2 in call to makeyogurt() in /usr/local/etc/httpd/htdocs/php3test/functest.html on line 41 Making a bowl of raspberry . |
그러면 이제 위의 것과 아래것을 비교해 보자. :
1 2 function makeyogurt ($flavour, $type = "acidophilus") { 3 return "Making a bowl of $type $flavour.\n"; 4 } 5 6 echo makeyogurt ("raspberry"); // works as expected 7 |
이 예제의 실행 결과는 다음과 같다. :
Making a bowl of acidophilus raspberry. |
PHP4에서는 사용자 정의 함수에 가변 길이(Variable-length) argument list를 제공한다. func_num_args(), func_get_arg(), func_get_args() 의 함수를 사용하여 쉽게 사용할 수 있다.
특별한 문법이 사용되지도 않고, 함수의 정의시나 사용시 argument list는 보통의 경우와 동일하게 사용하면 된다.
함수는 return 문을 통해 함수값을 돌려줄 수 있다. list와 object를 포함한 어떤 type도 돌려질 수 있다.
1 2 function square ($num) { 3 return $num * $num; 4 } 5 echo square (4); // outputs '16'. 6 |
여러값을 돌려주는 일은 할 수 없다. 그러나 list를 돌려줌으로써 비슷한 일을 할 수 있다. :
1 2 function small_numbers() { 3 return array (0, 1, 2); 4 } 5 list ($zero, $one, $two) = small_numbers(); 6 |
OLD_FUNCTION 문장은 PHP/FI2에서 동일한 함수 사용법을 제공한다. (function대신 old_function을 사용한다는 점은 제외하고)
이것을 사용하는 것은 좋지 않은 방법이다. 이것이 사용될 때는 PHP/FI2->PHP3 변환기에서 뿐이다.
주의 |
OLD_FUNCTION으로 정의된 함수들은 PHP의 내부 코드에서 호출될 수 없다. 이 말은 usort()나 array_walk(), register_shutdown_function()같은 함수에 사용할 수 없다는 의미이다. 이를 해결하기 위해서는 이 OLD_FUNCTION으로 선언된 함수를 호출하는 PHP3 형태의 함수를 만들어 사용하는 것이다. |
PHP는 가변 함수(variable functions) 개념을 지원한다. 이것은 변수명 뒤에 괄호가 왔을 때, PHP는 그 이름을 가진 함수를 찾아 실행한다는 것을 의미한다. 이 기능은 callbacks, function table 등의 기능에 사용하면 매우 유용하게 사용할 수 있다.
Example 12-1. Variable function example
|
( 역자주 : Class 문장은 Java의 subset이라 할만큼 동일하다. )
클래스는 일련의 변수와 이 변수들을 사용하는 함수들의 모음이다. 클래스는 다음과 같은 형태로 선언된다.
1 2 <?php 3 class Cart { 4 var $items; // Items in our shopping cart 5 6 // Add $num articles of $artnr to the cart 7 8 function add_item ($artnr, $num) { 9 $this->items[$artnr] += $num; 10 } 11 12 // Take $num articles of $artnr out of the cart 13 14 function remove_item ($artnr, $num) { 15 if ($this->items[$artnr] > $num) { 16 $this->items[$artnr] -= $num; 17 return true; 18 } else { 19 return false; 20 } 21 } 22 } 23 ?> 24 |
이 선언은 Cart라는 이름의 클래스로, 카트안에 들어있는 물품을 위한 한 개의 배열 변수와 cart에 물건을 넣거나 빼는 두 개의 함수로 구성되어 있다.
Classe는 Type으로, 실제 변수들의 청사진이라 할 수 있다. 여러분은 new 연산자를 사용하여 원하는 type의 변수를 생성하여야 한다.
1 2 $cart = new Cart; 3 $cart->add_item("10", 1); 4 |
위에 있는 예는 Cart 클래스의 $cart라는 object를 만드는 것이다. 이 object의 add_item() 함수를 호출하여 물품 번호 "10"번의 물품 1개를 카트에 넣는다.
클래스는 다른 클래스로 확장 될 수 있다. 확장 혹은 파생된(extended or derived) 클래스는 base 가 되는 클래스의 모든 변수들과 함수들을 그대로 가제게 되고, 여러분은 여기에 추가로 확장된 선언을 할 수 있다. 이를 위해 "extends"라는 키워드가 사용된다.
1 2 class Named_Cart extends Cart { 3 var $owner; 4 5 function set_owner ($name) { 6 $this->owner = $name; 7 } 8 } 9 |
위의 예는 Cart 클래스의 변수와 함수에 $owner 변수와 set_owner() 함수를 추가한 Named_Cart라는 클래스의 선언이다. 여러분은 이름붙은 카트(named cart)를 사용하여 카트의 주인을 설정하고 찾아볼 수 있다. 또한 기존의 일반 카트(normal cart)에 있던 함수도 사용할 수 있다.
1 2 $ncart = new Named_Cart; // Create a named cart 3 $ncart->set_owner ("kris"); // Name that cart 4 print $ncart->owner; // print the cart owners name 5 $ncart->add_item ("10", 1); // (inherited functionality from cart) 6 |
클래스 내부에 있는 함수에서 $this 라는 변수는 자기 자신 object를 의미한다. 여러분은 $this->something 의 형태로 현재 object의 변수나 함수를 사용하여야 한다.
생성자(Constructor)는 해당 클래스의 새 인스턴스(새로 만든 변수라고 생각해 두자)를 만들 때 자동적으로 실행되는 함수를 의미한다. 클래스의 이름과 같은 이름의 함수가 생성자가 된다.
1 2 class Auto_Cart extends Cart { 3 function Auto_Cart () { 4 $this->add_item ("10", 1); 5 } 6 } 7 |
위의 예는 Cart 클래스에 물품번호 10번의 물품을 한 개 자동으로 추가하는 생성자를 추가한 Auto_Cart라는 클래스의 선언이다. Auto_Cart는 "new"로 생성된다. 생성자는 또한 인수(argument)를 가질 수 있고, 이 인수들은 default값을 가진 옵션으로 선언 할 수 있다. 이 기능은 매우 유용하게 사용된다.
1 2 class Constructor_Cart extends Cart { 3 function Constructor_Cart ($item = "10", $num = 1) { 4 $this->add_item ($item, $num); 5 } 6 } 7 8 // Shop the same old boring stuff. 9 10 $default_cart = new Constructor_Cart; 11 12 // Shop for real... 13 14 $different_cart = new Constructor_Cart ("20", 17); 15 |
Caution |
파생된(derived) 클래스의 경우, 이 클래스의 생성자가 호출될 때 부모 클래스의 생성자는 자동으로 호출되지 않는다. |
PHP에는 다음과 같은 4가지의 에러와 경고 형태가 있다.
1 - Normal Function Errors (일반적인 에러)
2 - Normal Warnings (일반적인 경고)
4 - Parser Errors (문법 에러)
8 - Notices (무시할 수 있는 경고이나 버그의 가능성을 가지고 있는 경우)
error reporting level은 위의 4개의 숫자가 더해져서 결정된다. 기본 error reporting level 은 7로 1+2+4가 되고, 이는 Notice를 제외한 모든 것을 레포트하라는 의미이다. 이 레벨은 php3.ini 파일에서 error_reporting 지시자로 결정할 수 있다. 혹은, 아파치의 httpd.conf 파일에서 php3_error_reporting 지시자로 결정하거나, 스크립트 실행 중에 error_reporting() 함수를 사용하여 바꿔줄 수도 있다.
모든 PHP 표현식(expression)은 "@"를 앞에 붙이고 호출되면 error reporting을 하지 않는다. 만약 track_errors 기능이 Enabled로 되어 있는데 해당 문장에서 에러가 발생했다면, $php_errormsg라는 전역변수에서 에러 메시지를 찾을 수 있을 것이다.
PHP는 단지 HTML출력을 만드는 것만 할 수 있는 것이 아니다. PHP는 GIF image file도 만들 수 있을 있을 뿐아니라, 사용하기에 편리한 GIF image stream까지 만들 수 있다. 이를 위해서 여러분은 PHP를 컴파일 할 때, image 함수를 가지고 있는 GD 라이브러리를 포함하여야 한다.
Example 15-1. GIF creation with PHP
|
위의 예제는 <img src="button.php3?text">와 같은 tag이 있는 페이지로부터 불려지게 될 것이다. 그러면 위에있는 button.php 스크립트는 "text"라는 문자열을 "images/button1.gif"에 오버레이 시켜 결과 image에 출력한다. 이렇게 하면 버튼에 들어가는 글씨를 매번 손쉽게 바꿔 쓸 수 있고, 또한 매번 이미지 파일을 만들 필요가 없어 효율적이고 간단하다.
(역자주. HTTP authentication이란 Web Client에게 ID와 Password를 입력받아, 그 ID와 Password로 Web문서에 접근을 허가, 불허하는 기능을 말한다. 자세히 알고 싶다면 RFC1945의 Authentication 부분을 참고하기 바란다. http://pec.etri.re.kr/!qkim/HTTP/에 한글 번역 문서도 있으니 참조하자.)
PHP를 사용한 HTTP 인증은 Apache 모듈로 사용될 때만 동작한다. Apache 모듈의 PHP 스크립트에서 Header()라는 함수를 사용하면 Client 브라우저에게 Username과 Password를 입력받는 윈도우를 띄우도록 하는 "인증 요구"("Authentication Required") 메시지를 보내게 된다. 일단 사용자가 Username과 Password를 입력하면, user name, password, authentication type의 값을 가지는 $PHP_AUTH_USER, $PHP_AUTH_PW, $PHP_AUTH_TYPE의 3개의 변수를 가지고 해당 URL(PHP 스크립트를 포함한)이 다시 불리워진다. 현재 authentication type은 "Basic"만이 지원된다.
client authentication을 사용하여 그 입력된 값을 출력하는 예제가 아래에 있다. :
Example 16-1. HTTP Authentication example
|
여러분은 $PHP_AUTH_USER 와 $PHP_AUTH_PW를 단순히 출력하는 대신, 사용자의 식별을 위해 username과 password를 사용하기를 원할 것이다. 이때는 Database에 Query하거나 직접 dbm 파일에서 찾아보면 가능할 것이다.
Internet Explorer browser에서는 버그로 인해 Header의 순서가 매우 까다롭다. WWW-authenticate header를 HTTP/1.0 401 header보다 먼저 보내는 것이 현재 가능한 요령으로 보인다.
비밀번호의 유출을 우려하여 HTTP에서 제공하는 인증을 사용하는 대신 기존의 외부 메카니즘을 사용할 경우에는 물론 PHP_AUTH 변수는 설정되지 않는다.
유의할 점은 인증이 필요한 페이지와 인증이 필요없는 페이지가 같은 서버상에 존재할 때, 인증이 필요없는 URL을 control할 수 있는 누군가가, 인증이 필요한 URL의 암호를 훔쳐보는 것은 막을 수 없다는 점이다.
Netscape와 Internet Explorer 모두 401응답 코드를 서버에서 받게되면 local browser window의 authentication cache를 clear한다. 즉, 이것은 "log out"개념이 되는 것으로, 사용자들로 하여금 username과 암호를 다시 입력하게 한다. 일부는 이것을 login의 "time out"이나 "log-out"버튼을 만드는데 사용한다
Example 16-2. HTTP Authentication example forcing a new name/password
|
이 동작은 HTTP Basic authentication 기준에 요구되는 것은 아니므로 여러분은 이것에 의존하여서는 안된다. Lynx에서는 401 서버 응답을 받아도 authentication 정보를 clear하지 않는다. 따라서 Back을 누르고 다시 Forward 버튼을 눌러서 다시 접근할 수 있다.
또한 이 Authentication 기능은 Microsoft's IIS server에서 CGI version의 PHP를 사용할 경우에는 IIS의 제약으로인해 동작하지 않는다.
PHP는 HTTP Cookie를 투명하게(transparently) 지원한다. Cookie 메카니즘은 트래킹이나 사용자 식별 등을 위해 원격 browser에 저장된 데이터를 돌려 받는 과정을 말한다. 여러분은 cookie를 설정하기 위해 setcookie() 함수를 사용할 수 있다. Cookie는 HTTP 헤더의 한 부분이므로, SetCookie() 함수는 브라우저로 보내는 어떤 데이터보다도 앞에 사용해야 한다. 이 제약은 Header() 함수와 같은 제약으로 보면 된다.
당신이 보내준 모든 cookie는 자동적으로 GET이나 POST 방식 데이터와 같은 PHP 변수로 변환된다. 만약 여러분이 동일한 cookie에 여러 값을 저장하고 싶다면 Cookie이름에 []를 더하면 된다. 자세한 것은 setcookie() 함수 설명을 참조하자.
PHP는 RFC-1867을 지원하는 브라우저로부터 파일을 업로드 받을 수 있는 기능이 있다. 이 기능을 사용하면 Text분아니라 Binary파일도 업로드가 가능하다. 여러분은 PHP's authetication과 논리적인 함수들을 사용하여, Upload가 가능한 사용자와, 파일이 Upload된 후에 해야 할 일을 반드시 정해 두어야 한다. (역자주. RFC-1867은 Netscape 3.0이상, Explorer 4.0이상에서 지원한다. Netscape 2.x대의 일부 상위버젼도 지원하고, Explorer 3.02는 Patch가 나와 있으므로 patch시키면 가능하다.)
PHP는 또한 Netscape Composer 와 W3C's Amaya clients를 사용할 경우 PUT-method 의 파일 업로드도 지원한다. 자세한 내용은 PUT Method Support 를 읽어보기바란다.
파일 업로드 화면은 다음과 같은 좀 특별한 폼을 만들어 띄울 수 있다. :
Example 18-1. File Upload Form
|
여기서_URL_은 PHP html파일이어야 합니다. hidden 필드인 MAX_FILE_SIZE는 File input 필드들보다 선행되어야 합니다. 이 값은 PHP html이 받아들이는 최대 파일 크기를 Byte단위로 나타냅니다. 업로드가 성공적으로 되면 지정된 파일에는 다음과 같은 변수들이 정의되어 진다. :
$userfile - 업로드된 파일 내용이 저장되어 있는 서버의 임시 파일명
$userfile_name - 업로드한 시스템에서 사용하는 파일의 원래 이름.
$userfile_size - byte단위의 Upload된 파일의 크기.
$userfile_type - 만약 browser가 업로드된 파일의 mime 형식을 안다면, 그 mime 형식. (Ex. "image/gif").
위 변수의 "$userfile"부분은 upload form에서 TYPE=filed을 가진 INPUT 필드의 이름이 된다. 위의 예제에서 우리는 그 이름은 "userfile"이라고 정했다.
File은 기본적으로 우선 서버의 default temporary directory에 저장된다. 이 디폴트 디렉토리는 PHP가 돌아가는 컴퓨터의 환경변수 "TMPDIR"을 설정하여 변경할 수 있다. 이를 PHP 스크립트 안에서 putenv() 함수를 사용하여 변경하는 것은 동작하지 않는다.
업로드된 파일을 다루는 PHP 스크립트는 해당 파일을 가지고 하는 작업을 설정해 줄 필요가 있다. 예를들어, 여러분은 $file_size변수를 사용하여 너무 작거나 큰 파일을 버릴 수도 있다. 또한 여러분은 $file_type변수를 가지고 특정한 타입에 맞지 않는 파일을 버릴 수 있다. 어떤 로직이던, 여러분은 임시 디렉토리에 있는 파일을 지우거나 나중에 필요할 경우에는 다른 곳에 이동시켜야 한다.
만약 임시 디렉토리에 있는 파일을 해당 request가 끝날 때 까지도 지우거나 이동시키지 않았다면, 이 파일은 해당 request가 종료되는 시점에서 자동으로 지워진다.
MAX_FILE_SIZE 아이템의 값은 PHP3.ini에 설정된 upload_max_filesize의 값이나 Apache .conf에 설정한 php3_upload_max_filesize의 값보다 크게 설정할 수 없다. 기본값은 2메가 바이트이다.
CERN httpd 서버는 client로부터 입력받은 mime header의 앞쪽 여백을 모두 strip off 시켜버리므로, CERN httpd 서버에서는 File Upload 기능이 동작하지 않는다.
한번에 여러개의 파일을 동시에 전송하는 것도 가능하다. 이때 PHP는 이 파일들에 대한 정보를 배열로 전달한다. 따라서 이런 경우에는 여러개를 선택하는 select나 checkbox 때처럼 HTML의 form의 아이템에 동일한 array명을 적어주어야 한다.
Note: 여러 파일 전송 기능은 3.0.10부터 추가된 기능이다. (역자주: php 4.0.0은 버그로 인해 이 기능이 동작하지 않는다)
Example 18-2. Uploading multiple forms
|
위의 폼이 전송될 때 $userfile, $userfile_name, $userfile_size의 배열이 전역 변수로 만들어진다. ($HTTP_POST_VARS에도 만들어진다.) 이 배열들은 전송된 파일의 정보를 가지고 있고, 각 배열들은 번호로 인덱스되어 있다.
예를 들어, 위의 예에서 /home/test/review.html 과 /home/test/xwp.out 의 두 개의 파일을 전송했다면 $userfile_name[0]에는 review.html이라는 값이, $userfile_name[1]에는 xwp.out이라는 값이 저장되게 된다. 동시에, $userfile_size[0] 에는 review.html의 파일 크기가 저장되는 식이 된다.
PHP는 Netscape Composer나 W3C Amaya같은 클리이언트에 대해 HTTP PUT 방식(method)을 지원한다. PUT 요구(request)는 file upload보다 훨씬 쉽다. 단지 다음과 같이 하면 된다. :
1 2 PUT /path/filename.html HTTP/1.1 3 |
이것은 보통 원격 클라이언트가 보낸 내용을 웹 트리 밑의 /path/filename.html로 저장하라는 의미이다. 그런데 여러분의 웹 트리밑에 있는 파일들을 아무나 덮어 쓸 수 있다는 것은 Apache나 PHP에 있어서 확실히 좋지 않은 생각이다. 따라서 이와 같은 요구를 다루기 전에, 우선 웹 서버에게 이런 요구를 다루는 PHP 스크립트를 미리 지정해 주어야 한다. 아파치에서는 Script 지시자로 그 내용을 지정한다. 이 지시자는 Apache 설정 파일중의 어느 위치에 있어도 괜찮으나, 보통 <Directory> 블록 안이나 <Virtualhost> 블록 안에 위치하는 것이 일반적이다. 보통 다음과 같이 쓰여진다. :
1 2 Script PUT /put.php3 3 |
이것은 이 라인을 위치시킨 블록의 URI에 해당되는 모든 PUT 요구를 put.php3 스크립트에게 전달하라고 Apache에게 알려 준다. 물론 이 경우 .php3 확장자에 대하여 PHP설정이 완료되어 있고, PHP가 작동중이어야 한다.
put.php3 파일내에서는 보통 다음과 같이 사용할 수 있다. :
1 2 <? copy($PHP_UPLOADED_FILE_NAME,$DOCUMENT_ROOT.$REQUEST_URI); ?> 3 |
위의 명령은 해당 파일을 원격 클라이언트가 요청한 위치에 복사하는 것이다. 아마 여러분은 복사하기 전에 사용자를 확인하거나 파일을 검사하는 등의 기능을 원할 것이다. 여기서 알 수 있는 것은 PHP가 PUT-method의 요구를 받았을 때 POST-method기능과 마찬가지로 임시 파일에 해당 내용을 저장한다는 것이다. 즉, 요구가 끝나게 되면 임시파일은 지워진다. 따라서 PUT을 다루는 PHP 스크립트는 해당 파일을 어디 다른 곳에 복사해 두어야 한다. 임시파일의 이름은 $PHP_PUT_FILENAME 이라는 변수에 저장되고, $REQUEST_URI 변수에 클라이언트에서 보내온 저장할 파일의 경로와 이름이 저장된다.(Apache가 아닌 웹서버에서는 모양이 조금 달라진다.) 물론 여러분은 이 경로명과 파일명이 아닌 전혀 다른 위치에 다른 파일명을 사용할 수도 있다.
여러분이 PHP를 설정할 때 "URL fopen wrapper"를 enable로 설정하였다면(이 설정은 --disable-url-fopen-wrapper로 명시하지 않으면 설정된다.), 여러분은 대부분 함수의 파라메타로 있는 파일이름(filename)에 HTTP나 FTP URL을 사용할 수 있다. 심지어 require()나 include() 함수에도 사용이 가능하다.
예를 들어, 여러분은 이 기능을 사용하여 원격 웹 서버가 출력하는 내용을 파일로 열고, 그 출력 내용에서 여러분이 원하는 데이타를 분석하여, 이 원하는 데이타로 데이타베이스 질의에 사용하거나, 여러분의 웹 사이트에 맞는 모양으로 변형 시켜 출력할 수 있다.
Example 19-1. Getting the title of a remote page
|
여러분은 해당 서버에 권한이 있는 사용자로 접속하고, 해당 파일이 존재하지 않는다면, FTP를 이용한 파일로 쓸 수도 있다. 'anonymous'가 아닌 사용자로 접속하려면, URL내에 username을 (필요하다면 password도) 다음과 같이 명시해야 한다 : 'ftp://user:password@ftp.example.com/path/to/file'. (또한 HTTP에서 Basic authentication을 사용한 인증을 요구하는 경우에도 이와 같은 문법을 사용할 수 있다.)
Example 19-2. Storing data on a remote server
|
Note: 여러분은 위의 예제를 보고, 이 테크닉을 사용하여 remote log를 작성할 수 있겠다고 생각할 수도 있다. 그러나 위에 언급한대로 URL fopen() wrapper는 새 파일에만 쓸 수 있다. 여러분이 원하는 대로 분산된 log를 하고 싶다면 syslog()의 내용을 살펴보라.
Note: 이 기능은 PHP version 3.0.7 이후부터 적용된 것들이다.
내부적으로 PHP는 연결의 상태를 다음 3가지중 하나로 설정한다. :
0 - NORMAL
1 - ABORTED
2 - TIMEOUT
PHP 스크립트가 일반적으로 실행되고 있을 때는 NORMAL 상태가 active된다. 만약 원격 클라이언트가 연결을 끊게되면 ABORTED 상태 flag가 켜지게 된다. 보통 클라이언트가 연결을 끊는 것은 사용자가 STOP 버튼을 눌렀을 때 일어난다. 만약 PHP가 설정한 시간 제한에 (set_time_limit()을 보라) 걸리게 되면 TIMEOUT 상태 flag가 켜지게 된다.
여러분은 클라이언트가 연결을 끊었을 때 스크립트가 수행을 중단할 것인가 아닌가를 결정하여야 한다. 때때로 원격 브라우저가 어떤 결과도 받아들이지 않더라도 스크립트를 끝까지 실행하는 것이 편리할 때가 많다. 기본 동작은 클라이언트가 연결을 끊으면 스크립트도 중단되는 것이다. 이 동작은 ignore_user_abort라는 php3.ini 지시자(directive)나, php3_ignore_user_abort라는 Apache .conf의 지시자로 설정이 가능하고, ignore_user_abort() 함수를 사용하여 설정할 수도 있다. 만약 여러분이 PHP에게 사용자가 내린 중지 명령을 무시하라고 말해주지 않았다면, 사용자의 중지 신호는 여러분의 스크립트를 종료시킨다. 단, register_shutdown_function()을 사용하여 shutdown 함수를 등록해놓은 경우는 예외가 된다. shutdown 함수를 사용하면, 사용자가 STOP버튼을 눌렀을 때, 여러분의 스크립트는 남은 출력을 하려고 하고, PHP는 연결이 중단되었음을 인지하여 shutdown 함수를 호출하게 된다. shutdown 함수는 여러분의 스크립트가 정상적으로 종료되었을 때도 호출 된다. 따라서 클라이언트의 연결 중단 때와 일반적인 종료시에 다른 동작을 원한다면 connection_aborted() 함수를 사용하면 된다. 이 함수는 연결이 중단되었다면 true를 반환한다.
여러분의 스크립트는 내장된 타이머에 의해 종료될 수 있다. 기본 timeout 시간은 30초로 되어 있다. 이것은 max_execution_time이라는 php3.ini 지시자(directive)나 동일한 내용의 php3_max_execution_time이라는 Apache .conf 지시자에 의해 다르게 설정이 가능하고 set_time_limit() 함수를 사용하여 설정할 수도 있다. 시간이 다 되면 스크립트는 중단되고, 이 스크는 위에서 설명한 클라이언트와의 연결이 종료된 것처럼 동작한다. 따라서 shutdown 함수가 등록되어 있다면 이 함수가 실행된다. shutdown 함수내에서 이 함수가 timeout에 의해 호출된 것인가를 판단하려면 connection_timeout() 함수를 사용하면 된다. 이 함수는 timeout에 의해 shutdown 함수가 호출되었다면 true를 반환한다.
한가지 유의할 사항은 ABORTED와 TIMEOUT 상태는 두 개가 동시에 active될 수 있다는 것이다. 이것은 PHP가 사용자 중단을 무시하도록 설정해 놓았을 때 가능하다. 또 다른 경우는 사용자가 연결을 끊지는 않았지만 연결에 어떤 문제가 생겨 연결이 망가진 경우로, 이 때도 스크립트는 계속 실행된다. 이런 경우에 스크립트는 계속실행되고, 시간 제한에 걸려 스크립트의 수행이 중단되고 shutdown 함수가 호출되면, connection_timeout()과 connection_aborted() 함수 모두 true를 반환하게 된다. 여러분은 connection_status() 라는 함수를 사용하여 두가지 상태 모두를 검사할 수 있다. 이 함수는 각 상태에 대한 정보를 bit단위로 가지고 있다. 예를들어 위와같이 ABORT와 TIMEOUT 두 개의 상태가 모두 active되어 있다면 이 함수는 3을 반환한다.
영구적인 접속(Persistent connection)은 여러분의 스크립트가 종료되어도 SQL link를 닫지 않는 접속을 말한다. 영구적인 접속이 요청되면, PHP는 기존의 (이전에 열어 두었던) 동일한(identical) 영구적인 접속이 있는가를 검사한다. 만약 있다면 기존의 것을 사용하고, 없다면 새로운 link를 만든다. '동일한(identical)' 접속이란 같은 호스트에 같은 사용자명(username)과 같은 암호(password)를 사용한 접속을 말한다.
가끔 웹서버의 작동과 작업의 할당에 대해 잘 알고 있지 못한 사람들은 영구적인 접속이 사실은 별 것 아니라고 오해하기도 한다. 특히, 영구적인 접속이 동일한 SQL link에서 'user sessions'를 여는데 별 나을 것도 없다던가, transaction을 효율적으로 처리하는 것도 아니라다던가, 혹은 다른 어떤 작업을 하지 못한다고도 한다. 사실, 이런 말들에 대해 명백히 말하자면, 영구적인 접속은 비영구적인 접속에 비해 어떠한 기능적인 향상도 주지 못한다.
왜?
이것은 웹서버의 동작 방법대로 동작한다. 여러분의 웹서버가 웹 페이지를 만들기위해 PHP를 이용하는데는 3가지 방법이 있다.
첫 번째 방법은 PHP를 CGI "wrapper"이 형태로 사용하는 것이다. 이 방법의 경우, 웹서버에 매 PHP 페이지가 요구될 때 마다, PHP 인터프리터의 실행이 만들어지고 종료된다. 따라서 매 요구가 종료될 때마다 인터프리터의 실행이 종료되므로, 실행 중 만들었던 (SQL link를 포함한) 모든 자원은 실행 종료와 더불어 해제된다. 이 경우 여러분은 영구적입 접속을 사용하여 어떤 이득도 얻을 수 없다. 다르게 말하면 이 경우는 영구적인 접속을 해도 영구적이 아니다.
두 번째 방법은 가장 대중적인 방법인데, PHP를 다중프로세스(multiprocess) 웹서버의 모듈로 사용하는 것이다. (현재는 Apache가 유일하다.) 다중프로세스 서버는 보통 한 개의 부모(parent) 프로세스와, 이와 유기적으로 연결되어 웹 페이지를 실제로 만드는 작업을 하는 여러개의 자식(child) 프로세스들을 가지고 있다. 클라이언트로부터 들어오는 개별 요구는 다른 클라이언트의 료구를 처리하고 있지 않은 남는 자식 프로세스로 넘겨진다. 이것은 동일한 클라이언트가 서버에 두 번째 요구를 보낼 때, 보통 처음과 다른 자식 프로세스에서 처리된다는 것을 의미한다. 이 경우 영구적인 접속을 사용하면 각각의 자식 프로세스들은 처음 요구에서만 SQL 서버에 접속하게 된다. 다른 페이지에서 SQL 서버에의 접속 요구시는 기존에 만들어진 접속을 다시 사용하게 된다.
마지막 방법은 PHP를 멀티쓰레드(multithreaded) 웹서버의 플러그-인의 형태로 작동시키는 것인데, 현재 이방법은 이론적으로만 존재하고, 실제로 만들어 진 것은 없다. ISAPI, WSAPI, NSAPI (Windows에서) 등의 방법을 사용하여 Netscape FastTrack, Microsoft's Internet Information Server (IIS), O'Reilly's WebSite Pro 등의 멀티쓰레드 웹서버에서 PHP를 플러그-인으로 동작시키려는 작업이 현재 진행중이다. 이 경우 기본 동작은 위에서 언급한 다중프로세스 모델과 동일하게 동작한다.
영구적인 접속이 실제로 아무런 기능의 향상도 주지 못한다면, 이것을 사용해 어떤 이점이 있나요?
이것에 대한 간단한 답은 효율성이다. 영구적인 접속은 SQL 서버와의 link를 만드는 것에 따른 overhead가 클 경우에 유용하다. 이 overhead는 많은 요인에 따라 커지기도 하고 작아지기도 한다. 어떤 종류의 데이터베이스인가? 웹서버와 같은 컴퓨터에 데이터베이스 서버가 있는가? SQL 서버가 어떻게 사용되고 있는가? 등에 따라 크게 달라진다. 접속에 따른 overhead가 클 경우에 영구적인 접속은 여러분에게 적지 않은 도움을 줄 것이다. 이것은 자식 process에서 SQL 서버에 접속을 요청할 때 마다 접속을 만드는 대신, 이 프로세스가 종료될 때 까지 살아있는 한 개의 접속 만을 사용한다. 이것은 모든 영구적인 접속을 사용한 프로세스는, 그에 해당하는 한 대의 영구적인 접속을 가지고 있다는 것을 의미한다. 예를 들어 SQL 서버에 대하여 영구적인 접속을 사용하는 스크립트를 실행하였던 20개의 다른 자식 프로세스가 있다면, 아마도 각각의 자식 프로세스에대해 1개씩, 20개의 SQL 접속이 있을 것이다.
중요한 요약 한가지. 영구적인 접속은 일반적인 접속에 1대1로 대응되도록 설계되었다. 이것은 스크립트의 기능은 그대로 두고, 언제라도 비영구적인 연결을 영구적인 연결로 대치할 수 있다는 것을 의미한다. 이것으로 여러분은 아마도 스크립트의 효율을 향상시킬 수 있을 것이다.
(역자주: 이 Reference 부분은 비교적 간단한 내용들이고, 내용의 정확성을 기하기 위해 특별한 경우를 제외하고는 제목 부분만 번역하였다.)
apache_lookup_uri -- 특정 URI에 대한 부분적인 요청(partial request)을 수행하고 그것에 대한 모든 정보를 돌려준다.
class apache_lookup_uri
(string filename);
This performs a partial request for a URI. It goes just far enough to obtain all the important information about the given resource and returns this information in a class. The properties of the returned class are:
status |
the_request |
status_line |
method |
content_type |
handler |
uri |
filename |
path_info |
args |
boundary |
no_cache |
no_local_copy |
allowed |
send_bodyct |
bytes_sent |
byterange |
clength |
unparsed_uri |
mtime |
request_time |
Note: apache_lookup_uri 는 PHP가 모듈로 설치되었을 경우만 동작한다.
apache_note -- apache request note를 설정하거나 읽어온다.
string apache_note
(string note_name, string [note_value]);
apache_note() is an Apache-specific function which gets and sets values in a request's notes table. If called with one argument, it returns the current value of note note_name. If called with two arguments, it sets the value of note note_name to note_value and returns the previous value of note note_name.
getallheaders -- 모든 HTTP request header를 분석하여 읽어온다.
array getallheaders
(void);
This function returns an associative array of all the HTTP headers in the current request.
Note: You can also get at the value of the common CGI variables by reading them from the environment, which works whether or not you are using PHP as an Apache module. Use phpinfo() to see a list of all of the environment variables defined this way.
Example 1. getallheaders() Example
|
This example will display all the request headers for the current request.
Note: GetAllHeaders() 는 PHP가 모듈로 설치되었을 경우만 동작한다.
virtual -- Apache sub-request를 수행한다.
int virtual
(string filename);
이 BC 함수들은 PHP가 --enable-bcmath 설정 옵션으로 컴파일 된 경우에만 사용이 가능하다.
bcadd -- 두 개의 arbitrary precision number를 더한다.
string bcadd
(string left operand, string right operand, int [scale]);
Adds the left operand to the right operand and returns the sum in a string. The optional scale parameter is used to set the number of digits after the decimal place in the result.
See also bcsub().
bccomp -- 두 arbitrary precision numbers를 비교한다.
int bccomp
(string left operand, string right operand, int [scale]);
Compares the left operand to the right operand and returns the result as an integer. The optional scale parameter is used to set the number of digits after the decimal place which will be used in the comparion. The return value is 0 if the two operands are equal. If the left operand is larger than the right operand the return value is +1 and if the left operand is less than the right operand the return value is -1.
bcdiv -- 두 arbitrary precision number를 나눈다.
string bcdiv
(string left operand, string right operand, int [scale]);
Divides the left operand by the right operand and returns the result. The optional scale sets the number of digits after the decimal place in the result.
See also bcmul().
bcmod -- arbitrary precision number의 나머지를 구한다.
string bcmod
(string left operand, string modulus);
Get the modulus of the left operand using modulus.
See also bcdiv().
bcmul -- 두 arbitrary precision number를 곱한다.
string bcmul
(string left operand, string right operand, int [scale]);
Multiply the left operand by the right operand and returns the result. The optional scale sets the number of digits after the decimal place in the result.
See also bcdiv().
bcpow -- arbitrary precision number의 n 제곱한다.
string bcpow
(string x, string y, int [scale]);
Raise x to the power y. The scale can be used to set the number of digits after the decimal place in the result.
See also bcsqrt().
bcscale -- 모든 bc 수학 함수의 기본 scale parameter를 정한다.
string bcscale
(int scale);
This function sets the default scale parameter for all subsequent bc math functions that do not explicitly specify a scale parameter.
bcsqrt -- arbitray precision number의 제곱근을 구한다.
string bcsqrt
(string operand, int scale);
Return the square root of the operand. The optional scale parameter sets the number of digits after the decimal place in the result.
See also bcpow().
bcsub -- arbitrary precision number 를 뺀다.
string bcsub
(string left operand, string right operand, int [scale]);
Subtracts the right operand from the left operand and returns the result in a string. The optional scale parameter is used to set the number of digits after the decimal place in the result.
See also bcadd().
array -- 배열을 만든다.
array array
(...);
Returns an array of the parameters. The parameters can be given an index with the => operator.
Note: array() is a language construct used to represent literal arrays, and not a regular function.
The following example demonstrates how to create a two-dimensional array, how to specify keys for associative arrays, and how to skip-and-continue numeric indices in normal arrays.
Example 1. array() example
|
See also: list().
array array_count_values
(array input);
array_count_values() returns an array using the values of the input array as keys and their frequency in input as values.
Example 1. array_count_values() example
|
Note: This function was added in PHP 4.0.
array array_flip
(array trans);
array_flip() returns an array in flip order.
Example 1. array_flip() example
|
Note: This function was added in PHP 4.0.
array_keys -- 배열의 모든 키들을 반환한다,
array array_keys
(array input, mixed [search_value] );
array_keys() returns the keys, numeric and string, from the input array.
If the optional search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the input are returned.
Example 1. array_keys() example
|
See also array_values().
Note: This function was added in PHP 4.0.
array_merge -- 두 개 이상의 배열을 하나로 합친다.
array array_merge
(array array1, array array2,
[ ...] );
array_merge() merges the elements of two or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays had the same string keys, then the later value for that key will overwrite previous one. If, however, the arrays have the same numeric key, this does not happen since the values are appended.
Example 1. array_merge() example
Resulting array will be array("color" => "green", 2, 4, "a", "b", "shape" => "trapezoid"). |
Note: This function was added in PHP 4.0.
array array_pad
(array input, int pad_size,
mixed pad_value);
array_pad() returns a copy of the input padded to size specified by pad_size with value pad_value. If pad_size is positive then the array is padded on the right, if it's negative then on the left. If the absolute value of pad_size is less than or equal to the length of the input then no padding takes place.
Example 1. array_pad() example
|
array_pop -- 배열의 맨 뒤에 있는 원소를 꺼내고 그 원소를 삭제한다.
mixed array_pop
(array array);
array_pop() pops and returns the last value of the array, shortening the array by one element.
Example 1. array_pop() example
After this, $stack has only 2 elements: "orange" and "apple", and $fruit has "raspberry". |
See also array_push(), array_shift(), and array_unshift().
Note: This function was added in PHP 4.0.
array_push -- 배열의 맨 뒤에 한 개나 그 이상의 원소를 첨가한다.
int array_push
(array array, mixed var, [...] );
array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed. Has the same effect as:
1 2 $array[] = $var; 3 |
Returns the new number of elements in the array.
Example 1. array_push() example
|
See also array_pop(), array_shift(), and array_unshift().
Note: This function was added in PHP 4.0.
array array_reverse
(array array);
array_reverse() takes input array and returns a new array with the order of the elements reversed.
Example 1. array_reverse() example
|
Note: This function was added in PHP 4.0 Beta 3.
array_shift -- 배열의 맨 앞에 있는 원소를 꺼내고 그 원소를 삭제한다.
mixed array_shift
(array array);
array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down.
Example 1. array_shift() example
|
See also array_unshift(), array_push(), and array_pop().
Note: This function was added in PHP 4.0.
array_slice -- 배열의 일부를 추출한다.
array array_slice
(array array, int offset, int
[length] );
array_slice() returns a sequence of elements from the array specified by the offset and length parameters.
If offset is positive, the sequence will start at that offset in the array. If offset is negative, the sequence will start that far from the end of the array.
If length is given and is positive, then the sequence will have that many elements in it. If length is given and is negative then the sequence will stop that many elements from the end of the array. If it is omitted, then the sequence will have everything from offset up until the end of the array.
Example 1. array_slice() examples
|
See also array_splice().
Note: This function was added in PHP 4.0.
array_splice -- 배열의 일부를 삭제하고, 그 위치에 다른 내용을 끼워 넣는다.
array array_splice
(array input, int offset,
int [length] , array [replacement] );
array_splice() removed the elements designated by offset and length from the input array, and replaces them with the elements of the replacement array, if supplied.
If offset is positive then the start of removed portion is at that offset from the beginning of the input array. If offset is negative then it starts that far from the end of the input array.
If length is omitted, removes everything from offset to the end of the array. If length is specified and is positive, then that many elements will be removed. If length is specified and is negative then the end of the removed portion will be that many elements from the end of the array. Tip: to remove everything from offset to the end of the array when replacement is also specified, use count($input) for length.
If replacement array is specified, then the removed elements are replaced with elements from this array. If offset and length are such that nothing is removed, then the elements from the replacement array are inserted in the place specified by the offset. Tip: if the replacement is just one element it is not necessary to put array() around it, unless the element is an array itself.
The following equivalences hold:
1 2 array_push($input, $x, $y) array_splice($input, count($input), 0, array($x, $y)) 3 array_pop($input) array_splice($input, -1) 4 array_shift($input) array_splice($input, 0, 1) 5 array_unshift($input, $x, $y) array_splice($input, 0, 0, array($x, $y)) 6 $a[$x] = $y array_splice($input, $x, 1, $y) 7 |
Returns the array consisting of removed elements.
Example 1. array_splice() examples
|
See also array_slice().
Note: This function was added in PHP 4.0.
array_unshift -- 배열의 맨 앞에 한 개나 그 이상의 원소를 첨가한다.
int array_unshift
(array array, mixed var,
[...] );
array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order.
Returns the new number of elements in the array.
Example 1. array_unshift() example
|
See also array_shift(), array_push(), and array_pop().
Note: This function was added in PHP 4.0.
array_values -- 배열의 모든 값들을 반환한다.
array array_values
(array input);
array_values() returns all the values from the input array.
Example 1. array_values() example
|
Note: This function was added in PHP 4.0.
array_walk -- 배열의 개개의 원소에 특정 함수를 적용하여 수행한다.
int array_walk
(array arr, string func, mixed
userdata);
Applies the function named by func to each element of arr. func will be passed array value as the first parameter and array key as the second parameter. If userdata is supplied, it will be passed as the third parameter to the user function.
If func requires more than two or three arguments, depending on userdata, a warning will be generated each time array_walk() calls func. These warnings may be suppressed by prepending the '@' sign to the array_walk() call, or by using error_reporting().
Note: If func needs to be working with the actual values of the array, specify that the first parameter of func should be passed by reference. Then any changes made to those elements will be made in the array itself.
Note: Passing the key and userdata to func was added in 4.0.
In PHP 4 reset() needs to be called as necessary since array_walk() does not reset the array by default.
Example 1. array_walk() example
|
arsort -- 배열을 역순으로 정렬하고 index association을 유지한다.
void arsort
(array array);
This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.
Example 1. arsort() example
|
See also: asort(), rsort(), ksort(), and sort().
asort -- 배열을 정렬하고 index association을 유지한다.
void asort
(array array);
This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.
Example 1. asort() example
|
See also arsort(), rsort(), ksort(), and sort().
compact -- 주어진 여러 변수의 이름과 값을 가지는 배열을 만든다.
array compact
(string varname | array varnames,
[...] );
compact() takes a variable number of parameters. Each parameter can be either a string containing the name of the variable, or an array of variable names. The array can contain other arrays of variable names inside it; compact() handles it recursively.
For each of these, compact() looks for a variable with that name in the current symbol table and adds it to the output array such that the variable name becomes the key and the contents of the variable become the value for that key. In short, it does the opposite of extract(). It returns the output array with all the variables added to it.
Example 1. compact() example
After this, $result will be array ("event" => "SIGGRAPH", "city" => "San Francisco", "state" => "CA"). |
See also extract().
Note: This function was added in PHP 4.0.
count -- 배열 변수의 원소 개수를 구한다.
int count
(mixed var);
Returns the number of elements in var, which is typically an array (since anything else will have one element).
Returns 1 if the variable is not an array.
Returns 0 if the variable is not set.
Warning |
count() may return 0 for a variable that isn't set, but it may also return 0 for a variable that has been initialized with an empty array. Use isset() to test if a variable is set. |
See also: sizeof(), isset(), and is_array().
current -- 배열의 현재 원소를 돌려준다.
mixed current(array array);
각각의 배열 변수는 그것의 원소를 가르키는 내부적인 pointer를 가지고 있다. 게다가, 배열의 모든 원소들은 검색이 용이하도록 양방향 linked list로 연결되어 있다. 이 내부적인 pointer는 다른 어떤 조작을 하기 전에는 항상 첫 번째 요소를 가르키고 있다.
current() 함수는 단순히 내부적인 Pointer가 가르키고 있는 원소를 반환할 뿐이다. 만약 이 pointer가 원소 list의 범위를 넘어서 지시하고 있다면 current()는 false를 반환한다.
Warning |
current()는 현재 원소가 0이나 ""(빈 문자열)의 값을 가지고 있으면 false을 반환한다. 따라서 이 current() 함수는 원소의 값이 0인가 아니면 배열의 범위를 넘었는가를 판단할 수 없다. current()를 사용한 loop 코딩보다는 each() 함수를 사용하는 것이 좋다. |
See also: end(), next(), prev() and reset().
each -- 배열에서 다음 key/value 쌍을 돌려준다.
array each(array array);
array 배열에서 다음 key/value 쌍을 반환한다. 이 쌍은 네 개의 원소를 가진 배열로 반환되는데 이 네 개의 원소의 key는 0, 1, key, value이다. 0과 key 원소는 각각 변수의 key 이름을 가지고, 1과 value는 그 값을 가지고 있다.
Example 1. each() examples
$bar now contains the following key/value pairs:
$bar now contains the following key/value pairs:
|
보통 each()는 list() 함수와 함께 배열을 탐색하는데 사용된다. 예를 들어 다음과 같이 $HTTP_POST_VARS와 같은 배열을 탐색하는데 많이 사용된다
Example 2. Traversing $HTTP_POST_VARS with each()
|
After each() has executed, the array cursor will be left on the next element of the array, or on the last element if it hits the end of the array.
See also key(), current(), reset(), next(), and prev().
end -- 배열의 내부적인(internal) pointer를 맨 마지막 원소로 옮긴다.
end(array array);
end() advances array's internal pointer to the last element.
See also: current(), end() next() and reset()
extract -- 배열의 내용을 심볼 테이블로 읽어들여 일반적인 변수로 만든다.
void extract
(array var_array, int [extract_type] , string [prefix] );
This function is used to import variables from an array into the current symbol table. It takes associative array var_array and treats keys as variable names and values as variable values. For each key/value pair it will create a variable in the current symbol table, subject to extract_type and prefix parameters.
extract() checks for colissions with existing variables. The way collisions are treated is determined by extract_type. It can be one of the following values:
If there is a collision, overwrite the existing variable.
If there is a collision, don't overwrite the existing variable.
If there is a collision, prefix the new variable with prefix.
Prefix all variables with prefix.
If extract_type is not specified, it is assumed to be EXTR_OVERWRITE.
Note that prefix is only required if extract_type is EXTR_PREFIX_SAME or EXTR_PREFIX_ALL.
extract() checks each key to see if it constitues a valid variable name, and if it does only then does it proceed to import it.
A possible use for extract is to import into symbol table variables contained in an associative array returned by wddx_deserialize().
Example 1. Extract() example
|
The above example will produce:
1 2 blue, large, sphere, medium 3 |
The $size wasn't overwritten, becaus we specified EXTR_PREFIX_SAME, which resulted in $wddx_size being created. If EXTR_SKIP was specified, then $wddx_size wouldn't even have been created. EXTR_OVERWRITE would have cause $size to have value "medium", and EXTR_PREFIX_ALL would result in new variables being named $wddx_color, $wddx_size, and $wddx_shape.
in_array -- 배열에 찾는 값이 있으면 true를 반환한다.
bool in_array
(mixed needle, array haystack);
Searches haystack for needle and returns true if it is found in the array, false otherwise.
Example 1. in_array() example
|
Note: This function was added in PHP 4.0.
key --배열(associative array)에서 내부적인(internal) pointer가 가리키고 있는 원소의 key 값을 가져온다.
mixed prev(array array);
key() returns the index element of the current array position.
int krsort
(array array);
Sorts an array by key in reverse order, maintaining key to data correlations. This is useful mainly for associative arrays.
Example 1. krsort() example
|
See also asort(), arsort(), ksort(), sort(), and rsort().
ksort -- key 순으로 배열을 정렬한다.
int ksort
(array array);
Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays.
Example 1. ksort() example
|
See also asort(), arsort(), sort(), and rsort().
list -- 변수를 배열인 것처럼 만든다.
void list(...);
Like array(), this is not really a function, but a language construct. list() is used to assign a list of variables in one operation.
Example 1. list() example
|
See also: array().
next -- 배열의 internal pointer를 하나 전진시킨다.
mixed next
(array array);
Returns the array element in the next place that's pointed by the internal array pointer, or false if there are no more elements.
next() behaves like current(), with one difference. It advances the internal array pointer one place forward before returning the element. That means it returns the next array element and advances the internal array pointer by one. If advancing the internal array pointer results in going beyond the end of the element list, next() returns false.
Warning |
If the array contains empty elements then this function will return false for these elements as well. To properly traverse an array which may contain empty elements see the each() function. |
See also: current(), end() prev() and reset()
pos -- 배열의 현재 원소를 return한다.
mixed pos(array array);
This is an alias for current().
See also: end(), next(), prev() and reset().
prev -- 배열의 internal pointer를 하나 뒤로 후진시킨다.
mixed prev(array array);
Returns the array element in the previous place that's pointed by the internal array pointer, or false if there are no more elements.
Warning |
If the array contains empty elements then this function will return false for these elements as well. To properly traverse an array which may contain empty elements see the each() function. |
prev() behaves just like next(), except it rewinds the internal array pointer one place instead of advancing it.
See also: current(), end() next() and reset()
range -- 일정 범위에 있는 정수값을 일렬로 가진 배열을 만든다.
array range
(int low, int high);
range() returns an array of integers from low to high, inclusive.
이 함수의 사용 예는 shuffle()에 나와있다.
reset -- 배열의 internal pointer를 맨 처음 원소로 설정한다.
mixed reset
(array array);
reset() rewinds array's internal pointer to the first element.
reset() returns the value of the first array element.
See also: current(), next() prev() and reset()
rsort -- 배열을 역순으로 정렬한다.
void rsort
(array array);
This function sorts an array in reverse order (highest to lowest).
Example 1. rsort() example
|
See also arsort(), asort(), ksort(), and sort().
void shuffle
(array array);
This function shuffles (randomizes the order of the elements in) an array.
Example 1. shuffle() example
|
See also arsort(), asort(), ksort(), rsort(), sort() and usort().
sizeof -- 배열의 크기를 구한다. 원소의 개수가 구해진다.
int sizeof(array array);
Returns the number of elements in the array.
See also: count()
sort -- 배열을 정렬한다.
void sort
(array array);
This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.
Example 1. sort() example
|
See also arsort(), asort(), ksort(), rsort(), and usort().
uasort -- 사용자가 지정한 비교 함수를 사용하여 정렬하고 index association을 유지한다.
void uasort
(array array, function cmp_function);
This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant. The comparison function is user-defined.
uksort -- 사용자가 지정한 비교 함수를 사용하여 key 순으로 정렬한다.
Sort an array by keys using a user-defined comparison function
void uksort
(array array, function
cmp_function);
This function will sort the keys of an array using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.
Example 1. uksort() example
|
See also arsort(), asort(), uasort(), ksort(), rsort() and sort().
usort -- 사용자가 지정한 비교 함수를 사용하여 value 순으로 정렬한다.
void usort
(array array, function
cmp_function);
This function will sort an array by its values using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. If two members compare as equal, their order in the sorted array is undefined.
Example 1. usort() example
|
Note: Obviously in this trivial case the rsort() function would be more appropriate.
Warning |
The underlying quicksort function in some C libraries (such as on Solaris systems) may cause PHP to crash if the comparison function does not return consistent values. |
See also arsort(), asort(), ksort(), rsort() and sort().
aspell() 함수들은 여러분에게 단어의 철자를 검사하고 수정사항을 조언해 준다.
이 함수들을 사용하려면 aspell 라이브러리가 필요하다. 다음 사이트에서 찾을 수 있을 것이다. : http://metalab.unc.edu/kevina/aspell/
aspell_new -- 새 사전을 읽어 온다.
int aspell_new
(string master, string
personal);
aspell_new() opens up a new dictionary and returns the dictionary link identifier for use in other aspell functions.
Example 1. aspell_new
|
aspell_check -- 단어를 검사한다.
boolean aspell_check
(int dictionary_link,
string word);
aspell_check() checks the spelling of a word and returns true if the spelling is correct, false if not.
Example 1. aspell_check
|
aspell_check-raw -- 단어의 대/소문자를 변환하지 않고, 앞뒤의 공백도 제거하지 않은 채로 검사한다.
boolean aspell_check_raw
(int dictionary_link,
string word);
aspell_check_raw() checks the spelling of a word, without changing its case or trying to trim it in any way and returns true if the spelling is correct, false if not.
Example 1. aspell_check_raw
|
aspell_suggest -- 단어의 철자를 조언해 준다.
array aspell_suggest
(int dictionary_link,
string word);
aspell_suggest() returns an array of possible spellings for the given word.
Example 1. aspell_suggest
|
PHP에는 서로 다른 날짜(달력) 형태를 변환시켜 주는 함수들을 제공한다. Julian Day Count가 기본이 된다. 이것은 BC4000년의 어느 시점을 기준으로 잡아 그곳에서부터 얼마의 날짜가 지났는지를 기준으로 삼는 것이다. 이 Julian Day Count는 일반적으로 사용하는 Julian 달력과는 다르다는 것을 알아두자. Calendar 시스템에 대해 자세히 알고 싶다면 http://genealogy.org/~scottlee/cal-overview.html를 방문하여 보라. 이 설명서중에서는 위의 페이지에서 발췌된 내용을 ""로 둘러 싸고 있다.
( 역자주 : 이 함수들은 dl/calender extension을 Load한 후에 사용가능하다. dl/README 파일을 읽어보라. )
JDToGregorian -- Julian Day Count를 Gregorian date로 변환
string jdtogregorian(int julianday);
Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year"
GregorianToJD -- Gregorian date를 Julian Day Count로 변환
int gregoriantojd(int month, int day, int year);
Valid Range for Gregorian Calendar 4714 B.C. to 9999 A.D.
Although this software can handle dates all the way back to 4714 B.C., such use may not be meaningful. The Gregorian calendar was not instituted until October 15, 1582 (or October 5, 1582 in the Julian calendar). Some countries did not accept it until much later. For example, Britain converted in 1752, The USSR in 1918 and Greece in 1923. Most European countries used the Julian calendar prior to the Gregorian.
Example 1. Calendar functions
|
JDToJulian -- Julian Day Count를 Julian Calendar date로 변환
string jdtojulian(int julianday);
Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year".
JulianToJD -- Julian Calendar date를 Julian Day Count로 변환
int juliantojd(int month, int day, int year);
Valid Range for Julian Calendar 4713 B.C. to 9999 A.D.
Although this software can handle dates all the way back to 4713 B.C., such use may not be meaningful. The calendar was created in 46 B.C., but the details did not stabilize until at least 8 A.D., and perhaps as late at the 4th century. Also, the beginning of a year varied from one culture to another - not all accepted January as the first month.
JDToJewish -- Julian Day Count를 the 유대 Calendar로 변환.
string jdtojewish(int julianday);
Converts a Julian Day Count the the Jewish Calendar.
JewishToJD -- 유대 Calendar를 Julian Day Count로 변환.
int jewishtojd(int month, int day, int year);
Valid Range Although this software can handle dates all the way back to the year 1 (3761 B.C.), such use may not be meaningful.
The Jewish calendar has been in use for several thousand years, but in the early days there was no formula to determine the start of a month. A new month was started when the new moon was first observed.
JDToFrench -- Julian Day Count를 French Republican Calendar로 변환.
string jdtofrench(int month, int day, int year);
Converts a Julian Day Count to the French Republican Calendar.
FrenchToJD -- French Republican Calendar를 Julian Day Count로 변환.
int frenchtojd(int month, int day, int year);
Converts a date from the French Republican Calendar to a Julian Day Count
These routines only convert dates in years 1 through 14 (Gregorian dates 22 September 1792 through 22 September 1806). This more than covers the period when the calendar was in use.
JDMonthName -- 월의 이름을 반환
string jdmonthname(int julianday, int mode);
Returns a string containing a month name. mode tells this function which calendar to convert the Julian Day Count to, and what type of month names are to be returned.
Table 1. Calendar modes
Mode |
Meaning |
---|---|
0 |
Gregorian - apreviated |
1 |
Gregorian |
2 |
Julian - apreviated |
3 |
Julian |
4 |
Jewish |
5 |
French Republican |
JDDayOfWeek -- 해당 날짜의 요일을 반환한다.
mixed jddayofweek(int julianday, int mode);
Returns the day of the week. Can return a string or an int depending on the mode.
Table 1. Calendar week modes
Mode |
Meaning |
---|---|
0 |
returns the day number as an int (0=sunday, 1=monday, etc) |
1 |
returns string containing the day of week (english-gregorian) |
2 |
returns a string containing the abreviated day of week (english-gregorian) |
easter_date -- 주어진 연도의 부활절의 자정에 대한 UNIX timestamp를 얻는다.
int easter_date
(int year);
Returns the UNIX timestamp corresponding to midnight on Easter of the given year. If no year is specified, the current year is assumed.
Warning: This function will generate a warning if the year is outside of the range for UNIX timestamps (i.e. before 1970 or after 2037).
Example 1. easter_date() example
|
The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.
(The code is based on a C program by Simon Kershaw, <webmaster@ely.anglican.org>)
See easter_days() for calculating Easter before 1970 or after 2037.
easter_days -- 주어진 연도의 부활절이 3월 21일로부터 며칠이 지난 것인지를 얻는다.
int easter_days
(int year);
Returns the number of days after March 21 on which Easter falls for a given year. If no year is specified, the current year is assumed.
This function can be used instead of easter_date() to calculate Easter for years which fall outside the range of UNIX timestamps (i.e. before 1970 or after 2037).
Example 1. easter_date() example
|
The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.
(The code is based on a C program by Simon Kershaw, <webmaster@ely.anglican.org>)
See also easter_date().
이 함수들은 윈도우 버전의 PHP에서만 작동한다. 이 함수들은 PHP4에서 추가되었다.
(PHP3 >= 3.0.3, PHP4 )
com_load -- ???string com_load
(string
module name [, string server name])(PHP3 >= 3.0.3, PHP4 )
com_invoke -- ???mixed com_invoke
(resource object, string function_name [, mixed function parameters, ...])(PHP3 >= 3.0.3, PHP4 )
com_propget -- ???mixed com_propget
(resource object, string property)(PHP3 >= 3.0.3, PHP4 )
com_get -- ???mixed com_get
(resource
object, string property)(PHP3 >= 3.0.3, PHP4 )
com_propput -- ???void com_propput
(resource object, string property, mixed value)(PHP3 >= 3.0.3, PHP4 )
com_propset -- ???void com_propset
(resource object, string property, mixed value)
This function is an alias for com_propput().
(PHP3 >= 3.0.3, PHP4 )
com_set -- ???void com_set
(resource
object, string property, mixed value)
This function is an alias for com_set().
(PHP4 >= 4.0RC1)
get_class_methods -- 클래스의 methods 이름을 배열로 반환한다.array get_class_methods
(string class_name)
This function returns an array of method names defined for the class specified by class_name.
(PHP4 >= 4.0RC1)
get_class_vars -- 클래스의 default properties 이름을 배열로 반환한다.Returns an array of default properties of the class
array get_class_vars
(string class_name)
This function will return an array of default properties of the class.
(PHP4 >= 4.0RC1)
get_object_vars -- 객체(object)의 properties를 배열로 반환한다.array get_class_vars
(object obj)
This function returns an array of object properties for the specified object obj.
(PHP4 >= 4.0b2)
method_exists -- 해당 클래스의 method 가 존재하는가를 검사한다.Checks if the class method exists
bool method_exists
(object object, string method_name)
This function returns true if the method given by method_name has been defined for the given object, false otherwise.
ClibPDF는 PHP에서 pdf 문서를 만들 수 있게 해 준다. 이것은 FastIO에서 구할 수 있으나 무료(free software)는 아니다. 여러분은 ClibPDF를 사용하기 전에 라이센스를 자세히 읽어봐야 할 것이다. 만약 여러분이 이 라이센스에 동의하기를 원하지 않으면 Thomas Merz의 pdflib의 사용을 고려 할 수도 있다. pdflib도 역시 강력한 기능을 가지고 있다. ClibPDF는 Thomas Merz의 pdflib와 기능이나 API가 매우 유사하지만, FastIO에 따르면 ClibPDF는 문서를 더 작은 크기로 더 빠르게 만들 수 있다고 한다. ClibPDF는 pdflib 새로운 2.0 버전에서 변화된 것 같다. 간단한 예제(pdflib 2.0의 pdfclock.c를 php 스크립트로 고친 것)에서는 실질적인 속도의 차이는 없었다. 또한 압축기능을 꺼 놓으면 두 개의 파일 크기도 비슷하다.
여기의 설면은 ClibPDF의 매뉴얼과 같이 읽는 것이 좋을 것이다. 이 매뉴얼은 라이브러리에 대한 더 자세한 설명을 하고 있다. ClibPDF의 매뉴얼의 내용을 이해여야 여러분은 PHP에서 이 라이브러리를 사용할 수 있을 것이다.
대부분의 PHP 모듈의 함수이름은 ClibPDF 고유의 함수(pdflib도 마찬가지고) 이름과 동일하다. cpdf_open() 을 제외한 모든 함수들은 첫 번째 인수로 작업할 문서의 핸들을 가지게 된다. 현재 ClibPDF가 동시에 여러개의 PDF 문서를 만들지 못하기 때문에 이 핸들은 내부적으로 아무 의미가 없다. 그러나 이를 시험하지는 말라. 어떤 결과가 나올지 알 수 없다. 더구나 멀티 쓰레드 환경에서는 중대한 오류가 생길 수도 있다. ClibPDF의 제작자에 따르면 이 내용은 다음 버전에서 수정될 것이라고 한다.(현재 버전은 1.10이다.) 여러문서를 동시에 만드는 기능이 필요하다면 pdflib module을 사용하도록 하라.
Note: PHP3 이후로 cpdf_set_font() 함수는 2byte의 아시안 폰트를 지원하도록 바뀌었다. 그리고, 이 함수의 엔코딩 파라메터는 이제 정수값이 아니고 문자열이다.
pdflib에 비해서 ClibPDF의 가장 큰 장점은 pdf 문서를 임시 파일을 사용하지 않고 메모리 상에서 만들 수 있다는 점이다. 또한 ClibPDF는 미리 정의된 유닛 길이의 좌표를 넘겨줄 수 있다. 이것은 매유 편리한 기능이지만 pdflib에서도 pdf_translate()를 사용하면 비슷한 기능을 할 수 있다.
대부분의 함수들은 사용하기 쉽다. 간단한 pdf 문서를 하나 만들어보면 별로 어렵지 않다는 것을 알 수 있을 것이다. 다음 예를 보면 쉽게 시작할 수 있다. 이것은 한 장짜리 test.pdf라는 파일을 만드는 것이다. 이 페이지에는 외곽선 30pt의 "Times-Roman" 폰트의 text가 쓰여진다. 이 text는 밑줄이 그어진다.
Example 1. Simple ClibPDF Example
|
pdflib 배포본에 보면 아나로그 시계가 포함된 여러 페이지의 문서를 만드는 조금은 복잡한 예제가 있다. 여기 그 예제를 ClibPDF 확장을 사용한 PHP로 변환한 예가 있다.
Example 2. pdfclock example from pdflib 2.0 distribution
|
(PHP4 >= 4.0b4)
cpdf_global_set_document_limits -- 모든 pdf 문서에 대한 제한을 설정한다.void cpdf_global_set_document_limits
(int maxpages, int
maxfonts, int maximages, int maxannotations, int maxobjects)
The cpdf_global_set_document_limits() function sets several document limits. This function has to be called before cpdf_open() to take effect. It sets the limits for any document open afterwards.
See also cpdf_open().
cpdf_set_creator -- pdf 문서에서 creator 필드를 설정한다.
void cpdf_set_creator
(string creator);
The cpdf_set_creator() function sets the creator of a pdf document.
See also cpdf_set_subject(), cpdf_set_title(), cpdf_set_keywords().
cpdf_set_title -- pdf 문서에서 title 필드를 설정한다.
void cpdf_set_title
(string title);
The cpdf_set_title() function sets the title of a pdf document.
See also cpdf_set_subject(), cpdf_set_creator(), cpdf_set_keywords().
cpdf_set_subject -- pdf 문서에서 subject 필드를 설정한다.
void cpdf_set_subject
(string subject);
The cpdf_set_subject() function sets the subject of a pdf document.
See also cpdf_set_title(), cpdf_set_creator(), cpdf_set_keywords().
cpdf_set_keywords -- pdf 문서에서 keywords 필드를 설정한다.
void cpdf_set_keywords
(string keywords);
The cpdf_set_keywords() function sets the keywords of a pdf document.
See also cpdf_set_title(), cpdf_set_creator(), cpdf_set_subject().
cpdf_open -- 새 pdf 문서를 연다.
int cpdf_open
(int compression, string filename);
The cpdf_open() function opens a new pdf document. The first parameter turns document compression on if it is unequal to 0. The second optional parameter sets the file in which the document is written. If it is omitted the document is created in memory and can either be written into a file with the cpdf_save_to_file() or written to standard output with cpdf_output_buffer().
Note: The return value will be needed in futher versions of ClibPDF as the first parameter in all other functions which are writing to the pdf document.
The ClibPDF library takes the filename "-" as a synonym for stdout. If PHP is compiled as an apache module this will not work because the way ClibPDF outputs to stdout does not work with apache. You can solve this problem by skipping the filename and using cpdf_output_buffer() to output the pdf document.
See also cpdf_close(), cpdf_output_buffer().
cpdf_close -- pdf 문서를 닫는다.
void cpdf_close
(int pdf document);
The cpdf_close() function closes the pdf document. This should be the last function even after cpdf_finalize(), cpdf_output_buffer() and cpdf_save_to_file().
See also cpdf_open().
cpdf_page_init -- 새 page를 시작한다.
void cpdf_page_init
(int pdf document, int page number, int orientation, double height, double width, double unit);
The cpdf_page_init() function starts a new page with height height and width width. The page has number page number and orientation orientation. orientation can be 0 for portrait and 1 for landscape. The last optional parameter unit sets the unit for the koordinate system. The value should be the number of postscript points per unit. Since one inch is equal to 72 points, a value of 72 would set the unit to one inch. The default is also 72.
See also cpdf_set_current_page().
cpdf_finalize_page -- page를 끝낸다.
void cpdf_finalize_page
(int pdf document, int page number);
The cpdf_finalize_page() function ends the page with page number page number. This function is only for saving memory. A finalized page takes less memory but cannot be modified anymore.
See also cpdf_page_init().
cpdf_finalize -- 문서를 끝낸다.
void cpdf_finalize
(int pdf document);
The cpdf_finalize() function ends the document. You still have to call cpdf_close().
See also cpdf_close().
cpdf_output_buffer -- 메모리 버퍼의 PDF 문서를 출력한다.
void cpdf_output_buffer
(int pdf document);
The cpdf_output_buffer() function outputs the pdf document to stdout. The document has to be created in memory which is the case if cpdf_open() has been called with no filename parameter.
See also cpdf_open().
cpdf_save_to_file -- PDF문서를 파일로 출력한다.
void cpdf_save_to_file
(int pdf document, string filename);
The cpdf_save_to_file() function outputs the pdf document into a file if it has been created in memory. This function is not needed if the pdf document has been open by specifying a filename as a parameter of cpdf_open().
See also cpdf_output_buffer(), cpdf_open().
cpdf_set_current_page -- 현재 page를 설정한다.
void cpdf_set_current_page
(int pdf document, int page number);
The cpdf_set_current_page() function set the page on which all operations are performed. One can switch between pages until a page is finished with cpdf_finalize_page().
See also cpdf_finalize_page().
cpdf_begin_text -- text section을 시작한다.
void cpdf_begin_text
(int pdf document);
The cpdf_begin_text() function starts a text section. It must be ended with cpdf_end_text().
Example 1. Text output <?php cpdf_begin_text($pdf); cpdf_set_font($pdf, 16, "Helvetica", 4); cpdf_text($pdf, 100, 100, "Some text"); cpdf_end_text($pdf) ?> |
See also cpdf_end_text().
cpdf_end_text -- text section을 끝낸다.
void cpdf_end_text
(int pdf document);
The cpdf_end_text() function ends a text section which was started with cpdf_begin_text().
Example 1. Text output <?php cpdf_begin_text($pdf); cpdf_set_font($pdf, 16, "Helvetica", 4); cpdf_text($pdf, 100, 100, "Some text"); cpdf_end_text($pdf) ?> |
See also cpdf_begin_text().
cpdf_show -- 현재 위치에 text를 출력한다.
void cpdf_show
(int pdf document, string text);
The cpdf_show() function outputs the string in text at the current position.
See also cpdf_text(), cpdf_begin_text(), cpdf_end_text().
cpdf_show_xy -- 지정한 위치에 text를 출력한다.
void cpdf_show_xy
(int pdf document, string text, double x-koor, double y-koor, int mode);
The cpdf_show_xy() function outputs the string text at position with coordinates (x-koor, y-koor). The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
Note: The function cpdf_show_xy() is identical to cpdf_text().
See also cpdf_text().
cpdf_text -- 지정된 파라메터대로 text를 출력한다.
void cpdf_text
(int pdf document, string text, double x-koor, double y-koor, int mode, double orientation, int alignmode);
The cpdf_text() function outputs the string text at position with coordinates (x-koor, y-koor). The optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit. The optional parameter orientation is the rotation of the text in degree. The optional parameter alignmode determines how the text is align. See the ClibPDF documentation for possible values.
See also cpdf_show_xy().
cpdf_set_font -- 현재 사용할 폰트 모양과 크기를 선택한다.
void cpdf_set_font
(int
pdf document, string font name, double size, string encoding)
The cpdf_set_font() function sets the the current font face, font size and encoding. Currently only the standard postscript fonts are supported. The last parameter encoding can take the following values: "MacRomanEncoding", "MacExpertEncoding", "WinAnsiEncoding", and "NULL". "NULL" stands for the font's built-in encoding. See the ClibPDF Manual for more information, especially how to support asian fonts.
cpdf_set_leading -- text 줄간격을 지정한다.
void cpdf_set leading
(int pdf document, double distance);
The cpdf_set_leading() function sets the distance between text lines. This will be used if text is output by cpdf_continue_text().
See also cpdf_continue_text().
cpdf_set_text_rendering -- text의 rendering 방법을 결정한다.
void cpdf_set_text_rendering
(int pdf document, int mode);
The cpdf_set_text_rendering() function determines how text is rendered. The possible values for mode are 0=fill text, 1=stroke text, 2=fill and stroke text, 3=invisible, 4=fill text and add it to cliping path, 5=stroke text and add it to clipping path, 6=fill and stroke text and add it to cliping path, 7=add it to clipping path.
cpdf_set_horiz_scaling -- text의 수평 확대값을 정한다.
void cpdf_set_horiz_scaling
(int pdf document, double scale);
The cpdf_set_horiz_scaling() function sets the horizontal scaling to scale percent.
cpdf_set_text_rise -- text를 솟아 오른 모양(rise)으로 만든다.
void cpdf_set_text_rise
(int pdf document, double value);
The cpdf_set_text_rise() function sets the text rising to value units.
cpdf_set_text_matrix -- text를 행열의 형태로 설정한다.
void cpdf_set_text_matrix
(int pdf document, array matrix);
The cpdf_set_text_matrix() function sets a matrix which describes a transformation applied on the current text font.
cpdf_set_text_pos -- text 위치를 정한다.
void cpdf_set_text_pos
(int pdf document, double x-koor, double y-koor, int mode);
The cpdf_set_text_pos() function sets the position of text for the next cpdf_show() function call. The optional parameter mode
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
See also cpdf_show(), cpdf_text().
cpdf_set_char_spacing -- 글자간의 간격을 정한다.
void cpdf_set_char_spacing
(int pdf document, double space);
The cpdf_set_char_spacing() function sets the spacing between characters.
See also cpdf_set_word_spacing(), cpdf_set_leading().
cpdf_set_word_spacing -- 단어간의 간격을 정한다.
void cpdf_set_word_spacing
(int pdf document, double space);
The cpdf_set_word_spacing() function sets the spacing between words.
See also cpdf_set_char_spacing(), cpdf_set_leading().
cpdf_continue_text -- 다음줄에 text를 출력한다.
void cpdf_continue_text
(int pdf document, string text);
The cpdf_continue_text() function outputs the string in text in the next line.
See also cpdf_show_xy(), cpdf_text(), cpdf_set_leading(), cpdf_set_text_pos().
cpdf_stringwidth -- 현재 폰트를 사용한 해당 text의 넓이를 반환한다.
double cpdf_stringwidth
(int pdf document, string text);
The cpdf_stringwidth() function returns the width of the string in text. It requires a font to be set before.
See also cpdf_set_font().
cpdf_save -- 현재의 환경을 저장한다.
void cpdf_save
(int pdf document);
The cpdf_save() function saves the current enviroment. It works like the postscript command gsave. Very useful if you want to translate or rotate an object without effecting other objects.
See also cpdf_restore().
cpdf_restore -- 이전에 저장했던 환경으로 재설정한다.
void cpdf_restore
(int pdf document);
The cpdf_restore() function restores the enviroment saved with cpdf_save(). It works like the postscript command grestore. Very useful if you want to translate or rotate an object without effecting other objects.
Example 1. Save/Restore <?php cpdf_save($pdf); // do all kinds of rotations, transformations, ... cpdf_restore($pdf) ?> |
See also cpdf_save().
cpdf_translate -- 좌표 시스템의 원점을 지정한다.
void cpdf_translate
(int pdf document, double x-koor, double y-koor, int mode);
The cpdf_translate() function set the origin of coordinate system to the point (x-koor, y-koor).
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
cpdf_scale -- 화대/축소값을 정한다.
void cpdf_scale
(int pdf document, double x-scale, double y-scale);
The cpdf_scale() function set the scaling factor in both directions.
cpdf_rotate -- 회전 정도(rotation )를 정한다.
void cpdf_rotate
(int pdf document, double angle);
The cpdf_rotate() function set the rotation in degress to angle.
cpdf_setflat -- flatness를 정한다.
void cpdf_setflat
(int pdf document, double value);
The cpdf_setflat() function set the flatness to a value between 0 and 100.
cpdf_setlinejoin -- linejoin 파라메터를 설정한다.
void cpdf_setlinejoin
(int pdf document, long value);
The cpdf_setlinejoin() function set the linejoin parameter between a value of 0 and 2. 0 = miter, 1 = round, 2 = bevel.
cpdf_setlinecap -- linecap 파라메터를 설정한다.
void cpdf_setlinecap
(int pdf document, int value);
The cpdf_setlinecap() function set the linecap parameter between a value of 0 and 2. 0 = butt end, 1 = round, 2 = projecting square.
cpdf_setmiterlimit -- miter 한계를 설정한다.
void cpdf_setmiterlimit
(int pdf document, double value);
The cpdf_setmiterlimit() function set the miter limit to a value greater or equal than 1.
cpdf_setlinewidth -- 줄의 두께를 정한다.
void cpdf_setlinewidth
(int pdf document, double width);
The cpdf_setlinewidth() function set the line width to width.
cpdf_setdash -- 선이나 점선의 형태를 정한다.
void cpdf_setdash
(int pdf document, double white, double black);
The cpdf_setdash() function set the dash pattern white white units and black black units. If both are 0 a solid line is set.
cpdf_moveto -- 현재 위치를 정한다.
void cpdf_moveto
(int pdf document, double x-koor, double y-koor, int mode);
The cpdf_moveto() function set the current point to the coordinates x-koor and y-koor.
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
cpdf_rmoveto -- 현재 위치를 정한다. (현재 위치에서 상대적인 값을 준다.)
void cpdf_rmoveto
(int pdf document, double x-koor, double y-koor, int mode);
The cpdf_rmoveto() function set the current point relative to the coordinates x-koor and y-koor.
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
See also cpdf_moveto().
cpdf_curveto -- 곡선을 그린다.
void cpdf_curveto
(int pdf document, double x1, double y1, double x2, double y2, double x3, double y3, int mode);
The cpdf_curveto() function draws a Bezier curve from the current point to the point (x3, y3) using (x1, y1) and (x2, y2) as control points.
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
See also cpdf_moveto(), cpdf_rmoveto(), cpdf_rlineto(), cpdf_lineto().
cpdf_lineto -- 직선을 그린다.
void cpdf_lineto
(int pdf document, double x-koor, double y-koor, int mode);
The cpdf_lineto() function draws a line from the current point to the point with coordinates (x-koor, y-koor).
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
See also cpdf_moveto(), cpdf_rmoveto(), cpdf_curveto().
cpdf_rlineto -- 직선을 그린다. (현재 위치에서 상대적인 위치값으로 그린다.)
void cpdf_rlineto
(int pdf document, double x-koor, double y-koor, int mode);
The cpdf_rlineto() function draws a line from the current point to the relative point with coordinates (x-koor, y-koor).
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
See also cpdf_moveto(), cpdf_rmoveto(), cpdf_curveto().
cpdf_circle -- 윈을 그린다.
void cpdf_circle
(int pdf document, double x-koor, double y-koor, double radius, int mode);
The cpdf_circle() function draws a circle with center at point (x-koor, y-koor) and radius radius.
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
See also cpdf_arc().
cpdf_arc -- 원호를 그린다.
void cpdf_arc
(int pdf document, double x-koor, double y-koor, double radius, double start, double end, int mode);
The cpdf_arc() function draws an arc with center at point (x-koor, y-koor) and radius radius, starting at angle start and ending at angle end.
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
See also cpdf_circle().
cpdf_rect -- 직사각형을 그린다.
void cpdf_rect
(int pdf document, double x-koor, double y-koor, double width, double height, int mode);
The cpdf_rect() function draws a rectangle with its lower left corner at point (x-koor, y-koor). This width is set to widgth. This height is set to height.
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
cpdf_closepath -- path를 닫는다.
void cpdf_closepath
(int pdf document);
The cpdf_closepath() function closes the current path.
cpdf_stroke -- path를 따라 선을 그린다.
void cpdf_stroke
(int pdf document);
The cpdf_stroke() function draws a line along current path.
See also cpdf_closepath(), cpdf_closepath_stroke().
cpdf_closepath_stroke -- path를 닫고 해당 path에 따라 선을 그린다.
void cpdf_closepath_stroke
(int pdf document);
The cpdf_closepath_stroke() function is a combination of cpdf_closepath() and cpdf_stroke(). Than clears the path.
See also cpdf_closepath(), cpdf_stroke().
cpdf_fill -- 현재 path의 내부를 채운다.
void cpdf_fill
(int pdf document);
The cpdf_fill() function fills the interior of the current path with the current fill color.
See also cpdf_closepath(), cpdf_stroke(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().
cpdf_fill_stroke -- 현재 path를 채우고 선을 그린다.
void cpdf_fill_stroke
(int pdf document);
The cpdf_fill_stroke() function fills the interior of the current path with the current fill color and draws current path.
See also cpdf_closepath(), cpdf_stroke(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().
cpdf_closepath_fill_stroke -- 현재 path를 닫은 후, 채우고 선을 그린다.
void cpdf_closepath_fill_stroke
(int pdf document);
The cpdf_closepath_fill_stroke() function closes, fills the interior of the current path with the current fill color and draws current path.
See also cpdf_closepath(), cpdf_stroke(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().
cpdf_clip -- 현재 path를 따낸다.(clip)
void cpdf_clip
(int pdf document);
The cpdf_clip() function clips all drawing to the current path.
cpdf_setgray_fill -- 채우는 색을 흑백값으로 정한다.
void cpdf_setgray_fill
(int pdf document, double value);
The cpdf_setgray_fill() function sets the current gray value to fill a path.
See also cpdf_setrgbcolor_fill().
cpdf_setgray_stroke -- (선이나 글자를) 그리는 색을 흑백값으로 정한다.
void cpdf_setgray_stroke
(int pdf document, double gray value);
The cpdf_setgray_stroke() function sets the current drawing color to the given gray value.
See also cpdf_setrgbcolor_stroke().
cpdf_setgray -- 채우는 색과 그리는 색의 흑백값 정도를 정한다.
void cpdf_setgray
(int pdf document, double gray value);
The cpdf_setgray_stroke() function sets the current drawing and filling color to the given gray value.
See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor_fill().
cpdf_setrgbcolor_fill -- 채우는 색을 rgb color 값으로 정한다.
void cpdf_setrgbcolor_fill
(int pdf document, double red value, double green value, double blue value);
The cpdf_setrgbcolor_fill() function sets the current rgb color value to fill a path.
See also cpdf_setrgbcolor_fill().
cpdf_setrgbcolor_stroke -- 그리는 색을 rgb color 값으로 정한다.
void cpdf_setrgbcolor_stroke
(int pdf document, double red value, double green value, double blue value);
The cpdf_setrgbcolor_stroke() function sets the current drawing color to the given rgb color value.
See also cpdf_setrgbcolor_stroke().
cpdf_setrgbcolor -- 채우는 색과 그리는 색의 rgb color 값을 정한다.
void cpdf_setrgbcolor
(int pdf document, double red value, double green value, double blue value);
The cpdf_setrgbcolor_stroke() function sets the current drawing and filling color to the given rgb color value.
See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor_fill().
cpdf_add_outline -- 현재 page에 bookmark를 추가한다.
void cpdf_add_outline
(int pdf document, string text);
The cpdf_add_outline() function adds a bookmark with text text that points to the current page.
Example 1. Adding a page outline <?php $cpdf = cpdf_open(0); cpdf_page_init($cpdf, 1, 0, 595, 842); cpdf_add_outline($cpdf, 0, 0, 0, 1, "Page 1"); // ... // some drawing // ... cpdf_finalize($cpdf); Header("Content-type: application/pdf"); cpdf_output_buffer($cpdf); cpdf_close($cpdf); ?> |
cpdf_set_page_animation -- page간에 넘어가는 방법을 정한다.
void cpdf_set_page_animation
(int pdf document, int transition, double duration);
The cpdf_set_page_animation() function set the transition between following pages.
The value of transition can be
0 for none, |
1 for two lines sweeping across the screen reveal the page, |
2 for multiple lines sweeping across the screen reveal the page, |
3 for a box reveals the page, |
4 for a single line sweeping across the screen reveals the page, |
5 for the old page dissolves to reveal the page, |
6 for the dissolve effect moves from one screen edge to another, |
7 for the old page is simply replaced by the new page (default) |
The value of duration is the number of seconds between page flipping.
cpdf_import_jpeg -- JPEG 이미지를 연다.
int cpdf_open_jpeg
(int pdf document, string file name, double x-koor, double y-koor, double angle, double width, double height,
double x-scale, double y-scale, int mode);
The cpdf_import_jpeg() function opens an image stored in the file with the name file name. The format of the image has to be jpeg. The image is placed on the current page at position (x-koor, y-koor). The image is rotated by angle degres.
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
See also cpdf_place_inline_image(),
cpdf_place_inline_image -- 이미지를 해당 페이지에 위치시킨다.
void cpdf_place_inline_image
(int pdf document, int image, double x-koor, double y-koor, double angle, double width, double height, int
mode);
The cpdf_place_inline_image() function places an image created with the php image functions on the page at postion (x-koor, y-koor). The image can be scaled at the same time.
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
See also cpdf_import_jpeg()
cpdf_add_annotation -- 주석(annotation)을 단다.
void cpdf_add_annotation
(int pdf document, double llx, double lly, double urx, double ury, string title, string content, int mode);
The cpdf_add_annotation() adds a note with the lower left corner at (llx, lly) and the upper right corner at (urx, ury).
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
이 함수들은 PHP를 컴파일할 때 --with-cybercash=[DIR] 옵션을 주고 컴파일한 경우에만 사용가능하다. 이 함수들은 PHP4에 추가되었다.
(PHP4 >= 4.0b4)
cybercash_encr -- ???array cybercash_encr
(string wmk, string sk, string inbuff)
The function returns an associative array with the elements "errcode" and, if "errcode" is false, "outbuff" (string), "outLth" (long) and "macbuff" (string).
(PHP4 >= 4.0b4)
cybercash_decr -- ???array cybercash_decr
(string wmk, string sk, string inbuff)
The function returns an associative array with the elements "errcode" and, if "errcode" is false, "outbuff" (string), "outLth" (long) and "macbuff" (string).
(PHP4 >= 4.0b4)
cybercash_base64_encode -- ???string cybercash_base64_encode
(string inbuff)(PHP4 >= 4.0b4)
cybercash_base64_decode --string cybercash_base64_decode
(string inbuff)이 함수들은 GNOME xml 라이브러리를 사용하고, PHP를 설정할 때 --with-dom=[DIR] 옵션을 주었을 경우에만 사용가능하다. 이 함수들은 PHP4에 추가되었다.
이 모듈은 다음과 같은 상수들을 미리 정의해 놓고 있다.
Table 1. XML constants
Constant | Value | Description |
---|---|---|
XML_ELEMENT_NODE | 1 | |
XML_ATTRIBUTE_NODE | 2 | |
XML_TEXT_NODE | 3 | |
XML_CDATA_SECTION_NODE | 4 | |
XML_ENTITY_REF_NODE | 5 | |
XML_ENTITY_NODE | 6 | |
XML_PI_NODE | 7 | |
XML_COMMENT_NODE | 8 | |
XML_DOCUMENT_NODE | 9 | |
XML_DOCUMENT_TYPE_NODE | 10 | |
XML_DOCUMENT_FRAG_NODE | 11 | |
XML_NOTATION_NODE | 12 | |
XML_GLOBAL_NAMESPACE | 1 | |
XML_LOCAL_NAMESPACE | 2 |
This module defines a number of classes. The DOM XML functions return a parsed tree of the XML document with each node being an object belonging to one of these classes.
(PHP4 >= 4.0b4)
xmldoc -- XML 문서로부터 DOM 객체를 만들어낸다.object xmldoc
(string
str)
The function parses the XML document in str and returns an object of class "Dom document", having the properties "doc" (resource), "version" (string) and "type" (long).
(PHP4 >= 4.0b4)
xmldocfile -- XML 파일로부터 DOM 객체를 만들어낸다.object xmldocfile
(string filename)
The function parses the XML document in the file named filename and returns an object of class "Dom document", having the properties "doc" (resource), "version" (string).
(PHP4 >= 4.0b4)
xmltree -- XML 문서로부터 PHP 객체들의 tree를 만들어낸다.object xmltree
(string
str)
The function parses the XML document in str and returns a tree PHP objects as the parsed document.
이 모듈은 gzip(.gz)으로 압축된 파일을 투명하게(압축되지 않은 것처럼) 읽고 쓰기 위해 Jean-loup Gailly와 Mark Adler에 의한 zlib >= 1.0.9 (http://www.cdrom.com/pub/infozip/zlib/) 함수들을 사용한다.
이 모듈은 (socket을 제외한) 대부분의 파일관리(filesystem)함수에 gzip-압축과 압축해제 기능을 더한 내용의 함수들을 제공한다.
임시파일을 열어 문자열을 쓴 후에, 그 파일에 있는 내용을 다른 방법으로 두 번 출력하는 예제이다.
Example 1. Small Zlib example
|
gzclose -- gz-file pointer를 닫는다.
int gzclose(int zp);
The gz-file pointed to by zp is closed.
Returns true on success and false on failure.
The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().
gzeof -- gz-file pointer가 end-of-file에 있는가 검사한다.
int gzeof(int zp);
Returns true if the gz-file pointer is at EOF or an error occurs; otherwise returns false.
The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().
gzfile -- gz-file의 내용을 배열로 읽는다.
array gzfile(string filename);
Identical to readgzfile(), except that gzfile() returns the file in an array.
See also readgzfile(), and gzopen().
gzgetc -- gz-file pointer에서 한 문자를 읽는다.
string gzgetc(int zp);
Returns a string containing a single (uncompressed) character read from the file pointed to by zp. Returns FALSE on EOF (as does gzeof()).
The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().
See also gzopen(), and gzgets().
gzgets -- gz-file pointer에서 한 줄을 읽는다.
string gzgets(int zp, int length);
Returns a (uncompressed) string of up to length - 1 bytes read from the file pointed to by fp. Reading ends when length - 1 bytes have been read, on a newline, or on EOF (whichever comes first).
If an error occurs, returns false.
The file pointer must be valid, and must point to a file successfully opened by gzopen().
See also gzopen(), and gzgetc().
gzgetss -- gz-file pointer에서 한 줄을 읽어 HTML tag들을 strip한다.
string gzgetss(int zp, int length);
Identical to gzgets(), except that gzgetss attempts to strip any HTML and PHP tags from the text it reads.
See also gzgets(), and gzopen().
gzopen -- gz-file을 연다.
int gzopen(string filename, string mode);
Opens a gzip (.gz) file for reading or writing. The mode parameter is as in fopen() ("rb" or "wb") but can also include a compression level ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman only compression as in "wb1h". (See the description of deflateInit2 in zlib.h for more information about the strategy parameter.)
Gzopen can be used to read a file which is not in gzip format; in this case gzread will directly read from the file without decompression.
Gzopen returns a file pointer to the file opened, after that, everything you read from this file descriptor will be transparently decompressed and what you write gets compressed.
If the open fails, the function returns false.
Example 1. gzopen() example $fp = gzopen("/tmp/file.gz", "r"); |
See also gzclose().
gzpassthru -- gz-file pointer에서부터 뒤에 남아있는 모든 데이타를 출력(output)한다.
int gzpassthru(int zp);
Reads to EOF on the given gz-file pointer and writes the (uncompressed) results to standard output.
If an error occurs, returns false.
The file pointer must be valid, and must point to a file successfully opened by gzopen().
The gz-file is closed when gzpassthru() is done reading it (leaving zp useless).
gzputs -- gz-file pointer에 쓴다.
int gzputs
(int zp, string str, int [length]);
gzputs() is an alias to gzwrite(), and is identical in every way.
gzread -- gz-file에서 이진 데이타로 읽는다.
string gzread(int zp, int length);
gzread() reads up to length bytes from the gz-file pointer referenced by zp. Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first.
// 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 );
See also gzwrite(), gzopen(), gzgets(), gzgetss(), gzfile(), and gzpassthru().
gzrewind -- gz-file pointer의 위치를 맨 앞으로 가져간다.
int gzrewind(int zp);
Sets the file position indicator for zp to the beginning of the file stream.
If an error occurs, returns 0.
The file pointer must be valid, and must point to a file successfully opened by gzopen().
See also gzseek() and gztell().
gzseek -- gz-file pointer를 옮긴다.
int gzseek(int zp, int offset);
Sets the file position indicator for the file referenced by zp to offset bytes into the file stream. Equivalent to calling (in C) gzseek( zp, offset, SEEK_SET ).
If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; gzseek then compresses a sequence of zeroes up to the new starting position.
Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.
See also gztell() and gzrewind().
gztell -- gz-file pointer의 읽고, 쓸 위치를 반환한다.
int gztell(int zp);
Returns the position of the file pointer referenced by zp; i.e., its offset into the file stream.
If an error occurs, returns false.
The file pointer must be valid, and must point to a file successfully opened by gzopen().
See also gzopen(), gzseek() and gzrewind().
gzwrite -- gz-file에 이진 데이타를 쓴다.
int gzwrite
(int zp, string string, int [length]);
gzwrite() writes the contents of string to the gz-file stream pointed to by zp. If the length argument is given, writing will stop after length (uncompressed) bytes have been written or the end of string is reached, whichever comes first.
Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.
See also gzread(), gzopen(), and gzputs().
readgzfile -- gz-file을 출력(output)한다.
int readgzfile(string filename);
Reads a file, decompresses it and writes it to standard output.
Readgzfile() can be used to read a file which is not in gzip format; in this case readgzfile() will directly read from the file without decompression.
Returns the number of (uncompressed) bytes read from the file. If an error occurs, false is returned and unless the function was called as @readgzfile, an error message is printed.
The file filename will be opened from the filesystem and its contents written to standard output.
See also gzpassthru(), gzfile(), and gzopen().
string gzcompress
(string data [, int level])
This function returns a gzip-compressed version of the input data or false on errors. The optional parameter level can be given as 0 for no compression up to 9 for maximum compression.
See also gzuncompress().
string gzcompress
(string data [, int length])
This function takes data compressed by gzcompress() and returns the orignial uncompressed data or false on error. The function will return an error if the uncompressed data is more than 256 times the lenght of the compressed input data or more than the optional parameter length.
See also gzcompress().
이 함수들은 Berkeley DB 형태의 데이터베이스를 접근하기 위한 것이다.
이것은 여러 file-based 데이터베이스의 일반적인 abstraction layer이다. 기능적으로 이것은 Sleepycat Software's DB2 같은 현대적인 데이터베이스 기능의 부분 집합(subset)이 된다. (IBM의 DB2와 혼돈하지 말기 바란다. IBM의 DB2는 ODBC를 통해 지원된다.)
기초가 되는 데이터베이스의 구현에 따라 얼마나 다양하게 사용될 수 있는가가 결정된다. dba_optimize()나 dba_sync() 같은 함수는 단지 한 데이터베이스에 대해 작동되고 다른 데이터베이스에 대해서는 아무 영향을 미치지 못한다.
다음과 같은 handler를 지원한다. :
dbm은 가장 오래된(original) 형태의 Berkeley DB style 데이터베이스이다. 가능하면 이것은 사용하지 않는 것이 좋다. 우리는 DB2에 사용된 함수들과의 호환성을 제공하지 않는다. 왜냐하면 DB2는 dbm과 단지 소스 레벨에서만 서로 호환성이 있기 때문에, original dbm 형태(format)를 직접 다룰 수 없기 때문이다.
ndbm은 좀더 새로운 형태로 dbm에 비해 훨씬 유연하다. 그러나 이것 역시 dbm이 가진 여러 가지 한계(arbitrary limit)를 그대로 가지고 있다.
gdbm은 GNU database manager이다. 이것은 dbm과 gdbm에 대하여 호환성이 있다.
db2는 Sleepycat Software's DB2이다. 이것은 보통 다음과 같이 설명된다. : "standalone과 client/server 어플리케이션을 동시에 지원하는 고성능의 내장 데이터베이스를 제공해주는 프로그램 toolkit이다."("a programmatic toolkit that provides high-performance built-in database support for both standalone and client/server applications.")
cdb는 "내용이 변하지 않는(constant) 데이터베이스를 만들고 읽어 들이는데 빠르고, 믿음직하며, 경량인 패키지"이다. 이것은 qmail의 제작자가 제공하고 있고, http://pobox.com/~djb/cdb.html에서 찾을 수 있다. 이 데이터베이스는 내용이 변하지 않는 데이터 베이스이므로, 읽기 동작만 지원한다.
Example 1. DBA example
|
DBA는 binary safe하고 어떤 어떤 arbitrary limit도 가지고 있지 않다. 이것의 제한은 기초가 되는 데이터베이스 구현에 따른 한계에서 온 것이다.
모든 파일 기반(file-based) 데이터베이스는 새로 만들어진 데이터베이스에 대하여 파일 모드를 지정하는 방법을 제공해야 한다. 일반적으로 파일 모드는 dba_open()이나 dba_popen()의 네 번째 인수로 전달하게 된다.
여러분은 dba_firstkey()과 dba_nextkey()함수를 사용하여 전체 데이터를 순차적으로 접근할 수 있다. 그리고, 데이터베이스를 탐색하는 동안은 데이터베이스의 내용을 바꿀 수 없다.
Example 2. Traversing a database
|
dba_close -- 데이터베이스를 닫는다.
void dba_close
(int handle);
dba_close() closes the established database and frees all resources specified by handle.
handle is a database handle returned by dba_open().
dba_close() does not return any value.
See also: dba_open() dba_popen()
dba_delete -- 지정된 key값을 가지는 entry를 지운다.
string dba_delete
(string key, int handle);
dba_delete() deletes the entry specified by key from the database specified with handle.
key is the key of the entry which is deleted.
handle is a database handle returned by dba_open().
dba_delete() returns true or false, if the entry is deleted or not deleted, respectively.
See also: dba_exists() dba_fetch() dba_insert() dba_replace()
dba_exists -- 지정된 key가 있는가 검사한다.
bool dba_exists
(string key, int handle);
dba_exists() checks whether the specified key exists in the database specified by handle.
key is the key the check is performed for.
handle is a database handle returned by dba_open().
dba_exists() returns true or false, if the key is found or not found, respectively.
See also: dba_fetch() dba_delete() dba_insert() dba_replace()
dba_fetch -- 지정된 key값의 data를 가져온다.
string dba_fetch
(string key, int handle);
dba_fetch() fetches the data specified by key from the database specified with handle.
key is the key the data is specified by.
handle is a database handle returned by dba_open().
dba_fetch() returns the associated string or false, if the key/data pair is found or not found, respectively.
See also: dba_exists() dba_delete() dba_insert() dba_replace()
dba_firstkey -- 첫 번째 key의 값을 가져온다.
string dba_firstkey
(int handle);
dba_firstkey() returns the first key of the database specified by handle and resets the internal key pointer. This permits a linear search through the whole database.
handle is a database handle returned by dba_open().
dba_firstkey() returns the key or false depending on whether it succeeds or fails, respectively.
See also: dba_nextkey()
dba_insert -- entry를 삽입한다.
bool dba_insert
(string key, string value, int handle);
dba_insert() inserts the entry described with key and value into the database specified by handle. It fails, if an entry with the same key already exists.
key is the key of the entry to be inserted.
value is the value to be inserted.
handle is a database handle returned by dba_open().
dba_insert() returns true or false, depending on whether it succeeds of fails, respectively.
See also: dba_exists() dba_delete() dba_fetch() dba_replace()
dba_nextkey -- 다음 key값을 가져온다.
string dba_nextkey
(int handle);
dba_nextkey() returns the next key of the database specified by handle and increments the internal key pointer.
handle is a database handle returned by dba_open().
dba_nextkey() returns the key or false depending on whether it succeeds or fails, respectively.
See also: dba_firstkey()
dba_popen -- 데이터베이스를 영구적으로 연다.
int dba_popen
(string path, string mode, string handler, [...]);
dba_popen() establishes a persistent database instance for path with mode using handler.
path is commonly a regular path in your filesystem.
mode is "r" for read access, "w" for read/write access to an already existing database, "c" for read/write access and database creation if it doesn't currently exist, and "n" for create, truncate and read/write access.
handler is the name of the handler which shall be used for accessing path. It is passed all optional parameters given to dba_popen() and can act on behalf of them.
dba_popen() returns a positive handler id or false, in the case the open is successful or fails, respectively.
See also: dba_open() dba_close()
dba_open -- 데이터베이스를 연다.
int dba_open
(string path, string mode, string handler, [...]);
dba_open() establishes a database instance for path with mode using handler.
path is commonly a regular path in your filesystem.
mode is "r" for read access, "w" for read/write access to an already existing database, "c" for read/write access and database creation if it doesn't currently exist, and "n" for create, truncate and read/write access.
handler is the name of the handler which shall be used for accessing path. It is passed all optional parameters given to dba_open() and can act on behalf of them.
dba_open() returns a positive handler id or false, in the case the open is successful or fails, respectively.
See also: dba_popen() dba_close()
dba_optimize -- 데이터베이스를 최적화(Optimize)한다.
bool dba_optimize
(int handle);
dba_optimize() optimizes the underlying database specified by handle.
handle is a database handle returned by dba_open().
dba_optimize() returns true or false, if the optimization succeeds or fails, respectively.
See also: dba_sync()
dba_replace -- entry를 대치(replace)하거나 삽입한다.
bool dba_replace
(string key, string value, int handle);
dba_replace() replaces or inserts the entry described with key and value into the database specified by handle.
key is the key of the entry to be inserted.
value is the value to be inserted.
handle is a database handle returned by dba_open().
dba_replace() returns true or false, depending on whether it succeeds of fails, respectively.
See also: dba_exists() dba_delete() dba_fetch() dba_insert()
dba_sync -- 데이터베이스를 동기화(Synchronize)한다.
bool dba_sync
(int handle);
dba_sync() synchronizes the database specified by handle. This will probably trigger a physical write to disk, if supported.
handle is a database handle returned by dba_open().
dba_sync() returns true or false, if the synchronization succeeds or fails, respectively.
See also: dba_optimize()
checkdate -- date/time값이 올바른가 검사한다.
int checkdate(int month, int day, int year);
Returns true if the date given is valid; otherwise returns false. Checks the validity of the date formed by the arguments. A date is considered valid if:
year is between 1900 and 32767 inclusive
month is between 1 and 12 inclusive
day is within the allowed number of days for the given month. Leap years are taken into consideration.
date -- local time을 지정된 형태로 만들어 반환한다.
string date(string format, int timestamp);
Returns a string formatted according to the given format string using the given timestamp or the current local time if no timestamp is given.
The following characters are recognized in the format string:
a - "am" or "pm"
A - "AM" or "PM"
d - day of the month, numeric, 2 digits (with leading zeros)
D - day of the week, textual, 3 letters; i.e. "Fri"
F - month, textual, long; i.e. "January"
h - hour, numeric, 12 hour format
H - hour, numeric, 24 hour format
i - minutes, numeric
j - day of the month, numeric, without leading zeros
l (lowercase 'L') - day of the week, textual, long; i.e. "Friday"
m - month, numeric
M - month, textual, 3 letters; i.e. "Jan"
s - seconds, numeric
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
Y - year, numeric, 4 digits
w - day of the week, numeric, 0 represents Sunday
y - year, numeric, 2 digits
z - day of the year, numeric; i.e. "299"
Example 1. Date() example
|
It is possible to use date() and mktime() together to find dates in the future or the past.
Example 2. Date() and mktime() example
|
To format dates in other languages, you should use the setlocale() and strftime() functions.
See also gmdate() and mktime().
getdate -- date/time 정보를 얻는다.
array getdate(int timestamp);
Returns an associative array containing the date information of the timestamp as the following array elements:
"seconds" - seconds
"minutes" - minutes
"hours" - hours
"mday" - day of the month
"wday" - day of the week, numeric
"mon" - month, numeric
"year" - year, numeric
"yday" - day of the year, numeric; i.e. "299"
"weekday" - day of the week, textual, full; i.e. "Friday"
"month" - month, textual, full; i.e. "January"
gettimeofday -- 현재 시각을 얻는다.
array gettimeofday
(void);
This is an interface to gettimeofday(2). It returns an associative array containing the data returned from the system call.
"sec" - seconds
"usec" - microseconds
"minuteswest" - minutes west of Greenwich
"dsttime" - type of dst correction
gmdate -- GMT/CUT date/time을 지정된 형태로 만들어 반환한다.
string gmdate(string format, int timestamp);
Identical to the date() function except that the time returned is Greenwich Mean Time (GMT). For example, when run in Finland (GMT +0200), the first line below prints "Jan 01 1998 00:00:00", while the second prints "Dec 31 1997 22:00:00".
Example 1. Gmdate() example
|
See also date(), mktime() and gmmktime().
gmmktime -- GMT 날짜를 가지고 timestamp를 만든다.
int gmmktime(int hour, int minute, int second, int month, int day, int year);
Identical to mktime() except the passed parameters represents a GMT date.
gmstrftime -- GMT/CUT time/date를 locale 설정에 따른 형태로 만들어 반환한다.
string gmstrftime
(string format, int timestamp);
Behaves the same as strftime() except that the time returned is Greenwich Mean Time (GMT). For example, when run in Eastern Standard Time (GMT -0500), the first line below prints "Dec 31 1998 20:00:00", while the second prints "Jan 01 1999 01:00:00".
Example 1. Gmstrftime() example
|
See also strftime().
(PHP4 >= 4.0RC2)
localtime -- 현재 지역의 시간을 얻는다.array localtime
([int
timestamp [, bool is_associative]])
The localtime() function returns an array identical to that of the structure returned by the C function call. The first argument to localtime() is the timestamp, if this is not given the current time is used. The second argument to the localtime() is the is_associative, if this is set to 0 or not supplied than the array is returned as a regular, numerically indexed array. If the argument is set to 1 then localtime() is an associative array containing all the different elements of the structure returned by the C function call to localtime. The names of the different keys of the associative array are as follows:
"tm_sec" - seconds
"tm_min" - minutes
"tm_hour" - hour
"tm_mday" - day of the month
"tm_mon" - month of the year
"tm_year" - Year, not y2k compliant
"tm_wday" - Day of the week
"tm_yday" - Day of the year
"tm_isdst" - Is daylight savings time in effect
microtime -- 현재 시각의 timestamp를 1000분의 1초 단위까지 반환한다.
string microtime(void);
Returns the string "msec sec" where sec is the current time measured in the number of seconds since the Unix Epoch (0:00:00 January 1, 1970 GMT), and msec is the microseconds part. This function is only available on operating systems that support the gettimeofday() system call.
See also time().
mktime -- 지정된 날짜를 date()함수 등이 사용하는 timestamp로 만든다.
int mktime
(int hour,
int minute, int second, int month, int day, int year [, int is_dst])
Warning: Note the strange order of arguments, which differs from the order of arguments in a regular UNIX mktime() call and which does not lend itself well to leaving out parameters from right to left (see below). It is a common error to mix these values up in a script.
Returns the Unix timestamp corresponding to the arguments given. This timestamp is a long integer containing the number of seconds between the Unix Epoch (January 1 1970) and the time specified.
Arguments may be left out in order from right to left; any arguments thus omitted will be set to the current value according to the local date and time.
Is_dst can be set to 1 if the time is during daylight savings time, 0 if it is not, or -1 (the default) if it is unknown whether the time is within daylight savings time or not.
Note: Is_dst was added in 3.0.10.
Mktime() is useful for doing date arithmetic and validation, as it will automatically calculate the correct value for out-of-range input. For example, each of the following lines produces the string "Jan-01-1998".
Example 1. Mktime() example
|
The last day of any given month can be expressed as the "0" day of the next month, not the -1 day. Both of the following examples will produce the string "The last day in Feb 2000 is: 29".
Example 2. Last day of next month
|
( 역자주 : 다음과 같이 date() 함수를 같이 사용하면 과거나 미래의 특정일을 알 수 있다.
$tomorrow = mktime(0,0,0,date("d")+1,date("m"), date("Y"));
$lastmonth = mktime(0,0,0,date("d"),date("m")-1,date("Y"));
$nextyear = mktime(0,0,0,date("d"),date("m"),date("Y")+1); )
strftime -- 현재 시간/날짜를 지정한 형태로 변환한다.
string strftime
(string format, int timestamp);
Returns a string formatted according to the given format string using the given timestamp or the current local time if no timestamp is given. Month and weekday names and other language dependent strings respect the current locale set with setlocale().
The following conversion specifiers are recognized in the format string:
%a - abbreviated weekday name according to the current locale
%A - full weekday name according to the current locale
%b - abbreviated month name according to the current locale
%B - full month name according to the current locale
%c - preferred date and time representation for the current locale
%d - day of the month as a decimal number (range 0 to 31)
%H - hour as a decimal number using a 24-hour clock (range 00 to 23)
%I - hour as a decimal number using a 12-hour clock (range 01 to 12)
%j - day of the year as a decimal number (range 001 to 366)
%m - month as a decimal number (range 1 to 12)
%M - minute as a decimal number
%p - either `am' or `pm' according to the given time value, or the corresponding strings for the current locale
%S - second as a decimal number
%U - week number of the current year as a decimal number, starting with the first Sunday as the first day of the first week
%W - week number of the current year as a decimal number, starting with the first Monday as the first day of the first week
%w - day of the week as a decimal, Sunday being 0
%x - preferred date representation for the current locale without the time
%X - preferred time representation for the current locale without the date
%y - year as a decimal number without a century (range 00 to 99)
%Y - year as a decimal number including the century
%Z - time zone or name or abbreviation
%% - a literal `%' character
Example 1. Strftime() example
|
This example works if you have the respective locales installed in your system.
See also setlocale() and mktime() and the Open Group specification of strftime() .
time -- 현재 시각의 timestamp를 반환한다.
int time(void);
Returns the current time measured in the number of seconds since the Unix Epoch (January 1, 1970).
See also date().
(PHP3 >= 3.0.12, PHP4 >= 4.0b2)
strtotime -- 가능한 여러 형태의 영문 날짜/시간을 표시하는 문자열을 분석하여 UNIX timestamp로 만든다.int strtotime
(string
time [, int now])
The function expects to be given a string containing an english date format and will try to parse that format into a UNIX timestamp.
Example 1. Strtotime() example
|
이 함수들은 dBase 형태의 databse(dbf)에 저장된 레코드들을 접근할 수 있게 해 준다.
index와 memo 필드는 지원하지 않는다. 또한 locking도 지원하지 않는다. 두 개의 웹서버 프로세스가 동시에 같은 dBase 파일을 수정하려 한다면, database 자체가 망가질 수도 있다.
SQL 데이터베이스와 다르게 dBase 데이터베이스는 생성후에 그 구조를 바꿀 수 없다. 한 파일이 생성되면 해당 데이터베이스의 선언은 고정된다. 속도 향상 등을 위해 사용하는 index도 지원하지 않는다. dBase는 고정된 길이의 레코드를 가진 단순한 순차 파일이다. 새레코드는 파일의 맨 뒤에 붙고, 삭제된 레코드는 dbase_pack()이 수행되기 전에는 데이터 자체는 유지된다.
우리는 dBase 파일은 사용하지 말기를 권한다. 대신 진짜 SQL 서버를 사용하기를 권한다. MySQL이나 PostgreSQL이 PHP와 같이 많ㅇ 사용된다. dBase 지원은 단지 여러분이 사용하는 데이터베이스에 데이터를 읽어들이거나 내보낼 때만 사용하는 것이 좋다. dBase 포맷은 대부분의 Windows용 프로그램이 사용가능한 데이터 포맷이기 때문이다.
dbase_create -- dBase database를 생성한다.
int dbase_create(string filename, array fields);
The fields parameter is an array of arrays, each array describing the format of one field in the database. Each field consists of a name, a character indicating the field type, a length, and a precision.
The types of fields available are:
L - Boolean. These do not have a length or precision.
M - Memo. (Note that these aren't supported by PHP.) These do not have a length or precision.
D - Date (stored as YYYYMMDD). These do not have a length or precision.
N - Number. These have both a length and a precision (the number of digits after the decimal point).
C - String.
If the database is successfully created, a dbase_identifier is returned, otherwise false is returned.
Example 1. Creating a dBase database file // "database" name $dbname = "/tmp/test.dbf"; // database "definition" $def = array( array("date", "D"), array("name", "C", 50), array("age", "N", 3, 0), array("email", "C", 128), array("ismember", "L") ); // creation if (!dbase_create($dbname, $def)) print "<strong>Error!</strong>"; |
dbase_open -- dBase database를 연다.
int dbase_open(string filename, int flags);
The flags correspond to those for the open() system call. (Typically 0 means read-only, 1 means write-only, and 2 means read and write.)
Returns a dbase_identifier for the opened database, or false if the database couldn't be opened.
dbase_close -- dBase database를 닫는다.
bool dbase_close(int dbase_identifier);
Closes the database associated with dbase_identifier.
dbase_pack -- dBase database를 pack한다.
bool dbase_pack(int dbase_identifier);
Packs the specified database (permanently deleting all records marked for deletion using dbase_delete_record().
dbase_add_record -- dBase database에 한 record를 더한다.
bool dbase_add_record(int dbase_identifier, array record);
Adds the data in the record to the database. If the number of items in the supplied record isn't equal to the number of fields in the database, the operation will fail and false will be returned.
dbase_replace_record -- dBase database의 한 레코드의 내용을 바꾼다.
bool dbase_replace_record
(int dbase_identifier, array record, int dbase_record_number);
Replaces the data associated with the record record_number with the data in the record in the database. If the number of items in the supplied record is not equal to the number of fields in the database, the operation will fail and false will be returned.
dbase_record_number is an integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).
dbase_delete_record -- dBase database에서 한 record를 삭제한다
bool dbase_delete_record(int dbase_identifier, int record);
Marks record to be deleted from the database. To actually remove the record from the database, you must also call dbase_pack().
dbase_get_record -- dBase database에서 한 record를 읽어온다.
array dbase_get_record(int dbase_identifier, int record);
Returns the data from record in an array. The array is indexed starting at 0, and includes an associative member named 'deleted' which is set to 1 if the record has been marked for deletion (see dbase_delete_record().
Each field is converted to the appropriate PHP type. (Dates are left as strings.)
(PHP3 >= 3.0.4, PHP4 )
dbase_get_record_with_names -- dBase database에서 한 record를 associative 배열로 읽어온다.array dbase_get_record_with_names
(int dbase_identifier, int
record)
Returns the data from record in an associative array. The array also includes an associative member named 'deleted' which is set to 1 if the record has been marked for deletion (see dbase_delete_record()).
Each field is converted to the appropriate PHP type. (Dates are left as strings.)
dbase_numfields -- dBase database의 field의 개수를 구한다.
int dbase_numfields(int dbase_identifier);
Returns the number of fields (columns) in the specified database. Field numbers are between 0 and dbase_numfields($db)-1, while record numbers are between 1 and dbase_numrecords($db).
Example 1. Using dbase_numfields()
|
dbase_numrecords -- fdBase database의 record의 개수를 구한다.
int dbase_numrecords(int dbase_identifier);
Returns the number of records (rows) in the specified database. Record numbers are between 1 and dbase_numrecords($db), while field numbers are between 0 and dbase_numfields($db)-1.
이 함수들은 dbm 형태의 databse(dbf)에 저장된 레코드들을 접근할 수 있게 해 준다. 이 형태의 database는 Berkeley db, gdbm 등과 내장된 flatfile 라이브러리 같은 일부 system 라이브러리 등이 지원하는데, 일반적인 relational databases와 달리 key/value의 쌍으로 data를 저장한다.
Example 1. dbm example
|
dbmopen -- dbm database를 연다.
int dbmopen(string filename, int flags);
The first argument is the full-path filename of the dbm file to be opened and the second is the file open mode which is one of "r", "n", "c" or "w" for read-only, new (implies read-write, and most likely will truncate an already-existing database of the same name), create (implies read-write, and will not truncate an already-existing database of the same name) and read-write respectively.
Returns an identifer to be passed to the other dbm functions on success, or false on failure.
If ndbm support is used, ndbm will actually create filename.dir and filename.pag files. gdbm only uses one file, as does the internal flat-file support, and Berkeley db creates a filename.db file. Note that PHP does its own file locking in addition to any file locking that may be done by the dbm library itself. PHP does not delete the .lck files it creates. It uses these files simply as fixed inodes on which to do the file locking. For more information on dbm files, see your Unix man pages, or obtain GNU's gdbm.
dbmclose -- dbm database를 닫는다.
bool dbmclose(int dbm_identifier);
Unlocks and closes the specified database.
dbmexists -- dbm database에 주어진 key에 해당하는 값이 있는지 알아본다.
bool dbmexists(int dbm_identifier, string key);
Returns true if there is a value associated with the key.
dbmfetch -- dbm database에서 주어진 key의 value를 읽어온다.
string dbmfetch(int dbm_identifier, string key);
Returns the value associated with key.
dbminsert -- dbm database에 key의 value를 삽입한다.
int dbminsert(int dbm_identifier, string key, string value);
Adds the value to the database with the specified key.
Returns -1 if the database was opened read-only, 0 if the insert was successful, and 1 if the specified key already exists. (To replace the value, use dbmreplace().)
dbmreplace -- dbm database에서 key의 value를 바꾼다.
bool dbmreplace(int dbm_identifier, string key, string value);
Replaces the value for the specified key in the database.
This will also add the key to the database if it didn't already exist.
dbmdelete -- dbm database에서 key의 value를 삭제한다.
bool dbmdelete(int dbm_identifier, string key);
Deletes the value for key in the database.
Returns false if the key didn't exist in the database.
dbmfirstkey -- dbm database의 첫 번째 key를 검색한다.
string dbmfirstkey(int dbm_identifier);
Returns the first key in the database. Note that no particular order is guaranteed since the database may be built using a hash-table, which doesn't guarantee any ordering.
dbmnextkey -- dbm database의 다음 key를 검색한다.
string dbmnextkey(int dbm_identifier, string key);
Returns the next key after key. By calling dbmfirstkey() followed by successive calls to dbmnextkey() it is possible to visit every key/value pair in the dbm database. For example:
Example 1. Visiting every key/value pair in a dbm database.
|
dblist -- 사용중인 dbm-compatible library에 대한 정보를 표시한다.
string dblist(void);
chdir -- 현재 directory를 바꾼다.
int chdir(string directory);
Changes PHP's current directory to directory. Returns FALSE if unable to change directory, TRUE otherwise.
dir -- directory class
new dir(string directory);
A pseudo-object oriented mechanism for reading a directory. The given directory is opened. Two properties are available once directory has been opened. The handle property can be used with other directory functions such as readdir(), rewinddir() and closedir(). The path property is set to path the directory that was opened. Three methods are available: read, rewind and close.
Example 1. Dir() Example
|
closedir -- directory handle을 닫는다.
void closedir(int dir_handle);
Closes the directory stream indicated by dir_handle. The stream must have previously been opened by opendir().
opendir -- directory handle을 연다.
int opendir(string path);
Returns a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls.
readdir -- directory handle로 부터 항목을 읽어온다.
string readdir(int dir_handle);
Returns the filename of the next file from the directory. The filenames are not returned in any particular order.
Example 1. List all files in the current directory
|
rewinddir -- directory handle을 directory의 시작 위치로 되돌린다.
void rewinddir(int dir_handle);
Resets the directory stream indicated by dir_handle to the beginning of the directory.
dl -- PHP extension을 실행중에 load한다.
int dl(string library);
Loads the PHP extension defined in library. See also the extension_dir configuration directive.
이 함수들은 mcrypt와 같이 동작하기위해 만들었다.
이것은 mcrypt 라이브러리에 대한 인터페이스이다. mcrypt는 다음과 같은 광범위한 block 알고리즘을 지원한다. : DES, TripleDES, Blowfish (default), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST in CBC, OFB, CFB and ECB cipher modes 추가로 지원하는 RC6와 IDEA는 무료가 아니다.
이것을 사용하기 위해서는 우선 ftp://argeas.cs-net.gr/pub/unix/mcrypt/에서 libmcrypt-x.x.tar.gz을 다운받은 후에 포함된 설치 설명서 대로 설치한 후에, PHP를 --with-mcrypt 설정을 주어 이 확장을 활성화하여 컴파일 하여야 한다.
mcrypt는 위에서 언급된 암호방식(cipher)으로 암호화하거나 해독할 수 있다. mcrypt_cbc(), mcrypt_cfb(), mcrypt_ecb() mcrypt_ofb()의 네가지 중요한 mcrypt 명령은 각각 MCRYPT_ENCRYPT와 MCRYPT_DECRYPT로 명명된 두가지 모드로 동작한다.
Example 1. Encrypt an input value with TripleDES in ECB mode
|
위의 예제에서 여러분은 $encrypted_data에 암호화된 문자열 데이터를 얻게 된다.
mcrypt는 CBC, OFB, CFB, ECB의 4가지 암호 모드로 동작한다. 여기서는 개개의 모드에 대한 간략한 설명만을 하겠다. 보다 자세한 내용은 Schneier의 Applied Cryptography (ISBN 0-471-11709-9)를 보기 바란다.
ECB(electronic codebook)는 다른 키를 암호화하는 등의 랜덤 데이터에 적합하다. 데이터가 짧고 랜덤하므로 ECB는 다른 방식에 비해 보안수준이 조금 낮은 편이다.
CBC(cipher block chaining)는 특히 ECB에 비해 높은 보안 수준이 요구되는 파일을 암호화하는데 적합하다.
CFB(cipher feedback)는 개개의 바이트가 암호화 되어야 하는 byte stream을 암호화하는데 가장 좋은 모드이다.
OFB(output feedback)는 CFB와 호환되지만, 에러가 생기면 안되는 응용 프로그램에 사용할 수 있다.
PHP는 현재 bit stream에 대해서는 암호화하거나 해독할 수 없다. 현재의 PHP는 단지 문자열을 지원할 뿐이다.
지원되는 암호방식의 전체 리스트는 mcrypt.h 파일의 마지막에 있다. PHP에서 암호방식(cipher)을 사용하는 일반적인 법칙은 "MCRYPT_암호방식이름"의 형태이다.
아래는 현재 PHP/mcrypt에서 지원하는 암호방식의 간단한 List이다. mcrypt에서 지원한다고 표시되어 있으나, 여기에 나와있지 않은 것은 이 매뉴얼 이후에 추가로 지원된 것이므로 안심하고 사용하여도 된다.
CFB와 OFB 모드에서는 반드시 각각의 암호화 함수에 대해 initialization vector (IV)를 주어야 한다. CBC 모드에서는 옵션으로 줄 수 있다. IV는 유일하여야 하고, 암호/해제시에 동일하여야 한다. 암호화되어 저장된 데이터를 가지고, 데이터가 저장된곳의 index를 어떤 함수를 적용하여 여 얻은 값을 사용할 수 도 있다. (예, 파일이름의 MD5 키) 다른 대안으로 IV를 암호화된 데이터와 함께 보내는 방법이 있다. (여기에 대해서는 Schneier의 Applied Cryptography의 chapter 9.3을 보라.)
mcrypt_get_cipher_name -- 특정 암호방식(cipher)의 이름을 구한다.
string mcrypt_get_cipher_name
(int cipher)
Mcrypt_get_cipher_name() is used to get the name of the specified cipher.
Mcrypt_get_cipher_name() takes the cipher number as an argument and returns the name of the cipher or false, if the cipher does not exist.
Example 1. Mcrypt_get_cipher_name() example
|
The above example will produce:
1 2 TripleDES 3 |
mcrypt_get_block_size -- 특정 암호방식(cipher)의 블록 크기를 구한다.
int mcrypt_get_block_size
(int cipher);
mcrypt_get_block_size() is used to get the size of a block of the specified cipher.
mcrypt_get_block_size() takes one argument, the cipher and returns the size in bytes.
See also: mcrypt_get_key_size()
mcrypt_get_key_size -- 특정 암호방식(cipher)의 key의 길이를 구한다.
int mcrypt_get_key_size
(int cipher);
mcrypt_get_key_size() is used to get the size of a key of the specified cipher.
mcrypt_get_key_size() takes one argument, the cipher and returns the size in bytes.
See also: mcrypt_get_block_size()
mcrypt_create_iv -- 랜덤 소스에서 initialization vector(IV)를 만든다.
string mcrypt_create_iv
(int size, int source)
Mcrypt_create_iv() is used to create an IV.
mcrypt_create_iv() takes two arguments, size determines the size of the IV, source specifies the source of the IV.
The source can be MCRYPT_RAND (system random number generator), MCRYPT_DEV_RANDOM (read data from /dev/random) and MCRYPT_DEV_URANDOM (read data from /dev/urandom). If you use MCRYPT_RAND, make sure to call srand() before to initialize the random number generator.
Example 1. Mcrypt_create_iv() example
|
mcrypt_cbc -- CBC 모드로 데이터를 암호화하거나 해제 한다.
int mcrypt_cbc
(int cipher, string key, string data, int mode, string [iv]);
mcrypt_cbc() encrypts or decrypts (depending on mode) the data with cipher and key in CBC cipher mode and returns the resulting string.
cipher is one of the MCRYPT_ciphername constants.
key is the key supplied to the algorithm. It must be kept secret.
data is the data which shall be encrypted/decrypted.
mode is MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
iv is the optional initialization vector.
See also: mcrypt_cfb(), mcrypt_ecb(), mcrypt_ofb()
mcrypt_cfb -- CFB 모드로 데이터를 암호화하거나 해제 한다.
int mcrypt_cfb
(int cipher, string key, string data, int mode, string iv);
mcrypt_cfb() encrypts or decrypts (depending on mode) the data with cipher and key in CFB cipher mode and returns the resulting string.
cipher is one of the MCRYPT_ciphername constants.
key is the key supplied to the algorithm. It must be kept secret.
data is the data which shall be encrypted/decrypted.
mode is MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
iv is the initialization vector.
See also: mcrypt_cbc(), mcrypt_ecb(), mcrypt_ofb()
mcrypt_ecb -- ECB 모드로 데이터를 암호화하거나 해제 한다.
int mcrypt_ecb
(int cipher, string key, string data, int mode);
mcrypt_ecb() encrypts or decrypts (depending on mode) the data with cipher and key in ECB cipher mode and returns the resulting string.
cipher is one of the MCRYPT_ciphername constants.
key is the key supplied to the algorithm. It must be kept secret.
data is the data which shall be encrypted/decrypted.
mode is MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
See also: mcrypt_cbc(), mcrypt_cfb(), mcrypt_ofb()
mcrypt_ofb -- OFB 모드로 데이터를 암호화하거나 해제 한다.
int mcrypt_ofb
(int cipher, string key, string data, int mode, string iv);
mcrypt_ofb() encrypts or decrypts (depending on mode) the data with cipher and key in OFB cipher mode and returns the resulting string.
cipher is one of the MCRYPT_ciphername constants.
key is the key supplied to the algorithm. It must be kept secret.
data is the data which shall be encrypted/decrypted.
mode is MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
iv is the initialization vector.
See also: mcrypt_cbc(), mcrypt_cfb(), mcrypt_ecb()
이 함수들은 filePro 형태의 databse(dbf)에 저장된 레코드들을 read-only로 접근할 수 있게 해 준다.
filePro는 Fiserv, Inc.의 trademark로 등록되어 있다. 여러분은 http://www.fileproplus.com/에서 filePro에 관한 더 많은 정보를 얻을 수 있다.
filepro -- map file파일을 읽고 검증한다.
bool filepro(string directory);
This reads and verifies the map file, storing the field count and info.
No locking is done, so you should avoid modifying your filePro database while it may be opened in PHP.
filepro_fieldname -- field의 이름을 구한다.
string filepro_fieldname(int field_number);
Returns the name of the field corresponding to field_number.
filepro_fieldtype -- field의 type을 구한다.
string filepro_fieldtype(int field_number);
Returns the edit type of the field corresponding to field_number.
filepro_fieldwidth -- field의 크기(width)를 구한다.
int filepro_fieldwidth(int field_number);
Returns the width of the field corresponding to field_number.
filepro_retrieve -- filePro database에서 데이타를 검색한다.
string filepro_retrieve(int row_number, int field_number);
Returns the data from the specified location in the database.
filepro_fieldcount -- filePro database의 field의 개수를 구한다.
int filepro_fieldcount(void);
Returns the number of fields (columns) in the opened filePro database.
See also filepro().
filepro_rowcount -- filePro database의 row의 개수를 구한다.
int filepro_rowcount(void);
Returns the number of rows in the opened filePro database.
See also filepro().
basename -- path중 name 부분을 구한다.
string basename(string path);
Given a string containing a path to a file, this function will return the base name of the file.
On Windows, both slash (/) and backslash (\) are used as path separator character. In other environments, it is the forward slash (/).
Example 1. basename() example $path = "/home/httpd/html/index.php3"; $file = basename($path); // $file is set to "index.php3" |
See also: dirname()
chgrp -- 파일의 group을 바꾼다.
int chgrp(string filename, mixed group);
Attempts to change the group of the file filename to group. Only the superuser may change the group of a file arbitrarily; other users may change the group of a file to any group of which that user is a member.
Returns true on success; otherwise returns false.
On Windows, does nothing and returns true.
chmod -- 파일의 mode를 바꾼다.
int chmod(string filename, int mode);
Attempts to change the mode of the file specified by filename to that given in mode.
Note that mode is not automatically assumed to be an octal value. To ensure the expected operation, you need to prefix mode with a zero (0):
chmod( "/somedir/somefile", 755 ); // decimal; probably incorrect chmod( "/somedir/somefile", 0755 ); // octal; correct value of mode
Returns true on success and false otherwise.
chown -- 파일의 owner를 바꾼다.
int chown(string filename, mixed user);
Attempts to change the owner of the file filename to user user. Only the superuser may change the owner of a file.
Returns true on success; otherwise returns false.
NOTE: On Windows, does nothing and returns true.
See also chown() and chmod().
clearstatcache -- 파일의 stat cache를 바꾼다.
void clearstatcache(void);
Invoking the stat() or lstat() system call on most systems is quite expensive. Therefore, the result of the last call to any of the status functions (listed below) is stored for use on the next such call using the same filename. If you wish to force a new status check, for instance if the file is being checked many times and may change or disappear, use this function to clear the results of the last call from memory.
This value is only cached for the lifetime of a single request.
Affected functions include stat(), lstat(), file_exists(), is_writeable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype(), and fileperms().
copy -- 파일을 복사한다.
int copy(string source, string dest);
Makes a copy of a file. Returns true if the copy succeeded, false otherwise.
Example 1. copy() example if (!copy($file, $file.'.bak')) { print("failed to copy $file...<br>\n"); } |
See also: rename()
delete -- 실제로는 없는 명령
void delete
(string file);
이 명령을 찾는 사람들은 아마 unlink()나 unset() 명령을 사용하는 기능을 원할 것이다.
See also: 파일을 지우기 위해서는 unlink(), 변수를 지우기 위해서는 unset()
dirname -- path의 Directory부분을 돌려준다.
string dirname(string path);
Given a string containing a path to a file, this function will return the name of the directory.
On Windows, both slash (/) and backslash (\) are used as path separator character. In other environments, it is the forward slash (/).
Example 1. dirname() example $path = "/etc/passwd"; $file = dirname($path); // $file is set to "/etc" |
See also: basename()
diskfreespace -- 해당 디렉토리에 저장 가능한 남은 용량을 반환한다.
float diskfreespace
(string directory);
Given a string containing a directory, this function will return the number of bytes available on the corresponding disk.
Example 1. diskfreespace() example $df = diskfreespace("/"); // $df contains the number of bytes available on "/" |
fclose -- 지정된 file pointer를 닫는다.
int fclose(int fp);
The file pointed to by fp is closed.
Returns true on success and false on failure.
The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().
feof -- file pointer가 end-of-file에 있는가 검사한다.
int feof(int fp);
Returns true if the file pointer is at EOF or an error occurs; otherwise returns false.
The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen().
fgetc -- file pointer에서 문자를 읽는다.
string fgetc(int fp);
Returns a string containing a single character read from the file pointed to by fp. Returns FALSE on EOF (as does feof()).
The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen().
See also fread(), fopen(), popen(), fsockopen(), and fgets().
fgetcsv -- 파일의 현재 위치에서 CSV 필드로 된 줄을 읽어와서 parse한다.
array fgetcsv
(int fp, int length, string [delimiter]);
Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read. The field delimiter is a comma, unless you specifiy another delimiter with the optional third parameter.
fp must be a valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen()
length must be greater than the longest line to be found in the CSV file (allowing for trailing line-end characters).
fgetcsv() returns false on error, including end of file.
NB A blank line in a CSV file will be returned as an array comprising just one single null field, and will not be treated as an error.
Example 1. fgetcsv() example - Read and print entire contents of a CSV file $row=1; $fp = fopen("test.csv","r"); while ($data = fgetcsv($fp,1000)) { $num = count($data); print "<p> $num fields in line $row: <br>"; $row++; for ( $c=0; $c<$num; $c++ ) print $data[$c] . "<br>"; } fclose($fp); |
fgets -- file pointer에서 한 줄을 읽어 온다.
string fgets
(int fp, int length);
Returns a string of up to length - 1 bytes read from the file pointed to by fp. Reading ends when length - 1 bytes have been read, on a newline (which is included in the return value), or on EOF (whichever comes first).
If an error occurs, returns false.
Common Pitfalls:
People used to the 'C' semantics of fgets should note the difference in how EOF is returned.
The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen().
A simple example follows:
Example 1. Reading a file line by line $fd = fopen("/tmp/inputfile.txt", "r"); while ($buffer = fgets($fd, 4096)) { echo $buffer; } fclose($fd); |
See also fread(), fopen(), popen(), fgetc(), and fsockopen().
fgetss -- file pointer에서 한 줄을 읽어와 HTML tag들을 strip한다.
string fgetss(int fp, int length);
Identical to fgets(), except that fgetss attempts to strip any HTML and PHP tags from the text it reads.
See also fgets(), fopen(), fsockopen(), popen(), and strip_tags().
file -- 파일 전체를 읽어서 배열에 저장한다.
array file(string filename);
Identical to readfile(), except that file() returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached.
See also readfile(), fopen(), and popen().
file_exists -- 파일이 존재하는지 검사한다.
int file_exists(string filename);
Returns true if the file specified by filename exists; false otherwise.
The results of this function are cached. See clearstatcache() for more details.
fileatime -- 파일에 마지막으로 접근한 시간을 구한다.
int fileatime(string filename);
Returns the time the file was last accessed, or false in case of an error.
The results of this function are cached. See clearstatcache() for more details.
filectime -- 파일의 inode가 변경된 시간을 구한다.
int filectime
(string filename);
Returns the time the file was last changed, or false in case of an error.
The results of this function are cached. See clearstatcache() for more details.
filegroup -- 파일의 group을 구한다.
int filegroup
(string filename);
Returns the group ID of the owner of the file, or false in case of an error.
The results of this function are cached. See clearstatcache() for more details.
fileinode -- 파일의 inode를 구한다.
int fileinode
(string filename);
Returns the inode number of the file, or false in case of an error.
The results of this function are cached. See clearstatcache() for more details.
filemtime -- 파일이 수정된 시간을 구한다.
int filemtime(string filename);
Returns the time the file was last modified, or false in case of an error.
The results of this function are cached. See clearstatcache() for more details. error.
fileowner -- 파일의 owner를 구한다.
int fileowner(string filename);
Returns the user ID of the owner of the file, or false in case of an error.
The results of this function are cached. See clearstatcache() for more details. error.
fileperms -- 파일의 permission을 구한다.
int fileperms(string filename);
Returns the permissions on the file, or false in case of an error.
The results of this function are cached. See clearstatcache() for more details.
filesize -- 파일의 크기를 구한다.
int filesize(string filename);
Returns the size of the file, or false in case of an error.
The results of this function are cached. See clearstatcache() for more details.
filetype -- 파일의 type을 구한다.
string filetype(string filename);
Returns the type of the file. Possible values are fifo, char, dir, block, link, file, and unknown.
Returns false if an error occurs.
The results of this function are cached. See clearstatcache() for more details.
flock -- portable 파일 locking
bool flock
(int fp, int operation);
PHP supports a portable way of locking complete files in an advisory way (which means all accessing programs have to use the same way of locking or it will not work).
flock() operates on fp which must be an open file pointer. operation is one of the following values:
To acquire a shared lock (reader), set operation to 1.
To acquire an exclusive lock (writer), set operation to 2.
To release a lock (shared or exclusive), set operation to 3.
If you don't want flock() to block while locking, add 4 to operation.
flock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unices and even Windows).
flock() returns true on success and false on error (e.g. when a lock could not be acquired).
fopen -- 파일이나 URL을 연다.
int fopen
(string filename, string mode);
If filename begins with "http://" (not case sensitive), an HTTP 1.0 connection is opened to the specified server and a file pointer is returned to the beginning of the text of the response.
Does not handle HTTP redirects, so you must include trailing slashes on directories.
If filename begins with "ftp://" (not case sensitive), an ftp connection to the specified server is opened and a pointer to the requested file is returned. If the server does not support passive mode ftp, this will fail. You can open files for either reading and writing via ftp (but not both simultaneously).
If filename begins with anything else, the file will be opened from the filesystem, and a file pointer to the file opened is returned.
If the open fails, the function returns false.
mode may be any of the following:
'r' - Open for reading only; place the file pointer at the beginning of the file.
'r+' - Open for reading and writing; place the file pointer at the beginning of the file.
'w' - Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does
not exist, attempt to create it.
'w+' - Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the
file does not exist, attempt to create it.
'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
As well, mode may contain the letter 'b'. This is useful only on systems which differentiate between binary and text files (i.e., it's useless on Unix). If not needed, this will be ignored.
Example 1. fopen() example $fp = fopen("/home/rasmus/file.txt", "r"); $fp = fopen("http://www.php.net/", "r"); $fp = fopen("ftp://user:password@example.com/", "w"); |
If you are experiencing problems with reading and writing to files and you're using the server module version of PHP, remember to make sure that the files and directories you're using are accessible to the server process.
On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes.
$fp = fopen("c:\\data\\info.txt", "r");
See also fclose(), fsockopen(), and popen().
fpassthru -- file pointer에서부터 남아 있는 모든 데이타를 출력한다.
int fpassthru
(int fp);
Reads to EOF on the given file pointer and writes the results to standard output.
If an error occurs, fpassthru() returns false.
The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen(). The file is closed when fpassthru() is done reading it (leaving fp useless).
If you just want to dump the contents of a file to stdout you may want to use the readfile(), which saves you the fopen() call.
See also readfile(), fopen(), popen(), and fsockopen()
fputs -- file pointer에 쓴다.
int fputs
(int fp, string str, int [length]);
fputs() is an alias to fwrite(), and is identical in every way. Note that the length parameter is optional and if not specified the entire string will be written.
fread -- 파일을 binary로 읽어온다.
string fread(int fp, int length);
fread() reads up to length bytes from the file pointer referenced by fp. Reading stops when length bytes have been read or EOF is reached, whichever comes first.
// get contents of a file into a string $filename = "/usr/local/something.txt"; $fd = fopen( $filename, "r" ); $contents = fread( $fd, filesize( $filename ) ); fclose( $fd );
See also fwrite(), fopen(), fsockopen(), popen(), fgets(), fgetss(), file(), and fpassthru().
fseek -- file pointer를 옮긴다.
int fseek(int fp, int offset);
Sets the file position indicator for the file referenced by fp to offset bytes into the file stream. Equivalent to calling (in C) fseek( fp, offset, SEEK_SET ).
Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.
May not be used on file pointers returned by fopen() if they use the "http://" or "ftp://" formats.
See also ftell() and rewind().
ftell -- file pointer의 read/write 위치를 구한다.
int ftell(int fp);
Returns the position of the file pointer referenced by fp; i.e., its offset into the file stream.
If an error occurs, returns false.
The file pointer must be valid, and must point to a file successfully opened by fopen() or popen().
See also fopen(), popen(), fseek() and rewind().
(PHP4 >= 4.0RC1)
ftruncate -- 파일을 주어진 크기로 만든다.int ftruncate
(int fp,
int size)
Takes the filepointer, fp, and truncates the file to length, size. This function returns true on success and false on failure.
fwrite -- 파일을 Binary로 쓴다.
int fwrite(int fp, string string, int [length]);
fwrite() writes the contents of string to the file stream pointed to by fp. If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.
Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.
See also fread(), fopen(), fsockopen(), popen(), and fputs().
set_file_buffer -- 해당 파일 포인터에서 파일 버퍼링(buffering)을 지정한다.
int fwrite
(int fp, int buffer);
set_file_buffer() sets the buffering for write operations on the given filepointer fp to buffer bytes. If buffer is 0 then write operations are unbuffered.
The function returns 0 on success, or EOF if the request cannot be honored.
Note that the default for any fopen with calling set_file_buffer is 8K.
See also fopen().
is_dir -- 지정된 파일명이 directory인가 알려준다.
bool is_dir(string filename);
Returns true if the filename exists and is a directory.
The results of this function are cached. See clearstatcache() for more details.
See also is_file() and is_link().
is_executable -- 지정된 파일명이 실행가능 파일인가 알려준다.
bool is_executable(string filename);
Returns true if the filename exists and is executable.
The results of this function are cached. See clearstatcache() for more details.
See also is_file() and is_link().
is_file -- 지정된 파일명이 보통파일인가 알려준다.
bool is_file(string filename);
Returns true if the filename exists and is a regular file.
The results of this function are cached. See clearstatcache() for more details.
See also is_dir() and is_link().
is_link -- 지정된 파일명이 symbolic link인가 알려준다.
bool is_link(string filename);
Returns true if the filename exists and is a symbolic link.
The results of this function are cached. See clearstatcache() for more details.
See also is_dir() and is_file().
is_readable -- 지정된 파일명이 읽기 가능인가 알려준다.
bool is_readable(string filename);
Returns true if the filename exists and is readable.
Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account.
The results of this function are cached. See clearstatcache() for more details.
See also is_writeable().
is_writeable -- 지정된 파일명이 쓰기 가능인가 알려준다.
bool is_readable(string filename);
Returns true if the filename exists and is writeable. The filename argument may be a directory name allowing you to check if a directory is writeable.
Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account.
The results of this function are cached. See clearstatcache() for more details.
See also is_readable().
link -- hard link를 만든다.
int link(string target, string link);
Link() creates a hard link.
See also the symlink() to create soft links, and readlink() along with linkinfo().
linkinfo -- link에 대한 정보를 구한다.
int linkinfo(string path);
Linkinfo() returns the st_dev field of the UNIX C stat structure returned by the lstat system call. This function is used to verify if a link (pointed to by path) really exists (using the same method as the S_ISLNK macro defined in stat.h). Returns 0 or FALSE in case of error.
See also symlink(), link(), and readlink().
mkdir -- directory를 만든다.
int mkdir
(string pathname, int mode);
Attempts to create the directory specified by pathname.
Note that you probably want to specify the mode as an octal number, which means it should have a leading zero.
mkdir("/path/to/my/dir", 0700);
Returns true on success and false on failure.
See also rmdir().
pclose -- process file pointer를 닫는다.
int pclose(int fp);
Closes a file pointer to a pipe opened by popen().
The file pointer must be valid, and must have been returned by a successful call to popen().
Returns the termination status of the process that was run.
See also popen().
popen -- process file pointer를 연다.
int popen(string command, string mode);
Opens a pipe to a process executed by forking the command given by command.
Returns a file pointer identical to that returned by fopen(), except that it is unidirectional (may only be used for reading or writing) and must be closed with pclose(). This pointer may be used with fgets(), fgetss(), and fputs().
If an error occurs, returns false.
$fp = popen( "/bin/ls", "r" );
See also pclose().
readfile -- file을 읽어 출력한다.
int readfile(string filename);
Reads a file and writes it to standard output.
Returns the number of bytes read from the file. If an error occurs, false is returned and unless the function was called as @readfile, an error message is printed.
If filename begins with "http://" (not case sensitive), an HTTP 1.0 connection is opened to the specified server and the text of the response is written to standard output.
Does not handle HTTP redirects, so you must include trailing slashes on directories.
If filename begins with "ftp://" (not case sensitive), an ftp connection to the specified server is opened and the requested file is written to standard output. If the server does not support passive mode ftp, this will fail.
If filename begins with neither of these strings, the file will be opened from the filesystem and its contents written to standard output.
See also fpassthru(), file(), fopen(), include(), require(), and virtual().
readlink -- symbolic link의 대상을 반환한다.
int readlink(string path);
Readlink() does the same as the readlink C function and returns the contents of the symbolic link path or 0 in case of error.
See also symlink(), readlink() and linkinfo().
rename -- 파일명을 바꾼다.
int rename(string oldname, string newname);
Attempts to rename oldname to newname.
Returns true on success and false on failure.
rewind -- file pointer를 파일의 처음 위치로 설정한다.
int rewind(int fp);
Sets the file position indicator for fp to the beginning of the file stream.
If an error occurs, returns 0.
The file pointer must be valid, and must point to a file successfully opened by fopen().
rmdir -- directory를 지운다.
int rmdir(string dirname);
Attempts to remove the directory named by pathname. The directory must be empty, and the relevant permissions must permit this.
If an error occurs, returns 0.
See also mkdir().
stat -- 파일의 stat 정보를 구한다.
array stat(string filename);
Gathers the statistics of the file named by filename.
Returns an array with the statistics of the file with the following elements:
device
inode
number of links
user id of owner
group id owner
device type if inode device *
size in bytes
time of last access
time of last modification
time of last change
blocksize for filesystem I/O *
number of blocks allocated
* - only valid on systems supporting the st_blksize type--other systems (i.e. Windows) return -1
The results of this function are cached. See clearstatcache() for more details.
lstat -- 파일이나 symbolic link의 stat 정보를 구한다.
array lstat
(string filename);
Gathers the statistics of the file or symbolic link named by filename. This function is identical to the stat() function except that if the filename parameter is a symbolic link, the status of the symbolic link is returned, not the status of the file pointed to by the symbolic link.
Returns an array with the statistics of the file with the following elements:
device
inode
number of links
user id of owner
group id owner
device type if inode device *
size in bytes
time of last access
time of last modification
time of last change
blocksize for filesystem I/O *
number of blocks allocated
* - only valid on systems supporting the st_blksize type--other systems (i.e. Windows) return -1
The results of this function are cached. See clearstatcache() for more details.
symlink -- symbolic link를 만든다.
int symlink(string target, string link);
symlink() creates a symbolic link from the existing target with the specified name link.
See also link() to create hard links, and readlink() along with linkinfo().
tempnam -- 유일한 파일명을 만든다.
string tempnam
(string dir, string prefix);
Creates a unique temporary filename in the specified directory. If the directory does not exist, tempnam() may generate a filename in the system's temporary directory.
The behaviour of the tempnam() function is system dependent. On Windows the TMP environment variable will override the dir parameter, on Linux the TMPDIR environment variable has precedence, while SVR4 will always use your dir parameter if the directory it points to exists. Consult your system documentation on the tempnam(3) function if in doubt.
Returns the new temporary filename, or the null string on failure.
Example 1. tempnam() example $tmpfname = tempnam( "/tmp", "FOO" ); |
touch -- 파일의 수정 시각을 설정한다.
int touch(string filename, int time);
Attempts to set the modification time of the file named by filename to the value given by time. If the option time is not given, uses the present time.
If the file does not exist, it is created.
Returns true on success and false otherwise.
umask -- 현재의 umask를 변경한다.
int umask(int mask);
Umask() sets PHP's umask to mask & 0777 and returns the old umask. When PHP is being used as a server module, the umask is restored when each request is finished.
Umask() without arguments simply returns the current umask.
unlink -- 파일을 지운다.
int unlink(string filename);
Deletes filename. Similar to the Unix C unlink() function.
Returns 0 or FALSE on an error.
See also rmdir() for removing directories.
이것은 PHP에서 Forms Data Format (FDF)을 지원하기위한 첫 번째 시도이다. FDF와 이것의 사용법에 대해 알고 싶다면 http://partners.adobe.com/asn/developer/acrosdk/forms.html을 읽어보아야 할 것이다.
Note: 현재 Adobe는 Linux용으로 libc5에 호환되는 버전만을 제공한다. glibc2에서 테스트 해 보았으나 segmentation fault가 발생하였다. 만약 누군가 이것을 가능하게 한 사람이 있다면 언급해 주기를 바란다.
Note: 만약 php를 fdftk 지원으로 설정하는 것이 잘 안되는 경우, 헤더 파일인 FdfTk.h와 libFdfTk.so 라이브러리 파일이 제자리에 있는가부터 확인해 보자. 두 파일은 각각 fdftk-dir/include와 fdftk-dir/lib 디렉토리에 있어야 한다. 여러분이 FdfTk 배포본을 풀어놓기만 한 경우 아마도 이 두 파일은 제 위치에 있지 않을 것이다.
FDF의 아이디어는 HTML 폼과 비슷하다. 기본적으로 다른 것은 submit 버튼이 눌려졌을 때 서버에 전송되는 포맷(실제로 이것이 Form Data Format이다)과, 폼 자체의 형태(이것은 Portable Document Format, PDF이다)이다. FDF 데이터를 처리하는 것이 fdf 함수들이 제공하는 기능중 하나이다. 하지만 그것이 전부는 아니다. 이것은 기존의 PDF 폼에 이 폼 자체를 수정하지 않고도 input 필드와 데이터를 추가할 수 있다. 이런 경우 FDF 문서를 생성하여 (fdf_create()) 각각의 input 필드에 값을 설정하고 (fdf_set_value()), 이것을 PDF 폼에 배치시키면 된다. (fdf_set_file()) 마지막으로 이것은 application/vnd.fdf라는 MimeType을 가지고 브라우저로 전송되어야 한다. 여러분의 브라우저에 있는 Acrobat reader plugin은 이 마임 타입을 인식하고, 이 결합된 PDF form을 읽어 FDF 문서로부터 데이터를 읽어 데이터를 채운다.
다음은 form data를 사용해보는 예제이다.
Example 1. Evaluating a FDF document
|
fdf_open -- 새 fdf document를 연다
int pdf_open
(string filename);
The fdf_open() function opens a file with form data. This file must contain the data as returned from a PDF form. Currently, the file has to be created 'manually' by using fopen() and writing the content of HTTP_FDF_DATA with fwrite() into it. A mechanism like for HTML form data where for each input field a variable is created does not exist.
Example 1. Accessing the form data <?php // Save the FDF data into a temp file $fdffp = fopen("test.fdf", "w"); fwrite($fdffp, $HTTP_FDF_DATA, strlen($HTTP_FDF_DATA)); fclose($fdffp); // Open temp file and evaluate data $fdf = fdf_open("test.fdf"); ... fdf_close($fdf); ?> |
See also fdf_close().
fdf_close -- fdf document를 닫는다.
void fdf_close
(int fdf_document);
The fdf_close() function closes the fdf document.
See also fdf_open().
fdf_create -- 새 fdf document를 만든다.
int fdf_create
(void );
The fdf_create() creates a new FDF document. This function is needed if one would like to populate input fields in a PDF document with data.
Example 1. Populating a PDF document <?php $outfdf = fdf_create(); fdf_set_value($outfdf, "volume", $volume, 0); fdf_set_file($outfdf, "http:/testfdf/resultlabel.pdf"); fdf_save($outfdf, "outtest.fdf"); fdf_close($outfdf); Header("Content-type: application/vnd.fdf"); $fp = fopen("outtest.fdf", "r"); fpassthru($fp); unlink("outtest.fdf"); ?> |
See also fdf_close(), fdf_save(), fdf_open().
fdf_save -- fdf document를 저장한다.
int fdf_save
(string filename);
The fdf_save() function saves a FDF document. The FDF Toolkit provides a way to output the document to stdout if the parameter filename is '.'. This does not work if PHP is used as an apache module. In such a case one will have to write to a file and use e.g. fpassthru(). to output it.
See also fdf_close() and example for fdf_create().
fdf_get_value -- 한 필드의 값을 읽어온다.
string fdf_get_value
(int fdf_document, string fieldname);
The fdf_get_value() function returns the value of a field.
See also fdf_set_value().
fdf_set_value -- 한 필드의 값을 설정한다.
void fdf_set_value
(int fdf_document, string fieldname, string value, int isName);
The fdf_set_value() function sets the value of a field. The last parameter determines if the field value is to be converted to a PDF Name (isName = 1) or set to a PDF String (isName = 0).
See also fdf_get_value().
fdf_next_field_name -- 다음 필드의 이름을 반환한다.
string fdf_next_field_name
(int fdf_document, string fieldname);
The fdf_next_field_name() function returns the name of the field after the field in fieldname or the field name of the first field if the second paramter is NULL.
See also fdf_set_field(), fdf_get_field().
fdf_set_ap -- 한 필드의 appearance를 설정한다.
void fdf_set_ap
(int fdf_document, string field_name, int face, string filename, int page_number);
The fdf_set_ap() function sets the appearance of a field (i.e. the value of the /AP key). The possible values of face are 1=FDFNormalAP, 2=FDFRolloverAP, 3=FDFDownAP.
fdf_set_status -- /STATUS 키의 값을 설정한다.
void fdf_set_status
(int fdf_document, string status);
The fdf_set_status() sets the value of the /STATUS key.
See also fdf_get_status().
fdf_get_status -- /STATUS 키의 값을 읽어온다.
string fdf_get_status
(int fdf_document);
The fdf_get_status() returns the value of the /STATUS key.
See also fdf_set_status().
fdf_set_file -- /F 키의 값을 설정한다.
void fdf_set_file
(int fdf_document, string filename);
The fdf_set_file() sets the value of the /F key. The /F key is just a reference to a PDF form which is to be populated with data. In a web environment it is a URL (e.g. http:/testfdf/resultlabel.pdf).
See also fdf_get_file() and example for fdf_create().
fdf_get_file -- /F 키의 값을 읽어온다.
string fdf_get_file
(int fdf_document);
The fdf_set_file() returns the value of the /F key.
See also fdf_set_file().
File Transfer Protocol인 FTP 함수들이다.
FTP_ASCII 와 FTP_BINARY 의 두 개의 상수가 FTP 모듈에 미리 정의되어 있다.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_connect -- FTP 연결을 연다.int ftp_connect
(string
host [, int port])
Returns a FTP stream on success, false on error.
ftp_connect() opens up a FTP connection to the specified host. The port parameter specifies an alternate port to connect to. If it is omitted or zero, then the default FTP port, 21, will be used.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_login -- FTP 연결에 로그인한다.int ftp_login
(int
ftp_stream, string username, string password)
Returns true on success, false on error.
Logs in the given FTP stream.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_pwd -- 현재 디렉토리명을 반환한다.int ftp_pwd
(int
ftp_stream)
Returns the current directory, or false on error.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_cdup -- 부모 디렉토리로 이동한다.int ftp_cdup
(int
ftp_stream)
Returns true on success, false on error.
Changes to the parent directory.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_chdir -- FTP 서버의 특정 디렉토리로 이동한다.int ftp_chdir
(int
ftp_stream, string directory)
Returns true on success, false on error.
Changes to the specified directory.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_mkdir -- 디렉토리를 만든다.string ftp_mkdir
(int
ftp_stream, string directory)
Returns the newly created directory name on success, false on error.
Creates the specified directory.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_rmdir -- 디렉토리를 지운다.int ftp_rmdir
(int
ftp_stream, string directory)
Returns true on success, false on error.
Removes the specified directory.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_nlist -- 주어진 디렉토리의 파일명의 목록을 배열로 돌려준다.int ftp_nlist
(int
ftp_stream, string directory)
Returns an array of filenames on success, false on error.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_rawlist -- 주어진 디렉토리의 파일의 자세한 목록을 배열로 돌려준다.int ftp_rawlist
(int
ftp_stream, string directory)
ftp_rawlist() executes the FTP LIST command, and returns the result as an array. Each array element corresponds to one line of text. The output is not parsed in any way. The system type identifier returned by ftp_systype() can be used to determine how the results should be interpreted.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_systype -- 원격 FTP 서버의 시스템 종류 식별자(system type identifier)를 반환한다.int ftp_systype
(int
ftp_stream)
Returns the remote system type, or false on error.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_pasv -- passive 모드를 켜거나 끈다.int ftp_pasv
(int
ftp_stream, int pasv)
Returns true on success, false on error.
ftp_pasv() turns on passive mode if the pasv parameter is true (it turns off passive mode if pasv is false.) In passive mode, data connections are initiated by the client, rather than by the server.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_get -- FTP 서버로부터 한 파일을 가져온다.int ftp_get
(int
ftp_stream, string local_file, string remote_file, int mode)
Returns true on success, false on error.
ftp_get() retrieves remote_file from the FTP server, and saves it to local_file locally. The transfer mode specified must be either FTP_ASCII or FTP_BINARY.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_fget -- FTP 서버로부터 한 파일을 가져와 기존에 열려진 파일로 저장한다.int ftp_fget
(int
ftp_stream, int fp, string remote_file, int mode)
Returns true on success, false on error.
ftp_fget() retrieves remote_file from the FTP server, and writes it to the given file pointer, fp. The transfer mode specified must be either FTP_ASCII or FTP_BINARY.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_put -- FTP 서버로 한 파일을 올린다.int ftp_put
(int
ftp_stream, string remote_file, string local_file, int mode)
Returns true on success, false on error.
ftp_put() stores local_file on the FTP server, as remote_file. The transfer mode specified must be either FTP_ASCII or FTP_BINARY.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_fput -- 열려져 있는 파일을 FTP 서버로 올린다.Uploads from an open file to the FTP server.
int ftp_fput
(int
ftp_stream, string remote_file, int fp, int mode)
Returns true on success, false on error.
ftp_fput() uploads the data from the file pointer fp until end of file. The results are stored in remote_file on the FTP server. The transfer mode specified must be either FTP_ASCII or FTP_BINARY.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_size -- 파일의 크기를 반환한다.int ftp_size
(int
ftp_stream, string remote_file)
Returns the file size on success, or -1 on error.
ftp_size() returns the size of a file. If an error occurs, of if the file does not exist, -1 is returned. Not all servers support this feature.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_mdtm -- 파일이 마지막으로 수정된 시각을 반환한다.int ftp_mdtm
(int
ftp_stream, string remote_file)
Returns a UNIX timestamp on success, or -1 on error.
ftp_mdtm() checks the last-modified time for a file, and returns it as a UNIX timestamp. If an error occurs, or the file does not exist, -1 is returned. Note that not all servers support this feature.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_rename -- FTP 서버에 있는 파일의 이름을 바꾼다.int ftp_rename
(int
ftp_stream, string from, string to)
Returns true on success, false on error.
ftp_rename() renames the file specified by from to the new name to.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_delete -- FTP 서버에 있는 파일을 지운다.int ftp_delete
(int
ftp_stream, string path)
Returns true on success, false on error.
ftp_delete() deletes the file specified by path from the FTP server.
(PHP3 >= 3.0.15, PHP4 >= 4.0RC1)
ftp_site -- SITE 명령을 서버에 보낸다.int ftp_site
(int
ftp_stream, string cmd)
Returns true on success, false on error.
ftp_site() sends the command specified by cmd to the FTP server. SITE commands are not standardized, and vary from server to server. They are useful for handling such things as file permissions and group membership.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_quit -- FTP 연결을 닫는다.(PHP3 >= 3.0.7, PHP4 )
bindtextdomain -- domain의 path를 설정한다.string bindtextdomain
(string domain, string directory)
The bindtextdomain() function sets the path for a domain.
(PHP3 >= 3.0.7, PHP4 )
dcgettext -- Overrides the domain for a single lookupstring dcgettext
(string
domain, string message, int category)
This function allows you to override the current domain for a single message lookup. It also allows you to specify a category.
(PHP3 >= 3.0.7, PHP4 )
dgettext -- Override the current domainstring dgettext
(string
domain, string message)
The dgettext() function allows you to override the current domain for a single message lookup.
(PHP3 >= 3.0.7, PHP4 )
gettext -- Lookup a message in the current domainstring gettext
(string
message)
This function returns a translated string if one is found in the translation table, or the submitted message if not found. You may use an underscore character as an alias to this function.
Example 1. Gettext()-check
|
(PHP3 >= 3.0.7, PHP4 )
textdomain -- Sets the default domainint textdomain
([string
library])
This function sets the domain to search within when calls are made to gettext(), usually the named after an application. The previous default domain is returned. Call it with no parameters to get the current setting without changing it.
이 함수들은 mhash와 함께 동작하도록 만들어졌다.
이것은 mhash 라이브러리에 대한 인터페이스이다. mhash는 MD5나 SHA1, GOST와 여타의 광범위한 해쉬 알고리즘을 디원한다.
이것을 사용하고 싶으면 우선 mhash 홈페이지에서 mhash-x.x.x.tar.gz를 다운받고 포함된 설치설명서대로 설치한다. PHP에서 이 확장을 사용하려면 컴파일시에 --with-mhash 파라메터를 주고 컴파일하여야 한다.
mhash는 checksums이나 message digests 등의 것을 만드는데 사용될 수 있다.
Example 1. Compute the SHA1 key and print it out as hex
|
위의 예는 다음과 같은 결과를 출력한다.:
1 2 The hash is d3b85d710d8f6e4e5efd4d5e67d041f9cecedafe 3 |
지원되는 hash 알고리즘에 대한 완벽한 리스트는 mhash안에 있는 문서를 참조하자. PHP에서 hash 방식을 지칭하는 일반적인 법칙은 "MHASH_해쉬이름"의 형태이다.
현재 mhash에세 지원하는 해쉬의 리스트는 다음과 같다. mhash에서 지원한다고 표시되어 있으나, 여기에 나와있지 않은 것은 이 매뉴얼 이후에 추가로 지원된 것이므로 안심하고 사용하여도 된다.
MHASH_MD5
MHASH_SHA1
MHASH_HAVAL
MHASH_RIPEMD160
MHASH_RIPEMD128
MHASH_SNEFRU
MHASH_TIGER
MHASH_GOST
MHASH_CRC32
MHASH_CRC32B
mhash_get_hash_name -- 지정된 hash의 이름을 구한다.
string mhash_get_hash_name
(int hash)
mhash_get_hash_name() is used to get the name of the specified hash.
mhash_get_hash_name() takes the hash id as an argument and returns the name of the hash or false, if the hash does not exist.
Example 1. mhash_get_hash_name example
|
1 2 MD5 3 |
mhash_get_block_size -- 지정된 hash의 블록 크기를 구한다.
int mhash_get_block_size
(int hash);
mhash_get_block_size() is used to get the size of a block of the specified hash.
mhash_get_block_size() takes one argument, the hash and returns the size in bytes or false, if the hash does not exist.
mhash_count -- 가능한 가장 큰 hash id를 구한다.
int mhash_count
(void)
mhash_count() returns the highest available hash id. Hashes are numbered from 0 to this hash id.
Example 1. Traversing all hashes
|
mhash -- hash 값을 계산한다.
string mhash
(int hash, string data);
mhash() applies a hash function specified by hash to the data and returns the resulting hash (also called digest).
이 함수들은 HTTP protocol leve에서 데이타를 remote browser로 직접 전송할 수 있도록 해 준다.
header -- HTTP 헤더 데이타를 적어준 그대로 보낸다.
int header
(string string);
The Header() function is used at the top of an HTML file to send raw HTTP header strings. See the HTTP 1.1 Specification for more information on raw http headers. Note: Remember that the Header() function must be called before any actual output is sent either by normal HTML tags or from PHP. It is a very common error to read code with include() or with auto_prepend and have spaces or empty lines in this code that force output before header() is called.
There are two special-case header calls. The first is the "Location" header. Not only does it send this header back to the browser, it also returns a REDIRECT status code to Apache. From a script writer's point of view this should not be important, but for people who understand Apache internals it is important to understand.
1 2 header ("Location: http://www.php.net"); /* Redirect browser 3 to PHP web site */ 4 exit; /* Make sure that code below does 5 not get executed when we redirect. */ 6 |
The second special-case is any header that starts with the string, "HTTP/" (case is not significant). For example, if you have your ErrorDocument 404 Apache directive pointed to a PHP script, it would be a good idea to make sure that your PHP script is actually generating a 404. The first thing you do in your script should then be:
1 2 header ("http/1.0 404 Not Found"); 3 |
PHP scripts often generate dynamic HTML that must not be cached by the client browser or any proxy caches between the server and the client browser. Many proxies and clients can be forced to disable caching with
1 2 header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past 3 header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 4 // always modified 5 header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 6 header ("Pragma: no-cache"); // HTTP/1.0 7 |
setcookie -- cookie를 설정하도록 데이타를 브라우저로 보낸다.
int setcookie
(string name, string value, int expire, string path, string domain, int secure);
setcookie() defines a cookie to be sent along with the rest of the header information. Cookies must be sent before any other headers are sent (this is a restriction of cookies, not PHP). This requires you to place calls to this function before any <html> or <head> tags.
All the arguments except the name argument are optional. If only the name argument is present, the cookie by that name will be deleted from the remote client. You may also replace any argument with an empty string ("") in order to skip that argument. The expire and secure arguments are integers and cannot be skipped with an empty string. Use a zero (0) instead. The expire argument is a regular Unix time integer as returned by the time() or mktime() functions. The secure indicates that the cookie should only be transmitted over a secure HTTPS connection.
Common Pitfalls:
Cookies will not become visible until the next loading of a page that the cookie should be visible for.
In PHP3, multiple calls to setcookie() in the same script will be performed in reverse order. If you are trying to delete one cookie before inserting another you should put the insert before the delete. In PHP4, multiple calls to setcookie() are performed in the order called.
Some examples follow:
Example 1. setcookie() examples
|
Note that the value portion of the cookie will automatically be urlencoded when you send the cookie, and when it is received, it is automatically decoded and assigned to a variable by the same name as the cookie name. To see the contents of our test cookie in a script, simply use one of the following examples:
1 2 echo $TestCookie; 3 echo $HTTP_COOKIE_VARS["TestCookie"]; 4 |
You may also set array cookies by using array notation in the cookie name. This has the effect of setting as many cookies as you have array elements, but when the cookie is received by your script, the values are all placed in an array with the cookie's name:
1 2 setcookie ("cookie[three]", "cookiethree"); 3 setcookie ("cookie[two]", "cookietwo"); 4 setcookie ("cookie[one]", "cookieone"); 5 if (isset ($cookie)) { 6 while (list ($name, $value) = each ($cookie)) { 7 echo "$name == $value<br>\n"; 8 } 9 } 10 |
For more information on cookies, see Netscape's cookie specification at http://www.netscape.com/newsref/std/cookie_spec.html.
Microsoft Internet Explorer 4 with Service Pack 1 applied does not correctly deal with cookies that have their path parameter set.
Netscape Communicator 4.05 and Microsoft Internet Explorer 3.x appear to handle cookies incorrectly when the path and time are not set.
Hyperwave는 Graz의 IICM에서 개발되었다. 이것은 처음에는 Hyper-G라는 이름으로 시작되었다가 상업화되면거 Hyperwave라는 이름으로 바뀌었다. (아마 기억에는 1996년인 것 같다.)
Hyperwave는 free software가 아니다. 현재 버전은 4.0이고 이 버전은 www.hyperwave.com에서 구할 수 있다. 30일간 사용해 볼 수 있는 시간 제약이 있는 버전을 받을 수 있을 것이다.
Hyperwave 는 데이터베이스와 비슷한 information 시스템(HIS, Hyperwave Information Server)이다. 이것의 초점은 문서를 보관하고 관리하는 것이다. 여기서 문서는 파일로 저장될 수 있는 모든 종류의 데이터를 의미한다. 각각의 문서는 그것의 object 레코드를 동반한다. 그 object 레코드에는 해당 문서에 대한 각종 meta data가 저장된다. 그 meta data는 사용자가 확장가능한 속성(attribute)들의 목록(list)으로 되어있다. 어떤 속성들은 Hyperwave 서버에 의해서 설정된다. 다른 속성들은 사용자가 수정해 줄 수 있다.
문서외에도 문서에 포함된 모든 hyper link까지도 object 레코드로 저장된다. 문서를 데이터베이스에 저장할 때 문서에 포함된 hyper link는 문서에서는 삭제되고 개개의 object로 저장된다. 해당 link의 object 레코드는 그 링크가 문서에서 차지하는 시작 위치와 끝나는 위치에 대한 정보를 저장하고 있게 된다. 원래의 문서를 얻기 위해서 여러분은 우선 링크가 없는 문서를 검색한 후에 링크를 리스트하고, 그것들을 끼워 넣는다. (hw_pipedocument()와 hw_gettext() 함수가 이를 위해 사용된다.) 문서에서 link를 분리하는 것의 장점은 명확하다. 우선 링크의 내용을 수정하는 것이 간단하다. 링크의 수정이 문서 전체에 영향을 미치지 않기 때문이다. 또한 문서를 수정하지 않고도 링크를 추가할 수도 있다.
hw_pipedocument()와 hw_gettext()를 사용하여 링크를 삽입하는 것은 보기보다 쉬운일이 아니다. 링크의 삽입은 문서의 명확한 계층 구조를 요구한다. 웹 서버에서 이것은 파일 시스템으로 설정한다. 그러나 Hyperwave는 해당 파일 시스템 계층 구조와는 관계없는 고유의 계층구조와 이름을 가지게 된다. 그러므로, 링크를 만들 때는 우선 Hyperwave 계층 구조와 namespace를 웹의 계층구조와 namespace로 맵핑하는 것부터 하여야 한다. Hyperwave와 웹 간의 가장 기본적인 차이는 이름의 명확한 구별성과 Hyperwave 계층구조에 있다. Hyperwave에서 이름은 object가 계층구조에서의 위치에 대한 정보는 전혀 가지고 있지 않다. 그러나 웹에서는 이름이 계층구조의 어디에 위치하는가에 대한 정보를 포함하고 있게 된다. 이로서 두가지 맵핑 방법이 가능하다. Hyperwave object의 Hyperwave 계층구조와 이름을 사용하여 URL에 반영하는 방법과 이름만을 사용하는 방법이다. 일반적으로 간단한 방법은 이름만을 사용하는 방법이다. Hyperwave 계층구조 안에 존재하는 'my_object'이라는 이름을 가진 Hyperwave object는 'http://host/my_object' 로 맵핑된다. Hyperwave 계층구조에서는 'parent/my_object' 라는 이름을 가진 object가 'my_object'의 밑에(child) 있을 수도 있다. 물론, 웹 namespace에서는 그것이 상반되는 것이며 사용자들에게 혼란을 가져다 준다. 적절한 obect 이름을 선택하는 것만이 이 혼란을 피할 수 있다.
이 결정을 내리게 되면 두분째 문제가 생긴다. 어떻게 PHP에 포함시킬 것인가? http://host/my_object의 URL로는 어떤 PHP스크립트도 호출하지 못한다. 이를 위해서는 여러분이 웹서버에 이주소를 'http://host/php3_script/my_object'같은 주소로 재설정하도록 알려주어야 하고, $PATH_INFO 변수와 Hyperwave server의 'my_object'라는 이름의 object를 검색하여 평가하는 'php3_script'라는 스크립트가 있어야 한다.
여기에는 쉽게 고칠 수 있는 결점이 하나 있다. 웹서버에서 언제나 다른 문서로의 접근이 가능한 URL을 재설정할 수 있는 것은 아니라는 것이다. Hyperwave 서버룰 검색하기 위한 PHP 스크립트는 아마 불가능할 것이다. 그러므로 여러분은 최소한 http://host/Hyperwave로 시작하는 것 같은 특정 URL은 제외시키는 두 번째 재설정 규칙을 설정할 필요가 있다. 이것이 웹의 namespace와 Hyperwave 서버를 공유하는 기본이 된다.
링크의 삽입은 위의 메카니즘하에서 이루어 진다. 만약 PHP가 module이나 CGI 스크립트가 아닌 독립 실행 프로그램이라면(예를들어 CD-ROM에 있는 Hyperwave 서버의 내용을 덤프해 본다던지 하는) 이 동작은 매우 복잡해진다. 이런 경우라면 Hyperwave 계층구조를 유지하고 이를 바탕으로 파일 시스템에 맵한다. 만약 Hyperwave 계층구조를 파일 시스템의 계층구조에 그대로 반영하고자 한다면 계층구조와 object 이름간에 모순이 생길 수 있다 ('/'이 포함된 이름의 경우). 따라서 '/'는 반드시 '_'같은 다른 글자로 대치되어야만 한다.
Hyperwave 서버와 통신하는 네트워크 프로토콜은 HG-CSP (Hyper-G Client/Server Protocol)이라고 불린다. 이것은 특정 동작(object 레코드를 일거오는 것 같은)을 시작하는 메세지에 기반한다. Hyperwave 서버의 초기 버전에는 서버와의 통신을 제공하기 위해 Harmony와 Amadeus라는 두 개의 고유한 클라이언트가 있었다. 그러나 이 두가지는 Hyperwave가 상용화되면서 사라지고, wavemaster 라는 것으로 대치되었다. wavemaster는 HTTP에서 HG-CSP로의 프로토콜 변환기(protocol converter) 같은 것이다. 이것은 데이터베이스의 관리와 문서의 표시 등 모든 것을 웹 환경에서 해결하려는 생각이다. wavemaster는 사용자가 인터페이스를 수정하는 특정 동작을 위한 일련의 placeholder들을 제공한다. 이 일련의 placeholder들을 PLACE 언어라고 부른다. PLACE는 진정한 프로그래밍 언어나 이를 위한 다른 extension에 비해서는 많은 면에서 부족하다. PLACE는 단지 placeholder 개수를 늘려주는 것 뿐이다. 따라서 Javascript의 사용이 필수적으로 요구된다.
PHP에 Hyperwave 지원을 추가함으로써, interface customisation부분에서 PHP의 프로그래밍 언어의 부족한 부분을 보충할 수 있다. 이것은 HG-CSP에 의해 정의된 모든 메시지를 구현하는 것이고, 나아가 완성된 문서를 검색하는 등의 더 강력한 명령들을 추가하였다.
Hyperwave는 정보의 특정한 단편들에 이름을 붙이기 위한 자신만의 작명법(terminology)을 가지고 있다. 이것은 광범위하게 확대되고 있다. 대부분의 함수들은 다음 데이터 타입 중에 하나에 작용한다.
object ID: Hyperwave 서버에 있는 개개의 object에 대응하는 유일한 정수값. 이것은 또한 object 레코드의 한 속성이기도 하다. Object id는 때때로 특정 object를 지정하기 위한 input 파라메터로도 사용된다.
object record: 속성=값(attribute=value)의 형태로 짝지워진 속성-값의 문자열. 각각의 쌍은 carriage return("\r")으로 구분된다. 하나의 object 레코드는 hw_object2array() 함수를 사용하여 하나의 object 배열로 변환된다. 몇몇의 함수는 object 레코드를 결과값으로 돌려주는데, 이런 함수들의 이름은 obj로 끝난다.
object array: object의 모든 속성(attribute)들을 담고 있는 연합된(associated) 배열(key-value가 쌍으로 저장되는 배열). 배열의 key로는 속성의 이름이 사용된다. 만약 어떤 속성이 한 object 레코드에 한번 이상 나타난다면, 그것은 다른 인덱스되거나 연합된 배열에 저장한다. title이나 keyword, description 값은 사용 언어에 종속적인 속성들은 언어의 약호를 key로 사용하여 연합 배열을 형성한다. 다른 모든 복합적인 속성들은 인덱스된 배열로 현성된다. PHP함수들은 절대로 object array를 함수의 결과값으로 돌려주지 않는다.
hw_document: 이 타입은 HTML이나 PDF 같은 실제 문서를 담아두는 완전히 새로운 타입이다. 이 형태는 HTML 문서에 대하여 어느정도 최적화 되어있으나 다른 현태의 문서에도 사용할 수 있다.
object 레코드의 배열를 반환하는 몇몇 함수들을 해당 레코드들에 대한 통계적 정보를 가진 연합 배열도 함께 반환한다. 반환된 전체 object 레코드의 배열의 마지막 원소가 이 배열이다. 통계적 정보를 가진 배열에는 다음과 같은 요소들의 정보가 있다.
|
PresentationHints 속성이 Hidden으로 설정된 object 레코드의 개수 |
|
PresentationHints 속성이 CollectionHead으로 설정된 object 레코드의 개수 |
|
PresentationHints 속성이 FullCollectionHead으로 설정된 object 레코드의 개수 |
|
PresentationHints 속성이 CollectionHead으로 설정된 object 레코드 배열의 index |
|
PresentationHints 속성이 FullCollectionHead으로 설정된 object 레코드 배열의 index |
|
object 레코드의 전체 개수 |
Hyperwave 모듈은 PHP가 아파치 모듈로 컴파일되었을 때 가장 잘 사용될 수 있다. 이 경우에 아파치가 자신의 재작성(rewriting) 엔진을 사용하게 되면 Hyperwave 서버의 존재는 사용자가 거의 느낄 수 없게 된다. 다음의 내용들이 이것을 설명해 줄 것이다.
Hyperwave를 지원하는 아파치로 만들어진 PHP가 wavemaster기반의 독자적인 Hyperwave 솔루션을 대신하려 할 때부터, 아파치 서버가 Hyperwave 웹 인터페이스를 지원하는 유일한 서버가 되리라 당연히 추정되었다.
이것은 반드시 필요한 것은 아니지만 설정을 쉽게 해준다. 개념은 단순하다. 우선, 여러분은 PATH_INFO 변수를 평가하고 이 변수의 값을 Hyperwave object로 다룰 PHP 스크립트가 필요하다. 이제 이 스크립트의 이름을 'Hyperwave'라고 부르자. http://your.hostname/Hyperwave/name_of_object라는 URL은 아마도 'name_of_object'라는 이름을 가진 Hyperwave object를 반환할 것이다. 스크립트는 그 object의 타입에 따라서 적절히 반응한다. 만약 타입이 collection이라면 아마도 children의 리스트를 반환한다. 만약 타입이 문서(document)라면 mime 타입과 그 내용을 반환한다. 아파치 재작성 엔진 (apache rewriting engine)이 사용된다면 약간의 개선을 얻을 수 있다. http://your.hostname/name_of_object같은 형태로 URL을 사용하여 object를 반환한다면 사용자 입장에서 좀더 직관적일 수 있다. 이를 위한 재작성(rewriting) 규칙은 다음과 같이 매우 쉽다. :
1 2 RewriteRule ^/(.*) /usr/local/apache/htdocs/HyperWave/$1 [L] 3 |
이제 모든 URL은 Hyperwave 서버의 object와 연결된다. 이것은 비교적 간단히 해결할 수 있는 한가지 문제를 만들어 낸다. 이로써 'Hyperwave' 스크립트 이외의 다른 스크립트(예를들어, 검색을 위한 스크립트 등)는 실행할 수 없게 된다. 이를 해결하기 위한 또다른 작성(rewriting) 규칙을 다음과 같이 작성해 준다.
1 2 RewriteRule ^/hw/(.*) /usr/local/apache/htdocs/hw/$1 [L] 3 |
이것으로 추가적인 스크립트와 파일들을 위한 /usr/local/apache/htdocs/hw 디렉토리를 남겨두게 된다. 그리고 이 규칙을 위의 규칙보다 먼저 평가되도록 한다. 약간의 결점이 있는데, 'hw/'로 시작하는 이름을 가진 Hyperwave object는 접근할 수 없게 된다. 그러므로 여러분은 그런 이름은 쓰지 않도록 한다. 만약 여러분이 더 많은 디렉토리(예를들어, 이미지를 위한 디렉토리)가 필요하다면, 새로운 규칙을 첨가하거나 원하는 디렉토리들을 모두 한 디렉토리 밑에 놓으면 된다. 마지막으로, 다음과 같이하여 재작성 엔진(rewriting engine)을 켜도록 한다. :
1 2 RewriteEngine on 3 |
내 경험으로 보았을 때 여러분을 다음의 스크립트들이 필요하게 될 것이다. :
object 자신을 돌려주기 (to return the object itself)
검색 가능하게 하기 (to allow searching)
자기 자신에 대한 확인 (to identify yourself)
profile 설정 (to set your profile)
object 속성을 보여주거나, 사용자의 정보를 보여주거나, 서버의 상태를 보여주는 것 같은 종류의 함수들
아직 해야할 일은 다음과 같다. :
hw_InsertDocument를 hw_InsertObject()와 hw_PutDocument()의 두 함수로 나누기
개개의 함수들은 그 이름이 아직 확정되지 않았다.
대부분의 함수는 첫 번째 파라메터로 현재의 연결(connection)을 요구한다. 이것은 한 개의 연결만 있는 경우 대부분 별 필요없는 타이핑이 필요하게 된다. 이를 위해 기본 연결(default connection)이 필요할 것이다.
다중 속성(multiple attribute)을 다루기 위해 object record 로부터 object array 로의 변환기능이 필요하다.
strin hw_array2objrec
(array object_array)
Converts an object_array into an object record. Multiple attributes like 'Title' in different languages are treated properly.
See also hw_objrec2array().
hw_Children -- children의 object id들
array hw_children
(int connection, int objectID);
Returns an array of object ids. Each id belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.
hw_ChildrenObj -- children의 object record들
array hw_childrenobj
(int connection, int objectID);
Returns an array of object records. Each object record belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.
hw_Close -- Hyperwave connection을 닫는다.
int hw_close
(int connection);
Returns false if connection is not a valid connection index, otherwise true. Closes down the connection to a Hyperwave server with the given connection index.
hw_Connect -- Hyperwave connection을 연다.
int hw_connect
(string host, int port, string username, string password);
Opens a connection to a Hyperwave server and returns a connection index on success, or false if the connection could not be made. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple connections open at once. Keep in mind, that the password is not encrypted.
See also hw_pConnect().
hw_Cp -- 지정한 object들을 복사한다.
int hw_cp
(int connection, array object_id_array, int destination id);
Copies the objects with object ids as specified in the second parameter to the collection with the id destination id.
The value return is the number of copied objects.
See also hw_mv().
hw_Deleteobject -- 특정 object를 삭제한다.
int hw_deleteobject
(int connection, int object_to_delete);
Deletes the the object with the given object id in the second parameter. It will delete all instances of the object.
Returns TRUE if no error occurs otherwise FALSE.
See also hw_mv().
hw_DocByAnchor -- 지정된 anchor에 속하는 object의 object id
int hw_docbyanchor
(int connection, int anchorID);
Returns an th object id of the document to which anchorID belongs.
hw_DocByAnchorObj -- 지정된 anchor에 속하는 object의 object record
string hw_docbyanchorobj
(int connection, int anchorID);
Returns an th object record of the document to which anchorID belongs.
hw_DocumentAttributes -- hw_document의 object record
string hw_documentattributes
(int hw_document);
Returns the object record of the document.
See also hw_DocumentBodyTag(), hw_DocumentSize().
hw_DocumentBodyTag -- hw_document의 body tag을 반환한다.
string hw_documentbodytag
(int hw_document);
Returns the BODY tag of the document. If the document is an HTML document the BODY tag should be printed before the document.
See also hw_DocumentAttributes(), hw_DocumentSize().
hw_DocumentContent -- hw_document의 내용을 반환한다.
string hw_documentcontent
(int hw_document);
Returns the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record.
See also hw_DocumentAttributes(), hw_DocumentSize(), hw_DocumentSetContent().
hw_DocumentSetContent -- hw_document의 내용을 설정하거나 재지정한다.
string hw_documentsetcontent
(int hw_document, string content);
Sets or replaces the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record. If you provide this information in the content of the document too, the Hyperwave server will change the object record accordingly when the document is inserted. Probably not a very good idea. If this functions fails the document will retain its old content.
See also hw_DocumentAttributes(), hw_DocumentSize(), hw_DocumentContent().
hw_DocumentSize -- hw_document의 크기
int hw_documentsize
(int hw_document);
Returns the size in bytes of the document.
See also hw_DocumentBodyTag(), hw_DocumentAttributes().
hw_ErrorMsg -- error message를 반환한다.
string hw_errormsg
(int connection);
Returns a string containing the last error message or 'No Error'. If false is returned, this function failed. The message relates to the last command.
hw_EditText -- text 문서를 원래대로 복구(retrieve)한다.
int hw_edittext
(int connection, int hw_document);
Uploads the text document to the server. The object record of the document may not be modified while the document is edited. This function will only works for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.
See also hw_PipeDocument(), hw_FreeDocument(), hw_DocumentBodyTag(), hw_DocumentSize(), hw_OutputDocument(), hw_GetText().
hw_Error -- error 번호를 반환한다.
int hw_error
(int connection);
Returns the last error number. If the return value is 0 no error has occurred. The error relates to the last command.
hw_Free_Document -- hw_document가 점유하고 있는 자원들을 풀어준다.
int hw_free_document
(int hw_document);
Frees the memory occupied by the Hyperwave document.
hw_GetParents -- parent들의 object id들
array hw_getparentsobj
(int connection, int objectID);
Returns an indexed array of object ids. Each object id belongs to a parent of the object with ID objectID.
hw_GetParentsObj -- parent들의 object record들
array hw_getparentsobj
(int connection, int objectID);
Returns an indexed array of object records plus an associated array with statistical information about the object records. The associated array is the last entry of the returned array. Each object record belongs to a parent of the object with ID objectID.
hw_GetChildColl -- child collection들의 object id들
array hw_getchildcoll
(int connection, int objectID);
Returns an array of object ids. Each object ID belongs to a child collection of the collection with ID objectID. The function will not return child documents.
See also hw_GetChildren(), hw_GetChildDocColl().
hw_GetChildCollObj -- child collection들의 object record들
array hw_getchildcollobj
(int connection, int objectID);
Returns an array of object records. Each object records belongs to a child collection of the collection with ID objectID. The function will not return child documents.
See also hw_ChildrenObj(), hw_GetChildDocCollObj().
hw_GetRemote -- remote document를 구한다.
int hw_getremote
(int connection, int objectID);
Returns a remote document. Remote documents in Hyperwave notation are documents retrieved from an external source. Common remote documents are for example external web pages or queries in a database. In order to be able to access external sources throught remote documents Hyperwave introduces the HGI (Hyperwave Gateway Interface) which is similar to the CGI. Currently, only ftp, http-servers and some databases can be accessed by the HGI. Calling hw_GetRemote() returns the document from the external source. If you want to use this function you should be very familiar with HGIs. You should also consider to use PHP instead of Hyperwave to access external sources. Adding database support by a Hyperwave gateway should be more difficult than doing it in PHP.
See also hw_GetRemoteChildren().
hw_GetRemoteChildren -- remote document의 children을 구한다.
int hw_getremotechildren
(int connection, string object record);
Returns the children of a remote document. Children of a remote document are remote documents itself. This makes sense if a database query has to be narrowed and is explained in Hyperwave Programmers' Guide. If the number of children is 1 the function will return the document itself formated by the Hyperwave Gateway Interface (HGI). If the number of children is greater than 1 it will return an array of object record with each maybe the input value for another call to hw_GetRemoteChildren(). Those object records are virtual and do not exist in the Hyperwave server, therefore they do not have a valid object ID. How exactely such an object record looks like is up to the HGI. If you want to use this function you should be very familiar with HGIs. You should also consider to use PHP instead of Hyperwave to access external sources. Adding database support by a Hyperwave gateway should be more difficult than doing it in PHP.
See also hw_GetRemote().
hw_GetSrcByDestObj -- 지정된 object를 지시하는 anchor들을 반환한다.
array hw_getsrcbydestobj
(int connection, int objectID);
Returns the object records of all anchors pointing to the object with ID objectID. The object can either be a document or an anchor of type destination.
See also hw_GetAnchors().
hw_GetObject -- 지정한 object record를 반환한다.
array hw_getobject
(int connection, [int|array] objectID, string query);
Returns the object record for the object with ID objectID if the second parameter is an integer. If the second parameter is an array of integer the function will return an array of object records. In such a case the last parameter is also evaluated which is a query string.
The query string has the following syntax:
<expr> ::= "(" <expr> ")" |
"!" <expr> | /* NOT */
<expr> "||" <expr> | /* OR */
<expr> "&&" <expr> | /* AND */
<attribute> <operator> <value>
<attribute> ::= /* any attribute name (Title, Author, DocumentType ...) */
<operator> ::= "=" | /* equal */
"<" | /* less than (string compare) */
">" | /* greater than (string compare) */
"~" /* regular expression matching */
The query allows to further select certain objects from the list of given objects. Unlike the other query functions, this query may use not indexed attributes. How many object records are returned depends on the query and if access to the object is allowed.
See also hw_GetAndLock(), hw_GetObjectByQuery().
hw_GetAndLock -- object record를 반환하고 해당 object를 lock한다.
string hw_getandlock
(int connection, int objectID);
Returns the object record for the object with ID objectID. It will also lock the object, so other users cannot access it until it is unlocked.
See also hw_Unlock(), hw_GetObject().
hw_GetText -- text 문서를 원래대로 복구(retrieve)한다.
int hw_gettext
(int connection, int objectID, mixed [rootID/prefix] );
Returns the document with object ID objectID. If the document has anchors which can be inserted, they will be inserted already. The optional parameter rootID/prefix can be a string or an integer. If it is an integer it determines how links are inserted into the document. The default is 0 and will result in links that are constructed from the name of the link's destination object. This is useful for web applications. If a link points to an object with name 'internet_movie' the HTML link will be <A HREF="/internet_movie">. The actual location of the source and destination object in the document hierachy is disregarded. You will have to set up your web browser, to rewrite that URL to for example '/my_script.php3/internet_movie'. 'my_script.php3' will have to evaluate $PATH_INFO and retrieve the document. All links will have the prefix '/my_script.php3/'. If you do not want this you can set the optional parameter rootID/prefix to any prefix which is used instead. Is this case it has to be a string.
If rootID/prefix is an integer and unequal to 0 the link is constructed from all the names starting at the object with the id rootID/prefix separated by a slash relative to the current object. If for example the above document 'internet_movie' is located at 'a-b-c-internet_movie' with '-' being the seperator between hierachy levels on the Hyperwave server and the source document is located at 'a-b-d-source' the resulting HTML link would be: <A HREF="../c/internet_movie">. This is useful if you want to download the whole server content onto disk and map the document hierachy onto the file system.
This function will only work for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.
See also hw_PipeDocument(), hw_FreeDocument(), hw_DocumentBodyTag(), hw_DocumentSize(), hw_OutputDocument().
hw_GetObjectByQuery -- object를 찾는다.
array hw_getobjectbyquery
(int connection, string query, int max_hits);
Searches for objects on the whole server and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.
The query will only work with indexed attributes.
See also hw_GetObjectByQueryObj().
hw_GetObjectByQueryObj -- object를 찾는다.
array hw_getobjectbyqueryobj
(int connection, string query, int max_hits);
Searches for objects on the whole server and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.
The query will only work with indexed attributes.
See also hw_GetObjectByQuery().
hw_GetObjectByQueryColl -- collection 안에서 object을 찾는다.
array hw_getobjectbyquerycoll
(int connection, int objectID, string query, int max_hits);
Searches for objects in collection with ID objectID and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.
The query will only work with indexed attributes.
See also hw_GetObjectByQueryCollObj().
hw_GetObjectByQueryCollObj -- collection 안에서 object을 찾는다.
array hw_getobjectbyquerycollobj
(int connection, int objectID, string query, int max_hits);
Searches for objects in collection with ID objectID and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.
The query will only work with indexed attributes.
See also hw_GetObjectByQueryColl().
hw_GetChildDocColl -- collection 안의 child 문서들의 object id를 구한다.
array hw_getchilddoccoll
(int connection, int objectID);
Returns array of object ids for child documents of a collection.
See also hw_GetChildren(), hw_GetChildColl().
hw_GetChildDocCollObj -- collection 안의 child 문서들의 object record를 구한다.
array hw_getchilddoccollobj
(int connection, int objectID);
Returns an array of object records for child documents of a collection.
See also hw_ChildrenObj(), hw_GetChildCollObj().
hw_GetAnchors -- 문서의 anchor들의 object id
array hw_getanchors
(int connection, int objectID);
Returns an array of object ids with anchors of the document with object ID objectID.
hw_GetAnchorsObj -- 문서의 anchor들의 object record
array hw_getanchorsobj
(int connection, int objectID);
Returns an array of object records with anchors of the document with object ID objectID.
hw_Mv -- object들을 옮긴다.
int hw_mv
(int connection, array object id array, int source id, int destination id);
Moves the objects with object ids as specified in the second parameter from the collection with id source id to the collection with the id destination id. If the destination id is 0 the objects will be unlinked from the source collection. If this is the last instance of that object it will be deleted. If you want to delete all instances at once, use hw_deleteobject().
The value return is the number of moved objects.
See also hw_cp(), hw_deleteobject().
hw_Identify -- 사용자를 identify한다.
int hw_identify
(string username, string password);
Identifies as user with username and password. Identification is only valid for the current session. I do not thing this function will be needed very often. In most cases it will be easier to identify with the opening of the connection.
See also hw_Connect().
hw_InCollections -- object id의 object가 collection에 속하는가 검사한다.
array hw_incollections
(int connection, array object_id_array, array collection_id array, int return_collections);
Checks whether a set of objects (documents or collections) specified by the object_id_array is part of the collections listed in collection_id_array. When the fourth parameter return_collections is 0, the subset of object ids that is part of the collections (i.e., the documents or collections that are children of one or more collections of collection ids or their subcollections, recursively) is returned as an array. When the fourth parameter is 1, however, the set of collections that have one or more objects of this subset as children are returned as an array. This option allows a client to, e.g., highlight the part of the collection hierarchy that contains the matches of a previous query, in a graphical overview.
hw_Info -- connection에 대한 정보
string hw_info
(int connection);
Returns information about the current connection. The returned string has the following format: <Serverstring>, <Host>, <Port>, <Username>, <Port of Client>, <Byte swapping>
hw_InsColl -- collection을 삽입한다.
int hw_inscoll
(int connection, int objectID, array object_array);
Inserts a new collection with attributes as in object_array into collection with object ID objectID.
hw_InsDoc -- document를 삽입한다.
int hw_insdoc
(int connection, int parentID, string object_record, string text);
Inserts a new document with attributes as in object_record into collection with object ID parentID. This function inserts either an object record only or an object record and a pure ascii text in text if text is given. If you want to insert a general document of any kind use hw_insertdocument() instead.
See also hw_InsertDocument(), hw_InsColl().
hw_InsertDocument -- 어떤 document를 collection으로 upload 한다.
int hw_insertdocument
(int connection, int parent_id, int hw_document);
Uploads a document into the collection with parent_id. The document has to be created before with hw_NewDocument(). Make sure that the object record of the new document contains at least the attributes: Type, DocumentType, Title and Name. Possibly you also want to set the MimeType. The functions returns the object id of the new document or false.
See also hw_PipeDocument().
hw_InsertObject -- object record를 추가한다.
int hw_insertobject
(int connection, string object rec, string parameter);
Inserts an object into the server. The object can be any valid hyperwave object. See the HG-CSP documentation for a detailed information on how the parameters have to be.
Note: If you want to insert an Anchor, the attribute Position has always been set either to a start/end value or to 'invisible'. Invisible positions are needed if the annotation has no correspondig link in the annotation text.
See also hw_PipeDocument(), hw_InsertDocument(), hw_InsDoc(), hw_InsColl().
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
hw_mapid -- global id 를 가상의 local id로 맵핑시킨다.int hw_mapid
(int
connection, int server id, int object id)
Maps a global object id on any hyperwave server, even those you did not connect to with hw_connect(), onto a virtual object id. This virtual object id can then be used as any other object id, e.g. to obtain the object record with hw_getobject(). The server id is the first part of the global object id (GOid) of the object which is actually the IP number as an integer.
Note: In order to use this function you will have to set the F_DISTRIBUTED flag, which can currently only be set at compile time in hg_comm.c. It is not set by default. Read the comment at the beginning of hg_comm.c
hw_Modifyobject -- object 레코드를 수정한다.
int hw_modifyobject
(int connection, int object_to_change, array remove, array add, int mode);
This command allows to remove, add, or modify individual attributes of an object record. The object is specified by the Object ID object_to_change. The first array remove is a list of attributes to remove. The second array add is a list of attributes to add. In order to modify an attribute one will have to remove the old one and add a new one. hw_modifyobject() will always remove the attributes before it adds attributes unless the value of the attribute to remove is not a string or array.
The last parameter determines if the modification is performed recursively. 1 means recurive modification. If some of the objects cannot be modified they will be skiped without notice. hw_error() may not indicate an error though some of the objects could not be modified.
The keys of both arrays are the attributes name. The value of each array element can either be an array, a string or anything else. If it is an array each attribute value is constructed by the key of each element plus a colon and the value of each element. If it is a string it is taken as the attribute value. An empty string will result in a complete removal of that attribute. If the value is neither a string nor an array but something else, e.g. an integer, no operation at all will be performed on the attribute. This is neccessary if you want to to add a completely new attribute not just a new value for an existing attribute. If the remove array contained an empty string for that attribute, the attribute would be tried to be removed which would fail since it doesn't exist. The following addition of a new value for that attribute would also fail. Setting the value for that attribute to e.g. 0 would not even try to remove it and the addition will work.
If you would like to change the attribute 'Name' with the current value 'books' into 'articles' you will have to create two arrays and call hw_modifyobject().
Example 1. modifying an attribute
|
Example 2. adding a completely new attribute
|
Note: Multilingual attributes, e.g. 'Title', can be modified in two ways. Either by providing the attributes value in its native form 'language':'title' or by providing an array with elements for each language as described above. The above example would than be:
Example 3. modifying Title attribute
|
Example 4. modifying Title attribute
|
Example 5. removing attribute
|
Note: This will remove all attributes with the name 'Title' and adds a new 'Title' attribute. This comes in handy if you want to remove attributes recursively.
Note: If you need to delete all attributes with a certain name you will have to pass an empty string as the attribute value.
Note: Only the attributes 'Title', 'Description' and 'Keyword' will properly handle the language prefix. If those attributes don't carry a language prefix, the prefix 'xx' will be assigned.
Note: The 'Name' attribute is somewhat special. In some cases it cannot be complete removed. You will get an error message 'Change of base attribute' (not clear when this happens). Therefore you will always have to add a new Name first and than remove the old one.
Note: You may not suround this function by calls to hw_getandlock() and hw_unlock(). hw_modifyobject() does this internally.
Returns TRUE if no error occurs otherwise FALSE.
hw_New_Document -- 새 document를 만든다.
int hw_new_document
(string object_record, string document_data, int document_size);
Returns a new Hyperwave document with document data set to document_data and object record set to object_record. The length of the document_data has to passed in document_sizeThis function does not insert the document into the Hyperwave server.
See also hw_FreeDocument(), hw_DocumentSize(), hw_DocumentBodyTag(), hw_OutputDocument(), hw_InsertDocument().
hw_Objrec2Array -- object record의 속성(attributes)을 object array로 변환한다.
array hw_objrec2array
(string object_record);
Converts an object_record into an object array. The keys of the resulting array are the attributes names. Multiple attributes like 'Title' in different languages form its own array. The keys of this array are the left part to the colon of the attribute value. Currently only the attributes 'Title', 'Description' and 'Keyword' are treated properly.
See also hw_Array2Objrec().
hw_OutputDocument -- hw_document를 print한다.
int hw_outputdocument
(int hw_document);
Prints the document without the BODY tag.
hw_pConnect -- 영구적인(persistent) database connection을 만든다.
int hw_pconnect
(string host, int port, string username, string password);
Returns a connection index on success, or false if the connection could not be made. Opens a persistent connection to a Hyperwave server. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple persistent connections open at once.
See also hw_Connect().
hw_PipeDocument -- document를 원래대로 복구(retrieve)한다.
int hw_pipedocument
(int connection, int objectID);
Returns the Hyperwave document with object ID objectID. If the document has anchors which can be inserted, they will have been inserted already. The document will be transfered via a special data connection which does not block the control connection.
See also hw_GetText() for more on link insertion, hw_FreeDocument(), hw_DocumentSize(), hw_DocumentBodyTag(), hw_OutputDocument().
hw_Root -- root object의 object id
int hw_root
();
Returns the object ID of the hyperroot collection. Currently this is always 0. The child collection of the hyperroot is the root collection of the connected server.
hw_Unlock -- object를 unlock 한다.
int hw_unlock
(int connection, int objectID);
Unlocks a document, so other users regain access.
See also hw_GetAndLock().
hw_Who -- 현재 login 되어 있는 사용자들을 list한다.
int hw_who
(int connection);
Returns an array of users currently logged into the Hyperwave server. Each entry in this array is an array itself containing the elements id, name, system, onSinceDate, onSinceTime, TotalTime and self. 'self' is 1 if this entry belongs to the user who initianted the request.
hw_Username -- 현재 log in 하고 있는 user의 이름
string hw_getusername
(int connection);
Returns the username of the connection.
여러분은 여기의 함수들로 JPEG, GIF, PNG 이미지의 크기를 알아볼 수 있다. 또한 여러분이 GD library(http://www.boutell.com/gd/에 있다.)를 가지고 있다면, 여러분은 GIF 이미지를 만들거나 수정할 수 있다.
GetImageSize -- GIF나 JPG, PNG 그림의 크기를 구한다.
array getimagesize
(string filename [, array imageinfo])
The GetImageSize() function will determine the size of any GIF, JPG or PNG image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML IMG tag.
Returns an array with 4 elements. Index 0 contains the width of the image in pixels. Index 1 contains the height. Index 2 a flag indicating the type of the image. 1 = GIF, 2 = JPG, 3 = PNG. Index 3 is a text string with the correct "height=xxx width=xxx" string that can be used directly in an IMG tag.
Example 1. GetImageSize
|
The optional imageinfo parameter allows you to extract some extended information from the image file. Currently this will return the diffrent JPG APP markers in an associative Array. Some Programs use these APP markers to embedd text information in images. A very common one in to embed IPTC http://www.xe.net/iptc/ information in the APP13 marker. You can use the iptcparse() function to parse the binary APP13 marker into something readable.
Example 2. GetImageSize returning IPTC
|
Note: This function does not require the GD image library.
ImageArc -- 타원 호를 그 린 다.
int imagearc
(int im,
int cx, int cy, int w, int h, int s, int e, int col)
ImageArc() draws a partial ellipse centered at cx, cy (top left is 0, 0) in the image represented by im. W and h specifies the ellipse's width and height respectively while the start and end points are specified in degrees indicated by the s and e. arguments.
ImageChar -- 한 글자를 수평으로 그린다.
int imagechar
(int im,
int font, int x, int y, string c, int col)
ImageChar() draws the first character of c in the image identified by id with its upper-left at x,y (top left is 0, 0) with the color col. If font is 1, 2, 3, 4 or 5, a built-in font is used (with higher numbers corresponding to larger fonts).
See also imageloadfont().
ImageCharUp -- 한 글자를 수직으로 그린다.
int imagecharup
(int im,
int font, int x, int y, string c, int col)
ImageCharUp() draws the character c vertically in the image identified by im at coordinates x, y (top left is 0, 0) with the color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.
See also imageloadfont().
ImageColorAllocate -- 그림을 위한 색깔을 할당한다.
int imagecolorallocate
(int im, int red, int green, int blue)
ImageColorAllocate() returns a color identifier representing the color composed of the given RGB components. The im argument is the return from the imagecreate() function. ImageColorAllocate() must be called to create each color that is to be used in the image represented by im.
1 2 $white = ImageColorAllocate ($im, 255, 255, 255); 3 $black = ImageColorAllocate ($im, 0, 0, 0); 4 |
int imagecolordeallocate
(int im, int index)
The ImageColorDeAllocate() function de-allocates a color previously allocated with the ImageColorAllocate() function.
1 2 $white = ImageColorAllocate($im, 255, 255, 255); 3 ImageColorDeAllocate($im, $white); 4 |
ImageColorAt -- 해당 pixel 색깔의 index를 구한다.
int imagecolorat
(int im, int
x, int y)Returns the index of the color of the pixel at the specified location in the image.
See also imagecolorset() and imagecolorsforindex().
ImageColorClosest -- 지정된 색과 가장 가까운 색의 index를 구한다.
int imagecolorclosest
(int im,
int red, int green, int blue);Returns the index of the color in the palette of the image which is "closest" to the specified RGB value.
The "distance" between the desired color and each color in the palette is calculated as if the RGB values represented points in three-dimensional space.
See also imagecolorexact().
ImageColorExact -- 지정된 색의 index를 구한다.
iint imagecolorexact
(int im,
int red, int green, int blue);
Returns the index of the specified color in the palette of the image.
If the color does not exist in the image's palette, -1 is returned.
See also imagecolorclosest().
ImageColorResolve -- 특정색이나 그에 가장 가까운 색의 index를 구한다.
int imagecolorresolve
(int im,
int red, int green, int blue);This function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.
See also imagecolorclosest().
int imagegammacorrect
(int im, double inputgamma, double outputgamma)
The ImageGammaCorrect() function applies gamma correction to a gd image stream (im) given an input gamma, the parameter inputgamma and an output gamma, the parameter outputgamma.
ImageColorSet -- 지정한 색을 특정 palette index로 정한다.
bool imagecolorset
(int im, int
index, int red, int green, int blue);This sets the specified index in the palette to the specified color. This is useful for creating flood-fill-like effects in paletted images without the overhead of performing the actual flood-fill.
See also imagecolorat().
ImageColorsForIndex -- 지정한 index의 색을 구한다.
array imagecolorsforindex
(int
im, int index);This returns an associative array with red, green, and blue keys that contain the appropriate values for the specified color index.
See also imagecolorat() and imagecolorexact().
ImageColorsTotal -- 그림의 palette에 있는 색의 개수를 구한다.
int imagecolorstotal
(int im);This returns the number of colors in the specified image's palette.
See also imagecolorat() and imagecolorsforindex().
ImageColorTransparent -- 투명한 색깔을 지정한다.
int imagecolortransparent
(int im [, int col])
ImageColorTransparent() sets the transparent color in the im image to col. Im is the image identifier returned by ImageCreate() and col is a color identifier returned by ImageColorAllocate().
The identifier of the new (or current, if none is specified) transparent color is returned
int ImageCopy
(int
dst_im, int src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int
src_h)
Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y.
ImageCopyResized -- 그림의 일부분을 복사하고 크기를 바꾼다.
int imagecopyresized
(int
dst_im, int src_im, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH,
int srcW, int srcH);ImageCopyResized() copies a rectangular portion of one image to another image. Dst_im is the destination image, src_im is the source image identifier. If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_im is the same as src_im) but if the regions overlap the results will be unpredictable.
ImageCreate -- 새 image를 만든다.
int imagecreate
(int x_size,
int y_size);ImageCreate returns an image identifier representing a blank image of size x_size by y_size.
ImageCreateFromGif -- GIF 형태의 파일이나 URL로부터 새 image를 만든다.
int imagecreatefromgif
(string filename)
ImageCreateFromGif() returns an image identifier representing the image obtained from the given filename.
ImageCreateFromGif() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error GIF:
Example 1. Example to handle an error during creation (courtesy vic@zymsys.com)
|
Note: Since all GIF support was removed from the GD library in version 1.6, this function is not available if you are using that version of the GD library.
int imagecreatefromjpeg
(string filename)
ImageCreateFromJPEG() returns an image identifier representing the image obtained from the given filename.
ImagecreateFromJPEG() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error JPEG:
Example 1. Example to handle an error during creation (courtesy vic@zymsys.com )
|
int imagecreatefrompng
(string filename)
ImageCreateFromPNG() returns an image identifier representing the image obtained from the given filename.
ImageCreateFromPNG() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error PNG:
Example 1. Example to handle an error during creation (courtesy vic@zymsys.com)
|
ImageDashedLine -- 점선을 그린다.
int imagedashedline
(int im,
int x1, int y1, int x2, int y2, int col);
ImageDashedLine() draws a dashed line from x1, y1 to x2, y2 (top left is 0, 0) in image im of color col.
See also imageline().
ImageDestroy -- image를 없앤다.
int imagedestroy
(int im));ImageDestroy() frees any memory associated with image im. im is the image identifier returned by the imagecreate() function.
ImageFill -- 색을 채운다.
int imagefill
(int im,
int x, int y, int col)
ImageFill() performs a flood fill starting at coordinate x, y (top left is 0, 0) with color col in the image im.
ImageFilledPolygon -- 색이 채워진 다각형을 그린다.
int imagefilledpolygon
(int im, array points, int num_points, int col)
ImageFilledPolygon() creates a filled polygon in image im. Points is a PHP array containing the polygon's vertices, ie. points[0] = x0, points[1] = y0, points[2] = x1, points[3] = y1, etc. Num_points is the total number of vertices.
ImageFilledRectangle -- 색이 채워진 직사각형을 그린다.
int imagefilledrectangle
(int im, int x1, int y1, int x2, int y2, int col)
ImageFilledRectangle() creates a filled rectangle of color col() in image im starting at upper left coordinates x1, y1 and ending at bottom right coordinates x2, y2. 0, 0 is the top left corner of the image.
ImageFillToBorder -- 지정된 색으로 채운다.
int imagefilltoborder
(int im, int x, int y, int border, int col)
ImageFillToBorder() performs a flood fill whose border color is defined by border. The starting point for the fill is x, y (top left is 0, 0) and the region is filled with color col.
ImageFontHeight -- 폰트의 높이를 구한다.
int imagefontheight
(int
font)
Returns the pixel height of a character in the specified font.
See also imagefontwidth() and imageloadfont().
ImageFontWidth -- 폰트의 넓이를 구한다.
int imagefontwidth
(int
font)
Returns the pixel width of a character in font.
See also imagefontheight() and imageloadfont().
ImageGif -- 브라우저나 파일로 GIF 형태의 이미지를 출력한다.
int imagegif
(int im [, string
filename]);imagegif() creates the GIF file in filename from the image im. The im argument is the return from the imagecreate() function.
The image format will be GIF87a unless the image has been made transparent with imagecolortransparent(), in which case the image format will be GIF89a.
The filename argument is optional, and if left off, the raw image stream will be output directly. By sending an image/gif content-type using header(), you can create a PHP script that outputs GIF images directly.
Note: Since all GIF support was removed from the GD library in version 1.6, this function is not available if you are using that version of the GD library.
int imagepng
(int im [,
string filename])
The ImagePng() outputs a GD image stream (im) in PNG format to standard output (usually the browser) or, if a filename is given by the filename it outputs the image to the file.
1 2 $im = ImageCreateFromPng("test.png"); 3 ImagePng($im); 4 |
int imagejpeg
(int im [,
string filename [, int quality]])
ImageJPEG() creates the JPEG file in filename from the image im. The im argument is the return from the ImageCreate() function.
The filename argument is optional, and if left off, the raw image stream will be output directly. To skip the filename argument in order to provide a quality argument just use an empty string (''). By sending an image/jpg content-type using header(), you can create a PHP script that outputs JPEG images directly.
Note: JPEG support is only available in PHP if PHP was compiled against GD-1.8 or later.
ImageInterlace -- 그림이 섞이게 하는 interlace 설정을 켜거나 끈다.
int imageinterlace
(int im [,
int interlace]);ImageInterlace() turns the interlace bit on or off. If interlace is 1 the im image will be interlaced, and if interlace is 0 the interlace bit is turned off.
This functions returns whether the interlace bit is set for the image.
ImageLine -- 선을 그린다.
int imageline
(int im,
int x1, int y1, int x2, int y2, int col)
ImageLine() draws a line from x1, y1 to x2, y2 (top left is 0, 0) in image im of color col.
See also imagecreate() and imagecolorallocate().
ImageLoadFont -- 새 폰트를 load한다.
int imageloadfont
(string file)
ImageLoadFont() loads a user-defined bitmap font and returns an identifier for the font (that is always greater than 5, so it will not conflict with the built-in fonts).
The font file format is currently binary and architecture dependent. This means you should generate the font files on the same type of CPU as the machine you are running PHP on.
Table 1. Font file format
byte position | C data type | description |
---|---|---|
byte 0-3 | int | number of characters in the font |
byte 4-7 | int | value of first character in the font (often 32 for space) |
byte 8-11 | int | pixel width of each character |
byte 12-15 | int | pixel height of each character |
byte 16- | char | array with character data, one byte per pixel in each character, for a total of (nchars*width*height) bytes. |
See also ImageFontWidth() and ImageFontHeight().
ImagePolygon -- 다각형을 그린다.
int imagepolygon
(int
im, array points, int num_points, int col)
ImagePolygon() creates a polygon in image id. Points is a PHP array containing the polygon's vertices, ie. points[0] = x0, points[1] = y0, points[2] = x1, points[3] = y1, etc. Num_points is the total number of vertices.
See also imagecreate().
ImagePSBBox -- PostScript Type1 폰트를 사용하여 출력할 텍스트의 경계가 되는 영역을 지정한다.
array imagepsbbox
(string text, int font, int size [, int space [, int tightness [, float
angle]]])
Size is expressed in pixels.
Space allows you to change the default value of a space in a font. This amount is added to the normal value and can also be negative.
Tightness allows you to control the amount of white space between characters. This amount is added to the normal character width and can also be negative.
Angle is in degrees.
Parameters space and tightness are expressed in character space units, where 1 unit is 1/1000th of an em-square.
Parameters space, tightness, and angle are optional.
The bounding box is calculated using information available from character metrics, and unfortunately tends to differ slightly from the results achieved by actually rasterizing the text. If the angle is 0 degrees, you can expect the text to need 1 pixel more to every direction.
This function returns an array containing the following elements:
0 | lower left x-coordinate |
1 | lower left y-coordinate |
2 | upper right x-coordinate |
3 | upper right y-coordinate |
See also imagepstext().
ImagePSEncodeFont -- 폰트의 character encoding vector를 바꿔준다.
int imagepsencodefont
(string encodingfile)
Loads a character encoding vector from from a file and changes the fonts encoding vector to it. As a PostScript fonts default vector lacks most of the character positions above 127, you'll definitely want to change this if you use an other language than english. The exact format of this file is described in T1libs documentation. T1lib comes with two ready-to-use files, IsoLatin1.enc and IsoLatin2.enc.
If you find yourself using this function all the time, a much better way to define the encoding is to set ps.default_encoding in the configuration file to point to the right encoding file and all fonts you load will automatically have the right encoding
ImagePSFreeFont -- PostScript Type 1 폰트에 사용된 메모리를 풀어준다.
void imagepsfreefont
(int fontindex);
See also imagepsloadfont().
ImagePSLoadFont -- PostScript Type 1 폰트를 파일로부터 읽어온다.
int imagepsloadfont
(string filename)
In the case everything went right, a valid font index will be returned and can be used for further purposes. Otherwise the function returns false and prints a message describing what went wrong.
See also imagepsfreefont().
bool imagepsextendfont
(int font_index, double extend)
Extend or condense a font (font_index), if the value of the extend parameter is less than one you will be condensing the font.
bool imagepsslantfont
(int font_index, double slant)
Slant a font given by the font_index parameter with a slant of the value of the slant parameter.
ImagePSText -- 이미지에 PostScript Type1 폰트를 사용하여 문자열을 그린다.
array imagepstext
(int image,
string text, int font, int size, int foreground, int background, int x, int y [,
int space [, int tightness [, float angle [, int antialias_steps]]]])Size is expressed in pixels.
Foreground is the color in which the text will be painted. Background is the color to which the text will try to fade in with antialiasing. No pixels with the color background are actually painted, so the background image does not need to be of solid color.
The coordinates given by x, y will define the origin (or reference point) of the first character (roughly the lower-left corner of the character). This is different from the ImageString(), where x, y define the upper-right corner of the first character. Refer to PostScipt documentation about fonts and their measuring system if you have trouble understanding how this works.
Space allows you to change the default value of a space in a font. This amount is added to the normal value and can also be negative.
Tightness allows you to control the amount of white space between characters. This amount is added to the normal character width and can also be negative.
Angle is in degrees.
Antialias_steps allows you to control the number of colours used for antialiasing text. Allowed values are 4 and 16. The higher value is recommended for text sizes lower than 20, where the effect in text quality is quite visible. With bigger sizes, use 4. It's less computationally intensive.
Parameters space and tightness are expressed in character space units, where 1 unit is 1/1000th of an em-square.
Parameters space, tightness, angle and antialias are optional.
This function returns an array containing the following elements:
0 |
lower left x-coordinate |
1 |
lower left y-coordinate |
2 |
upper right x-coordinate |
3 |
upper right y-coordinate |
See also imagepsbbox().
ImageRectangle -- 직사각형을 그린다.
int imagerectangle
(int
im, int x1, int y1, int x2, int y2, int col)
ImageRectangle() creates a rectangle of color col in image im starting at upper left coordinate x1, y1 and ending at bottom right coordinate x2, y2. 0, 0 is the top left corner of the image.
ImageSetPixel -- 지정한 색으로 점을 찍는다.
int imagesetpixel
(int
im, int x, int y, int col)
ImageSetPixel() draws a pixel at x, y (top left is 0, 0) in image im of color col.
See also imagecreate() and imagecolorallocate().
ImageString -- 문자열을 수평으로 그린다.
int imagestring
(int im,
int font, int x, int y, string s, int col)
ImageString() draws the string s in the image identified by im at coordinates x, y (top left is 0, 0) in color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.
See also imageloadfont().
ImageStringUp -- 문자열을 수직으로 그린다.
int imagestringup
(int
im, int font, int x, int y, string s, int col)
ImageStringUp() draws the string s vertically in the image identified by im at coordinates x, y (top left is 0, 0) in color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.
See also imageloadfont().
ImageSX -- 그림의 폭을 구한다.
int imagesx
(int im)
ImageSX() returns the width of the image identified by im.
See also imagecreate() and imagesy().
ImageSY -- 그림의 높이를 구한다.
int imagesy
(int im)
ImageSY() returns the height of the image identified by im.
See also imagecreate() and imagesx().
ImageTTFBBox -- TrueType font를 사용하여 문자열 쓰고, 주위의 문자 주위에 경계선을 그린다.
array imagettfbbox
(int size,
int angle, string fontfile, string text)This function calculates and returns the bounding box in pixels a TrueType text.
text The string to be measured.
size The font size.
fontfile The name of the TrueType font file. (Can also be an URL.)
angle Angle in degrees in which text will be measured.
ImageTTFBBox() returns an array with 8 elements representing four points making the bounding box of the text:
0 |
lower left corner, X position |
1 |
lower left corner, Y position |
2 |
lower right corner, X position |
3 |
lower right corner, Y position |
4 |
upper right corner, X position |
5 |
upper right corner, Y position |
6 |
upper left corner, X position |
7 |
upper left corner, Y position |
The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner seeing the text horizontallty.
This function requires both the GD library and the Freetype library.
See also ImageTTFText().
ImageTTFText -- TrueType 폰트를 사용하여 문자열을 쓴다.
array imagettftext
(int im, int
size, int angle, int x, int y, int col, string fontfile, string text);ImageTTFText() draws the string text in the image identified by im, starting at coordinates x, y (top left is 0, 0), at an angle of angle in color col, using the TrueType font file identified by fontfile.
The coordinates given by x, y will define the basepoint of the first character (roughly the lower-left corner of the character). This is different from the ImageString(), where x, y define the upper-right corner of the first character.
Angle is in degrees, with 0 degrees being left-to-right reading text (3 o'clock direction), and higher values representing a counter-clockwise rotation. (i.e., a value of 90 would result in bottom-to-top reading text).
Fontfile is the path to the TrueType font you wish to use.
Text is the text string which may include UTF-8 character sequences (of the form: {) to access characters in a font beyond the first 255.
Col is the color index. Using the negative of a color index has the effect of turning off antialiasing.
ImageTTFText() returns an array with 8 elements representing four points making the bounding box of the text. The order of the points is upper left, upper right, lower right, lower left. The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner when you see the text horizontallty.
This example script will produce a black GIF 400x30 pixels, with the words "Testing..." in white in the font Arial.
Example 1. ImageTTFText
|
This function requires both the GD library and the FreeType library.
See also ImageTTFBBox().
이 함수들을 동작시키려면 PHP를 --with-imap 옵션을 주고 컴파일 하여야 한다. 또한 이것이 설치되기 위해서는 c-client library가 필요하다. 가장 최신 버전은 ftp://ftp.cac.washington.edu/imap/에 있으므로, 구하여 컴파일하면 된다. 컴파일 후 c-client/c-client.a를 /usr/local/lib나 여러분이 설정해 놓은 link path의 디렉토리로 복사하고, c-client/rfc822.h와 mail.h, linkage.h를 /usr/local/include나 여러분의 include path에 복사해 둔다.
비록 함수들의 이름이 imap_*이라도 이 함수들이 IMAP 프로토콜에 대해서만 사용할 수 있는 것은 아니다. c-client 라이브러리에 근간하고 있는 이 함수들은 NNTP와 POP3 심지어 local mailbox에 접근하는 방법도 제공한다.
이 문서는 제공되는 함수의 모든 세세한 내용을 설명하지 못하고 있다. 자세한 정보는 c-client library 소스와 같이 제공되는 문서(docs/internal.txt)와 다음의 RFC문서들을 참조하기 바란다.
David Wood 가 쓴 Programming Internet Email 이라는 책에도 비교적 잘 설명되어 있다.
imap_append -- 지정한 편지함에 문자열 메세지를 덧붙인다.
int imap_append
(int
imap_stream, string mbox, string message [, string flags])
Returns true on sucess, false on error.
imap_append() appends a string message to the specified mailbox mbox. If the optional flags is specified, writes the flags to that mailbox also.
When talking to the Cyrus IMAP server, you must use "\r\n" as your end-of-line terminator instead of "\n" or the operation will fail.
Example 1. imap_append() example
|
imap_base64 -- BASE64로 encode된 text를 decode한다.
string imap_base64
(string text)
imap_base64() function decodes BASE-64 encoded text (see RFC2045, Section 6.8). The decoded message is returned as a string.
See also imap_binary().
imap_body -- message body를 읽는다.
string imap_body
(int
imap_stream, int msg_number [, int flags])
imap_body() returns the body of the message, numbered msg_number in the current mailbox. The optional flags are a bit mask with one or more of the following:
imap_check -- 현 mailbox를 검사한다.
object imap_check
(int
imap_stream)
Returns information about the current mailbox. Returns FALSE on failure.
The imap_check() function checks the current mailbox status on the server and returns the information in an object with following properties:
imap_close -- IMAP stream을 닫는다.
int imap_close
(int
imap_stream [, int flags])
Close the imap stream. Takes an optional flag CL_EXPUNGE, which will silently expunge the mailbox before closing, removing all messages marked for deletion.
imap_createmailbox -- 새 편지함을 만든다.
int imap_createmailbox
(int imap_stream, string mbox)
imap_createmailbox() creates a new mailbox specified by mbox. Names containing international characters should be encoded by imap_utf7_encode().
Returns true on success and false on error.
See also imap_renamemailbox(), imap_deletemailbox() and imap_open() for the format of mbox names.
Example 1. imap_createmailbox() example
|
imap_delete -- 현재 편지함에서 어떤 messge에 삭제 마크를 한다.
int imap_delete
(int
imap_stream, int msg_number [, int flags])
Returns true.
imap_delete() function marks message pointed by msg_number for deletion. The optional flags parameter only has a single option, FT_UID, which tells the function to treat the msg_number argument as a UID. Messages marked for deletion will stay in the mailbox until either imap_expunge() is called or imap_close() is called with the optional parameter CL_EXPUNGE.
imap_deletemailbox -- 편지함을 지운다.
int imap_deletemailbox
(int imap_stream, string mbox)
imap_deletemailbox() deletes the specified mailbox (see imap_open() for the format of mbox names).
Returns true on success and false on error.
See also imap_createmailbox(), imap_reanmemailbox(), and imap_open() for the format of mbox
imap_expunge -- 삭제 마크가 되어 있는 모든 메세지를 지운다.
int imap_expunge
(int
imap_stream)
imap_expunge() deletes all the messages marked for deletion by imap_delete(), imap_move_mail(), or imap_setflag_full().
Returns true.
imap_fetchbody -- message의 body중 particular section을 가지고 온다.
string imap_fetchbody
(int imap_stream, int msg_number, string part_number [, flags flags])
This function causes a fetch of a particular section of the body of the specified messages as a text string and returns that text string. The section specification is a string of integers delimited by period which index into a body part list as per the IMAP4 specification. Body parts are not decoded by this function.
The options for imap_fetchbody() is a bitmask with one or more of the following:
imap_fetchstructure -- particular message의 구조를 읽어온다.
object imap_fetchstructure
(int imap_stream, int msg_number [, int flags])
This function fetches all the structured information for a given message. The optional flags parameter only has a single option, FT_UID, which tells the function to treat the msg_number argument as a UID. The returned object includes the envelope, internal date, size, flags and body structure along with a similar object for each mime attachement. The structure of the returned objects is as follows:
Table 1. Returned Objects for imap_fetchstructure()
type | Primary body type |
encoding | Body transfer encoding |
ifsubtype | True if there is a subtype string |
subtype | MIME subtype |
ifdescription | True if there is a description string |
description | Content description string |
ifid | True if there is an identification string |
id | Identification string |
lines | Number of lines |
bytes | Number of bytes |
ifdisposition | True if there is a disposition string |
disposition | Disposition string |
ifdparameters | True if the dparameters array exists |
dparameters | Disposition parameter array |
ifparameters | True if the parameters array exists |
parameters | MIME parameters array |
parts | Array of objects describing each message part |
- dparameters is an array of objects where each object has an "attribute" and a "value" property.
- Parameter is an array of objects where each object has an "attributte" and a "value" property.
- Parts is an array of objects identical in structure to the top-level object, with the limitation that it cannot contain further 'parts' objects.
Table 2. Primary body type
0 | text |
1 | multipart |
2 | message |
3 | application |
4 | audio |
5 | image |
6 | video |
7 | other |
Table 3. Transfer encodings
0 | 7BIT |
1 | 8BIT |
2 | BINARY |
3 | BASE64 |
4 | QUOTED-PRINTABLE |
5 | OTHER |
imap_header -- message의 header를 읽어온다.
object imap_header
(int
imap_stream, int msg_number [, int fromlength [, int subjectlength [, string
defaulthost]]])
This function returns an object of various header elements.
remail, date, Date, subject, Subject, in_reply_to, message_id,
newsgroups, followup_to, references
message flags:
Recent - 'R' if recent and seen,
'N' if recent and not seen,
' ' if not recent
Unseen - 'U' if not seen AND not recent,
' ' if seen OR not seen and recent
Answered -'A' if answered,
' ' if unanswered
Deleted - 'D' if deleted,
' ' if not deleted
Draft - 'X' if draft,
' ' if not draft
Flagged - 'F' if flagged,
' ' if not flagged
NOTE that the Recent/Unseen behavior is a little odd. If you want to
know if a message is Unseen, you must check for
Unseen == 'U' || Recent == 'N'
toaddress (full to: line, up to 1024 characters)
to[] (returns an array of objects from the To line, containing):
personal
adl
mailbox
host
fromaddress (full from: line, up to 1024 characters)
from[] (returns an array of objects from the From line, containing):
personal
adl
mailbox
host
ccaddress (full cc: line, up to 1024 characters)
cc[] (returns an array of objects from the Cc line, containing):
personal
adl
mailbox
host
bccaddress (full bcc line, up to 1024 characters)
bcc[] (returns an array of objects from the Bcc line, containing):
personal
adl
mailbox
host
reply_toaddress (full reply_to: line, up to 1024 characters)
reply_to[] (returns an array of objects from the Reply_to line,
containing):
personal
adl
mailbox
host
senderaddress (full sender: line, up to 1024 characters)
sender[] (returns an array of objects from the sender line, containing):
personal
adl
mailbox
host
return_path (full return-path: line, up to 1024 characters)
return_path[] (returns an array of objects from the return_path line,
containing):
personal
adl
mailbox
host
udate (mail message date in unix time)
fetchfrom (from line formatted to fit fromlength
characters)
fetchsubject (subject line formatted to fit subjectlength characters)
(PHP4 >= 4.0RC1)
imap_rfc822_parse_headers -- 주어진 문자열내의 메일 헤더에 대한 정보를 분석한다.object imap_rfc822_parse_headers
(string headers [, string
defaulthost])
This function returns an object of various header elements, similar to imap_header(), except without the flags and other elements that come from the IMAP server
imap_headers -- 한 편지함의 모든 message들의 header를 읽어온다.
array imap_headers
(int
imap_stream)
Returns an array of string formatted with header info. One element per mail message.
imap_listmailbox -- 편지함의 목록을 읽어 온다.
array imap_listmailbox
(int imap_stream, string ref, string pattern)
Returns an array containing the names of the mailboxes. See imap_getmailboxes() for a description of ref and pattern.
Example 1. imap_listmailbox() example
|
(PHP3 >= 3.0.12, PHP4 >= 4.0b4)
imap_getmailboxes -- 편지함들의 목록을 읽고, 각각에 대한 자세한 정보를 반환한다.
array imap_getmailboxes
(int imap_stream, string ref, string pattern)Returns an array of objects containing mailbox information. Each object has the attributes name, specifying the full name of the mailbox; delimiter, which is the hierarchy delimiter for the part of the hierarchy this mailbox is in; and attributes. Attributes is a bitmask that can be tested against:
Mailbox names containing international Characters outside the printable ASCII range will be encoded and may be decoded by imap_utf7_decode().
ref should normally be just the server specification as described in imap_open(), and pattern specifies where in the mailbox hierarchy to start searching. If you want all mailboxes, pass '*' for pattern.
There are two special characters you can pass as part of the pattern: '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.
Example 1. imap_getmailboxes() example
|
imap_listsubscribed -- 모든 subscribed 편지함의 목록을 읽어 온다.
array imap_listsubscribed
(int imap_stream, string ref,
string pattern)
Returns an array of all the mailboxes that you have subscribed. This is almost identical to imap_listmailbox(), but will only return mailboxes the user you logged in as has subscribed.
imap_getsubscribed -- 모든 subscribed 편지함들의 목록을 반환한다.
array imap_getsubscribed
(int imap_stream, string ref, string pattern)
This function is identical to imap_getmailboxes(), except that it only returns mailboxes that the user is subscribed to.
imap_mail_copy -- 특정 message들을 다른 편지함으로 복사한다.
int imap_mail_copy
(int
imap_stream, string msglist, string mbox [, int flags])
Returns true on success and false on error.
Copies mail messages specified by msglist to specified mailbox. msglist is a range not just message numbers (as described in RFC2060).
Flags is a bitmask of one or more of
imap_mail_move -- 특정 message들을 다른 편지함으로 옮긴다.
int imap_mail_move
(int
imap_stream, string msglist, string mbox [, int flags])
Moves mail messages specified by msglist to specified mailbox. msglist is a range not just message numbers (as described in RFC2060).
Flags is a bitmask and may contain the single option
Returns true on success and false on error.
imap_num_msg -- 현재 편지함의 메세지 개수를 구한다.
int imap_num_msg
(int
imap_stream)
Return the number of messages in the current mailbox.
imap_num_recent -- 현재 편지함의 최근 메세지 개수를 구한다.
int imap_num_recent
(int
imap_stream)
Returns the number of recent messages in the current mailbox.
imap_open -- 한 편지함에 대해 IMAP stream을 연다.
int imap_open
(string
mailbox, string username, string password [, int flags])
Returns an IMAP stream on success and false on error. This function can also be used to open streams to POP3 and NNTP servers, but some functions and features are not available on IMAP servers.
A mailbox name consists of a server part and a mailbox path on this server. The special name INBOX stands for the current users personal mailbox. The server part, which is enclosed in '{' and '}', consists of the servers name or ip address, a protocol secification (beginning with '/') and an optional port specifier beginnung with ':'. The server part is mandatory in all mailbox parameters. Mailbos names that contain international characters besides those in the printable ASCII space have to be encoded with imap_utf7_encode().
The options are a bit mask with one or more of the following:
To connect to an IMAP server running on port 143 on the local machine, do the following:
1 2 $mbox = imap_open ("{localhost:143}INBOX", "user_id", "password"); 3 |
To connect to a POP3 server on port 110 on the local server, use:
1 2 $mbox = imap_open ("{localhost/pop3:110}INBOX", "user_id", "password"); 3 |
To connect to an NNTP server on port 119 on the local server, use:
1 2 $nntp = imap_open ("{localhost/nntp:119}comp.test", "", ""); 3 |
To connect to a remote server replace "localhost" with the name or the IP address of the server you want to connect to.
Example 1. imap_open() example
|
imap_ping -- IMAP stream이 여전히 active인지 검사한다.
int imap_ping
(int imap_stream)Returns true if the stream is still alive, false otherwise.
imap_ping() function pings the stream to see it is still active. It may discover new mail; this is the preferred method for a periodic "new mail check" as well as a "keep alive" for servers which have inactivity timeout. (As PHP scripts do not tend to run that long, i can hardly imagine that this function will be usefull to anyone.)
imap_renamemailbox -- 편지함의 이름을 바꾼다.
int imap_renamemailbox
(int imap_stream, string old_mbox, string new_mbox)
This function renames on old mailbox to new mailbox (see imap_open() for the format of mbox names).
Returns true on success and false on error.
See also imap_createmailbox(), imap_deletemailbox(), and imap_open() for the format of mbox.
imap_reopen -- 기존에 열려있는 IMAP stream을 새 편지함으로 연다.
int imap_reopen
(string
imap_stream, string mailbox [, string flags])
This function reopens the specified stream to a new mailbox on an IMAP or NNTP server.
The options are a bit mask with one or more of the following:
Returns true on success and false on error.
imap_subscribe -- 새 편지함을 subscribe한다.
int imap_subscribe
(int
imap_stream, string mbox)
Subscribe to a new mailbox.
Returns true on success and false on error.
imap_undelete -- 삭제 표시된 message의 삭제 표시를 지운다 .
int imap_undelete
(int
imap_stream, int msg_number)
This function removes the deletion flag for a specified message, which is set by imap_delete() or imap_mail_move().
Returns true on success and false on error.
imap_unsubscribe -- 편지함을 unsubscribe한다.
int imap_unsubscribe
(int imap_stream, string mbox)
Unsubscribe from a specified mailbox.
Returns true on success and false on error.
imap_qprint -- quoted-printable 문자열을 8 bit 문자열로 바꾼다.
string imap_qprint
(string string)
Convert a quoted-printable string to an 8 bit string (according to RFC2045, section 6.7).
Returns an 8 bit (binary) string.
See also imap_8bit().
imap_8bit -- 8 bit 문자열을 quoted-printable 문자열로 바꾼다.
string imap_8bit
(string
string)
Convert an 8bit string to a quoted-printable string (according to RFC2045, section 6.7).
Returns a quoted-printable string.
See also imap_qprint().
imap_binary -- 8bit 문자열을 base64 문자열로 바꾼다.
string imap_binary
(string string)
Convert an 8bit string to a base64 string (according to RFC2045, Section 6.8).
Returns a base64 string.
See also imap_base64().
imap_scanmailbox -- mailbox들의 list를 읽고, 검색할 문자열을 mailbox의 text에서 취한다.
array imap_scanmailbox
(int imap_stream, string content)
Returns an array containing the names of the mailboxes that have string in the text of the mailbox. This function is simmilar to imap_listmailbox(), but it will additionally check for the presence of the string content inside the mailbox data.
imap_mailboxmsginfo -- 현재 mailbox에 대한 정보를 구한다.
object imap_mailboxmsginfo
(int imap_stream)
Returns information about the current mailbox. Returns FALSE on failure.
The imap_mailboxmsginfo() function checks the current mailbox status on the server. It is similar to imap_status(), but will additionally sum up the size of all messages in the mailbox, which will take some additional time to execute. It returns the information in an object with following properties.
Table 1. Mailbox properties
Date | date of last change |
Driver | driver |
Mailbox | name of the mailbox |
Nmsgs | number of messages |
Recent | number of recent messages |
Unread | number of unread messages |
Size |
mailbox size |
Example 1. imap_mailboxmsginfo() example
|
imap_rfc822_write_address -- 주어진 mailbox와 host, personal info로 적합한 모양의 email address를 만들어 낸다.
string imap_rfc822_write_address
(string mailbox, string
host, string personal)
Returns a properly formatted email address as defined in RFC822 given the mailbox, host, and personal info.
Example 1. imap_rfc822_write_address() example
|
imap_rfc822_parse_adrlist -- address 문자열을 parsing한다.
array imap_rfc822_parse_adrlist
(string address, string default_host)
This function parses the address string as defined in RFC822 and for each address, returns an array of objects. The objects properties are:
Example 1. imap_rfc822_parse_adrlist() example
|
imap_setflag_full -- message들의 여러 flag를 설정(set)한다.
string imap_setflag_full
(int stream, string sequence, string flag, string options)
This function causes a store to add the specified flag to the flags set for the messages in the specified sequence.
The flags which you can set are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", "\\Draft", and "\\Recent" (as defined by RFC2060).
The options are a bit mask with one or more of the following:
Example 1. imap_setflag_full() example
|
imap_clearflag_full -- message들의 여러 flag를 clear 한다.
string imap_clearflag_full
(int stream, string sequence, string flag, string options)
This function causes a store to delete the specified flag to the flags set for the messages in the specified sequence. The flags which you can unset are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", "\\Draft", and "\\Recent" (as defined by RFC2060).
The options are a bit mask with one or more of the following:
imap_sort -- 메시지들을 주어진 방식대로 정렬한 메시지 번호의 배열을 구한다.
string imap_sort
(int
stream, int criteria, int reverse, int options)
Returns an array of message numbers sorted by the given parameters.
Reverse is 1 for reverse-sorting.
Criteria can be one (and only one) of the following:
SORTDATE message Date
SORTARRIVAL arrival date
SORTFROM mailbox in first From address
SORTSUBJECT message Subject
SORTTO mailbox in first To address
SORTCC mailbox in first cc address
SORTSIZE size of message in octets
The flags are a bitmask of one or more of the following:
SE_UID Return UIDs instead of sequence numbers
SE_NOPREFETCH Don't prefetch searched messages.
imap_fetchheader -- message의 헤더를 반환한다.
string imap_fetchheader
(int imap_stream, int msgno, int flags)
This function causes a fetch of the complete, unfiltered RFC822 format header of the specified message as a text string and returns that text string.
The options are:
imap_uid -- 선택한 message의 일련 번호(sequence number)인 UID를 반환한다.
int imap_uid
(int
imap_stream, int msgno)
This function returns the UID for the given message sequence number. An UID is an unique identifier that will not change over time while a message sequence number may change whenever the content of the mailbox changes. This function is the inverse of imap_msgno().
imap_msgno -- 주어진 UID에 해당하는 메세지 순서 번호를 반환한다.
int imap_msgno
(int
imap_stream, int uid)
This function returns the message sequence number for the given UID. It is the inverse of imap_uid().
imap_search -- 주어진 검색 기준에 맞는 메세지들의 배열을 반환한다.
array imap_search
(int
imap_stream, string criteria, int flags)
This function performs a search on the mailbox currently opened in the given imap stream. criteria is a string, delimited by spaces, in which the following keywords are allowed. Any multi-word arguments (eg. FROM "joey smith") must be quoted.
For example, to match all unanswered messages sent by Mom, you'd use: "UNANSWERED FROM mom". Searches appear to be case insensitive. This list of criteria is from a reading of the UW c-client source code and may be uncomplete or inaccurate (see also RFC2060, section 6.4.4).
Valid values for flags are SE_UID, which causes the returned array to contain UIDs instead of messages sequence numbers.
imap_last_error -- 요구된 현재 페이지에서 IMAP 에러중 가장 최근에 발생한 것을 반환한다.
string imap_last_error
(void)
This function returns the full text of the last IMAP error message that occurred on the current page. The error stack is untouched; calling imap_last_error() subsequently, with no intervening errors, will return the same error.
imap_errors -- 요구된 현재 페이지에서 처음부터, 혹은 에러 스택이 reset된 적이 있다면 그 이후에 발생한 모든 IMAP 에러를 반환한다.
array imap_errors
(void)
This function returns an array of all of the IMAP error messages generated since the last imap_errors() call, or the beginning of the page. When imap_errors() is called, the error stack is subsequently cleared.
imap_alerts -- 요구된 현재 페이지에서 처음부터, 혹은 에러 스택이 reset된 적이 있다면 그 이후에 발생한 모든 IMAP 주의(alert) 메세지를 반환한다.
array imap_alerts
(void)
This function returns an array of all of the IMAP alert messages generated since the last imap_alerts() call, or the beginning of the page. When imap_alerts() is called, the alert stack is subsequently cleared. The IMAP specification requires that these messages be passed to the user.
imap_status -- 현재의 편지함이외의 다른 편지함의 상태 정보를 반환한다.
object imap_status
(int
imap_stream, string mailbox, int options)This function returns an object containing status information. Valid flags are:
status->flags is also set, which contains a bitmask which can be checked against any of the above constants.
Example 1. imap_status() example
|
(PHP3 >= 3.0.15, PHP4 >= 4.0b4)
imap_utf7_decode -- modified UTF-7 으로 엔코딩된 문자열을 디코드한다.string imap_utf7_decode
(string text)
Decodes modified UTF-7 text into 8bit data.
Returns the decoded 8bit data, or false if the input string was not valid modified UTF-7. This function is needed to decode mailbox names that contain international characters outside of the printable ASCII range. The modified UTF-7 encoding is defined in RFC 2060, section 5.1.3 (original UTF-7 was defned in RFC1642).
(PHP3 >= 3.0.15, PHP4 >= 4.0b4)
imap_utf7_encode -- 8bit 데이터를 modified UTF-7 문자열로 변환한다.string imap_utf7_encode
(string data)
Converts 8bit data to modified UTF-7 text. This is needed to encode mailbox names that contain international characters outside of the printable ASCII range. The modified UTF-7 encoding is defined in RFC 2060, section 5.1.3 (original UTF-7 was defned in RFC1642).
Returns the modified UTF-7 text.
(PHP3 >= 3.0.13, PHP4 >= 4.0RC1)
imap_utf8 -- 텍스트를 UTF8 형태로 변환한다.(PHP3 >= 3.0.4, PHP4 )
imap_fetch_overview -- 주어진 메시지의 헤더에 있는 정보를 전체적으로 읽어온다.array imap_fetch_overview
(int imap_stream, string sequence
[, int flags])
This function fetches mail headers for the given sequence and returns an overview of their contents. sequence will contain a sequence of message indices or UIDs, if flags contains FT_UID. The returned value is an array of objects describing one message header each:
Example 1. imap_fetch_overview() example
|
(PHP3 CVS only, PHP4 >= 4.0RC1)
imap_mime_header_decode -- MIME 헤더 요소를 디코드한다.array imap_header_decode
(string text)
imap_mime_header_decode() function decodes MIME message header extensions that are non ASCII text (see RFC2047) The decoded elements are returned in an array of objects, where each object has two properties, "charset" & "text". If the element hasn't been encoded, and in other words is in plain US-ASCII,the "charset" property of that element is set to "default".
Example 1. imap_mime_header_decode() example
|
(PHP3 >= 3.0.5, PHP4 )
imap_mail_compose -- 주어진 envelope 와 body 부분을 가지고 MIME 메시지를 만들어낸다.string imap_mail_compose
(array envelope, array body)(PHP3 >= 3.0.14, PHP4 >= 4.0b4)
imap_mail -- email 메시지를 보낸다.string imap_mail
(string
to, string subject, string message [, string additional_headers [, string cc [,
string bcc [, string rpath]]]])
This function is currently only available in PHP3.
Informix (IDS) 7.x, SE 7.x, Universal Server (IUS) 9.x and IDS 2000 를 위한 드라이버는 informix extension 디렉토리의 "ifx.ec"와 "php3_ifx.h"에 구현되어 있다. IDS 7.x 에 대한 지원은, BYTE and TEXT 칼럼에 대한 완전한 지원을 포함하여, 충분한 정도로(fairly) 완성되었다. IUS 9.x에 대한 지원은 부분적으로만 완료되었다. 새로운 데이터 타입들은 완료되었으나, SLOB와 CLOB에 대한 지원은 아직 진행중이다.
설정시 주의 사항 (Configuration notes) :
PHP Informix 드라이버를 컴파일하려면 ESQL/C 버전이 필요하다. 7.2x 이후의 ESQL/C 버전이면 문제 없다. ESQL/C는 이제 Informix Client SDK의 한 부분이 되어있다.
"configure" 스크립트를실행하기 전에, 반드시 "INFORMIXDIR" 환경 변수를 설정해 놓아야 하고, $INFORMIXDIR/bin 디렉토리가 여러분의 PATH 에 포함되어 있어야 한다.
이렇게 해 놓고 "configure --with_informix=yes"로 스크립트 파일을 실행하면, configure 스크립트는 라이브러리와 include가 있는 디렉토리를 자동으로 찾는다. 만약 여러분이 손으로 설정 내용을 지정하고 싶다면 "IFX_LIBDIR", "IFX_LIBS", "IFX_INCDIR"의 환경변수에 원하는 값을 지정하면 된다. 또한, configure 스크립트는 여러분이 사용중인 Informix의 버전을 체크한다. 만약 여러분이 Informix 버전이 9.00이상이라면 이 값이 "HAVE_IFX_IUS" 라는 conditional compilation variable에 설정한다.
실행시 주의사항 :
PHP ifx 드라이버를 사용하려면 INFORMIXDIR과 INFORMIXSERVER듸 두 개의 Informix 환경 변수를 설정해 두어야 하고, $INFORMIXDIR/bin 디렉토리가 여러분의 PATH 에 포함되어 있어야 한다.이 것이 포함되어 있는가는 informix에 대한 실험을 하기 전이라도 phpinfo() 함수를 사용하면 이 변수들의 설정여부와 내용을 알 수 있다. 이것은 CGI 버전과 아파치 모듈버전 모두 적용되는 내용이다. 따라서 여러분은 이 환경변수를 Apache의 startup script에 설정해 두는 것이 좋을 것이다.
그리고, Informix 공유 라이브러리 역시 로더(loader)가 접근 가능한 곳에 있어야 한다.(LD_LINBRARY_PATH 나 ld.so.conf/ldconfig를 접검하자.)
BLOB 사용시 주의 사항 (Some notes on the use of BLOBs(TEXT and BYTE columns)) :
현재 버전(September 18, 1998)은 select/insert/update에서 BLOB 컬럼을 완벽하게 지원한다.
BLOB는 보통 정수값인 BLOB identifier를 사용하여 주소화(addressed)된다. Select 질의는 모든 BYTE와 TEXT 컬럼에 대한 "blob id"를 반환한다. 여러분이 "ifx_blobinfile(0);"를 사용하여 BLOB를 메모리에서 가져오기로 결정해 두었다면, 여러분은 "string_var = ifx_get_blob($blob_id);" 같은 명령을 사용하여 그 내용을 얻어올 수 있다. 만약, "ifx_blobinfile(1);"를 사용하여 파일에 있는 BLOB 컬럼의 내용을 자져오기로 하였다면, "ifx_get_blob($blob_id);"를 사용하여 해당 파일 이름을 얻을 수 있다. 이때 얻은 파일 이름은 일반적인 파일 I/O 방식을 사용하여 그 내용을 읽어올 수 있다.
insert/update 질의의 경우 여러분은 "ifx_create_blob(..);"를 사용하여 "blob id(들)"를 손수 만들어 주어야 한다. 만든 blob id들은 배열에 저장한 후에, blob 컬럼은 질의 문자열의 물음표(?)로 바꾼다. updates/inserts를 위해서 여러분은 ifx_update_blob(...)를 사용하여 blob의 내용을 설정하여야 한다.
BLOB 컬럼에 대한 동작은 다음과 같은 설정 변수(configuration variables)에 따라 달라진다. 이 설정 변수(configuration variables)은 실행중에도 변경할 수 있다. :
설정변수(configuration variable) :
ifx.textasvarchar
ifx.byteasvarchar
실행 함수(runtime functions) :
ifx_textasvarchar(0) : select 질의시 TEXT 컬럼처럼 blob id를 사용한다.
ifx_byteasvarchar(0) : select 질의시 BYTE 컬럼처럼 blob id를 사용한다.
ifx_textasvarchar(1) : select 질의에서 blob id를 사용하지 않고, VARCHAR 컬럼인 것 처럼 TEXT 컬럼으로 반환하고
ifx_byteasvarchar(1) : select 질의에서 blob id를 사용하지 않고, VARCHAR 칼럼인 것 처럼 BYTE 칼럼으로 반환하고
설정변수(configuration variable) :
ifx.blobinfile
실행 함수(runtime functions) :
ifx_blobinfile_mode(0) : 메모리에 있는 BYTE 컬럼을 반환한다. 여러분은 blob id를 사용하여 그 내용을 얻을 수 있다.
ifx_blobinfile_mode(1) : 파일에 있는 BYTE 컬럼을 반환한다. 여러분은 blob id를 사용하여 그 내용이 있는 파일의 이름을 얻을 수 있다.
만약 여러분이 ifx_text/byteasvarchar를 1로 설정하면, 여러분은 select 질의에서 TEXT와 BYTE 컬럼을 일반적인 (그러나 보다 긴) VARCHAR 필드처럼 사용할 수 있다. PHP에서 모든 문자열이 계산("counted") 되어지는 한, 이것은 "binary safe"한 상태로 있게 된다. 이것을 올바르게 사용하는 것은 여러분에게 달려있다. 돌려받을 데이터는 여러분이 그 내용에 대해 책임질 수 있다면, 어떤 내용도 포함할 수 있다.
만약 여러분이 ifx_blobinfile을 1로 설정하면, blob의 내용을 가져오기 위해 ifx_get_blob(..)를 사용하여 반환 받은 파일명을 사용하여야 한다. 이 경우에 어떤 row를 가져오게(fetch) 되면 여러분은 INFORMIX가 만든 임시 파일들을 지워줄 책임이 있다. Informix는 새 row fetch때 마다 모든 BYTE 컬럼에 하나씩 새 임시 파일을 만든다.
임시 파일이 있는 디렉토리는 환경변수인 "blobdir"에 설정된 된 값을 사용한다. 기본값은 현재 디렉토리인 "." 이다. putenv(blobdir=tmpblob"); 같이 사용하면 남겨진 ("blb"로 시작하는 이름을 가진) 임시 파일들을 쉽게 청소할 수 있다.
자동 공백 제거 (Automatically trimming "char" <SQLCHAR and SQLNCHAR> data) :
이 기능은 다음 설정 변수(configuration variable)로 설정할 수 있다.
ifx.charasvarchar : 1로 설정되어있으면 뒤에 붙은 공백문자를 자동으로 제거한다.
널(NULL) 값 :
환경변수 ifx.nullformat의 값(ifx_nullformat() 함수로 설정)이 TRUE로 설정되에 있으면 NULL 칼럼이 반환될 때 "NULL"이라는 문자열이 반환되고, FALSE로 설정되어 있으면 공백 문자열("")이 반환된다.
ifx_connect -- Informix 서버 connection을 연다.
int ifx_connect
(string [database] , string [userid] , string [password] );
Returns an connection identifier on success, or FALSE on error.
ifx_connect() establishes a connection to an Informix server. All of the arguments are optional, and if they're missing, defaults are taken from values supplied in php3.ini (ifx.default_host for the host (Informix libraries will use $INFORMIXSERVER environment value if not defined), ifx.default_user for user, ifx.default_password for the password (none if not defined).
In case a second call is made to ifx_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.
The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling ifx_close().
See also ifx_pconnect(), and ifx_close().
Example 1. Connect to a Informix database
|
ifx_pconnect -- 영구적인(persistent) Informix 서버 connection을 연다.
int ifx_pconnect
(string [database] , string [userid] , string [password] );
Returns: A positive Informix persistent link identifier on success, or false on error
ifx_pconnect() acts very much like ifx_connect() with two major differences.
This function behaves exactly like ifx_connect() when PHP is not running as an Apache module. First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ifx_close() will not close links established by ifx_pconnect()).
This type of links is therefore called 'persistent'.
See also: ifx_connect().
ifx_close -- Informix connection을 닫는다.
int ifx_close
(int [link_identifier] );
Returns: always true.
ifx_close() closes the link to an Informix database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.
Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
ifx_close() will not close persistent links generated by ifx_pconnect().
See also: ifx_connect(), and ifx_pconnect().
Example 1. Closing a Informix connection
|
ifx_query -- Informix 질의를 전송한다.
int ifx_query
(string query, int [link_identifier] , int [cursor_type] , mixed [blobidarray] );
Returns: A positive Informix result identifier on success, or false on error.
An integer "result_id" used by other functions to retrieve the query results. Sets "affected_rows" for retrieval by the ifx_affected_rows() function.
ifx_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if ifx_connect() was called, and use it.
Executes query on connection conn_id. For "select-type" queries a cursor is declared and opened. The optional cursor_type parameter allows you to make this a "scroll" and/or "hold" cursor. It's a mask and can be either IFX_SCROLL, IFX_HOLD, or both or'ed together. Non-select queries are "execute immediate".
For either query type the number of (estimated or real) affected rows is saved for retrieval by ifx_affected_rows().
If you have BLOB (BYTE or TEXT) columns in an update query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.
If the contents of the TEXT (or BYTE) column allow it, you can also use "ifx_textasvarchar(1)" and "ifx_byteasvarchar(1)". This allows you to treat TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR columns for select queries, and you don't need to bother with blob id's.
With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation), select queries will return BLOB columns as blob id's (integer value). You can get the value of the blob as a string or file with the blob functions (see below).
See also: ifx_connect().
Example 1. Show all rows of the "orders" table as a html table
|
Example 2. Insert some values into the "catalog" table
|
ifx_prepare -- 실행을 위한 SQL문을 준비한다.
int ifx_prepare
(string query,
int conn_id [, int cursor_def, mixed blobidarray])Returns a integer result_id for use by ifx_do(). Sets affected_rows for retrieval by the ifx_affected_rows() function.
Prepares query on connection conn_id. For "select-type" queries a cursor is declared and opened. The optional cursor_type parameter allows you to make this a "scroll" and/or "hold" cursor. It's a mask and can be either IFX_SCROLL, IFX_HOLD, or both or'ed together.
For either query type the estimated number of affected rows is saved for retrieval by ifx_affected_rows().
If you have BLOB (BYTE or TEXT) columns in the query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.
If the contents of the TEXT (or BYTE) column allow it, you can also use "ifx_textasvarchar(1)" and "ifx_byteasvarchar(1)". This allows you to treat TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR columns for select queries, and you don't need to bother with blob id's.
With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation), select queries will return BLOB columns as blob id's (integer value). You can get the value of the blob as a string or file with the blob functions (see below).
See also: ifx_do().
ifx_do -- 이전에 준비된 SQL문을 실행한다.
int ifx_do
(int result_id);
Returns TRUE on success, FALSE on error.
Executes a previously prepared query or opens a cursor for it.
Does NOT free result_id on error.
Also sets the real number of ifx_affected_rows() for non-select statements for retrieval by ifx_affected_rows()
See also: ifx_prepare(). There is a example.
ifx_error -- 마지막에 수행한 Informix 명령의 에러 코드를 돌려준다.
string ifx_error
(void);
The Informix error codes (SQLSTATE & SQLCODE) formatted as follows :
x [SQLSTATE = aa bbb SQLCODE=cccc]
where x =
space : no error
E : error
N : no more data
W : warning
? : undefined
If the "x" character is anything other than space, SQLSTATE and SQLCODE describe the error in more detail.
See the Informix manual for the description of SQLSTATE and SQLCODE
Returns in a string one character describing the general results of a statement and both SQLSTATE and SQLCODE associated with the most recent SQL statement executed. The format of the string is "(char) [SQLSTATE=(two digits) (three digits) SQLCODE=(one digit)]". The first character can be ' ' (space) (success), 'W' (the statement caused some warning), 'E' (an error happened when executing the statement) or 'N' (the statement didn't return any data).
See also: ifx_errormsg()
ifx_errormsg -- 마지막에 수행한 Informix 명령의 에러 메세지를 돌려준다.
string ifx_errormsg
(int [errorcode]);
Returns the Informix error message associated with the most recent Informix error, or, when the optional "errorcode" param is present, the error message corresponding to "errorcode".
See also: ifx_error()
1 2 printf("%s\n<br>", ifx_errormsg(-201)); 3 |
ifx_affected_rows -- 질의에 영향을 받는 row의 개수를 구한다.
int ifx_affected_rows
(int
result_id)result_id is a valid result id returned by ifx_query() or ifx_prepare().
Returns the number of rows affected by a query associated with result_id.
For inserts, updates and deletes the number is the real number (sqlerrd[2]) of affected rows. For selects it is an estimate (sqlerrd[0]). Don't rely on it.
Useful after ifx_prepare() to limit queries to reasonable result sets.
See also: ifx_num_rows()
Example 1. Informix affected rows
|
ifx_getsqlca -- 질의 후 sqlca.sqlerrd[0..5]의 내용을 구한다.
array ifx_getsqlca
(int result_id);
result_id is a valid result id returned by ifx_query() or ifx_prepare().
Returns a pseudo-row (assiociative arry) with sqlca.sqlerrd[0] to sqlca.sqlerrd[5] after the query associated with result_id.
For inserts, updates and deletes the values returned are those as set by the server after executing the query. This gives access to the number of affected rows and the serial insert value. For selects the values are those saved after the prepare statement. This gives access to the estimated number of affected rows. The use of this function saves the overhead of executing a "select dbinfo('sqlca.sqlerrdx')" query, as it retrieves the values that were saved by the ifx driver at the appropriate moment.
Example 1. Retrieve Informix sqlca.sqlerrd[x] values
|
ifx_fetch_row -- row를 배열(enumerated array)로 가져온다.
array ifx_fetch_row
(int
result_id [, mixed position])Returns an associative array that corresponds to the fetched row, or false if there are no more rows.
Blob columns are returned as integer blob id values for use in ifx_get_blob() unless you have used ifx_textasvarchar(1) or ifx_byteasvarchar(1), in which case blobs are returned as string values. Returns FALSE on error
result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).
[position] is an optional parameter for a "fetch" operation on "scroll" cursors: "NEXT", "PREVIOUS", "CURRENT", "FIRST", "LAST" or a number. If you specify a number, an "absolute" row fetch is executed. This parameter is optional, and only valid for scrollcursors.
ifx_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
Subsequent call to ifx_fetch_row() would return the next row in the result set, or false if there are no more rows.
Example 1. Informix fetch rows
|
ifx_htmltbl_result -- 질의의 모든 결과 row를 HTML table 모양으로 출력한다.
int ifx_htmltbl_result
(int result_id [, string html_table_options])
Returns the number of rows fetched or FALSE on error.
Formats all rows of the result_id query into a html table. The optional second argument is a string of <table> tag options
Example 1. Informix results as HTML table
|
ifx_fieldtypes -- Informix SQL 필드들을 list한다.
array ifx_fieldtypes
(int result_id)
Returns an associative array with fieldnames as key and the SQL fieldtypes as data for query with result_id. Returns FALSE on error.
Example 1. Fielnames and SQL fieldtypes
|
ifx_fieldproperties -- SQL 필드 특성을 list 한다.
array ifx_fieldproperties
(int result_id)
Returns an associative array with fieldnames as key and the SQL fieldproperties as data for a query with result_id. Returns FALSE on error.
Returns the Informix SQL fieldproperies of every field in the query as an associative array. Properties are encoded as: "SQLTYPE;length;precision;scale;ISNULLABLE" where SQLTYPE = the Informix type like "SQLVCHAR" etc. and ISNULLABLE = "Y" or "N".
Example 1. Informix SQL fieldproperties
|
ifx_num_fields -- 질의의 컬럼 개수를 구한다.
int ifx_num_fields (
int result_id);
Returns the number of columns in query for result_id or FALSE on error
After preparing or executing a query, this call gives you the number of columns in the query.
ifx_num_rows -- 질의 결과의 row 개수
int ifx_num_rows
(int result_id);
Gives the number of rows fetched so far for a query with result_id after a ifx_query() or ifx_do() query.
ifx_free_result -- 질의에 사용된 자원을 풀어준다.
int ifx_free_result
(int result_id);
Releases resources for the query associated with result_id. Returns FALSE on error.
ifx_create_char -- char object를 만든다.
int ifx_create_char
(string param);
Creates an char object. param should be the char content.
ifx_free_char -- char object를 삭제한다.
int ifx_free_char
(int bid);
Deletes the charobject for the given char object-id bid. Returns FALSE on error otherwise TRUE.
ifx_update_char -- char object의 내용을 수정한다.
int ifx_update_char
(int bid, string content);
Updates the content of the char object for the given char object bid. content is a string with new data. Returns FALSE on error otherwise TRUE.
ifx_get_char -- char object의 내용을 반환한다.
int ifx_get_char
(int bid);
Returns the content of the char object for the given char object-id bid.
ifx_create_blob -- blob object를 만든다.
int ifx_create_blob
(int type, int mode, string param);
Creates an blob object.
type: 1 = TEXT, 0 = BYTE
mode: 0 = blob-object holds the content in memory, 1 = blob-object holds the content in file.
param: if mode = 0: pointer to the content, if mode = 1: pointer to the filestring.
Return FALSE on error, otherwise the new blob object-id.
ifx_copy_blob -- 주어진 blob object의 사본을 만든다.
int ifx_copy_blob
(int bid);
Duplicates the given blob object. bid is the ID of the blob object.
Returns FALSE on error otherwise the new blob object-id.
ifx_free_blob -- blob object를 삭제한다.
int ifx_free_blob
(int bid);
Deletes the blobobject for the given blob object-id bid. Returns FALSE on error otherwise TRUE.
ifx_get_blob -- blob object의 내용을 반환한다.
int ifx_get_blob
(int bid);
Returns the content of the blob object for the given blob object-id bid.
ifx_update_blob -- blob object의 내용을 수정한다.
ifx_update_blob
(int bid, string content);
Updates the content of the blob object for the given blob object bid. content is a string with new data. Returns FALSE on error otherwise TRUE.
ifx_blobinfile_mode -- select 질의에서 사용되는 기본(default) blob mode를 설정한다.
void ifx_blobinfile_mode
(int mode);
Set the default blob mode for all select queries. Mode "0" means save Byte-Blobs in memory, and mode "1" means save Byte-Blobs in a file.
ifx_textasvarchar -- select 질의에서 사용되는 기본(default) text mode를 설정한다.
void ifx_textasvarchar
(int mode);
Sets the default text mode for all select-queries. Mode "0" will return a blob id, and mode "1" will return a varchar with text content.
ifx_byteasvarchar -- select 질의에서 사용되는 기본(default) byte mode를 설정한다.
void ifx_byteasvarchar
(int mode);
Sets the default byte mode for all select-queries. Mode "0" will return a blob id, and mode "1" will return a varchar with text content.
ifx_nullformat -- row를 가져올 때 사용할 결과값의 기본 형태를 정한다.
void ifx_nullformat
(int mode);
Sets the default return value of a NULL-value on a fetch row. Mode "0" returns "", and mode "1" returns "NULL".
ifxus_create_slob -- slob object를 만들고, 그것을 연다.
int ifxus_create_slob
(int mode);
Creates an slob object and opens it. Modes: 1 = LO_RDONLY, 2 = LO_WRONLY, 4 = LO_APPEND, 8 = LO_RDWR, 16 = LO_BUFFER, 32 = LO_NOBUFFER -> or-mask. You can also use constants named IFX_LO_RDONLY, IFX_LO_WRONLY etc. Return FALSE on error otherwise the new slob object-id.
ifx_free_slob -- slob object를 삭제한다.
int ifxus_free_slob
(int bid);
Deletes the slob object. bid is the Id of the slob object. Returns FALSE on error otherwise TRUE.
ifxus_close_slob -- slob object를 삭제한다.
int ifxus_close_slob
(int bid);
Deletes the slob object on the given slob object-id bid. Return FALSE on error otherwise TRUE.
ifxus_open_slob -- slob object를 연다.
int ifxus_open_slob
(long bid, int mode);
Opens an slob object. bid should be an existing slob id. Modes: 1 = LO_RDONLY, 2 = LO_WRONLY, 4 = LO_APPEND, 8 = LO_RDWR, 16 = LO_BUFFER, 32 = LO_NOBUFFER -> or-mask. Returns FALSE on error otherwise the new slob object-id.
ifxus_tell_slob -- 현재 파일이나 seek 위치를 반환한다.
int ifxus_tell_slob
(long bid);
Returns the current file or seek position of an open slob object bid should be an existing slob id. Return FALSE on error otherwise the seek position.
ifxus_seek_slob -- 현재 파일이나 seek 위치를 설정한다.
int ifxus_seek_slob
(long bid, int mode, long offset);
Sets the current file or seek position of an open slob object. bid should be an existing slob id. Modes: 0 = LO_SEEK_SET, 1 = LO_SEEK_CUR, 2 = LO_SEEK_END and offset is an byte offset. Return FALSE on error otherwise the seek position.
ifxus_read_slob -- slob object의 nbytes를 읽는다.of the
int ifxus_read_slob
(long bid, long nbytes);
Reads nbytes of the slob object. bid is a existing slob id and nbytes is the number of bytes zu read. Return FALSE on error otherwise the string.
ifxus_write_slob -- slob object에 문자열을 써 넣는다.
int ifxus_write_slob
(long bid, string content);
Writes a string into the slob object. bid is a existing slob id and content the content to write. Return FALSE on error otherwise bytes written.
InterBase는 Borland/Inprise에서 출시된 대중적인 데이터베이스이다. InterBase에 대한 자세한 정보는 http://www.interbase.com/에서 찾아보기바란다. 참고로 InterBase는 오픈 소스 운동에 참여하고 있다.
Note: PHP4에서는 InterBase 6 에 대한 완전한 지원이 추가되었다.
int ibase_connect
(string database [, string username [, string password [, string charset [, int
buffers [, int dialect [, string role]]]]]])
Establishes a connection to an InterBase server. The database argument has to be a valid path to database file on the server it resides on. If the server is not local, it must be prefixed with either 'hostname:' (TCP/IP), '//hostname/' (NetBEUI) or 'hostname@' (IPX/SPX), depending on the connection protocol used. username and password can also be specified with PHP configuration directives ibase.default_user and ibase.default_password. charset is the default character set for a database. buffers is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default. dialect selects the default SQL dialect for any statement executed within a connection, and it defaults to the highest one supported by client libraries.
In case a second call is made to ibase_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling ibase_close().
Example 1. Ibase_connect() example
|
Note: buffers was added in PHP4-RC2.
Note: dialect was added in PHP4-RC2. It is functional only with InterBase 6 and versions higher than that.
Note: role was added in PHP4-RC2. It is functional only with InterBase 5 and versions higher than that.
See also: ibase_pconnect().
ibase_pconnect -- InterBase 데이터베이스로의 영구적인(persistent) 연결을 연다.
int ibase_connect
(string database [, string username [, string password [, string charset [,
string role]]]])
ibase_pconnect() acts very much like ibase_connect() with two major differences. First, when connecting, the function will first try to find a (persistent) link that's already opened with the same parameters. If one is found, an identifier for it will be returned instead of opening a new connection. Second, the connection to the InterBase server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ibase_close() will not close links established by ibase_pconnect()). This type of link is therefore called 'persistent'.
See also ibase_connect() for the meaning of parameters passed to this function. They are exactly the same.
ibase_close -- InterBase 데이터베이스와의 연결을 닫는다.
int ibase_close
([int
connection_id])
Closes the link to an InterBase database that's associated with a connection id returned from ibase_connect(). If the connection id is omitted, the last opened link is assumed. Default transaction on link is committed, other transactions are rolled back.
ibase_query -- InterBase 데이터베이스의 질의를 수행한다.
int ibase_query
([int
link_identifier, string query [, int bind_args]])
Performs a query on an InterBase database, returning a result identifier for use with ibase_fetch_row(), ibase_fetch_object(), ibase_free_result() and ibase_free_query().
Note: Although this function supports variable binding to parameter placeholders, there is not very much meaning using this capability with it. For real life use and an example, see ibase_prepare() and ibase_execute().
array ibase_fetch_row
(int result_identifier)
Returns the next row specified by the result identifier obtained using the ibase_query().
(PHP3 >= 3.0.7, PHP4 >= 4.0RC1)
ibase_fetch_object -- Get an object from a InterBase databaseobject ibase_fetch_object
(int result_id)
Fetches a row as a pseudo-object from a result_id obtained either by ibase_query() or ibase_execute().
1 2 <php 3 $dbh = ibase_connect ($host, $username, $password); 4 $stmt = 'SELECT * FROM tblname'; 5 $sth = ibase_query ($dbh, $stmt); 6 while ($row = ibase_fetch_object ($sth)) { 7 print $row->email . "\n"; 8 } 9 ibase_close ($dbh); 10 ?> 11 |
See also ibase_fetch_row().
ibase_free_result -- result set을 해제한다.
int ibase_free_result
(int result_identifier)
Free's a result set the has been created by ibase_query().
ibase_prepare -- 파라메터를 바인딩하고 실행하기 위한 질의를 준비한다.
int ibase_prepare
([int
link_identifier, string query])
Prepare a query for later binding of parameter placeholders and execution (via ibase_execute()).
ibase_execute -- 미리 준비된 질의를 수행한다.
int ibase_execute
(int
query [, int bind_args])
Execute a query prepared by ibase_prepare(). This is a lot more effective than using ibase_query() if you are repeating a same kind of query several times with only some parameters changing.
1 2 <?php 3 $updates = array( 4 1 => 'Eric', 5 5 => 'Filip', 6 7 => 'Larry' 7 ); 8 9 $query = ibase_prepare("UPDATE FOO SET BAR = ? WHERE BAZ = ?"); 10 11 while (list($baz, $bar) = each($updates)) { 12 ibase_execute($query, $bar, $baz); 13 } 14 ?> 15 |
ibase_free_query -- 질의를 준비하는데 사용된 메모리를 해제한다.
ibase_timefmt -- 질의 결과중 timestamp나 날짜와 시간 형태의 칼럼이 출력될 형태를 정한다.
int ibase_timefmt
(string format [, int columntype])
Sets the format of timestamp, date or time type columns returned from queries. Internally, the columns are formatted by c-function strftime(), so refer to it's documentation regarding to the format of the string. columntype is one of the constants IBASE_TIMESTAMP, IBASE_DATE and IBASE_TIME. If omitted, defaults to IBASE_TIMESTAMP for backwards compatibility.
1 2 <?php 3 // InterBase 6 TIME-type columns will be returned in 4 // the form '05 hours 37 minutes'. 5 ibase_timefmt("%H hours %M minutes", IBASE_TIME); 6 ?> 7 |
You can also set defaults for these formats with PHP configuration directives ibase.timestampformat, ibase.dateformat and ibase.timeformat.
Note: columntype was added in PHP 4.0. It has any meaning only with InterBase version 6 and higher.
Note: A backwards incompatible change happened in PHP 4.0 when PHP configuration directive ibase.timeformat was renamed to ibase.timestampformat and directives ibase.dateformat and ibase.timeformat were added, so that the names would match better their functionality.
(PHP3 >= 3.0.7, PHP4 >= 4.0RC1)
ibase_num_fields -- 질의 결과(result set)의 필드 개수를 구한다.int ibase_num_fields
(int result_id)
Returns an integer containing the number of fields in a result set.
1 2 <?php 3 $dbh = ibase_connect ($host, $username, $password); 4 $stmt = 'SELECT * FROM tblname'; 5 $sth = ibase_query ($dbh, $stmt); 6 7 if (ibase_num_fields($sth) > 0) { 8 while ($row = ibase_fetch_object ($sth)) { 9 print $row->email . "\n"; 10 } 11 } else { 12 die ("No Results were found for your query"); 13 } 14 15 ibase_close ($dbh); 16 ?> 17 |
See also: ibase_field_info().
Note: Ibase_num_fields() is currently not functional in PHP4.
LDAP은 Lightweight Directory Access Protocol의 약자로, "Directory Servers"에 접근하는데 사용되는 프로토콜이다. Directory 라는 것은 트리 구조를 가지고 정보를 저장하는 특별한 종류의 Database라고 할 수 있다.
기본 개념은 하드디스크의 디렉토리 구조와 비슷하다. 다른 점은 root 디렉토리가 "world(지구 전체)"이고, 첫 번째 레벨이 "국가들", 그 이하의 레벨이 회사나, 각종 조직, 장소 등이 된다는 점이다. 그 이하로 계속 내려가다 보면 특정인이나 설비, 문서 등의 항목까지도 내려갈 수 있다.
하드디스크의 subdirectory에 있는 파일을 참조할 때 보통 다음과 같이 사용한다. :
/usr/local/myapp/docs
이 파일 레퍼런스의 각부분은 슬래시(/) 기호로 구분되고, 읽는 순서는 왼쪽에서 오른쪽으로 읽어나간다.
LDAP에서 파일 레퍼런스와 같은 것은 보통 "dn"으로 표시되는 "distinguished name"이다. dn의 예는 다음과 같다. :
cn=John Smith,ou=Accounts,o=My Company,c=US
레퍼런스의 각 부분은 쉼표(,)로 구분되고, 오른쪽에서 왼쪽의 순서로 읽는다. 여러분은 이 dn을 다음과 같은 의미로 읽는다. :
country(나라) = US
organization(조직) = My Company
organizationalUnit(부서) = Accounts
commonName(이름) = John Smith
하드디스크에서 여러분이 디렉토리 구성을 어떻게 하는가에 대한 특별한 규칙이 없듯이, 디렉토리 서버의 관리도 목적에 따라 의미있게 구성된다면 어떤 모습을 하고 있어도 상관없다. 하지만, 사용되고 있는 약간의 관습이 있다. 그 메시지는 여러분이 데이타베이스에 어떤 정보가 사용가능한지 알지 못한다면 그 데이터베이스를 사용할 수 없듯이, 여러분이 디렉토리 구조에 대해 알지 못한다면 여러분은 그 디렉토리 서버에 접근하기 위한 코드를 만들 수 없다는 것이다.
디렉토리 서버에서 "S"로 시작하는 성을 가진 항목에 대한 정보를 검색하고, 이름과 email 주소를 출력한다.
Example 1. LDAP search example
|
여러분은 University of Michigan ldap-3.3 package나 Netscape Directory SDK같은 LDAP client libraries를 얻어서 컴파일할 필요하 있다. 또한 PHP를 LDAP지원으로 다시 컴파일할 필요가 있다.
LDAP 호출을 사용하기 전에 여러분은 다음과 같은 것을 알고 있어야 한다.
여러분이 사용하려하는 LDAP 서버의 이름이나 주소.
해당 서버의 "base dn" (world 디렉토리 밑의 어떤 한 부분으로 해당 서버에 저장된 부분. "o=My Company,c=US"같은 것이 가능하다.)
서버에 접근가능한 암호가 필요할 수도 있다. (많은 서버들이 "anonymous bind"를 사용하여 읽기 접근을 허용하고 있지만 그외의 동작을 위해서는 암호를 요구한다.)
여러분이 application을 작성할 때 사용할 전형적인 LDAP 호출은 다음의 형식을 따른다. :
ldap_connect() // 서버에 connection을 만든다.
|
ldap_bind() // 익명(anonymous)이나 인증된 "login"
|
디렉토리의 검색이나 수정 같은 작업을 하고 결과를 출력한다.
|
ldap_close() // "logout"
LDAP에 관한 자세한 자료는 다음 사이트에 가 보자.
Netscape SDK에는 Programmer's Guide가 .html 형태로 있습니다.
ldap_add -- LDAP directory에 entry를 추가한다.
int ldap_add
(int
link_identifier, string dn, array entry)
returns true on success and false on error.
The ldap_add() function is used to add entries in the LDAP directory. The DN of the entry to be added is specified by dn. Array entry specifies the information about the entry. The values in the entries are indexed by individual attributes. In case of multiple values for an attribute, they are indexed using integers starting with 0.
entry["attribute1"] = value
entry["attribute2"][0] = value1
entry["attribute2"][1] = value2
Example 1. Complete example with authenticated bind
|
ldap_mod_add -- 현재 속성에 특정 속성값을 더한다.
int ldap_mod_add
(int link_identifier, string dn, array entry);
returns true on success and false on error.
This function adds attribute(s) to the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level additions are done by the ldap_add() function.
ldap_mod_del -- 현재 속성에 특정 속성값을 뺀다.
int ldap_mod_del
(int link_identifier, string dn, array entry);
returns true on success and false on error.
This function removes attribute(s) from the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level deletions are done by the ldap_del() function.
ldap_mod_replace -- 현재 속성값들을 새로운 값으로 바꾼다.
int ldap_mod_replace
(int link_identifier, string dn, array entry);
returns true on success and false on error.
This function replaces attribute(s) from the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level modifications are done by the ldap_modify() function.
ldap_bind -- LDAP directory에 bind 한다.
int ldap_bind
(int link_identifier, string [bind_rdn], string [bind_password]);
Binds to the LDAP directory with specified RDN and password. Returns true on success and false on error.
ldap_bind() does a bind operation on the directory. bind_rdn and bind_password are optional. If not specified, anonymous bind is attempted.
ldap_close -- LDAP server와의 연결을 닫는다.
int ldap_close
(int link_identifier);
Returns true on success, false on error.
ldap_close() closes the link to the LDAP server that's associated with the specified link_identifier.
This call is internally identical to ldap_unbind(). The LDAP API uses the call ldap_unbind(), so perhaps you should use this in preference to ldap_close().
ldap_connect -- LDAP server와 연결한다.
int ldap_connect
([string hostname [, int port]])
Returns a positive LDAP link identifier on success, or false on error.
ldap_connect() establishes a connection to a LDAP server on a specified hostname and port. Both the arguments are optional. If no arguments are specified then the link identifier of the already opened link will be returned. If only hostname is specified, then the port defaults to 389.
ldap_count_entries -- 탐색 범위 안에 있는 entry의 개수
int ldap_count_entries
(int link_identifier, int result_identifier)
Returns number of entries in the result or false on error.
ldap_count_entries() returns the number of entries stored in the result of previous search operations. result_identifier identifies the internal ldap result.
ldap_delete -- directory안의 한 entry를 삭제한다..
int ldap_delete
(int
link_identifier, string dn)
Returns true on success and false on error.
ldap_delete() function delete a particular entry in LDAP directory specified by dn.
ldap_dn2ufn -- DN을 User Friendly Naming 형식으로 변환한다.
int ldap_delete
(int
link_identifier, string dn)
Returns true on success and false on error.
ldap_delete() function delete a particular entry in LDAP directory specified by dn.
ldap_explode_dn -- DN을 그것의 구성 부분으로 나눈다.
array ldap_explode_dn
(string dn, int with_attrib)
ldap_explode_dn() function is used to split the a DN returned by ldap_get_dn() and breaks it up into its component parts. Each part is known as Relative Distinguished Name, or RDN. ldap_explode_dn() returns an array of all those components. with_attrib is used to request if the RDNs are returned with only values or their attributes as well. To get RDNs with the attributes (i.e. in attribute=value format) set with_attrib to 0 and to get only values set it to 1.
ldap_first_attribute -- 첫번째 속성을 반환한다.
string ldap_first_attribute
(int link_identifier, int
result_entry_identifier, int ber_identifier)
Returns the first attribute in the entry on success and false on error.
Similar to reading entries, attributes are also read one by one from a particular entry. ldap_first_attribute() returns the first attribute in the entry pointed by the entry identifier. Remaining attributes are retrieved by calling ldap_next_attribute() successively. ber_identifier is the identifier to internal memory location pointer. It is passed by reference. The same ber_identifier is passed to the ldap_next_attribute() function, which modifies that pointer.
see also ldap_get_attributes()
ldap_first_entry -- 첫번째 result id를 반환한다.
int ldap_first_entry
(int
link_identifier, int result_identifier)Returns the result entry identifier for the first entry on success and false on error.
Entries in the LDAP result are read sequentially using the ldap_first_entry() and ldap_next_entry() functions. ldap_first_entry() returns the entry identifier for first entry in the result. This entry identifier is then supplied to lap_next_entry() routine to get successive entries from the result.
see also ldap_get_entries().
ldap_free_result -- result memory를 풀어준다.
int ldap_free_result
(int result_identifier)
Returns true on success and false on error.
ldap_free_result() frees up the memory allocated internally to store the result and pointed by the result_identifier. All result memory will be automatically freed when the script terminates.
Typically all the memory allocated for the ldap result gets freed at the end of the script. In case the script is making successive searches which return large result sets, ldap_free_result() could be called to keep the runtime memory usage by the script low.
ldap_get_attributes -- search result entry로부터 속성을 구한다.
array ldap_get_attributes
(int link_identifier, int
result_entry_identifier)
Returns a complete entry information in a multi-dimensional array on success and false on error.
ldap_get_attributes() function is used to simplify reading the attributes and values from an entry in the search result. The return value is a multi-dimensional array of attributes and values.
Having located a specific entry in the directory, you can find out what information is held for that entry by using this call. You would use this call for an application which "browses" directory entries and/or where you do not know the structure of the directory entries. In many applications you will be searching for a specific attribute such as an email address or a surname, and won't care what other data is held.
return_value["count"] = number of attributes in the entry
return_value[0] = first attribute
return_value[n] = nth attribute
return_value["attribute"]["count"] = number of values for attribute
return_value["attribute"][0] = first value of the attribute
return_value["attribute"][i] = ith value of the attribute
Example 1. Show the list of attributes held for a particular directory entry
|
see also ldap_first_attribute() and ldap_next_attribute()
ldap_get_dn -- result entry의 DN을 구한다.
string ldap_get_dn
(int
link_identifier, int result_entry_identifier)
Returns the DN of the result entry and false on error.
ldap_get_dn() function is used to find out the DN of an entry in the result.
ldap_get_entries -- 모든 result entry들을 구한다.
array ldap_get_entries
(int link_identifier, int result_identifier)
Returns a complete result information in a multi-dimenasional array on success and false on error.
ldap_get_entries() function is used to simplify reading multiple entries from the result and then reading the attributes and multiple values. The entire information is returned by one function call in a multi-dimensional array. The structure of the array is as follows.
The attribute index is converted to lowercase. (Attributes are case-insensitive for directory servers, but not when used as array indices)
return_value["count"] = number of entries in the result
return_value[0] : refers to the details of first entry
return_value[i]["dn"] = DN of the ith entry in the result
return_value[i]["count"] = number of attributes in ith entry
return_value[i][j] = jth attribute in the ith entry in the result
return_value[i]["attribute"]["count"] = number of values for attribute in ith entry
return_value[i]["attribute"][j] = jth value of attribute in ith entry
see also ldap_first_entry() and ldap_next_entry()
ldap_get_values -- result entry로 부터 모든 값을 구한다.
array ldap_get_values
(int
link_identifier, int result_entry_identifier, string attribute)Returns an array of values for the attribute on success and false on error.
ldap_get_values() function is used to read all the values of the attribute in the entry in the result. entry is specified by the result_entry_identifier. The number of values can be found by indexing "count" in the resultant array. Individual values are accessed by integer index in the array. The first index is 0.
This call needs a result_entry_identifier, so needs to be preceded by one of the ldap search calls and one of the calls to get an individual entry.
You application will either be hard coded to look for certain attributes (such as "surname" or "mail") or you will have to use the ldap_get_attributes() call to work out what attributes exist for a given entry.
LDAP allows more than one entry for an attribute, so it can, for example, store a number of email addresses for one person's directory entry all labeled with the attribute "mail"
return_value["count"] = number of values for attribute
return_value[0] = first value of attribute
return_value[i] = ith value of attribute
Example 1. List all values of the "mail" attribute for a directory entry
|
(PHP3 >= 3.0.13, PHP4 >= 4.0RC2)
ldap_get_values_len -- result entry로 부터 모든 binary 값을 구한다.array ldap_get_values_len
(int link_identifier, int
result_entry_identifier, string attribute)
Returns an array of values for the attribute on success and false on error.
ldap_get_values_len() function is used to read all the values of the attribute in the entry in the result. entry is specified by the result_entry_identifier. The number of values can be found by indexing "count" in the resultant array. Individual values are accessed by integer index in the array. The first index is 0.
This function is used exactly like ldap_get_values() except that it handles binary data and not string data.
Note: This function was added in 4.0.
ldap_list -- Single-level 검색 (search)
int ldap_list
(int
link_identifier, string base_dn, string filter [, array attributes])
Returns a search result identifier or false on error.
ldap_list() performs the search for a specified filter on the directory with the scope LDAP_SCOPE_ONELEVEL.
LDAP_SCOPE_ONELEVEL means that the search should only return information that is at the level immediately below the base dn given in the call. (Equivalent to typing "ls" and getting a list of files and folders in the current working directory.)
This call takes an optional fourth parameter which is an array of the attributes required. See ldap_search() notes.
Example 1. Produce a list of all organizational units of an organization
|
ldap_modify -- LDAP entry를 수정한다.
int ldap_modify
(int
link_identifier, string dn, array entry)Returns true on success and false on error.
ldap_modify() function is used to modify the existing entries in the LDAP directory. The structure of the entry is same as in ldap_add().
ldap_next_attribute -- result의 다음 속성을 구한다.
s
tring ldap_next_attribute
(int link_identifier, int
result_entry_identifier, int ber_identifier)
Returns the next attribute in an entry on success and false on error.
ldap_next_attribute() is called to retrieve the attributes in an entry. The internal state of the pointer is maintained by the ber_identifier. It is passed by reference to the function. The first call to ldap_next_attribute() is made with the result_entry_identifier returned from ldap_first_attribute().
see also ldap_get_attributes()
ldap_next_entry -- 다음 result entry를 구한다.
int ldap_next_entry
(int
link_identifier, int result_entry_identifier)Returns entry identifier for the next entry in the result whose entries are being read starting with ldap_first_entry(). If there are no more entries in the result then it returns false.
ldap_next_entry() function is used to retrieve the entries stored in the result. Successive calls to the ldap_next_entry() return entries one by one till there are no more entries. The first call to ldap_next_entry() is made after the call to ldap_first_entry() with the result_identifier as returned from the ldap_first_entry().
see also ldap_get_entries()
ldap_read -- entry를 읽는다.
int ldap_read
(int link_identifier, string base_dn, string filter, array [attributes]);
Returns a search result identifier or false on error.
ldap_read() performs the search for a specified filter on the directory with the scope LDAP_SCOPE_BASE. So it is equivalent to reading an entry from the directory.
An empty filter is not allowed. If you want to retrieve absolutely all information for this entry, use a filter of "objectClass=*". If you know which entry types are used on the directory server, you might use an appropriate filter such as "objectClass=inetOrgPerson".
This call takes an optional fourth parameter which is an array of the attributes required. See ldap_search() notes.
ldap_search -- LDAP tree를 검색한다.
int ldap_search
(int
link_identifier, string base_dn, string filter [, array attributes])
Returns a search result identifier or false on error.
ldap_search() performs the search for a specified filter on the directory with the scope of LDAP_SCOPE_SUBTREE. This is equivalent to searching the entire directory. base_dn specifies the base DN for the directory.
There is a optional fourth parameter, that can be added to restrict the attributes and values returned by the server to just those required. This is much more efficient than the default action (which is to return all attributes and their associated values). The use of the fourth parameter should therefore be considered good practice.
The fourth parameter is a standard PHP string array of the required attributes, eg array("mail","sn","cn") Note that the "dn" is always returned irrespective of which attributes types are requested.
Note too that some directory server hosts will be configured to return no more than a preset number of entries. If this occurs, the server will indicate that it has only returned a partial results set.
The search filter can be simple or advanced, using boolean operators in the format described in the LDAP doumentation (see the Netscape Directory SDK for full information on filters).
The example below retrieves the organizational unit, surname, given name and email address for all people in "My Company" where the surname or given name contains the substring $person. This example uses a boolean filter to tell the server to look for information in more than one attribute.
Example 1. LDAP search
|
ldap_unbind -- LDAP directory로부터 unbind한다.
int ldap_unbind
(int
link_identifier)
Returns true on success and false on error.
ldap_unbind() function unbinds from the LDAP directory.
(PHP3 >= 3.0.13, PHP4 >= 4.0RC2)
ldap_err2str -- LDAP 에러번호를 에러 메시지 문자열로 변환한다.string ldap_err2str
(int
errno)
returns string error message.
This function returns the string error message explaining the error number errno. While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check.
See also ldap_errno() and ldap_error().
Example 1. Enumerating all LDAP error messages
|
(PHP3 >= 3.0.12, PHP4 >= 4.0RC2)
ldap_errno -- 최근에 사용한 LDAP 명령에 대한 LDAP 에러 번호를 반환한다.int ldap_errno
(int
link_id)
return the LDAP error number of the last LDAP command for this link.
This function returns the standardized error number returned by the last LDAP command for the given link identifier. This number can be converted into a textual error message using ldap_err2str().
Unless you lower your warning level in your php3.ini sufficiently or prefix your LDAP commands with @ (at) characters to suppress warning output, the errors generated will also show up in your HTML output.
Example 1. Generating and catching an error
|
(PHP3 >= 3.0.12, PHP4 >= 4.0RC2)
ldap_error -- 최근에 사용한 LDAP 명령에 대한 LDAP 에러 메세지를 반환한다.string ldap_error
(int
link_id)
returns string error message.
This function returns the string error message explaining the error generated by the last LDAP command for the given link identifier. While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check.
Unless you lower your warning level in your php3.ini sufficiently or prefix your LDAP commands with @ (at) characters to suppress warning output, the errors generated will also show up in your HTML output.
see also ldap_err2str() and ldap_errno().
mail() 함수는 편지를 보낼 수 있게 해 준다.
mail -- 편지를 보낸다.
bool mail
(string to,
string subject, string message [, string additional_headers])
Mail() automatically mails the message specified in message to the receiver specified in to. Multiple recipients can be specified by putting a comma between each address in to.
Example 1. Sending mail.
|
If a fourth string argument is passed, this string is inserted at the end of the header. This is typically used to add extra headers. Multiple extra headers are separated with a newline.
Example 2. Sending mail with extra headers.
|
이 수학 함수들은 여러분의 컴퓨터의 long과 double 형태로만 사용됩니다. 만약 여러분이 이 이상의 숫자를 다루어야한다면 arbitrary precision math functions를 사용하도록한다.
PHP의 수학 함수 확장에서 다음값이 상수로 지정되어있다. :
Table 1. Math constants
Constant | Value | Description |
---|---|---|
M_PI | 3.14159265358979323846 | Der Wert π (Pi) |
M_E | 2.7182818284590452354 | e |
M_LOG2E | 1.4426950408889634074 | log_2 e |
M_LOG10E | 0.43429448190325182765 | log_10 e |
M_LN2 | 0.69314718055994530942 | log_e 2 |
M_LN10 | 2.30258509299404568402 | log_e 10 |
M_PI_2 | 1.57079632679489661923 | pi/2 |
M_PI_4 | 0.78539816339744830962 | pi/4 |
M_1_PI | 0.31830988618379067154 | 1/pi |
M_2_PI | 0.63661977236758134308 | 2/pi |
M_2_SQRTPI | 1.12837916709551257390 | 2/sqrt(pi) |
M_SQRT2 | 1.41421356237309504880 | sqrt(2) |
M_SQRT1_2 | 0.70710678118654752440 | 1/sqrt(2) |
Abs -- 절대값
mixed abs(mixed number);
Returns the absolute value of number. If the argument number is float, return type is also float, otherwise it is int.
Acos -- arc cosine
float acos(float arg);
Returns the arc cosine of arg in radians.
Asin -- arc sine
float asin(float arg);
Returns the arc sine of arg in radians.
Atan -- arc tangent
float atan(float arg);
Returns the arc tangent of arg in radians.
See also acos() and atan().
Atan2 -- arc tangent of two variables
float atan2
(float y, float x);
This function calculates the arc tangent of the two variables x and y. It is similar to calculating the arc tangent of y / x, except that the signs of both arguments are used to determine the quadrant of the result.
The function returns the result in radians, which is between -PI and PI (inclusive).
base_convert -- 숫자를 진법간에 변환한다.
strin base_convert
(string number, int frombase, int tobase)
Returns a string containing number represented in base tobase. The base in which number is given is specified in frombase. Both frombase and tobase have to be between 2 and 36, inclusive. Digits in numbers with a base higher than 10 will be represented with the letters a-z, with a meaning 10, b meaning 11 and z meaning 36.
Example 1. base_convert()
|
BinDec -- 2진수를 10진수로 바꾼다.
int bindec(string binary_string);
Returns the decimal equivalent of the binary number represented by the binary_string argument.
BinDec converts a binary number to a decimal number. The largest number that can be converted is 31 bits of 1's or 2147483647 in decimal.
See also the decbin() function.
Ceil -- 올림을 한 값
int ceil(float number);
Returns the next highest integer value from number. Using ceil() on integers is absolutely a waste of time.
NOTE: PHP/FI 2's ceil() returned a float. Use: $new = (double)ceil($number); to get the old behaviour.
Cos -- cosine
float cos(float arg);
Returns the cosine of arg in radians.
DecBin -- 10진수를 2진수로 바꾼다.
string decbin(int number);
Returns a string containing a binary representation of the given number argument. The largest number that can be converted is 2147483647 in decimal resulting to a string of 31 1's.
See also the bindec() function.
DecHex -- 십진수를 16진수로
string dechex(int number);
Returns a string containing a hexadecimal representation of the given number argument. The largest number that can be converted is 2147483647 in decimal resulting to "7fffffff".
See also the hexdec() function.
DecOct -- 십진수를 8진수로 바꾼다
string decoct(int number);
Returns a string containing an octal representation of the given number argument. The largest number that can be converted is 2147483647 in decimal resulting to "17777777777". See also octdec().
(PHP3 >= 3.0.4, PHP4 )
deg2rad -- degrees 각도 값을 radian 각도값으로 변환한다.double deg2rad
(double
number)
This function converts number from degrees to the radian equivalent.
See also rad2deg().
Exp -- 자연대수 e의 n 제곱값
float exp(float arg);
Returns e raised to the power of arg.
See also pow().
Floor -- 내림을 한 값
int floor(float number);
Returns the next lowest integer value from number. Using floor() on integers is absolutely a waste of time.
NOTE: PHP/FI 2's floor() returned a float. Use: $new = (double)floor($number); to get the old behaviour.
getrandmax -- 가능한 난수의 최대값
int getrandmax(void );
Returns the maximum value that can be returned by a call to rand().
See also rand(), srand(), mt-rand() ,mt_srand() and mt_getrandmax(),
HexDec -- 16진수를 10진수로
int hexdec(string hex_string);
Returns the decimal equivalent of the hexadecimal number represented by the hex_string argument. HexDec converts a hexadecimal string to a decimal number. The largest number that can be converted is 7fffffff or 2147483647 in decimal.
See also the dechex() function.
Log -- 자연 로그
float log(float arg);
Returns the natural logarithm of arg.
Log10 -- 상용 로그
float log10(float arg);
Returns the base-10 logarithm of arg.
max -- 가장 큰 값을 찾는다.
mixed max(mixed arg1, mixed arg2, mixed argn);
max() returns the numerically highest of the parameter values.
If the first parameter is an array, max() returns the highest value in that array. If the first parameter is an integer, string or double, you need at least two parameters and max() returns the biggest of these values. You can compare an unlimited number of values.
If one or more of the values is a double, all the values will be treated as doubles, and a double is returned. If none of the values is a double, all of them will be treated as integers, and an integer is returned.
min -- 가장 작은 값을 찾는다.
mixed min(mixed arg1, mixed arg2, mixed argn);
min() returns the numerically lowest of the parameter values.
If the first parameter is an array, min() returns the lowest value in that array. If the first parameter is an integer, string or double, you need at least two parameters and min() returns the lowest of these values. You can compare an unlimited number of values.
If one or more of the values is a double, all the values will be treated as doubles, and a double is returned. If none of the values is a double, all of them will be treated as integers, and an integer is returned.
mt_rand -- 더 좋은 난수 값을 만들어 낸다.
int mt_rand
([int min], [int max]);
Many random number generators of older libcs have dubious or unknown characteristics and are slow. By default, PHP uses the libc random number generator with the rand() function. mt_rand() function is a drop-in replacement for this. It uses a random number generator with known characteristics, the Mersenne Twister, which will produce random numbers that should be suitable for cryptographic purposes and is four times faster than what the average libc provides. The Homepage of the Mersenne Twister can be found at http://www.math.keio.ac.jp/~matumoto/emt.html, and an optimized version of the MT source is available from http://www.scp.syr.edu/~marc/hawk/twister.html.
If called without the optional min,max arguments mt_rand() returns a pseudo-random value between 0 and RAND_MAX. If you want a random number between 5 and 15 (inclusive), for example, use mt_rand(5,15).
Remember to seed the random number generator before use with mt_srand().
See also mt_srand(), mt_getrandmax(), srand(), rand() and getrandmax().
mt_srand -- 더 좋은 난수 발생기에 초기값을 정한다.
void mt_srand
(int seed);
Seeds the random number generator with seed.
// seed with microseconds since last "whole" second mt_srand((double)microtime()*1000000); $randval = mt_rand();
See also mt_rand(), mt_getrandmax(), srand(), rand() and getrandmax().
mt_getrandmax -- 가능한 가장 큰 난수값
int mt_getrandmax
(void );
Returns the maximum value that can be returned by a call to mt_rand().
See also mt_rand(), mt_srand(), rand(), srand() and getrandmax().
number_format -- 숫자를 1000단위와 소수점에 ,와 .등을 찍어준다.
string number_format
(float number, int decimals, string dec_point, string thousands_sep);
number_format() returns a formatted version of number. This function accepts either one, two or four parameters (not three):
If only one parameter is given, number will be formatted without decimals, but with a comma (",") between every group of thousands.
If two parameters are given, number will be formatted with decimals decimals with a dot (".") in front, and a comma (",") between every group of thousands.
If all four parameters are given, number will be formatted with decimals decimals, dec_point instead of a dot (".") before the decimals and thousands_sep instead of a comma (",") between every group of thousands.
OctDec -- 8진수를 10진수로
int octdec(string octal_string);
Returns the decimal equivalent of the octal number represented by the octal_string argument. OctDec converts an octal string to a decimal number. The largest number that can be converted is 17777777777 or 2147483647 in decimal.
See also decoct().
pi -- 파이 값
double pi(void);
Returns an approximation of pi.
pow -- 지수 표현식(x의 y승)
float pow(float base, float exp);
Returns base raised to the power of exp.
See also exp().
(PHP3 >= 3.0.4, PHP4 )
rad2deg -- radian 각도 값을 degrees 각도값으로 변환한다.double rad2deg
(double
number)
This function converts number from radian to degrees.
See also deg2rad().
rand -- 난수의 발생
int rand
([int min], [int max]);
If called without the optional min,max arguments rand() returns a pseudo-random value between 0 and RAND_MAX. If you want a random number between 5 and 15 (inclusive), for example, use rand(5,15).
Remember to seed the random number generator before use with srand().
See also srand(), getrandmax(), mt-rand() ,mt_srand() and mt_getrandmax(),
round -- 반올림 한 값
double round(double val);
Returns the rounded value of val.
$foo = round( 3.4 ); // $foo == 3.0 $foo = round( 3.5 ); // $foo == 4.0 $foo = round( 3.6 ); // $foo == 4.0
Sin -- sine
float sin(float arg);
Returns the sine of arg in radians.
Sqrt -- 제곱근
float sqrt(float arg);
Returns the square root of arg.
srand -- 난수 발생시 사용하는 seed 값
void srand(int seed);
Seeds the random number generator with seed.
// seed with microseconds since last "whole" second srand((double)microtime()*1000000); $randval = rand();
See also rand(), getrandmax(), mt-rand() ,mt_srand() and mt_getrandmax(),
Tan -- tangent
float tan(float arg);
Returns the tangent of arg in radians.
MCAL은 Modular Calendar Access Library의 줄임말이다.
Libmcal은 일정관리(calandar)를 하는 C 라이브러리이다. 이것은 추가/삭제가 가능한 드라이버들로 잘 모듈화되어 있다. IMAP 모듈이 메일박스에 대해 모듈화 되어 있는 것과 같이 MCAL은 일정관리에 모듈화 되어 있다.
IMAP에서의 mailbox stream같이 mcal에서는 일정 stream이 열릴 수 있다. 일정관리 내용은 지역파일로 저장될 수도 있고, 원격 ICAP 서버에 저장될 수도 있으며, mcal 라이브러리가 지원하는 다른 형태로 저장될 수도 있다.
개개의 일정(event)은 서버에서 가져올 수 있고, 검색할 수 있고, 저장되기도 한다. 또한 알람기능을 하는 날짜 트리거(triggers)를 지원하고 반복적인 일정도 지원한다.
libmcal은 중앙 집중 일정 서버를 사용하여 특정 데이터베이스나 로컬 파일을 직접 다루어야 하는 필요를 없앨 수 있다.
이 함수들을 동작시키려면, PHP를 --with-mcal 옵션을 주고 컴파일 하여야 한다. 그리고, 당연히 mcal 라이브러리는 미리 설치되어 있어야 한다. http://mcal.chek.com/ 에서 최신 버전을 받아다 컴파일하여 설치하면 된다.
MCAL 모듈이 사용될 수 있다면 다음과 같은 함수가 미리 정의되어 있다. : MCAL_SUNDAY, MCAL_MONDAY, MCAL_TUESDAY, MCAL_WEDNESDAY, MCAL_THURSDAY, MCAL_FRIDAY, MCAL_SATURDAY, MCAL_RECUR_NONE, MCAL_RECUR_DAILY, MCAL_RECUR_WEEKLY, MCAL_RECUR_MONTHLY_MDAY, MCAL_RECUR_MONTHLY_WDAY, MCAL_RECUR_YEARLY, MCAL_JANUARY, MCAL_FEBRUARY, MCAL_MARCH, MCAL_APRIL, MCAL_MAY, MCAL_JUNE, MCAL_JULY, MCAL_AUGUGT, MCAL_SEPTEMBER, MCAL_OCTOBER, MCAL_NOVEMBER, MCAL_DECEMBER. 대부분의 함수는 각각의 스트림에 대해 하나씩 설정되어 있는 내부적인 일정 구조체(internal event structure)를 사용한다. 이것은 함수들간에 크기가 큰 객체를 전달하기 수월하게 한다. 여기에서는 일정 구조체 (event structure)의 값을 설정하고, 초기화하고, 조회하는데 사용하기 쉬운 함수들을 제공한다.
int mcal_open
(string calendar, string
username, string password, string options);
Returns an MCAL stream on success, false on error.
mcal_open() opens up an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also. The streams internal event structure is also initialized upon connection.
int mcal_close
(int mcal_stream, int flags);
Closes the given mcal stream.
object mcal_fetch_event
(int mcal_stream, int
event_id, int [options]);
mcal_fetch_event() fetches an event from the calendar stream specified by id.
Returns an event object consisting of:
All datetime entries consist of an object that contains:
array mcal_list_events
(int mcal_stream, int
[begin_year] , int [begin_month] , int [begin_day]
, int [end_year] , int [end_month] , int [end_day] );
Returns an array of event ID's that are between the start and end dates, or if just a stream is given, uses the start and end dates in the global event structure.
mcal_list_events() function takes in an optional beginning date and an end date for a calendar stream. An array of event id's that are between the given dates or the internal event dates are returned.
int mcal_append_event
(int mcal_stream);
mcal_append_event() Stores the global event into an MCAL calendar for the given stream.
Returns the uid of the newly inserted event.
int mcal_store_event
(int mcal_stream);
mcal_store_event() Stores the modifications to the current global event for the given stream.
Returns true on success and false on error.
Delete an event from an MCAL calendar
int mcal_delete_event
(int uid);
mcal_delete_event() deletes the calendar event specified by the uid.
Returns true.
Turn off an alarm for an event
int mcal_snooze
(int uid);
mcal_snooze() turns off an alarm for a calendar event specified by the uid.
Returns true.
array mcal_list_events
(int mcal_stream, int
[begin_year] , int [begin_month] , int [begin_day]
, int [end_year] , int [end_month] , int [end_day] );
Returns an array of event ID's that has an alarm going off between the start and end dates, or if just a stream is given, uses the start and end dates in the global event structure.
mcal_list_events() function takes in an optional beginning date and an end date for a calendar stream. An array of event id's that are between the given dates or the internal event dates are returned.
int mcal_event_init
(int stream);
mcal_event_init() initializes a streams global event structure. this effectively sets all elements of the structure to 0, or the default settings.
Returns true.
int mcal_event_set_category
(int stream, string
category);
mcal_event_set_category() sets the streams global event structure's category to the given string.
Returns true.
int mcal_event_set_title
(int stream, string
title);
mcal_event_set_title() sets the streams global event structure's title to the given string.
Returns true.
int mcal_event_set_description
(int stream,
string description);
mcal_event_set_description() sets the streams global event structure's description to the given string.
Returns true.
int mcal_event_set_start
(int stream, int year,
int month, int [day] , int [hour] , int [min] , int [sec] );
mcal_event_set_start() sets the streams global event structure's start date and time to the given values.
Returns true.
int mcal_event_set_end
(int stream, int year,
int month, int [day] , int [hour] , int [min] , int [sec] );
mcal_event_set_end() sets the streams global event structure's end date and time to the given values.
Returns true.
int mcal_event_set_alarm
(int stream, int
alarm);
mcal_event_set_alarm() sets the streams global event structure's alarm to the given minutes before the event.
Returns true.
int mcal_event_set_class
(int stream, int
class);
mcal_event_set_class() sets the streams global event structure's class to the given value. The class is either 0 for public, or 1 for private.
Returns true.
int mcal_is_leap_year
(int year);
mcal_is_leap_year() returns 1 if the given year is a leap year, 1 if not. (역자주: 원본이 좀 이상한데, 아마 윤년이 아니면 0을 반환할 것이다)
int mcal_days_in_month
(int month, int leap
year);
mcal_days_in_month() Returns the number of days in the given month, taking into account if the given year is a leap year or not.
int mcal_date_valid
(int year, int month, int
day);
mcal_date_valid() Returns true if the given year, month and day is a valid date, false if not.
int mcal_time_valid
(int hour, int minutes, int
seconds);
mcal_time_valid() Returns true if the given hour, minutes and seconds is a valid time, false if not.
int mcal_
(int year, int month, int day);
mcal_day_of_week() returns the day of the week of the given date
int mcal_
(int year, int month, int day);
mcal_day_of_year() returns the day of the year of the given date.
int mcal_date_compare
(int a_year, int a_month,
int a_day, int b_year, int b_month, int b_day);
mcal_date_compare() Compares the two given dates, returns <0, 0, >0 if a<b, a==b, a>b respectively
int mcal_next_recurrence
(int stream, int
weekstart, array next);
mcal_next_recurrence() returns an object filled with the next date the event occurs, on or after the supplied date. Returns empty date field if event does not occur or something is invalid. Uses weekstart to determine what day is considered the beginning of the week.
int mcal_event_set_recur_none
(int stream);
mcal_event_set_recur_none() sets the streams global event structure to not recur (event->recur_type is set to MCAL_RECUR_NONE).
int mcal_event_set_recur_daily
(int stream,
int year, int month, int day, int interval);
mcal_event_set_recur_daily() sets the streams global event structure's recurrence to the given value to be reoccuring on a daily basis, ending at the given date.
int mcal_event_set_recur_weekly
(int stream,
int year, int month, int day, int interval, int weekdays);
mcal_event_set_recur_weekly() sets the streams global event structure's recurrence to the given value to be reoccuring on a weekly basis, ending at the given date.
int mcal_event_set_recur_monthly_mday
(int
stream, int year, int month, int day, int interval);
mcal_event_set_recur_monthly_mday() sets the streams global event structure's recurrence to the given value to be reoccuring on a monthly by month day basis, ending at the given date.
int mcal_event_set_recur_monthly_wday
(int
stream, int year, int month, int day, int interval);
mcal_event_set_recur_monthly_wday() sets the streams global event structure's recurrence to the given value to be reoccuring on a monthly by week basis, ending at the given date.
int mcal_event_set_recur_yearly
(int stream,
int year, int month, int day, int interval);
mcal_event_set_recur_yearly() sets the streams global event structure's recurrence to the given value to be reoccuring on a yearly basis,ending at the given date .
int mcal_fetch_current_stream_event
(int
stream);
mcal_event_fetch_current_stream_event() returns the current stream's event structure as an object containing:
All datetime entries consist of an object that contains:
mssql_close -- MS SQL Server connection을 닫는다.
int mssql_close
([int
link_identifier])r);Returns: true on success, false on error
mssql_close() closes the link to a MS SQL Server database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.
Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
mssql_close() will not close persistent links generated by mssql_pconnect().
See also: mssql_connect(), mssql_pconnect().
mssql_connect -- MS SQL server connection을 연다.
int mssql_connect
([string
servername [, string username [, string password]]])Returns: A positive MS SQL link identifier on success, or false on error.
mssql_connect() establishes a connection to a MS SQL server. The servername argument has to be a valid servername that is defined in the 'interfaces' file.
In case a second call is made to mssql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.
The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling mssql_close().
See also mssql_pconnect(), mssql_close().
mssql_data_seek -- internal row pointer를 옮긴다.
int mssql_data_seek
(int
result_identifier, int row_number)Returns: true on success, false on failure
mssql_data_seek() moves the internal row pointer of the MS SQL result associated with the specified result identifier to pointer to the specifyed row number. The next call to mssql_fetch_row() would return that row.
See also: mssql_data_seek().
mssql_fetch_array -- row를 배열로 가져온다.
int mssql_fetch_array
(int
result)Returns: An array that corresponds to the fetched row, or false if there are no more rows.
mssql_fetch_array() is an extended version of mssql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.
An important thing to note is that using mssql_fetch_array() is NOT significantly slower than using mssql_fetch_row(), while it provides a significant added value.
For further details, also see mssql_fetch_row()
mssql_fetch_field -- 필드의 정보를 구한다.
object mssql_fetch_field
(int
result [, int field_offset])Returns an object containing field information.
mssql_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retreived by mssql_fetch_field() is retreived.
The properties of the object are:
name - column name. if the column is a result of a function, this property is set to computed#N, where #N is a serial number.
column_source - the table from which the column was taken
max_length - maximum length of the column
numeric - 1 if the column is numeric
See also mssql_field_seek()
mssql_fetch_object -- row를 object로 가져온다.
int mssql_fetch_object
(int
result)Returns: An object with properties that correspond to the fetched row, or false if there are no more rows.
mssql_fetch_object() is similar to mssql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).
Speed-wise, the function is identical to mssql_fetch_array(), and almost as quick as mssql_fetch_row() (the difference is insignificant).
See also: mssql_fetch-array() and mssql_fetch-row().
mssql_fetch_row -- row를 배열(enumerated array)로 가져온다.
array mssql_fetch_row
(int result)
Returns: An array that corresponds to the fetched row, or false if there are no more rows.
Mssql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
Subsequent call to mssql_fetch_rows() would return the next row in the result set, or false if there are no more rows.
See also: mssql_fetch_array(), mssql_fetch_object(), mssql_data_seek(), mssql_fetch_lengths(), and mssql_result().
(PHP3 >= 3.0.3, PHP4 >= 4.0b4)
mssql_field_length -- 필드의 길이를 구한다.int mssql_field_length
(int result [, int offset])(PHP3 >= 3.0.3, PHP4 >= 4.0b4)
mssql_field_name -- 필드의 이름을 구한다.int mssql_field_name
(int result [, int offset])mssql_field_seek -- 필드의 offset을 설정한다.
int mssql_field_seek
(int result, int field_offset);
Seeks to the specified field offset. If the next call to mssql_fetch_field() won't include a field offset, this field would be returned.
See also: mssql_fetch_field().
(PHP3 >= 3.0.3, PHP4 >= 4.0b4)
mssql_field_type -- 필드의 타입을 구한다.string mssql_field_type
(int result [, int offset])mssql_free_result -- result memory를 풀어준다.
int mssql_free_result
(int result)
mssql_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script, you may call mssql_free_result() with the result identifier as an argument and the associated result memory will be freed.
string mssql_get_last_message
(void )void mssql_min_error_severity
(int severity)void mssql_min_message_severity
(int severity)mssql_num_fields -- result의 field 개수를 구한다.
int mssql_num_fields
(int result)
Mssql_num_fields() returns the number of fields in a result set.
See also: mssql_db_query(), mssql_query(), mssql_fetch_field(), mssql_num_rows().
mssql_num_rows -- result의 row 개수를 구한다.
int mssql_num_rows
(string result);
mssql_num_rows() returns the number of rows in a result set.
See also: mssql_db_query(), mssql_query() and, mssql_fetch_row().
mssql_pconnect -- 영구적인(persistent) MS SQL connection을 연다.
int mssql_pconnect
(string servername, string username, string password);
Returns: A positive MS SQL persistent link identifier on success, or false on error
mssql_pconnect() acts very much like mssql_connect() with two major differences.
First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mssql_close() will not close links established by mssql_pconnect()).
This type of links is therefore called 'persistent'.
mssql_query -- MS SQL 질의를 전송한다.
int mssql_query
(string query, int link_identifier);
Returns: A positive MS SQL result identifier on success, or false on error.
mssql_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if mssql_connect() was called, and use it.
See also: mssql_db_query(), mssql_select_db(), and mssql_connect().
mssql_result -- result data를 구한다.
int mssql_result
(int result, int i, mixed field);
Returns: The contents of the cell at the row and offset in the specified MS SQL result set.
mssql_result() returns the contents of one cell from a MS SQL result set. The field argument can be the field's offset, or the field's name, or the field's table dot field's name (fieldname.tablename). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.
When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than mssql_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.
Recommended high-performance alternatives: mssql_fetch_row(), mssql_fetch_array(), and mssql_fetch_object().
mssql_select_db -- 사용할 MS SQL database를 선택한다.
int mssql_select_db
(string database_name, int link_identifier);
Returns: true on success, false on error
mssql_select_db() sets the current active database on the server that's associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if mssql_connect() was called, and use it.
Every subsequent call to mssql_query() will be made on the active database.
See also: mssql_connect(), mssql_pconnect(), and mssql_query()
이 함수들은 기존 범주에 포함시키기 곤란한 것들이다.
connection_aborted -- 클라이언트가 접속을 끊었다면 true를 반환한다.
int connection_aborted
(void )Returns true if client disconnected. See the Connection Handling description in the Feature chapter for a complete explanation.
connection_status -- 연결 상태를 bit단위의 값으로 반환한다.
int connection_status
(void )Returns the connection status bitfield. See the Connection Handling description in the Feature chapter for a complete explanation.
connection_timeout -- 스크립트가 설정된 시간을 초과하여 timed out되었으면 true를 반환한다.
int connection_timeout
(void )Returns true if script timed out. See the Connection Handling description in the Feature chapter for a complete explanation.
(PHP3 , PHP4 )
define -- 상수를 선언한다.int define
(string name,
mixed value [, int case_insensitive])
Defines a named constant, which is similar to a variable except:
The name of the constant is given by name; the value is given by value.
The optional third parameter case_insensitive is also available. If the value 1 is given, then the constant will be defined case-insensitive. The default behaviour is case-sensitive; i.e. CONSTANT and Constant represent different values.
Example 1. Defining Constants
|
Define() returns TRUE on success and FALSE if an error occurs.
(PHP3 , PHP4 )
defined -- 주어진 이름의 상수가 선언되어 있는가 검사한다.int defined
(string
name)
Returns true if the named constant given by name has been defined, false otherwise.
die -- 메시지를 출력하고 현재 스크립트의 실행을 중단한다.
void die
(string
message)
This language construct outputs a message and terminates parsing of the script. It does not return anything.
Example 1. die example
|
See also exit().
eval -- PHP 코드를 가진 문자열을 실행한다.
void eval
(string
code_str)
eval() evaluates the string given in code_str as PHP code. Among other things, this can be useful for storing code in a database text field for later execution.
There are some factors to keep in mind when using eval(). Remember that the string passed must be valid PHP code, including things like terminating statements with a semicolon so the parser doesn't die on the line after the eval(), and properly escaping things in code_str.
Also remember that variables given values under eval() will retain these values in the main script afterwards.
Example 1. Eval() example - simple text merge
|
exit -- 현재 스크립트의 실행을 중단한다.
void exit
(void);
This language construct terminates parsing of the script. It does not return.
See also die().
(PHP4 >= 4.0b4)
func_get_arg -- 함수의 파라메터로 넘어온 아이템을 구한다.int func_get_arg
(int
arg_num)
Returns the argument which is at the arg_num'th offset into a user-defined function's argument list. Function arguments are counted starting from zero. Func_get_arg() will generate a warning if called from outside of a function definition.
If arg_num is greater than the number of arguments actually passed, a warning will be generated and func_get_arg() will return FALSE.
1 2 <?php 3 function foo() { 4 $numargs = func_num_args(); 5 echo "Number of arguments: $numargs<br>\n"; 6 if ($numargs >= 2) { 7 echo "Second argument is: " . func_get_arg (1) . "<br>\n"; 8 } 9 } 10 11 foo (1, 2, 3); 12 ?> 13 |
Func_get_arg() may be used in conjunction with func_num_args() and func_get_args() to allow user-defined functions to accept variable-length argument lists.
Note: This function was added in PHP 4.
(PHP4 >= 4.0b4)
func_get_args -- 함수의 파라메터로 넘어온 argument들을 배열로 반환한다.int func_get_args
(void
)
Returns an array in which each element is the corresponding member of the current user-defined function's argument list. Func_get_args() will generate a warning if called from outside of a function definition.
1 2 <?php 3 function foo() { 4 $numargs = func_num_args(); 5 echo "Number of arguments: $numargs<br>\n"; 6 if ($numargs >= 2) { 7 echo "Second argument is: " . func_get_arg (1) . "<br>\n"; 8 } 9 $arg_list = func_get_args(); 10 for ($i = 0; $i < $numargs; $i++) { 11 echo "Argument $i is: " . $arg_list[$i] . "<br>\n"; 12 } 13 } 14 15 foo (1, 2, 3); 16 ?> 17 |
Func_get_args() may be used in conjunction with func_num_args() and func_get_arg() to allow user-defined functions to accept variable-length argument lists.
Note: This function was added in PHP 4.
(PHP4 >= 4.0b4)
func_num_args -- 함수로 넘어온 파라메터의 갯수를 구한다.int func_num_args
(void
)
Returns the number of arguments passed into the current user-defined function. Func_num_args() will generate a warning if called from outside of a function definition.
1 2 <?php 3 function foo() { 4 $numargs = func_num_args(); 5 echo "Number of arguments: $numargs\n"; 6 } 7 8 foo (1, 2, 3); // Prints 'Number of arguments: 3' 9 ?> 10 |
Func_num_args() may be used in conjunction with func_get_arg() and func_get_args() to allow user-defined functions to accept variable-length argument lists.
Note: This function was added in PHP 4.
function_exists -- 주어진 이름의 함수가 정의되어 있다면 true를 반환한다.
int function_exists
(string
function_name)Checks the list of defined functions for function_name. Returns true if the given function name was found, false otherwise.
(PHP3 , PHP4 )
get_browser -- 사용자의 브라우저가 어떤 기능을 가지고 있는가를 말해준다.object get_browser
([string user_agent])
get_browser() attempts to determine the capabilities of the user's browser. This is done by looking up the browser's information in the browscap.ini file. By default, the value of $HTTP_USER_AGENT is used; however, you can alter this (i.e., look up another browser's info) by passing the optional user_agent parameter to get_browser().
The information is returned in an object, which will contain various data elements representing, for instance, the browser's major and minor version numbers and ID string; true/false values for features such as frames, JavaScript, and cookies; and so forth.
While browscap.ini contains information on many browsers, it relies on user updates to keep the database current. The format of the file is fairly self-explanatory.
The following example shows how one might list all available information retrieved about the user's browser.
Example 1. Get_browser() example
|
The output of the above script would look something like this:
1 2 Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586)<hr> 3 <b>browser_name_pattern:</b> Mozilla/4\.5.*<br> 4 <b>parent:</b> Netscape 4.0<br> 5 <b>platform:</b> Unknown<br> 6 <b>majorver:</b> 4<br> 7 <b>minorver:</b> 5<br> 8 <b>browser:</b> Netscape<br> 9 <b>version:</b> 4<br> 10 <b>frames:</b> 1<br> 11 <b>tables:</b> 1<br> 12 <b>cookies:</b> 1<br> 13 <b>backgroundsounds:</b> <br> 14 <b>vbscript:</b> <br> 15 <b>javascript:</b> 1<br> 16 <b>javaapplets:</b> 1<br> 17 <b>activexcontrols:</b> <br> 18 <b>beta:</b> <br> 19 <b>crawler:</b> <br> 20 <b>authenticodeupdate:</b> <br> 21 <b>msn:</b> <br> 22 |
In order for this to work, your browscap configuration file setting must point to the correct location of the browscap.ini file.
For more information (including locations from which you may obtain a browscap.ini file), check the PHP FAQ at http://www.php.net/FAQ.php3.
Note: Browscap support was added to PHP in version 3.0b2.
ignore_user_abort -- 클라이언트가 접속을 끊었을 때 스크립트의 수행을 중단하는가를 정한다.
int ignore_user_abort
(int [setting]);
This function sets whether a client disconnect should cause a script to be aborted. It will return the previous setting and can be called without an argument to not change the current setting and only return the current setting. See the Connection Handling section in the Features chapter for a complete description of connection handling in PHP.
iptcparse -- binary IPTC http://www.xe.net/iptc/ block을 하나의 택으로 parse한다.
array iptcparse
(string iptcblock);
This function parses a binary IPTC block into its single tags. It returns an array using the tagmarker as an index and the value as the value. It returns false on error or if no IPTC data was found. See GetImageSize() for a sample.
leak -- 메모리를 누설(Leak) 한다.
void leak
(int bytes)Leak() leaks the specified amount of memory.
This is useful when debugging the memory manager, which automatically cleans up "leaked" memory when each request is completed.
pack -- data를 binary 문자열로 pack한다.
string pack
(string format [,
mixed args ...])Pack given arguments into binary string according to format. Returns binary string containing data.
The idea to this function was taken from Perl and all formatting codes work the same as there. The format string consists of format codes followed by an optional repeater argument. The repeater argument can be either an integer value or * for repeating to the end of the input data. For a, A, h, H the repeat count specifies how many characters of one data argument are taken, for @ it is the absolute position where to put the next data, for everything else the repeat count specifies how many data arguments are consumed and packed into the resulting binary string. Currently implemented are
a NUL-padded string
A SPACE-padded string
h Hex string, low nibble first
H Hex string, high nibble first
c signed char
C unsigned char
s signed short (always 16 bit, machine byte order)
S unsigned short (always 16 bit, machine byte order)
n unsigned short (always 16 bit, big endian byte order)
v unsigned short (always 16 bit, little endian byte order)
i signed integer (machine dependant size and byte order)
I unsigned integer (machine dependant size and byte order)
l signed long (always 32 bit, machine byte order)
L unsigned long (always 32 bit, machine byte order)
N unsigned long (always 32 bit, big endian byte order)
V unsigned long (always 32 bit, little endian byte order)
f float (machine dependent size and representation)
d double (machine dependent size and representation)
x NUL byte
X Back up one byte
@ NUL-fill to absolute position
Example 1. Pack() format string
The resulting binary string will be 6 bytes long and contain the byte sequence 0x12, 0x34, 0x78, 0x56, 0x41, 0x42. |
Note that the distinction between signed and unsigned values only affects the function unpack(), where as function pack() gives the same result for signed and unsigned format codes.
Also note that PHP internally stores integral values as signed values of a machine dependant size. If you give it an unsigned integral value too large to be stored that way it is converted to a double which often yields an undesired result.
register_shutdown_function -- 스크립트가 종료될 때 실행될 함수를 설정한다.
int register_shutdown_function
(string func)Registers the function named by func to be executed when script processing is complete.
Common Pitfalls:
Since no output is allowed to the browser in this function, you will be unable to debug it using statements such as print or echo.
serialize -- 어떤 형태의 값이라도 저장 가능한 형태의 문자열로 만들어 준다.
string serialize
(mixed
value)
Serialize() returns a string containing a byte-stream representation of value that can be stored anywhere.
This is useful for storing or passing PHP values around without losing their type and structure.
To make the serialized string into a PHP value again, use unserialize(). Serialize() handles the types integer, double, string, array (multidimensional) and object (object properties will be serialized, but methods are lost).
Example 1. Serialize() example
|
sleep -- 실행을 잠시 지연시킨다.
void sleep
(int seconds)The sleep function delays program execution for the given number of seconds.
See also usleep().
uniqid -- 유일한 id를 생성한다.
int uniqid
(string
prefix [, boolean lcg])
Uniqid() returns a prefixed unique identifier based on the current time in microseconds. The prefix can be useful for instance if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same microsecond. Prefix can be up to 114 characters long.
If the optional lcg parameter is true, uniqid() will add additional "combined LCG" entropy at the end of the return value, which should make the results more unique.
With an empty prefix, the returned string will be 13 characters long. If lcg is true, it will be 23 characters.
Note: The lcg parameter is only available in PHP 4 and PHP 3.0.13 and later.
If you need a unique identifier or token and you intend to give out that token to the user via the network (i.e. session cookies), it is recommended that you use something along the lines of
1 2 $token = md5 (uniqid ("")); // no random portion 3 $better_token = md5 (uniqid (rand())); // better, difficult to guess 4 |
This will create a 32 character identifier (a 128 bit hex number) that is extremely difficult to predict.
unpack -- binary 문자열을 data로 unpack한다.
array unpack
(string
format, string data)
Unpack() from binary string into array according to format. Returns array containing unpacked elements of binary string.
Unpack() works slightly different from Perl as the unpacked data is stored in an associative array. To accomplish this you have to name the different format codes and separate them by a slash /.
Example 1. Unpack() format string
The resulting array will contain the entries "chars1", "chars2" and "int". |
For an explanation of the format codes see also: pack()
Note that PHP internally stores integral values as signed. If you unpack a large unsigned long and it is of the same size as PHP internally stored values the result will be a negative number even though unsigned unpacking was specified.
unserialize -- 저장가능한 형태로 표현된 문자열을 PHP 값으로 만들어준다.
mixed unserialize
(string str)
unserialize() takes a single serialized variable (see serialize()) and converts it back into a PHP value. The converted value is returned, and can be an integer, double, string, array or object. If an object was serialized, its methods are not preserved in the returned value.
Example 1. Unserialize() example
|
usleep -- 실행을 백만분의 일초 단위로 지연시킨다.
void usleep
(int micro_seconds)The usleep() function delays program execution for the given number of micro_seconds.
See also sleep().
msql -- mSQL 질의를 전송한다.
int msql(string database, string query, int link_identifier);
Returns a positive mSQL result identifier to the query result, or false on error.
msql() selects a database and executes a query on it. If the optional link identifier isn't specified, the function will try to find an open link to the mSQL server and if no such link is found it'll try to create one as if msql_connect() was called with no arguments (see msql_connect()).
msql_affected_rows -- 최근 질의에 영향을 받는 row의 개수를 구한다.
int msql_affected_rows
(int query_identifier);
Returns number of affected ("touched") rows by a specific query (i.e. the number of rows returned by a SELECT, the number of rows modified by an update, or the number of rows removed by a delete).
See also: msql_query()
msql_close -- mSQL connection을 닫는다.
int msql_close(int link_identifier);
Returns true on success, false on error.
msql_close() closes the link to a mSQL database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.
Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
msql_close() will not close persistent links generated by msql_pconnect().
See also: msql_connect() and msql_pconnect().
msql_connect -- mSQL connection을 연다.
int msql_connect(string hostname);
Returns a positive mSQL link identifier on success, or false on error.
msql_connect() establishes a connection to a mSQL server. The hostname argument is optional, and if it's missing, localhost is assumed.
In case a second call is made to msql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.
The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling msql_close().
See also msql_pconnect(), msql_close().
msql_create_db -- mSQL database를 만든다.
int msql_create_db
(string database name, int [link_identifier] );
msql_create_db() attempts to create a new database on the server associated with the specified link identifier.
See also: msql_drop_db().
msql_createdb -- mSQL database를 만든다.
int msql_createdb
(string database name, int [link_identifier] );
Identical to msql_create_db().
msql_data_seek -- 내부적인 row pointer를 이동한다.
int msql_data_seek(int result_identifier, int row_number);
Returns true on success, false on failure.
msql_data_seek() moves the internal row pointer of the mSQL result associated with the specified result identifier to pointer to the specifyed row number. The next call to msql_fetch_row() would return that row.
See also: msql_fetch_row().
msql_dbname -- 현재 mSQL database의 이름을 구한다.
string msql_dbname(string result, int i);
msql_dbname() returns the database name stored in position i of the result pointer returned from the msql_listdbs() function. The msql_numrows() function can be used to determine how many database names are available.
msql_drop_db -- mSQL database를 버린다.(drop = delete)
int msql_drop_db(string database_name, int link_identifier);
Returns true on success, false on failure.
msql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier.
See also: msql_create_db().
msql_dropdb -- mSQL database를 버린다.(drop = delete)
See msql_drop_db().
msql_error -- 마지막 mSQL 호출의 에러 메세지를 반환한다.
string msql_error( );
Errors coming back from the mSQL database backend no longer issue warnings. Instead, use these functions to retrieve the error string.
msql_fetch_array -- row를 배열로 가져온다.
int msql_fetch_array
(int query_identifier, int [result_type] );
Returns an array that corresponds to the fetched row, or false if there are no more rows.
msql_fetch_array() is an extended version of msql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.
The second optional argument result_type in msql_fetch_array() is a constant and can take the following values: MSQL_ASSOC, MSQL_NUM, and MYSQL_BOTH.
Be careful if you are retrieving results from a query that may return a record that contains only one field that has a value of 0 (or an empty string, or NULL).
An important thing to note is that using msql_fetch_array() is NOT significantly slower than using msql_fetch_row(), while it provides a significant added value.
For further details, also see msql_fetch_row()
msql_fetch_field -- 필드 정보를 구한다.
object msql_fetch_field
(int query_identifier, int field_offset);
Returns an object containing field information
msql_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retreived by msql_fetch_field() is retreived.
The properties of the object are:
name - column name
table - name of the table the column belongs to
not_null - 1 if the column cannot be null
primary_key - 1 if the column is a primary key
unique - 1 if the column is a unique key
type - the type of the column
See also msql_field_seek().
msql_fetch_object -- row를 객체(Object)로 가져온다.
int msql_fetch_object
(int query_identifier, int [result_type] );
Returns an object with properties that correspond to the fetched row, or false if there are no more rows.
msql_fetch_object() is similar to msql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).
The optional second argument result_type in msql_fetch_array() is a constant and can take the following values: MSQL_ASSOC, MSQL_NUM, and MSQL_BOTH.
Speed-wise, the function is identical to msql_fetch_array(), and almost as quick as msql_fetch_row() (the difference is insignificant).
See also: msql_fetch_array() and msql_fetch_row().
msql_fetch_row -- row를 배열(enumerated array)로 가져온다.
array msql_fetch_row
(int query_identifier);
Returns an array that corresponds to the fetched row, or false if there are no more rows.
msql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
Subsequent call to msql_fetch_row() would return the next row in the result set, or false if there are no more rows.
See also: msql_fetch_array(), msql_fetch_object(), msql_data_seek(), and msql_result().
msql_fieldname -- 필드 이름을 구한다.
string msql_fieldname
(int query_identifier, int field);
msql_fieldname() returns the name of the specified field. query_identifier is the query identifier, and field is the field index. msql_fieldname($result, 2); will return the name of the second field in the result associated with the result identifier.
msql_field_seek -- 필드의 offset을 설정한다.
int msql_field_seek
(int query_identifier, int field_offset);
Seeks to the specified field offset. If the next call to msql_fetch_field() won't include a field offset, this field would be returned.
See also: msql_fetch_field().
msql_fieldtable -- 해당 필드를 가져 온 Table 이름을 구한다.
int msql_fieldtable(int result, int field);
Returns the name of the table field was fetched from.
msql_fieldtype -- 필드 type을 구한다.
string msql_fieldtype
(int query_identifier, int i);
msql_fieldtype() is similar to the msql_fieldname() function. The arguments are identical, but the field type is returned. This will be one of "int", "string" or "real".
msql_fieldflags -- 필드 flag를 구한다.
string msql_fieldflags
(int query_identifier, int i);
msql_fieldflags() returns the field flags of the specified field. Currently this is either, "not null", "primary key", a combination of the two or "" (an empty string).
msql_fieldlen -- 필드 길이를 구한다.
int msql_fieldlen
(int query_identifier, int i);
msql_fieldlen() returns the length of the specified field.
msql_free_result -- result memory를 풀어준다.
int msql_free_result
(int query_identifier);
msql_free_result() frees the memory associated with query_identifier. When PHP completes a request, this memory is freed automatically, so you only need to call this function when you want to make sure you don't use too much memory while the script is running.
msql_freeresult -- result memory를 풀어준다.
msql_list_fields -- result field들을 나열한다.
int msql_list_fields(string database, string tablename);
msql_list_fields() retrieves information about the given tablename. Arguments are the database name and the table name. A result pointer is returned which can be used with msql_fieldflags(), msql_fieldlen(), msql_fieldname(), and msql_fieldtype(). A query identifier is a positive integer. The function returns -1 if a error occurs. A string describing the error will be placed in $phperrmsg, and unless the function was called as @msql_list_fields() then this error string will also be printed out.
See also msql_error().
msql_listfields -- result field들을 나열한다.
See msql_list_fields().
msql_list_dbs -- server의 mSQL database들을 나열한다.
int msql_list_dbs(void);
msql_list_dbs() will return a result pointer containing the databases available from the current msql daemon. Use the msql_dbname() function to traverse this result pointer.
msql_listdbs -- server의 mSQL database들을 나열한다.
See msql_list_dbs().
msql_list_tables -- mSQL database의 table들을 나열한다.
int msql_list_tables(string database);
msql_list_tables() takes a database name and result pointer much like the msql() function. The msql_tablename() function should be used to extract the actual table names from the result pointer.
msql_listtables -- mSQL database의 table들을 나열한다.
See msql_list_tables().
msql_num_fields -- result의 field 개수를 구한다.
int msql_num_fields(int result);
msql_num_fields() returns the number of fields in a result set.
See also: msql(), msql_query(), msql_fetch_field(), and msql_num_rows().
msql_num_rows -- result의 row 개수를 구한다.
int msql_num_rows(string result);
msql_num_rows() returns the number of rows in a result set.
See also: msql(), msql_query(), and msql_fetch_row().
msql_numfields -- result의 field 개수를 구한다.
int msql_numfields(void);
Identical to msql_num_fields().
msql_numrows -- result의 row 개수를 구한다.
int msql_numrows(void);
Identical to msql_num_rows().
msql_pconnect -- 영구적인 mSQL 접속을 연다.
int msql_pconnect(string hostname);
Returns a positive mSQL persistent link identifier on success, or false on error.
msql_pconnect() acts very much like msql_connect() with two major differences.
First, when connecting, the function would first try to find a (persistent) link that's already open with the same host. If one is found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (msql_close() will not close links established by msql_pconnect()).
This type of links is therefore called 'persistent'.
msql_query -- mSQL 질의를 전송한다.
int msql_query(string query, int link_identifier);
msql_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if msql_connect() was called, and use it.
Returns a positive mSQL result identifier on success, or false on error.
See also: msql(), msql_select_db(), and msql_connect().
msql_regcase -- 정규 표현식(regular expression)을 대,소문자를 가리지 않도록 한다.
See sql_regcase().
msql_result -- result data를 구한다.
int msql_result
(int query_identifier, int i, mixed field);
Returns the contents of the cell at the row and offset in the specified mSQL result set.
msql_result() returns the contents of one cell from a mSQL result set. The field argument can be the field's offset, or the field's name, or the field's table dot field's name (fieldname.tablename). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.
When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than msql_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.
Recommended high-performance alternatives: msql_fetch_row(), msql_fetch_array(), and msql_fetch_object().
msql_select_db -- mSQL database를 선택한다.
int msql_select_db(string database_name, int link_identifier);
Returns true on success, false on error.
msql_select_db() sets the current active database on the server that's associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if msql_connect() was called, and use it.
Every subsequent call to msql_query() will be made on the active database.
See also: msql_connect(), msql_pconnect(), and msql_query().
msql_selectdb -- mSQL database를 선택한다.
See msql_select_db().
msql_tablename -- 해당 필드를 가져 온 Table 이름을 구한다.
string msql_tablename
(int query_identifier, int field);
msql_tablename() takes a result pointer returned by the msql_list_tables() function as well as an integer index and returns the name of a table. The msql_numrows() function may be used to determine the number of tables in the result pointer.
Example 1. Msql_tablename() example
|
이 함수들은 MySQL 데이터베이스 서버에 접근할 수 있도록 해 준다.
MySQL에 대한 좀 더 자세한 설명은 http://www.mysql.com/에서 찾을 수 있다.
( 역자주 : Solaris MySQL with pthreads note:
만약 여러분이 MySQL이 threaded client library(default는 아니다)를 사용하고, PHP를 MySQL지원으로 컴파일한다면 아마 여러분은
다음과 같은 에러를 만나게 된다....
Undefined first referenced
symbol in file
pthread_attr_setschedparam /opt/GNUmysql/lib/mysql/libmysqlclient.a(my_pthread.o)
pthread_setschedparam /opt/GNUmysql/lib/mysql/libmysqlclient.a(my_pthread.o)
이때는 Makefile을 손으로 고쳐주어야 한다. "LIBS"로 시작되는 줄을 찾아 "-lpthreads"를 줄의 마지막에 삽입한다. 그후에 "make"하면 될
것이다.)
mysql_affected_rows -- 최근 질의에 영향을 받는 row의 개수를 구한다.
int mysql_affected_rows
(int [link_identifier] );
mysql_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or DELETE query on the server associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.
If the last query was a DELETE query with no WHERE clause, all of the records will have been deleted from the table but this function will return zero.
This command is not effective for SELECT statements, only on statements which modify records. To retrieve the number of rows returned from a SELECT, use mysql_num_rows().
(PHP3 >= 3.0.13)
mysql_change_user -- 현재 활성화 되어있는 연결에 LOGIN되어있는 사용자를 바꾼다.int mysql_change_user
(string user, string password [, string database [, int link_identifier]])
mysql_change_user() changes the logged in user on the current active connection, or, if specified on the connection given by the link identifier. If a database is specified, this will default or current database after the user has been changed. If the new user/password combination fails to be authorized the current connected user stays active.
Note: This function was introduced in PHP 3.0.13 and requires MySQL 3.23.3 or higher.
mysql_close -- MySQL connection을 닫는다.
int mysql_close
(int [link_identifier] );
Returns: true on success, false on error
mysql_close() closes the link to a MySQL database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.
Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
mysql_close() will not close persistent links generated by mysql_pconnect().
See also: mysql_connect(), and mysql_pconnect().
mysql_connect -- MySQL server connection을 연다.
int mysql_connect
(string [hostname [:port] [:/path/to/socket] ] , string [username] , string [password] );
Returns: A positive MySQL link identifier on success, or false on error.
mysql_connect() establishes a connection to a MySQL server. All of the arguments are optional, and if they're missing, defaults are assumed ('localhost', user name of the user that owns the server process, empty password).
The hostname string can also include a port number. eg. "hostname:port" or a path to a socket eg. ":/path/to/socket" for the localhost.
Note: Support for ":port" wass added in 3.0B4.
Support for the ":/path/to/socket" was added in 3.0.10.
In case a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.
The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling mysql_close().
See also mysql_pconnect(), and mysql_close().
mysql_create_db -- MySQL database를 만든다.
int mysql_create_db
(string database name, int [link_identifier] );
mysql_create_db() attempts to create a new database on the server associated with the specified link identifier.
See also: mysql_drop_db(). For downwards compatibility mysql_createdb() can also be used.
mysql_data_seek -- internal row pointer를 옮긴다.
int mysql_data_seek(int result_identifier, int row_number);
Returns: true on success, false on failure
mysql_data_seek() moves the internal row pointer of the MySQL result associated with the specified result identifier to point to the specified row number. The next call to mysql_fetch_row() would return that row.
mysql_db_query -- MySQL 질의를 전송한다.
int mysql_db_query(string database, string query, int [link_identifier]);
Returns: A positive MySQL result identifier to the query result, or false on error.
mysql_db_query() selects a database and executes a query on it. If the optional link identifier isn't specified, the function will try to find an open link to the MySQL server and if no such link is found it'll try to create one as if mysql_connect() was called with no arguments
See also mysql_connect(). For downwards compatibility mysql() can also be used.
mysql_drop_db -- MySQL database를 버린다.(drop = delete)
int mysql_drop_db
(string database_name, int [link_identifier] );
Returns: true on success, false on failure.
mysql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier.
See also: mysql_create_db(). For downward compatibility mysql_dropdb() can also be used.
mysql_errno -- 마지막 MySQL 호출의 에러 번호를 반환한다.
int mysql_errno
(int [link_identifier] );
Errors coming back from the mySQL database backend no longer issue warnings. Instead, use these functions to retrieve the error number.
<?php mysql_connect("marliesle"); echo mysql_errno().": ".mysql_error()."<BR>"; mysql_select_db("nonexistentdb"); echo mysql_errno().": ".mysql_error()."<BR>"; $conn = mysql_query("SELECT * FROM nonexistenttable"); echo mysql_errno().": ".mysql_error()."<BR>"; ?>
See also: mysql_error()
mysql_error -- 마지막 MySQL 호출의 에러 메세지를 반환한다.
string mysql_error
(int [link_identifier] );
Errors coming back from the mySQL database backend no longer issue warnings. Instead, use these functions to retrieve the error string.
<?php mysql_connect("marliesle"); echo mysql_errno().": ".mysql_error()."<BR>"; mysql_select_db("nonexistentdb"); echo mysql_errno().": ".mysql_error()."<BR>"; $conn = mysql_query("SELECT * FROM nonexistenttable"); echo mysql_errno().": ".mysql_error()."<BR>"; ?>
See also: mysql_errno()
mysql_fetch_array -- row를 배열로 가져온다.
array mysql_fetch_array
(int result, int [result_type] );
Returns an array that corresponds to the fetched row, or false if there are no more rows.
mysql_fetch_array() is an extended version of mysql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.
If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must the numeric index of the column or make an alias for the column.
select t1.f1 as foo t2.f1 as bar from t1, t2
An important thing to note is that using mysql_fetch_array() is NOT significantly slower than using mysql_fetch_row(), while it provides a significant added value.
The optional second argument result_type in mysql_fetch_array() is a constant and can take the following values: MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH.
For further details, also see mysql_fetch_row()
Example 1. mysql fetch array <?php mysql_connect($host,$user,$password); $result = mysql_db_query("database","select * from table"); while($row = mysql_fetch_array($result)) { echo $row["user_id"]; echo $row["fullname"]; } mysql_free_result($result); ?> |
mysql_fetch_field -- 필드 정보를 구한다.
object mysql_fetch_field
(int result, int [field_offset] );
Returns an object containing field information.
mysql_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retreived by mysql_fetch_field() is retreived.
The properties of the object are:
name - column name
table - name of the table the column belongs to
max_length - maximum length of the column
not_null - 1 if the column cannot be null
primary_key - 1 if the column is a primary key
unique_key - 1 if the column is a unique key
multiple_key - 1 if the column is a non-unique key
numeric - 1 if the column is numeric
blob - 1 it the column is a BLOB
type - the type of the column
unsigned - 1 if the column is unsigned
zerofill - 1 if the column is zero-filled
See also mysql_field_seek()
mysql_fetch_lengths -- output column의 최대 data 길이를 구한다.
int mysql_fetch_lengths(int result);
Returns: An array that corresponds to the lengths of each field in the last row fetched by mysql_fetch_row(), or false on error.
mysql_fetch_lengths() stores the lengths of each result column in the last row returned by mysql_fetch_row() in an array, starting at offset 0.
See also: mysql_fetch_row().
mysql_fetch_object -- row를 객체(Object)로 가져온다.
object mysql_fetch_object
(int result, int [result_type]);
Returns an object with properties that correspond to the fetched row, or false if there are no more rows.
mysql_fetch_object() is similar to mysql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).
The optional argument result_typ is a constant and can take the following values: MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH.
Speed-wise, the function is identical to mysql_fetch_array(), and almost as quick as mysql_fetch_row() (the difference is insignificant).
Example 1. mysql fetch object <?php mysql_connect($host,$user,$password); $result = mysql_db_query("database","select * from table"); while($row = mysql_fetch_object($result)) { echo $row->user_id; echo $row->fullname; } mysql_free_result($result); ?> |
See also: mysql_fetch_array() and mysql_fetch_row().
mysql_fetch_row -- row를 배열(enumerated array)로 가져온다.
array mysql_fetch_row(int result);
Returns: An array that corresponds to the fetched row, or false if there are no more rows.
mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
Subsequent call to mysql_fetch_row() would return the next row in the result set, or false if there are no more rows.
See also: mysql_fetch_array(), mysql_fetch_object(), mysql_data_seek(), mysql_fetch_lengths(), and mysql_result().
mysql_field_name -- 필드 이름을 구한다.
string mysql_field_name
(int result, int field_index);
mysql_field_name() returns the name of the specified field. Arguments to the function is the result identifier and the field index, ie. mysql_field_name($result,2);
Will return the name of the second field in the result associated with the result identifier.
For downwards compatibility mysql_fieldname() can also be used.
mysql_field_seek -- 필드의 offset을 설정한다.
int mysql_field_seek(int result, int field_offset);
Seeks to the specified field offset. If the next call to mysql_fetch_field() won't include a field offset, this field would be returned.
See also: mysql_fetch_field().
mysql_field_table -- 해당 필드를 가져 온 Table 이름을 구한다.
string mysql_field_table(int result, int field_offset);
Get the table name for field. For downward compatibility mysql_fieldtable() can also be used.
mysql_field_type -- 필드 type을 구한다.
string mysql_field_type
(int result, int field_offset);
mysql_field_type() is similar to the mysql_field_name() function. The arguments are identical, but the field type is returned. This will be one of "int", "real", "string", "blob", or others as detailed in the MySQL documentation.
Example 1. mysql field types <?php mysql_connect("localhost:3306"); mysql_select_db("wisconsin"); $result = mysql_query("SELECT * FROM onek"); $fields = mysql_num_fields($result); $rows = mysql_num_rows($result); $i = 0; $table = mysql_field_table($result, $i); echo "Your '".$table."' table has ".$fields." fields and ".$rows." records <BR>"; echo "The table has the following fields <BR>"; while ($i < $fields) { $type = mysql_field_type ($result, $i); $name = mysql_field_name ($result, $i); $len = mysql_field_len ($result, $i); $flags = mysql_field_flags ($result, $i); echo $type." ".$name." ".$len." ".$flags."<BR>"; $i++; } mysql_close(); ?> |
For downward compatibility mysql_fieldtype() can also be used.
mysql_field_flags -- 필드 flag를 구한다.
string mysql_field_flags
(string result, int field_offset);
mysql_field_flags() returns the field flags of the specified field. The flags are reported as a single word per flag separated by a single space, so that you can split the returned value using explode().
The following flags are reported, if your version of MySQL is current enough to support them: "not_null", "primary_key", "unique_key", "multiple_key", "blob", "unsigned", "zerofill", "binary", "enum", "auto_increment", "timestamp".
For downward compatibility mysql_fieldflags() can also be used.
mysql_field_len -- 필드 길이를 구한다.
int mysql_field_len(string result, int field_offset);
mysql_field_len() returns the length of the specified field. For downward compatibility mysql_fieldlen() can also be used.
mysql_free_result -- result memory를 풀어준다.
int mysql_free_result(int result);
mysql_free_result() only needs to be called if you are worried about using too much memory while your script is running. All associated result memory for the specified result identifier will automatically be freed.
For downward compatibility mysql_freeresult() can also be used.
mysql_insert_id -- 최근 INSERT에서 만들어진 id (generated id)를 구한다.
int mysql_insert_id
(int [link_identifier]);
mysql_insert_id() returns the ID generated for an AUTO_INCREMENTED field. This function takes no arguments. It will return the auto-generated ID returned by the last INSERT query performed.
mysql_list_fields -- result field들을 나열한다.
int mysql_list_fields
(string database_name, string table_name, int [link_identifier] );
mysql_list_fields() retrieves information about the given tablename. Arguments are the database name and the table name. A result pointer is returned which can be used with mysql_field_flags(), mysql_field_len(), mysql_field_name(), and mysql_field_type().
A result identifier is a positive integer. The function returns -1 if a error occurs. A string describing the error will be placed in $phperrmsg, and unless the function was called as @mysql() then this error string will also be printed out.
For downward compatibility mysql_listfields() can also be used.
mysql_list_dbs -- server의 MySQL database들을 나열한다.
int mysql_list_dbs
(int [link_identifier] );
mysql_list_dbs() will return a result pointer containing the databases available from the current mysql daemon. Use the mysql_tablename() function to traverse this result pointer.
For downward compatibility mysql_listdbs() can also be used.
mysql_list_tables -- MySQL database의 table들을 나열한다.
int mysql_list_tables
(string database, int [link_identifier] );
mysql_list_tables() takes a database name and result pointer much like the mysql_db_query() function. The mysql_tablename() function should be used to extract the actual table names from the result pointer.
For downward compatibility mysql_listtables() can also be used.
mysql_num_fields -- result의 field 개수를 구한다.
int mysql_num_fields(int result);
mysql_num_fields() returns the number of fields in a result set.
See also: mysql_db_query(), mysql_query(), mysql_fetch_field(), mysql_num_rows().
For downward compatibility mysql_numfields() can also be used.
mysql_num_rows -- result의 row 개수를 구한다.
int mysql_num_rows
(int result);
mysql_num_rows() returns the number of rows in a result set.
See also: mysql_db_query(), mysql_query() and, mysql_fetch_row().
For downward compatibility mysql_numrows() can also be used.
mysql_pconnect -- 영구적인 MySQL 접속을 연다.
int mysql_pconnect
(string [hostname [:port] [:/path/to/socket] ] , string [username] , string [password] );
Returns: A positive MySQL persistent link identifier on success, or false on error
mysql_pconnect() establishes a connection to a MySQL server. All of the arguments are optional, and if they're missing, defaults are assumed ('localhost', user name of the user that owns the server process, empty password).
The hostname string can also include a port number. eg. "hostname:port" or a path to a socket eg. ":/path/to/socket" for the localhost.
Note: Support for ":port" was added in 3.0B4.
Support for the ":/path/to/socket" was added in 3.0.10.
mysql_pconnect() acts very much like mysql_connect() with two major differences.
First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mysql_close() will not close links established by mysql_pconnect()).
This type of links is therefore called 'persistent'.
mysql_query -- MySQL 질의를 전송한다.
int mysql_query
(string query, int [link_identifier] );
mysql_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if mysql_connect() was called with no arguments, and use it.
The query string should not end with a semicolon.
mysql_query() returns TRUE (non-zero) or FALSE to indicate whether or not the query succeeded. A return value of TRUE means that the query was legal and could be executed by the server. It does not indicate anything about the number of rows affected or returned. It is perfectly possible for a query to succeed but affect no rows or return no rows.
The following query is syntactically invalid, so mysql_query() fails and returns FALSE:
Example 1. mysql_query() <?php $result = mysql_query ("SELECT * WHERE 1=1") or die ("Invalid query"); ?> |
The following query is semantically invalid if my_col is not a column in the table my_tbl, so mysql_query() fails and returns FALSE:
Example 2. mysql_query() <?php $result = mysql_query ("SELECT my_col FROM my_tbl") or die ("Invalid query"); ?> |
mysql_query() will also fail and return FALSE if you don't have permission to access the table(s) referenced by the query.
Assuming the query succeeds, you can call mysql_affected_rows() to find out how many rows were affected (for DELETE, INSERT, REPLACE, or UPDATE statements). For SELECT statements, mysql_query() returns a new result identifier that you can pass to mysql_result(). When you are done with the result set, you can free the resources associated with it by calling mysql_free_result().
See also: mysql_affected_rows(), mysql_db_query(), mysql_free_result(), mysql_result(), mysql_select_db(), and mysql_connect().
mysql_result -- result data를 구한다.
int mysql_result
(int result, int row, mixed [field] );
mysql_result() returns the contents of one cell from a MySQL result set. The field argument can be the field's offset, or the field's name, or the field's table dot field's name (fieldname.tablename). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.
When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than mysql_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.
Calls mysql_result() should not be mixed with calls to other functions that deal with the result set.
Recommended high-performance alternatives: mysql_fetch_row(), mysql_fetch_array(), and mysql_fetch_object().
mysql_select_db -- MySQL database를 선택한다.
int mysql_select_db
(string database_name, int [link_identifier] );
Returns: true on success, false on error
mysql_select_db() sets the current active database on the server that's associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if mysql_connect() was called, and use it.
Every subsequent call to mysql_query() will be made on the active database.
See also: mysql_connect(), mysql_pconnect(), and mysql_query()
For downward compatibility mysql_selectdb() can also be used.
mysql_tablename -- 해당 필드를 가져 온 Table 이름을 구한다.
string mysql_tablename(int result, int i);
mysql_tablename() takes a result pointer returned by the mysql_list_tables() function as well as an integer index and returns the name of a table. The mysql_num_rows() function may be used to determine the number of tables in the result pointer.
Example 1. mysql_tablename() example <?php mysql_connect ("localhost:3306"); $result = mysql_listtables ("wisconsin"); $i = 0; while ($i < mysql_num_rows ($result)) { $tb_names[$i] = mysql_tablename ($result, $i); echo $tb_names[$i] . "<BR>"; $i++; } ?> |
checkdnsrr -- 주어진 Internet host name or IP address에 해당하는 DNS record들을 검사한다 .
int checkdnsrr
(string host [,
string type])Searches DNS for records of type type corresponding to host. Returns true if any records are found; returns false if no records were found or if an error occurred.
type may be any one of: A, MX, NS, SOA, PTR, CNAME, or ANY. The default is MX.
host may either be the IP address in dotted-quad notation or the host name.
See also getmxrr(), gethostbyaddr(), gethostbyname(), gethostbynamel(), and the named(8) manual page.
closelog -- system logger로의 connection을 닫는다.
int closelog
(void);closelog() closes the descriptor being used to write to the system logger. The use of closelog() is optional.
debugger_on -- 내장된 PHP debugger를 enable 한다.
void debugger_on
(string address);Enables the internal PHP debugger, connecting it to address. The debugger is still under development.
debugger_off -- 내장된 PHP debugger를 disable 한다.
void debugger_off
(string address);Disables the internal PHP debugger. The debugger is still under development.
fsockopen -- Internet이나 Unix domain의 socket connection을 연다.
int fsockopen
(string hostname,
int port [, int errno [, string errstr [, double timeout]]])Initiates a stream connection in the Internet (AF_INET) or Unix (AF_UNIX) domain. For the Internet domain, it will open a TCP socket connection to hostname on port port. For the Unix domain, hostname will be used as the path to the socket, port must be set to 0 in this case. The optional timeout can be used to set a timeout in seconds for the connect system call.
fsockopen() returns a file pointer which may be used together with the other file functions (such as fgets(), fgetss(), fputs(), fclose(), feof()).
If the call fails, it will return false and if the optional errno and errstr arguments are present they will be set to indicate the actual system level error that occurred on the system-level connect() call. If the returned errno is 0 and the function returned false, it is an indication that the error occurred before the connect() call. This is most likely due to a problem initializing the socket. Note that the errno and errstr arguments must be passed by reference.
Depending on the environment, the Unix domain or the optional connect timeout may not be available.
The socket will by default be opened in blocking mode. You can switch it to non-blocking mode by using set_socket_blocking().
Example 1. Fsockopen() Example
|
See also: pfsockopen()
gethostbyaddr -- 주어진 IP address에 해당하는 Internet host name을 구한다.
string gethostbyaddr
(string ip_address)
Returns the host name of the Internet host specified by ip_address. If an error occurs, returns ip_address.
See also gethostbyname().
gethostbyname -- 주어진 Internet host name에 해당하는 IP address를 구한다.
string gethostbyname
(string hostname)
Returns the IP address of the Internet host specified by hostname.
See also gethostbyaddr().
gethostbynamel -- 주어진 Internet host name에 해당하는 IP addresse들의 list를 구한다.
array gethostbynamel
(string hostname)
Returns a list of IP addresses to which the Internet host specified by hostname resolves.
See also gethostbyname(), gethostbyaddr(), checkdnsrr(), getmxrr(), and the named(8) manual page.
getmxrr -- 주어진 Internet host name에 해당하는 MX record들을 구한다.
int getmxrr
(string
hostname, array mxhosts [, array weight])
Searches DNS for MX records corresponding to hostname. Returns true if any records are found; returns false if no records were found or if an error occurred.
A list of the MX records found is placed into the array mxhosts. If the weight array is given, it will be filled with the weight information gathered.
See also checkdnsrr(), gethostbyname(), gethostbynamel(), gethostbyaddr(), and the named(8) manual page.
(PHP4 >= 4.0b4)
getprotobyname -- 프로토콜 이름에 해당하는 프로토콜 번호를 구한다.Get protocol number associated with protocol name
int getprotobyname
(string name)
Getprotobyname() returns the protocol number associated with the protocol name as per /etc/protocols.
See also: getprotobynumber().
(PHP4 >= 4.0b4)
getprotobynumber -- 프로토콜 번호에 해당하는 프로토콜 이름을 구한다.string getprotobynumber
(int number)
Getprotobynumber() returns the protocol name associated with protocol number as per /etc/protocols.
See also: getprotobyname().
(PHP4 >= 4.0b4)
getservbyname -- 주어진 인터넷 서비스와 프로토콜에 해당하는 포트 번호를 구한다.int getservbyname
(string service, string protocol)
Getservbyname() returns the Internet port which corresponds to service for the specified protocol as per /etc/services. protocol is either TCP or UDP.
See also: getservbyport().
(PHP4 >= 4.0b4)
getservbyport -- 주어진 포트와 프로토콜에 해당하는 인터넷 서비스를 구한다.Get Internet service which corresponds to port and protocol
string getservbyport
(int port, string protocol)
Getservbyport() returns the Internet service associated with port for the specified protocol as per /etc/services. protocol is either TCP or UDP.
See also: getservbyname().
openlog -- system logger로의 connection을 연다.
int openlog
(string ident, int
option, int facility)openlog() opens a connection to the system logger for a program. The string ident is added to each message. Values for option and facility are given in the next section. The use of openlog() is optional; It will automatically be called by syslog() if necessary, in which case ident will default to false. See also syslog() and closelog().
pfsockopen -- 영구적인(persistent) Internet이나 Unix domain의 socket 연결을 연다.
int pfsockopen
(string
hostname, int port [, int errno [, string errstr [, int timeout]]])ut]);This function behaves exactly as fsockopen() with the difference that the connection is not closed after the script finishes. It is the persistent version of fsockopen().
set_socket_blocking -- 소켓의 blocking/non-blocking 모드를 설정한다.
int set_socket_blocking
(int
socket descriptor, int mode)If mode is false, the given socket descriptor will be switched to non-blocking mode, and if true, it will be switched to blocking mode. This affects calls like fgets() that read from the socket. In non-blocking mode an fgets() call will always return right away while in blocking mode it will wait for data to become available on the socket.
syslog -- system log message를 만든다.
int syslog
(int
priority, string message)
Syslog() generates a log message that will be distributed by the system logger. priority is a combination of the facility and the level, values for which are given in the next section. The remaining argument is the message to send, except that the two characters %m will be replaced by the error message string (strerror) corresponding to the present value of errno.
More information on the syslog facilities can be found in the man pages for syslog on Unix machines.
On Windows NT, the syslog service is emulated using the Event Log
NIS(과거에는 Yellow Pages라 불렸다.)는 password 파일 같은 중요한 관리 파일들을 네트웍상에서 관리할 수 있도록 해준다. NIS에 대한 자세한 정보는 NIS manpage와 Introduction to YP/NIS에서 찾아보도록한다. Hal Stern이 쓴 Managing NFS and NIS라는 책도 있다.
이 함수들이 작동하려면 --with-yp 옵션을 주고 PHP를 설정하여야 한다.
yp_get_default_domain -- 해당 시스템의 디폴트 NIS 도메인을 구한다.
int yp_get_default_domain
(void )
yp_get_default_domain() returns the default domain of the node or FALSE. Can be used as the domain parameter for successive NIS calls.
A NIS domain can be described a group of NIS maps. Every host that needs to look up information binds itself to a certain domain. Refer to the documents mentioned at the beginning for more detailed information.
Example 1. Example for the default domain
|
yp_order -- map에 대한 순서 번호를 반환한다.
int yp_order
(string
domain, string map)
yp_order() returns the order number for a map or FALSE.
Example 1. Example for the NIS order
|
See also: yp_get_default_domain
yp_master -- map에서의 마스터 NIS 서버의 시스템 이름을 반환한다.
string yp_master
(string
domain, string map)
yp_master() returns the machine name of the master NIS server for a map.
Example 1. Example for the NIS master
|
See also: yp_get_default_domain
yp_match -- 대응하는 값을 반환한다.
string yp_match
(string
domain, string map, string key)
yp_match() returns the value associated with the passed key out of the specified map or FALSE. This key must be exact.
Example 1. Example for NIS match
|
In this case this could be: joe:##joe:11111:100:Joe User:/home/j/joe:/usr/local/bin/bash
See also: yp_get_default_domain
yp_first -- 주어진 map에서 첫 번째 key-value 쌍을 반환한다.
string[] yp_first
(string domain, string map)
yp_first() returns the first key-value pair from the named map in the named domain, otherwise FALSE.
Example 1. Example for the NIS first
|
See also: yp_get_default_domain
yp_next -- 주어진 map에서 다음 key-value 쌍을 반환한다.
string[] yp_next
(string
domain, string map, string key)
yp_next() returns the next key-value pair in the named map after the specified key or FALSE.
Example 1. Example for NIS next
|
See also: yp_get_default_domain
yp_errno -- 이전 작업에서의 에러 코드를 반환한다.
int yp_errno
();
yp_errno() returns the error code of the previous operation.
Possible errors are:
1 args to function are bad |
2 RPC failure - domain has been unbound |
3 can't bind to server on this domain |
4 no such map in server's domain |
5 no such key in map |
6 internal yp server or client error |
7 resource allocation failure |
8 no more records in map database |
9 can't communicate with portmapper |
10 can't communicate with ypbind |
11 can't communicate with ypserv |
12 local domain name not set |
13 yp database is bad |
14 yp version mismatch |
15 access violation |
16 database busy |
See also: yp_err_string
yp_err_string -- 이전 작업에서의 에러 문자열을 반환한다.
string yp_err_string
(void );
yp_err_string() returns the error message associated with the previous operation. Useful to indicate what exactly went wrong.
Example 1. Example for NIS errors <?php echo "Error: " . yp_err_string(); ?> |
See also: yp_errno
odbc_autocommit -- autocommit 기능을 켜고, 끈다.
int odbc_autocommit
(int
connection_id [, int OnOff])Without the OnOff parameter, this function returns auto-commit status for connection_id. True is returned if auto-commit is on, false if it is off or an error occurs.
If OnOff is true, auto-commit is enabled, if it is false auto-commit is disabled. Returns true on success, false on failure.
By default, auto-commit is on for a connection. Disabling auto-commit is equivalent with starting a transaction.
See also odbc_commit() and odbc_rollback().
odbc_binmode -- binary column data를 다룬다.
int odbc_binmode
(int result_id, int mode);
(ODBC SQL types affected: BINARY, VARBINARY, LONGVARBINARY)
When binary SQL data is converted to character C data, each byte (8 bits) of source data is represented as two ASCII characters. These characters are the ASCII character representation of the number in its hexadecimal form. For example, a binary 00000001 is converted to "01" and a binary 11111111 is converted to "FF".
Table 1. LONGVARBINARY handling
binmode |
longreadlen |
result |
---|---|---|
ODBC_BINMODE_PASSTHRU |
0 |
passthru |
ODBC_BINMODE_RETURN |
0 |
passthru |
ODBC_BINMODE_CONVERT |
0 |
passthru |
ODBC_BINMODE_PASSTHRU |
0 |
passthru |
ODBC_BINMODE_PASSTHRU |
>0 |
passthru |
ODBC_BINMODE_RETURN |
>0 |
return as is |
ODBC_BINMODE_CONVERT |
>0 |
return as char |
If odbc_fetch_into() is used, passthru means that an empty string is returned for these columns.
If result_id is 0, the settings apply as default for new results.
Note: Default for longreadlen is 4096 and binmode defaults to ODBC_BINMODE_RETURN. Handling of binary long columns is also affected by odbc_longreadlen()
odbc_close -- ODBC connection을 닫는다.
void odbc_close
(int
connection_id)odbc_close() will close down the connection to the database server associated with the given connection identifier.
NOTE: This function will fail if there are open transactions on this connection. The connection will remain open in this case.
odbc_close_all -- 모든 ODBC connection들을 닫는다.
void odbc_close_all
(void);odbc_close_all() will close down all connections to database server(s).
NOTE: This function will fail if there are open transactions on a connection. This connection will remain open in this case.
odbc_commit -- ODBC transaction을 commit한다.
int odbc_commit
(int
connection_id)Returns: true on success, false on failure. All pending transactions on connection_id are committed.
odbc_connect -- datasource와 연결한다.
int odbc_connect
(string dsn, string user, string password[, int cursor_type]);
Returns an ODBC connection id or 0 (false) on error.
The connection id returned by this functions is needed by other ODBC functions. You can have multiple connections open at once. The optional fourth parameter sets the type of cursor to be used for this connection. This parameter is not normally needed, but can be useful for working around problems with some ODBC drivers.
With some ODBC drivers, executing a complex stored procedure may fail with an error similar to: "Cannot open a cursor on a stored procedure that has anything other than a single select statement in it". Using SQL_CUR_USE_ODBC may avoid that error. Also, some drivers don't support the optional row_number parameter in odbc_fetch_row(). SQL_CUR_USE_ODBC might help in that case, too.
The following constants are defined for cursortype:
For persistent connections see odbc_pconnect().
odbc_cursor -- cursorname을 구한다.
string odbc_cursor
(int
result_id)odbc_cursor will return a cursorname for the given result_id.
odbc_do -- odbc_exec()와 같다.
string odbc_do
(int conn_id, string query);
odbc_do will execute a query on the given connection
odbc_exec -- SQL 문장을 준비하고 실행한다.
int odbc_exec
(int connection_id, string query_string);
Returns false on error. Returns an ODBC result identifier if the SQL command was executed successfully.
odbc_exec() will send an SQL statement to the database server specified by connection_id. This parameter must be a valid identifier returned by odbc_connect() or odbc_pconnect().
See also: odbc_prepare() and odbc_execute() for multiple execution of SQL statements.
odbc_execute -- 실행할 준비가 된 문장을 실행한다.
int odbc_execute
(int result_id[, array parameters_array]);
Executes a statement prepared with odbc_prepare(). Returns true on successful execution, false otherwise. The array arameters_array only needs to be given if you really have parameters in your statement.
odbc_fetch_into -- 한개의 result row를 배열로 가져온다.
int odbc_fetch_into
(int
result_id [, int rownumber, array result_array])Returns the number of columns in the result; false on error. result_array must be passed by reference, but it can be of any type since it will be converted to type array. The array will contain the column values starting at array index 0.
odbc_fetch_row -- row를 가져온다.
int odbc_fetch_row
(int result_id[, int row_number]);
If odbc_fetch_row() was succesful (there was a row), true is returned. If there are no more rows, false is returned.
odbc_fetch_row() fetches a row of the data that was returned by odbc_do() / odbc_exec(). After odbc_fetch_row() is called, the fields of that row can be accessed with odbc_result().
If row_number is not specified, odbc_fetch_row() will try to fetch the next row in the result set. Calls to odbc_fetch_row() with and without row_number can be mixed.
To step through the result more than once, you can call odbc_fetch_row() with row_number 1, and then continue doing odbc_fetch_row() without row_number to review the result. If a driver doesn't support fetching rows by number, the row_number parameter is ignored.
odbc_field_name -- columnname을 구한다.
string odbc_fieldname
(int result_id, int field_number);
odbc_field_name() will return the name of the field occupying the given column number in the given ODBC result identifier. Field numbering starts at 1. false is returned on error.
odbc_field_type -- field의 datatype을 구한다.
string odbc_field_type
(int result_id, mixed field);
odbc_field_type() will return the SQL type of the field referecend by name or number in the given ODBC result identifier. Field numbering runs from 1.
odbc_field_len -- field의 길이를 구한다.
int odbc_field_len
(int result_id, int field_number);
odbc_field_len() will return the length of the field referecend by number in the given ODBC result identifier. Field numbering starts at 1.
(PHP4 >= 4.0.0)
odbc_field_precision -- odbc_field_len()과 같다.string odbc_field_precision
(int result_id, int field_number)
odbc_field_precision() will return the precision of the field referecend by number in the given ODBC result identifier.
See also: odbc_field_scale() to get the scale of a floating point number
(PHP4 >= 4.0.0)
odbc_field_scale -- 필드의 스케일(scale)을 구한다.string odbc_field_scale
(int result_id, int field_number)
odbc_field_precision() will return the scale of the field referecend by number in the given ODBC result identifier.
odbc_free_result -- 지정된 result에 관련된 resource를 해제한다.
int odbc_free_result
(int
result_id)Always returns true.
odbc_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script is finished. But, if you are sure you are not going to need the result data anymore in a script, you may call odbc_free_result(), and the memory associated with result_id will be freed.
NOTE: If auto-commit is disabled (see odbc_autocommit()) and you call odbc_free_result() before commiting, all pending transactions are rolled back.
odbc_longreadlen -- LONG column들을 다룬다.
int odbc_longreadlen
(int
result_id, int length)(ODBC SQL types affected: LONG, LONGVARBINARY) The number of bytes returned to PHP is controled by the parameter length. If it is set to 0, Long column data is passed thru to the client.
NOTE: Handling of LONGVARBINARY columns is also affected by odbc_binmode()
odbc_num_fields -- result의 column 개수
int odbc_num_fields
(int
result_id)odbc_num_fields() will return the number of fields (columns) in an ODBC result. This function will return -1 on error. The argument is a valid result identifier returned by odbc_exec().
odbc_pconnect -- 영구적인 database connection을 연다.
int odbc_pconnect
(string dsn,
string user, string password [, int cursor_type])Returns an ODBC connection id or 0 (false) on error. This function is much like odbc_connect(), except that the connection is not really closed when the script has finished. Future requests for a connection with the same dsn, user, password combination (via odbc_connect() and odbc_pconnect()) can reuse the persistent connection.
Note: Persistent connections have no effect if PHP is used as a CGI program.
For information about the optional cursor_type parameter see the odbc_connect() function. For more information on persistent connections, refer to the PHP FAQ.
odbc_prepare -- 실행할 문장을 준비한다.
int odbc_prepare(int connection_id, string query_string);
Returns false on error.
Returns an ODBC result identifier if the SQL command was prepared successfully. The result identifier can be used later to execute the statement with odbc_execute().
odbc_num_rows -- result의 row 개수
int odbc_num_rows
(int result_id);
odbc_num_rows() will return the number of rows in an ODBC result. This function will return -1 on error. For INSERT, UPDATE and DELETE statements odbc_num_rows() returns the number of rows affected. For a SELECT clause this can be the number of rows available.
Note: Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.
odbc_result -- result data를 구한다.
string odbc_result
(int
result_id, mixed field)Returns the contents of the field.
field can either be an integer containing the column number of the field you want; or it can be a string containing the name of the field. For example:
1 2 $item_3 = odbc_result ($Query_ID, 3); 3 $item_val = odbc_result ($Query_ID, "val"); 4 |
The first call to odbc_result() returns the value of the third field in the current record of the query result. The second function call to odbc_result() returns the value of the field whose field name is "val" in the current record of the query result. An error occurs if a column number parameter for a field is less than one or exceeds the number of columns (or fields) in the current record. Similarly, an error occurs if a field with a name that is not one of the fieldnames of the table(s) that is(are) being queried.
Field indices start from 1. Regarding the way binary or long column data is returned refer to odbc_binmode() and odbc_longreadlen().
odbc_result_all -- result를 HTML table로 인쇄한다.
int odbc_result_all
(int
result_id [, string format])Returns the number of rows in the result or false on error.
odbc_result_all() will print all rows from a result identifier produced by odbc_exec(). The result is printed in HTML table format. With the optional string argument format, additional overall table formatting can be done.
odbc_rollback -- transaction을 Rollback 한다.
int odbc_rollback
(int connection_id);
Rolls back all pending statements on connection_id. Returns true on success, false on failure.
odbc_setoption -- ODBC 설정을 조정한다. 에러가 발생한 경우 false를 반환하고 아니면 true를 반환한다.
int odbc_setoption
(int
id, int function, int option, int param)
This function allows fiddling with the ODBC options for a particular connection or query result. It was written to help find work arounds to problems in quirky ODBC drivers. You should probably only use this function if you are an ODBC programmer and understand the effects the various options will have. You will certainly need a good ODBC reference to explain all the different options and values that can be used. Different driver versions support different options.
Because the effects may vary depending on the ODBC driver, use of this function in scripts to be made publicly available is strongly discouraged. Also, some ODBC options are not available to this function because they must be set before the connection is established or the query is prepared. However, if on a particular job it can make PHP work so your boss doesn't tell you to use a commercial product, that's all that really matters.
ID is a connection id or result id on which to change the settings.For SQLSetConnectOption(), this is a connection id. For SQLSetStmtOption(), this is a result id.
Function is the ODBC function to use. The value should be 1 for SQLSetConnectOption() and 2 for SQLSetStmtOption().
Parameter option is the option to set.
Parameter param is the value for the given option.
Example 1. ODBC Setoption Examples
|
(PHP4 >= 4.0b4)
odbc_tables -- 지정된 데이터 소스에 저장되어 있는 테이블들의 이름을 목록으로 가져온다. 해당 정보를 가진 result identifier가 반환된다.int odbc_tables
(int
connection_id [, string qualifier [, string owner [, string name [, string
types]]]])
Lists all tables in the requested range. Returns an ODBC result identifier or false on failure.
The result set has the following columns:
The result set is ordered by TABLE_TYPE, TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.
The owner and name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).
To support enumeration of qualifiers, owners, and table types, the following special semantics for the qualifier, owner, name, and table_type are available:
If table_type is not an empty string, it must contain a list of comma-separated values for the types of interest; each value may be enclosed in single quotes (') or unquoted. For example, "'TABLE','VIEW'" or "TABLE, VIEW". If the data source does not support a specified table type, odbc_tables() does not return any results for that type.
See also odbc_tableprivileges() to retrieve associated privileges.
(PHP4 >= 4.0b4)
odbc_tableprivileges -- 테이블과, 그 각각의 테이블이 가지고 있는 권한(privileges)을 리스트한다.int odbc_tableprivileges
(int connection_id [, string qualifier [, string owner [, string name]]])
Lists tables in the requested range and the privileges associated with each table. Returns an ODBC result identifier or false on failure.
The result set has the following columns:
The result set is ordered by TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.
The owner and name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).
(PHP4 >= 4.0b4)
odbc_columns -- 지정된 데이터 테이블에 속한 컬럼들의 이름을 목록으로 가져온다. 해당 정보를 가진 result identifier가 반환된다.Lists the column names in specified tables. Returns a result identifier containing the information.
int odbc_columns
(int
connection_id [, string qualifier [, string owner [, string table_name [, string
column_name]]]])
Lists all columns in the requested range. Returns an ODBC result identifier or false on failure.
The result set has the following columns:
The result set is ordered by TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.
The owner, table_name and column_name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).
See also odbc_columnprivileges() to retrieve associated privileges.
(PHP4 >= 4.0b4)
odbc_columnprivileges -- 컬럼과 그 권한(privileges)의 목록을 가져오는데 사용할 result identifier를 반환한다.int odbc_columnprivileges
(int connection_id [, string
qualifier [, string owner [, string table_name [, string column_name]]]])
Lists columns and associated privileges for the given table. Returns an ODBC result identifier or false on failure.
The result set has the following columns:
The result set is ordered by TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.
The column_name argument accepts search patterns ('%' to match zero or more characters and '_' to match a single character).
(PHP4 >= 4.0b4)
odbc_gettypeinfo -- 해당 데이터 소스가 지원하는 데이터 형태(types)에 대한 정보를 가진 result identifier를 반환한다.int odbc_gettypeinfo
(int connection_id [, int data_type])
Retrieves information about data types supported by the data source. Returns an ODBC result identifier or false on failure. The optional argument data_type can be used to restrict the information to a single data type.
The result set has the following columns:
The result set is ordered by DATA_TYPE and TYPE_NAME.
(PHP4 >= 4.0b4)
odbc_primarykeys -- 해당 테이블의 프라이머리 키를 구성하는 필드 이름의 목록을 가져오는데 사용할 result identifier를 반환한다.int odbc_primarykeys
(int connection_id, string qualifier, string owner, string table)
Returns the column names that comprise the primary key for a table. Returns an ODBC result identifier or false on failure.
The result set has the following columns:
(PHP4 >= 4.0b4)
odbc_foreignkeys -- 지정된 테이블의 외부키(foreign keys)의 목록을 반환하거나, 지정된 테이블의 주키(primary key)를 참조하는 다른테이블들의 외부키(foreign keys)의 목록을 반환한다.int odbc_foreignkeys
(int connection_id, string pk_qualifier, string pk_owner, string pk_table,
string fk_qualifier, string fk_owner, string fk_table)
Odbc_foreignkeys() retrieves information about foreign keys. Returns an ODBC result identifier or false on failure.
The result set has the following columns:
If pk_table contains a table name, odbc_foreignkeys() returns a result set containing the primary key of the specified table and all of the foreign keys that refer to it.
If fk_table contains a table name, odbc_foreignkeys() returns a result set containing all of the foreign keys in the specified table and the primary keys (in other tables) to which they refer.
If both pk_table and fk_table contain table names, odbc_foreignkeys() returns the foreign keys in the table specified in fk_table that refer to the primary key of the table specified in pk_table. This should be one key at most.
(PHP4 >= 4.0b4)
odbc_procedures -- 지정된 데이터 소스에 저장되어 있는 procedures의 목록을 가져온다. 반환값은 해당 정보를 가진 result identifier 이다.int odbc_procedures
(int
connection_id [, string qualifier [, string owner [, string name]]])
Lists all procedures in the requested range. Returns an ODBC result identifier or false on failure.
The result set has the following columns:
The owner and name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).
(PHP4 >= 4.0b4)
odbc_procedurecolumns -- procedures의 파라메터에 대한 정보를 검색한다.int odbc_procedurecolumns
(int connection_id [, string
qualifier [, string owner [, string proc [, string column]]]])
Returns the list of input and output parameters, as well as the columns that make up the result set for the specified procedures. Returns an ODBC result identifier or false on failure.
The result set has the following columns:
The result set is ordered by PROCEDURE_QUALIFIER, PROCEDURE_OWNER, PROCEDURE_NAME and COLUMN_TYPE.
The owner, proc and column arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).
(PHP4 >= 4.0b4)
odbc_specialcolumns -- 테이블의 열(row)을 uniquely identify하는 컬럼들이나, transaction으로 해당 열의 어떤 값이 수정될 때 자동으로 값이 바뀌는 컬럼들의 최적의 집합을 반환한다.int odbc_specialcolumns
(int connection_id, int type, string qualifier, string owner, string table, int
scope, int nullable)
When the type argument is SQL_BEST_ROWID, odbc_specialcolumns() returns the column or columns that uniquely identify each row in the table.
When the type argument is SQL_ROWVER, odbc_specialcolumns() returns the optimal column or set of columns that, by retrieving values from the column or columns, allows any row in the specified table to be uniquely identified.
Returns an ODBC result identifier or false on failure.
The result set has the following columns:
The result set is ordered by SCOPE.
(PHP4 >= 4.0b4)
odbc_statistics -- 해당 테이블에 대한 통계 정보를 검색한다.int odbc_statistics
(int
connection_id, string qualifier, string owner, string table_name, int unique,
int accuracy)
Get statistics about a table and it's indexes. Returns an ODBC result identifier or false on failure.
The result set has the following columns:
The result set is ordered by NON_UNIQUE, TYPE, INDEX_QUALIFIER, INDEX_NAME and SEQ_IN_INDEX.
Ora_Bind -- PHP 변수를 Oracle 파라메터로 bind한다.
int ora_bind
(int cursor, string PHP variable name, string SQL parameter name, int length, int [type]);
Returns true if the bind succeeds, otherwise false. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.
This function binds the named PHP variable with a SQL parameter. The SQL parameter must be in the form ":name". With the optional type parameter, you can define whether the SQL parameter is an in/out (0, default), in (1) or out (2) parameter. As of PHP 3.0.1, you can use the constants ORA_BIND_INOUT, ORA_BIND_IN and ORA_BIND_OUT instead of the numbers.
ora_bind must be called after ora_parse() and before ora_exec(). Input values can be given by assignment to the bound PHP variables, after calling ora_exec() the bound PHP variables contain the output values if available.
1 2 <?php 3 ora_parse($curs, "declare tmp INTEGER; begin tmp := :in; :out := tmp; :x := 7.77; end;"); 4 ora_bind($curs, "result", ":x", $len, 2); 5 ora_bind($curs, "input", ":in", 5, 1); 6 ora_bind($curs, "output", ":out", 5, 2); 7 $input = 765; 8 ora_exec($curs); 9 echo "Result: $result<BR>Out: $output<BR>In: $input"; 10 ?> 11 |
Ora_Close -- Oracle cursor를 닫는다.
int ora_close(int cursor);
Returns true if the close succeeds, otherwise false. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.
( 역자주 : 이 함수는 언제나 "wrong parameter count" 이나"true"를 반환한다. 그러나 C-API인 "ora_del_cursor()"는 원래 아무것도 반환하지 않도록되어 있으므로 무시하도록 한다. )
This function closes a data cursor opened with ora_open().
Ora_ColumnName -- Oracle result column의 이름을 구한다.
string Ora_ColumnName(int cursor, int column);
Returns the name of the field/column column on the cursor cursor. The returned name is in all uppercase letters.
Ora_ColumnType -- Oracle result column의 type을 구한다.
string Ora_ColumnType(int cursor, int column);
Returns the Oracle data type name of the field/column column on the cursor cursor. The returned type will be one of the following:
"VARCHAR2" |
"VARCHAR" |
"CHAR" |
"NUMBER" |
"LONG" |
"LONG RAW" |
"ROWID" |
"DATE" |
"CURSOR" |
Ora_Commit -- Oracle transaction을 commit 한다.
int ora_commit(int conn);
Returns true on success, false on error. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions. This function commits an Oracle transaction. A transaction is defined as all the changes on a given connection since the last commit/rollback, autocommit was turned off or when the connection was established.
Ora_CommitOff -- automatic commit을 disable 한다.
int ora_commitoff(int conn);
Returns true on success, false on error. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.
This function turns off automatic commit after each ora_exec().
Ora_CommitOn -- automatic commit을 enable 한다.
int ora_commiton(int conn);
This function turns on automatic commit after each ora_exec() on the given connection.
Returns true on success, false on error. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.
Ora_Error -- Oracle error message를 구한다.
string Ora_Error
(int cursor);
Returns an error message of the form XXX-NNNNN where XXX is where the error comes from and NNNNN identifies the error message.
The cursor parameter can as of PHP 3. 0.6 also be a connection id.
On UNIX versions of Oracle, you can find details about an error message like this: $ oerr ora 00001 00001, 00000, "unique constraint (%s.%s) violated" // *Cause: An update or insert statement attempted to insert a duplicate key // For Trusted ORACLE configured in DBMS MAC mode, you may see // this message if a duplicate entry exists at a different level. // *Action: Either remove the unique restriction or do not insert the key
Ora_ErrorCode -- Oracle error code를 구한다.
int Ora_ErrorCode(int cursor);
Returns the numeric error code of the last executed statement on the specified cursor.
The cursor parameter can as of PHP 3. 0.6 also be a connection id.
Ora_Exec -- Oracle cursor에 있는 parse된 statement을 실행한다.
int ora_exec(int cursor);
Returns true on success, false on error. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.
Ora_Fetch -- cursor에서 data의 row를 가져온다.
int ora_fetch(int cursor);
Returns true (a row was fetched) or false (no more rows, or an error occured). If an error occured, details can be retrieved using the ora_error() and ora_errorcode() functions. If there was no error, ora_errorcode() will return 0. Retrieves a row of data from the specified cursor.
Ora_GetColumn -- 가져온 row에서 data를 구한다.
mixed ora_getcolumn(int cursor, mixed column);
Returns the column data. If an error occurs, False is returned and ora_errorcode() will return a non-zero value. Note, however, that a test for False on the results from this function may be true in cases where there is not error as well (NULL result, empty string, the number 0, the string "0"). Fetches the data for a column or function result.
Ora_Logoff -- Oracle connection을 닫는다.
int ora_logoff(int connection);
Returns true on success, False on error. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions. Logs out the user and disconnects from the server.
Ora_Logon -- Oracle connection을 연다.
int ora_logon
(string user, string password);
Establishes a connection between PHP and an Oracle database with the given username and password.
Connections can be made using SQL*Net by supplying the TNS name to user like this:
$conn = Ora_Logon("user@TNSNAME", "pass");
If you have character data with non-ASCII characters, you should make sure that NLS_LANG is set in your environment. For server modules, you should set it in the server's environment before starting the server.
Returns a connection index on success, or false on failure. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.
Ora_Open -- Oracle cursor를 연다.
int ora_open(int connection);
Opens an Oracle cursor associated with connection.
Returns a cursor index or False on failure. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.
Ora_Parse -- SQL 문장을 해석(parse)한다.
int ora_parse(int cursor_ind, string sql_statement, int defer);
This function parses an SQL statement or a PL/SQL block and associates it with the given cursor. Returns 0 on success or -1 on error.
Ora_Rollback -- transaction을 Rollback 한다.
int ora_rollback(int connection);
This function undoes an Oracle transaction. (See ora_commit() for the definition of a transaction.)
Returns true on success, false on error. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.
다음의 환경변수의 값을 알고 있어야 한다. :
이 변수 값들은 database에 연결하여 sqlplus를 사용할 수 있는 사용자로 login하여 확인할 수 있다. UNIX shell에서 다음과 같이 확인한다. :
prompt> echo $ORACLE_HOME /opt/oracle/oracle/8.0.3 prompt> echo $ORACLE_SID ORACLE
<?php putenv("ORACLE_SID=ORACLE"); putenv("ORACLE_HOME=/opt/oracle/oracle/8.0.3"); $conn = ora_login("scott", "tiger"); $curs = ora_open($conn); ora_commitoff($conn); $query = sprintf("select * from cat"); /* Long version */ /* ora_parse($curs, $query); ora_exec($curs); ora_fetch($curs); */ /* Short Version */ ora_do($conn, $query); $ncols = ora_numcols($curs); $nrows = ora_numrows($curs); printf("Result size is $ncols cols by $nrows rows.<br>"); for ($i=0; $i<$ncols; $i++) { printf("col[%s] = %s type[%d] = %s<br>",$i, ora_columnname($curs, $I), $i, ora_columntype($curs, $I)); } for ($j=0; $j<$nrows; $j++) { for ($i=0; $i<$ncols; $i++) { $col = ora_getcolumn($curs, $I); printf("val[%d, %d] = %s * ", $j, $i, ora_getcolumn($curs, $I); } printf("<br>"); } ?>ORACLE_HOME이 /opt/oracle/oracle/8.0.3이라고 가정했을 때, 솔라리스에서 PHP를 Orecle을 지원하도록 설정하는 방법은 다음과 같다. :
./configure --with-oracle \ --with-config-file-path=/opt/GNUphp3/lib \ --with-exec-dir=/opt/bin \ --enable-debug=yes \ --enable-safe-mode=no \ --enable-url-fopen-wrapper=yes \ --enable-track-vars=yes \ --prefix=/opt/GNUphp3then the resulting PHP binary will be dynamically linked against libclntsh.so in /opt/oracle/oracle/lib. The build process as generated by configure will include this directory with an -L option, but not with an -R option (run-time library search path). This means that the resulting binary will not be able to find libclntsh.so by itself, but depends on an appropriate LD_LIBRARY_PATH set within the web server CGI environment - which usually is not there. To fix this, grab the Makefile generated by configure and duplicate the -L/opt/oracle/oracle/8.0.3/lib option as an -R/opt/oracle/oracle/8.0.3/lib option (your -L and -R strings will look slightly different depending on the values for your oracle version and ORACLE_HOME). The -R option will compile in the corrent search path for libclntsh and you won't have any LD_LIBRARY_PATH pains any more.
이 함수들은 Oracle8과 Oracle7 데이터베이스를 접근할 수 있도록 해준다. 이것은 Oracle8 Call-Interface (OCI8)를 사용한다.이 드라이버를 사용하려면 Oracle8 client libraries가 필요하다.
이 드라이버는 보통의 PHP Ora_ 드라이버보다 더욱 유연하다. 이것은 PHP의 전역, 지역 변수들의 Oracle placeholder로의 binding을 지원하고, full LOB와 FILE, ROWID를 지원하며, user-supplied define variable을 사용할 수 있도록 해 준다.
OCIDefineByName -- SELECT 중의 degine-step으로 PHP 변수를 사용한다.
int OCIDefineByName
(int stmt, string Column-Name, mixed &variable, int [type]);
OCIDefineByName() uses fetches SQL-Columns into user-defined PHP-Variables. Be careful that Oracle user ALL-UPPERCASE column-names, whereby in your select you can also write lower-case. OCIDefineByName() expects the Column-Name to be in uppercase. If you define a variable that doesn't exists in you select statement, no error will be given!
If you need to define an abstract Datatype (LOB/ROWID/BFILE) you need to allocate it first using OCINewDescriptor() function. See also the OCIBindByName() function.
Example 1. OCIDefineByName <?php /* OCIDefineByPos example thies@digicol.de (980219) */ $conn = OCILogon("scott","tiger"); $stmt = OCIParse($conn,"select empno, ename from emp"); /* the define MUST be done BEFORE ociexecute! */ OCIDefineByName($stmt,"EMPNO",&$empno); OCIDefineByName($stmt,"ENAME",&$ename); OCIExecute($stmt); while (OCIFetch($stmt)) { echo "empno:".$empno."\n"; echo "ename:".$ename."\n"; } OCIFreeStatement($stmt); OCILogoff($conn); ?> |
OCIBindByName -- PHP 변수를 Oracle Placeholder로 bind 한다.
int OCIBindByName
(int stmt, string ph_name, mixed &variable, intlength, int [type]);
OCIBindByName() binds the PHP variable variable to the Oracle placeholder ph_name. Whether it will be used for input or output will be determined run-time, and the necessary storage space will be allocated. The length paramter sets the maximum length for the bind. If you set length to -1 OCIBindByName() will use the current length of variable to set the maximum length.
If you need to bind an abstract Datatype (LOB/ROWID/BFILE) you need to allocate it first using OCINewDescriptor() function. The length is not used for abstract Datatypes and should be set to -1. The type variable tells oracle, what kind of descriptor we want to use. Possible values are: OCI_B_FILE (Binary-File), OCI_B_CFILE (Character-File), OCI_B_CLOB (Character-LOB), OCI_B_BLOB (Binary-LOB) and OCI_B_ROWID (ROWID).
Example 1. OCIDefineByName <?php /* OCIBindByPos example thies@digicol.de (980221) inserts 3 resords into emp, and uses the ROWID for updating the records just after the insert. */ $conn = OCILogon("scott","tiger"); $stmt = OCIParse($conn,"insert into emp (empno, ename) ". "values (:empno,:ename) ". "returning ROWID into :rid"); $data = array(1111 => "Larry", 2222 => "Bill", 3333 => "Jim"); $rowid = OCINewDescriptor($conn,OCI_D_ROWID); OCIBindByName($stmt,":empno",&$empno,32); OCIBindByName($stmt,":ename",&$ename,32); OCIBindByName($stmt,":rid",&$rowid,-1,OCI_B_ROWID); $update = OCIParse($conn,"update emp set sal = :sal where ROWID = :rid"); OCIBindByName($update,":rid",&$rowid,-1,OCI_B_ROWID); OCIBindByName($update,":sal",&$sal,32); $sal = 10000; while (list($empno,$ename) = each($data)) { OCIExecute($stmt); OCIExecute($update); } $rowid->free(); OCIFreeStatement($update); OCIFreeStatement($stmt); $stmt = OCIParse($conn,"select * from emp where empno in (1111,2222,3333)"); OCIExecute($stmt); while (OCIFetchInto($stmt,&$arr,OCI_ASSOC)) { var_dump($arr); } OCIFreeStatement($stmt); /* delete our "junk" from the emp table.... */ $stmt = OCIParse($conn,"delete from emp where empno in (1111,2222,3333)"); OCIExecute($stmt); OCIFreeStatement($stmt); OCILogoff($conn); ?> |
OCILogon -- Oracle과 연결한다.
int OCILogon
(string username, string password, string [ORACLE_SID]);
OCILogon() returns an connection identified needed for most other OCI calls. If the optional third parameter is not specified, PHP uses the environment variable ORACLE_SID to determine which database to connect to. Connections are shared at the page level when using OCILogon(). This means that commits and rollbacks apply to all open transactions in the page, even if you have created multiple connections.
This example demonstrates how the connections are shared.
Example 1. OCILogon <?php print "<HTML><PRE>"; $db = ""; $c1 = ocilogon("scott","tiger",$db); $c2 = ocilogon("scott","tiger",$db); function create_table($conn) { $stmt = ociparse($conn,"create table scott.hallo (test varchar2(32))"); ociexecute($stmt); echo $conn." created table\n\n"; } function drop_table($conn) { $stmt = ociparse($conn,"drop table scott.hallo"); ociexecute($stmt); echo $conn." dropped table\n\n"; } function insert_data($conn) { $stmt = ociparse($conn,"insert into scott.hallo values($conn || ' ' || to_char(sysdate,'DD-MON-YY HH24:MI:SS'))"); ociexecute($stmt,OCI_DEFAULT); echo $conn." inserted hallo\n\n"; } function delete_data($conn) { $stmt = ociparse($conn,"delete from scott.hallo"); ociexecute($stmt,OCI_DEFAULT); echo $conn." deleted hallo\n\n"; } function commit($conn) { ocicommit($conn); echo $conn." commited\n\n"; } function rollback($conn) { ocirollback($conn); echo $conn." rollback\n\n"; } function select_data($conn) { $stmt = ociparse($conn,"select * from scott.hallo"); ociexecute($stmt,OCI_DEFAULT); echo $conn."----selecting\n\n"; while (ocifetch($stmt)) echo $conn." <".ociresult($stmt,"TEST").">\n\n"; echo $conn."----done\n\n"; } create_table($c1); insert_data($c1); // Insert a row using c1 insert_data($c2); // Insert a row using c2 select_data($c1); // Results of both inserts are returned select_data($c2); rollback($c1); // Rollback using c1 select_data($c1); // Both inserts have been rolled back select_data($c2); insert_data($c2); // Insert a row using c2 commit($c2); // commit using c2 select_data($c1); // result of c2 insert is returned delete_data($c1); // delete all rows in table using c1 select_data($c1); // no rows returned select_data($c2); // no rows returned commit($c1); // commit using c1 select_data($c1); // no rows returned select_data($c2); // no rows returned drop_table($c1); print "</PRE></HTML>"; ?> |
See also OCIPLogon() and OCINLogon().
OCIPLogon -- Oracle과 영구적인 접속으로 연결하고 logon한다. 새로운 session을 반환한다.
int OCIPLogon
(int conn);
OCIPLogin() Creates a persistent connection to an Oracle 8 database and logs on. If the optional third parameter is not specified, PHP uses the environment variable ORACLE_SID to determine which database to connect to.
See also OCILogon() and OCINLogon().
OCINLogon -- Oracle과 새로운 접속으로 연결하고 logon한다. 새로운 session을 반환한다.
int OCINLogon
(int conn);
OCINLogin() Creates a new connection to an Oracle 8 database and logs on. If the optional third parameter is not specified, PHP uses the environment variable ORACLE_SID to determine which database to connect to. OCINLogon() forces a new connection. This is should be used if you need to isolate a set of transactions. By default, connections are shared at the page level if using OCILogon() or at the web server process level if using OCIPLogon(). If you have multiple connections open using OCINLogon(), all commits and rollbacks apply to the specified connection only..
This example demonstrates how the connections are separated.
Example 1. OCINLogon <?php print "<HTML><PRE>"; $db = ""; $c1 = ocilogon("scott","tiger",$db); $c2 = ocinlogon("scott","tiger",$db); function create_table($conn) { $stmt = ociparse($conn,"create table scott.hallo (test varchar2(32))"); ociexecute($stmt); echo $conn." created table\n\n"; } function drop_table($conn) { $stmt = ociparse($conn,"drop table scott.hallo"); ociexecute($stmt); echo $conn." dropped table\n\n"; } function insert_data($conn) { $stmt = ociparse($conn,"insert into scott.hallo values($conn || ' ' || to_char(sysdate,'DD-MON-YY HH24:MI:SS'))"); ociexecute($stmt,OCI_DEFAULT); echo $conn." inserted hallo\n\n"; } function delete_data($conn) { $stmt = ociparse($conn,"delete from scott.hallo"); ociexecute($stmt,OCI_DEFAULT); echo $conn." deleted hallo\n\n"; } function commit($conn) { ocicommit($conn); echo $conn." commited\n\n"; } function rollback($conn) { ocirollback($conn); echo $conn." rollback\n\n"; } function select_data($conn) { $stmt = ociparse($conn,"select * from scott.hallo"); ociexecute($stmt,OCI_DEFAULT); echo $conn."----selecting\n\n"; while (ocifetch($stmt)) echo $conn." <".ociresult($stmt,"TEST").">\n\n"; echo $conn."----done\n\n"; } create_table($c1); insert_data($c1); select_data($c1); select_data($c2); rollback($c1); select_data($c1); select_data($c2); insert_data($c2); commit($c2); select_data($c1); delete_data($c1); select_data($c1); select_data($c2); commit($c1); select_data($c1); select_data($c2); drop_table($c1); print "</PRE></HTML>"; ?> |
See also OCILogon() and OCIPLogon().
OCILogOff -- Oracle과의 연결을 끊는다.
int OCILogOff
(int connection);
OCILogOff() closes an Oracle connection.
OCIExecute -- statement를 실행한다.
int OCIExecute
(int statement, int [mode]);
OCIExecute() executes a previously parsed statement. (see OCIParse()). The optional mode allows you to specify the execution-mode (default is OCI_COMMIT_ON_SUCCESS). If you don't want statements to be commited automaticly specify OCI_DEFAULT as your mode.
OCICommit -- 수행되었던 transaction들을 Commit한다.
int OCICommit
(int connection);
OCICommit() commits all outstanding statements for Oracle connection connection.
OCIRollback -- 수행되었던 transaction들을 Rolls back한다.
int OCIRollback
(int connection);
OCICommit() rolls back all outstanding statements for Oracle connection connection.
OCINewDescriptor -- 새로운 빈 descriptor LOB/FILE (LOB가 default)를 초기화(Initialize) 한다.
string OCINewDescriptor
(int connection, int [type]);
OCINewDescriptor() Allocates storage to hold descriptors or LOB locators. Valid values for the valid type are OCI_D_FILE, OCI_D_LOB, OCI_D_ROWID.
Example 1. OCINewDescriptor <?php /* This script is designed to be called from a HTML form. * It expects $user, $password, $table, $where, and $commitsize * to be passed in from the form. The script then deletes * the selected rows using the ROWID and commits after each * set of $commitsize rows. (Use with care, there is no rollback) */ $conn = OCILogon($user, $password); $stmt = OCIParse($conn,"select rowid from $table $where"); $rowid = OCINewDescriptor($conn,OCI_D_ROWID); OCIDefineByName($stmt,"ROWID",&$rowid); OCIExecute($stmt); while ( OCIFetch($stmt) ) { $nrows = OCIRowCount($stmt); $delete = OCIParse($conn,"delete from $table where ROWID = :rid"); OCIBindByName($delete,":rid",&$rowid,-1,OCI_B_ROWID); OCIExecute($delete); print "$nrows\n"; if ( ($nrows % $commitsize) == 0 ) { OCICommit($conn); } } $nrows = OCIRowCount($stmt); print "$nrows deleted...\n"; OCIFreeStatement($stmt); OCILogoff($conn); ?> |
OCIRowCount -- 영향받는 row의 개수를 구한다.
int OCIRowCount
(int statement);
OCIRowCounts() returns the number of rows affected for eg update-statements. This funtions will not tell you the number of rows that a select will return!
Example 1. OCIRowCount <?php print "<HTML><PRE>"; $conn = OCILogon("scott","tiger"); $stmt = OCIParse($conn,"create table emp2 as select * from emp"); OCIExecute($stmt); print OCIRowCount($stmt) . " rows inserted.<BR>"; OCIFreeStatement($stmt); $stmt = OCIParse($conn,"delete from emp2"); OCIExecute($stmt); print OCIRowCount($stmt) . " rows deleted.<BR>"; OCICommit($conn); OCIFreeStatement($stmt); $stmt = OCIParse($conn,"drop table emp2"); OCIExecute($stmt); OCIFreeStatement($stmt); OCILogOff($conn); print "</PRE></HTML>"; ?> |
OCINumCols -- 해당 statement의 결과에 있는 컬럼의 개수를 반환한다.
int OCINumCols
(int stmt);
OCINumCols() returns the number of columns in a statement
Example 1. OCINumCols <?php print "<HTML><PRE>\n"; $conn = OCILogon("scott", "tiger"); $stmt = OCIParse($conn,"select * from emp"); OCIExecute($stmt); while ( OCIFetch($stmt) ) { print "\n"; $ncols = OCINumCols($stmt); for ( $i = 1; $i <= $ncols; $i++ ) { $column_name = OCIColumnName($stmt,$i); $column_value = OCIResult($stmt,$i); print $column_name . ': ' . $column_value . "\n"; } print "\n"; } OCIFreeStatement($stmt); OCILogoff($conn); print "</PRE>"; print "</HTML>\n"; ?> |
OCIResult -- fetched row에 있는 coulumn 값을 반환한다.
int OCIResult
(int statement, mixed column);
OCIResult() returns the data for column column in the current row (see OCIFetch()).OCIResult() will return everything as strings except for abstract types (ROWIDs, LOBs and FILEs).
OCIFetch -- result-buffer로 다음 row를 가져온다.
int OCIFetch
(int statement);
OCIFetch() fetches the next row (for SELECT statements) into the internal result-buffer.
OCIFetchInto -- result-array로 다음 row를 가져온다.
int OCIFetchInto
(int stmt, array &result, int [mode]);
OCIFetchInto() fetches the next row (for SELECT statements) into the result array. OCIFetchInto() will overwrite the previous content of result. By default result will contain a one-based array of all columns that are not NULL.
The mode parameter allows you to change the default behaviour. You can specify more than one flag by simply addig them up (eg OCI_ASSOC+OCI_RETURN_NULLS). The known flags are:
OCI_ASSOC Return an associative array. |
OCI_NUM Return an numbered array starting with one. (DEFAULT) |
OCI_RETURN_NULLS Return empty columns. |
OCI_RETURN_LOBS Return the value of a LOB instead of the desxriptor. |
OCIFetchStatement -- 결과에 있는 모든 row들의 데이터를 하나의 배열로 가져온다.
int OCIFetchStatement
(int stmt, array &variable);
OCIFetchStatement() fetches all the rows from a result into a user-defined array. OCIFetchStatement() returns the number of rows fetched.
Example 1. OCIFetchStatement <?php /* OCIFetchStatement example mbritton@verinet.com (990624) */ $conn = OCILogon("scott","tiger"); $stmt = OCIParse($conn,"select * from emp"); OCIExecute($stmt); $nrows = OCIFetchStatement($stmt,$results); if ( $nrows > 0 ) { print "<TABLE BORDER=\"1\">\n"; print "<TR>\n"; while ( list( $key, $val ) = each( $results ) ) { print "<TH>$key</TH>\n"; } print "</TR>\n"; for ( $i = 0; $i < $nrows; $i++ ) { reset($results); print "<TR>\n"; while ( $column = each($results) ) { $data = $column['value']; print "<TD>$data[$i]</TD>\n"; } print "</TR>\n"; } print "</TABLE>\n"; } else { echo "No data found<BR>\n"; } print "$nrows Records Selected<BR>\n"; OCIFreeStatement($stmt); OCILogoff($conn); ?> |
OCIColumnIsNULL -- result 컬럼이 NULL인가 검사한다.
int OCIColumnIsNULL
(int stmt, mixed column);
OCIColumnIsNULL() returns true if the returned column col in the result from the statement stmt is NULL. You can either use the column-number (1-Based) or the column-name for the col parameter.
OCIColumnSize -- result 컬럼 크기를 반환한다.
int OCIColumnSize
(int stmt, mixed column);
OCIColumnSize() returns the size of the column as given by Oracle. You can either use the column-number (1-Based) or the column-name for the col parameter.
Example 1. OCIColumnSize <?php print "<HTML><PRE>\n"; $conn = OCILogon("scott", "tiger"); $stmt = OCIParse($conn,"select * from emp"); OCIExecute($stmt); print "<TABLE BORDER=\"1\">"; print "<TR>"; print "<TH>Name</TH>"; print "<TH>Type</TH>"; print "<TH>Length</TH>"; print "</TR>"; $ncols = OCINumCols($stmt); for ( $i = 1; $i <= $ncols; $i++ ) { $column_name = OCIColumnName($stmt,$i); $column_type = OCIColumnType($stmt,$i); $column_size = OCIColumnSize($stmt,$i); print "<TR>"; print "<TD>$column_name</TD>"; print "<TD>$column_type</TD>"; print "<TD>$column_size</TD>"; print "</TR>"; } OCIFreeStatement($stmt); OCILogoff($conn); print "</PRE>"; print "</HTML>\n"; ?> |
See also OCINumCols(), OCIColumnName(), and OCIColumnSize().
OCIServerVersion -- 서버의 버전 정보를 가지는 문자열을 반환한다.
string OCIServerVersion
(int conn);
Example 1. OCIServerVersion <?php $conn = OCILogon("scott","tiger"); print "Server Version: " . OCIServerVersion($conn); OCILogOff($conn); ?> |
OCIStatementType -- OCI statement의 type을 반환한다.
string OCIStatementType
(int stmt);
OCIStatementType() returns on of the following values:
"SELECT"
"UPDATE"
"DELETE"
"INSERT"
"CREATE"
"DROP"
"ALTER"
"BEGIN"
"DECLARE"
"UNKNOWN"
Example 1. Code examples <?php print "<HTML><PRE>"; $conn = OCILogon("scott","tiger"); $sql = "delete from emp where deptno = 10"; $stmt = OCIParse($conn,$sql); if ( OCIStatementType($stmt) == "DELETE" ) { die "You are not allowed to delete from this table<BR>"; } OCILogoff($conn); print "</PRE></HTML>"; ?> |
OCINewCursor -- 새로운 cursor(Statement-Handle)를 반환한다. 이것은 ref-cursor로 bind하는 데 사용한다.
int OCINewCursor
(int conn);
OCINewCursor() allocates a new statement handle on the specified connection.
Example 1. Using a REF CURSOR from a stored procedure <?php // suppose your stored procedure info.output returns a ref cursor in :data $conn = OCILogon("scott","tiger"); $curs = OCINewCursor($conn); $stmt = OCIParse($conn,"begin info.output(:data); end;"); ocibindbyname($stmt,"data",&$curs,-1,OCI_B_CURSOR); ociexecute($stmt); ociexecute($curs); while (OCIFetchInto($curs,&$data)) { var_dump($data); } OCIFreeCursor($stmt); OCIFreeStatement($curs); OCILogoff($conn); ?> |
Example 2. Using a REF CURSOR in a select statement <?php print "<HTML><BODY>"; $conn = OCILogon("scott","tiger"); $count_cursor = "CURSOR(select count(empno) num_emps from emp " . "where emp.deptno = dept.deptno) as EMPCNT from dept"; $stmt = OCIParse($conn,"select deptno,dname,$count_cursor"); ociexecute($stmt); print "<TABLE BORDER=\"1\">"; print "<TR>"; print "<TH>DEPT NAME</TH>"; print "<TH>DEPT #</TH>"; print "<TH># EMPLOYEES</TH>"; print "</TR>"; while (OCIFetchInto($stmt,&$data,OCI_ASSOC)) { print "<TR>"; $dname = $data["DNAME"]; $deptno = $data["DEPTNO"]; print "<TD>$dname</TD>"; print "<TD>$deptno</TD>"; ociexecute($data[ "EMPCNT" ]); while (OCIFetchInto($data[ "EMPCNT" ],&$subdata,OCI_ASSOC)) { $num_emps = $subdata["NUM_EMPS"]; print "<TD>$num_emps</TD>"; } print "</TR>"; } print "</TABLE>"; print "</BODY></HTML>"; OCIFreeStatement($stmt); OCILogoff($conn); ?> |
OCIFreeStatement -- statement에 관련된 모든 자원들을 풀어준다.
int OCIFreeStatement
(int stmt);
OCIFreeStatement() returns true if successful, or false if unsuccessful.
OCIFreeCursor -- cursor에 관련된 모든 자원들을 풀어준다.
int OCIFreeCursor
(int stmt);
OCIFreeCursor() returns true if successful, or false if unsuccessful.
OCIColumnName -- 컬럼의 이름을 반환한다.
string OCIColumnName
(int stmt, int col);
OCIColumnName() returns the name of the column corresponding to the column number (1-based) that is passed in.
Example 1. OCIColumnName <?php print "<HTML><PRE>\n"; $conn = OCILogon("scott", "tiger"); $stmt = OCIParse($conn,"select * from emp"); OCIExecute($stmt); print "<TABLE BORDER=\"1\">"; print "<TR>"; print "<TH>Name</TH>"; print "<TH>Type</TH>"; print "<TH>Length</TH>"; print "</TR>"; $ncols = OCINumCols($stmt); for ( $i = 1; $i <= $ncols; $i++ ) { $column_name = OCIColumnName($stmt,$i); $column_type = OCIColumnType($stmt,$i); $column_size = OCIColumnSize($stmt,$i); print "<TR>"; print "<TD>$column_name</TD>"; print "<TD>$column_type</TD>"; print "<TD>$column_size</TD>"; print "</TR>"; } OCIFreeStatement($stmt); OCILogoff($conn); print "</PRE>"; print "</HTML>\n"; ?> |
See also OCINumCols(), OCIColumnType(), and OCIColumnSize().
OCIColumnType -- 컬럼의 데이터 type을 반환한다.
mixed OCIColumnName
(int stmt, int col);
OCIColumnType() returns the data type of the column corresponding to the column number (1-based) that is passed in.
Example 1. OCIColumnType <?php print "<HTML><PRE>\n"; $conn = OCILogon("scott", "tiger"); $stmt = OCIParse($conn,"select * from emp"); OCIExecute($stmt); print "<TABLE BORDER=\"1\">"; print "<TR>"; print "<TH>Name</TH>"; print "<TH>Type</TH>"; print "<TH>Length</TH>"; print "</TR>"; $ncols = OCINumCols($stmt); for ( $i = 1; $i <= $ncols; $i++ ) { $column_name = OCIColumnName($stmt,$i); $column_type = OCIColumnType($stmt,$i); $column_size = OCIColumnSize($stmt,$i); print "<TR>"; print "<TD>$column_name</TD>"; print "<TD>$column_type</TD>"; print "<TD>$column_size</TD>"; print "</TR>"; } OCIFreeStatement($stmt); OCILogoff($conn); print "</PRE>"; print "</HTML>\n"; ?> |
See also OCINumCols(), OCIColumnName(), and OCIColumnSize().
OCIParse -- 질의(query)를 해석(parse)하고 statement를 반환한다.
int OCIParse
(int conn, strint query);
OCIParse() parses the query using conn. It returns true if the query is valid, false if not. The query can be any valid SQL statement.
OCIError -- stmt|conn|global의 최근 에러를 반환한다. 만약 에러가 발생하지 않았다면 false를 반환한다.
int OCIError
(int [stmt|conn]);
OCIError() returns the last error found. If the optional stmt|conn is not provided, the last error encountered is returned. If no error is found, OCIError() returns false.
OCIInternalDebug -- 내장 디버거 출력을 enable시키거나 disable시킨다. 기본값은 disable이다.
void OCIInternalDebug
(int onoff);
OCIInternalDebug() enables internal debug output. Set onoff to 0 to turn debug output off, 1 to turn it on.
여러분이 Thomas Merz가 제공하는 PDF 라이브러리를 가지고 있다면 여러분은 PHP에서 pdf 파일을 만들 수 있는 pdf 함수들을 사용할 수 있다. (http://www.ifconnection.de/~tm/에서 찾을 수 있다. 그리고, 이 PDF 라이브러리를 컴파일 하기 위해서는 the JPEG library와 the TIFF library가 필요할 것이다.그런데, 이 두 라이브러리는 php를 설정(configure)할 때 가끔 문제를 발생시킨다. 발생한 문제를 해결하기 위해서는 설정시 나오는 메시지를 살펴보기바란다. pdflib 2.01을 사용한다면 이 라이브러리가 어떻게 설치(install)되어 있는가 점검한다. libpdf.so이라는 파일이나 링크가 반드시 있어야 한다. 그러나, Version 2.01은 libpdf2.01.so이라는 이름의 라이브러리만 만든다. 이런 경우 여러분은 libpdf.so라는 이름의 symbolic link를 만들어 libpdf2.01.so에 연결해야 한다.)
pdflib의 2.20 버전은 API의 많은 부분이 변하였고, 중국어와 일본어 폰트를 지원하도록 바뀌었다. (역자주: 언제부터인지는 모르겠으나, PDFlib의 최근 버전인 3.01에서는 한국어도 지원한다.) 그러나 불행히도 이런 변화가 php4(php3는 아니다)의 pdf 모듈을 바꾸게 하였다. 만약 여러분이 pdflib 2.20을 사용한다면, 메모리 내에 PDF documents를 만드는 것은 매우 조심해서 해야 할 것이다. pdflib 3.0이전에는 이 기능이 매우 불안하다. pdf_set_font() 함수의 파라메터가 문자열로 바뀌었다. 이것은 예를들어 4라는 숫자 대신 'winansi'라는 문자열을 사용할 수 있다는 의미이다.
여러분이 pdflib 2.30을 사용하고 있다면 pdf_set_text_matrix() 함수는 없을 것이다. 이함수는 더 이상 지원되지 않는다.
2000년 3월 9일 이후 버전의 PHP4에서는 pdflib 3.0 이전의(older than) 버전은 지원하지 않는다. 그리고, PHP3에서는 2.01 이후의(newer than) 버전은 사용할 수 없다
pdflib에 대한 자세한 설명은 pdflib의 소스와 함께 배포되는 문서를 읽어보면 된다.(아주 잘 쓰여져 있다.) 이 문서는 pdflib가 할 수 있는 기능에 대하여 매우 잘 설명하고 있다. PHP의 모듈에 있는 함수는 대부분 pdflib 함수와 같은 이름을 사용한다. 또한 파라메터도 동일하다. 또한 여러분이 이 모듈을 효율적으로 사용하려면 여러분은 어느정도 PDF와 Postscript 의 개념에 대해 이해하고 있어야 한다. 모든 길이와 좌표는 Postscript points를 척도의 기준으로 삼고 있다. 일반적으로 1인치에 72 PostScript points를 기본으로 하고 있지만, 이것은 출력장치의 해상도에 따라 달라진다.
PHP에서 pdf 문서를 만드는 다른 모듈로는 FastIO's의 ClibPDF를 바탕으로 한 것이 있다. 이것은 조금 다른 API이다. 자세한 내용은 ClibPDF functions 장을 참조하기 바란다.
현재 모든 버전의 pdflib를 지원하고 있다. 보통 새 버전이 더 많은 기능을 제공하고 여러 문제를 해결하고 있기 때문에 가능하면 새 버전을 사용하는 것이 좋다. 하지만, 불행히도 2.x 버전의 pdflib API는 0.6 버전에 비해 PHP 함수에 몇가지 수정을 요구한다. 그 내용은 다음과 같다.
PHP는 pdflib의 2.01 버전에서 많은 변화가 있었다. 일부 함수는 더 이상 필요가 없어졌다.(예:pdf_put_image()). 당황하지 않으려면 주의가 필요하다.
pdf 모듈은 pdfdoc와 pdfinfo라는 두가지 새로운 변수 type을 제공한다.(pdflib 2.0에서는 pdfdoc가지 타입만 제공된다.) pdfdoc 은 PDF 문서의 포인터이고 거의 모든 함수가 이 파라메터를 필요로 한다. pdfinfo는 PDF 문서에 대한 meta data를 가지고 있다. pdfinfo의 값은 pdf_open()가 호출되기 이전에 설정되어 있어야 한다.
Note: 아래 내용은 pdflib 0.6에만 적용되는 이야기이다. 그 이후버전은 pdflib 매뉴얼을 읽어보기 바란다.
외부 text를 PDF 문서로 만들기 위해서는 각각의 폰트에 대한 afm 파일을 제공해 주어야 한다. 기본적으로 이 afm 파일들은 PHP스크립트가 위치한 디렉토리내에 'fonts' 라는 이름의 디렉토리에서 찾게 된다. (주의, 이 내용은 pdflib 0.6에서는 사실이다. 그러나 새 버전에서는 더 이상 afm 파일이 필요없다.)
대부분의 함수들은 사용하기 쉽다. 간단한 pdf 문서를 하나 만들어보면 별로 어렵지 않다는 것을 알 수 있을 것이다. 다음 예를 보면 쉽게 시작할 수 있다. 이것은 한 장짜리 test.pdf라는 파일을 만드는 것이다. 이 페이지에는 외곽선 30pt의 "Times-Roman" 폰트의 text가 쓰여진다. 이 text는 밑줄이 그어진다.
Example 1. Creating a PDF document with pdflib 0.6
|
다음의 getpdf.php3라는 PHP 스크립트는 pdf 문서를 출력한다.
1 2 <?php 3 $fp = fopen("test.pdf", "r"); 4 header("Content-type: application/pdf"); 5 fpassthru($fp); 6 fclose($fp); 7 ?> 8 |
위의 예제를 pdflib 2.0 으로 작성하면 다음과 같다.
Example 2. Creating a PDF document with pdflib 2.x
getpdf.php3 PHP 스크립트는 위와 동일하다. |
pdflib 배포본에 보면 아나로그 시계가 포함된 여러 퍼이지의 문서를 만드는 조금은 복잡한 예제가 있다. 여기 그 예제를 pdflib 2.x를 사용한 PHP로 변환한 예가 있다. (동일한 예제 문서를 clibpdf module에 포함된 문서에서 찾을 수 있다.):
Example 3. pdfclock example from pdflib 2.x distribution
다음의 getpdf.php3라는 PHP 스크립트는 pdf 문서를 출력한다.
|
PDF_get_info -- pdf 문서에 대한 기본 정보(info structure)를 반환한다.
info pdf_get_info
(string
filename)The PDF_get_info() function returns a default info structure for the pdf document. It should be filled with appropriate information like the author, subject etc. of the document.
Note: This functions is not available if pdflib 2.x support is activated.
See also PDF_set_info_creator(), PDF_set_info_author(), PDF_set_info_keywords(), PDF_set_info_title(), PDF_set_info_subject().
PDF_set_info_creator -- info structure의 creator 필드를 설정한다.
void pdf_set_info_creator
(info info, string creator);
The PDF_set_info_creator() function sets the creator of a pdf document. It has to be called after PDF_get_info() and before PDF_open(). Calling it after PDF_open() will have no effect on the document.
Note: This function is not part of the pdf library.
Note: This function takes a different first parameter if pdflib 2.x support is activated. The first parameter has to be the identifier of the pdf document as returned by pdf_open(). Consequently, pdf_open() has to be called before this function.
See also PDF_get_info(), PDF_set_info_keywords(), PDF_set_info_title(), PDF_set_info_subject().
PDF_set_info_title -- info structure의 title 필드를 설정한다.
void pdf_set_info_title
(info info, string title);
The PDF_set_info_title() function sets the title of a pdf document. It has to be called after PDF_get_info() and before PDF_open(). Calling it after PDF_open() will have no effect on the document.
Note: This function is not part of the pdf library.
Note: This function takes a different first parameter if pdflib 2.0 support is activated. The first parameter has to be the identifier of the pdf document as returned by pdf_open(). Consequently, pdf_open() has to be called before this function.
See also PDF_get_info(), PDF_set_info_creator(), PDF_set_info_author(), PDF_set_info_keywords(), PDF_set_info_subject().
PDF_set_info_subject -- info structure의 subject 필드를 설정한다.
void pdf_set_info_subject
(info info, string subject);
The PDF_set_info_subject() function sets the subject of a pdf document. It has to be called after PDF_get_info() and before PDF_open(). Calling it after PDF_open() will have no effect on the document.
Note: This function is not part of the pdf library.
Note: This function takes a different first parameter if pdflib 2.0 support is activated. The first parameter has to be the identifier of the pdf document as returned by pdf_open(). Consequently, pdf_open() has to be called before this function.
See also PDF_get_info(), PDF_set_info_creator(), PDF_set_info_author(), PDF_set_info_title(), PDF_set_info_keywords().
PDF_set_info_keywords -- info structure의 keyword 필드를 설정한다.
void pdf_set_info_keywords
(info info, string keywords);
The PDF_set_info_keywords() function sets the keywords of a pdf document. It has to be called after PDF_get_info() and before PDF_open(). Calling it after PDF_open() will have no effect on the document.
Note: This function is not part of the pdf library.
Note: This function takes a different first parameter if pdflib 2.0 support is activated. The first parameter has to be the identifier of the pdf document as returned by pdf_open(). Consequently, pdf_open() has to be called before this function.
See also PDF_get_info(), PDF_set_info_creator(), PDF_set_info_author(), PDF_set_info_title(), PDF_set_info_subject().
PDF_set_info_author -- info structure의 author 필드를 설정한다.
void pdf_set_info_author
(info info, string author);
The PDF_set_info_author() function sets the author of a pdf document. It has to be called after PDF_get_info() and before PDF_open(). Calling it after PDF_open() will have no effect on the document.
Note: This function is not part of the pdf library.
Note: This function takes a different first parameter if pdflib 2.0 support is activated. The first parameter has to be the identifier of the pdf document as returned by pdf_open(). Consequently, pdf_open() has to be called before this function.
See also PDF_get_info(), PDF_set_info_creator(), PDF_set_info_keywords(), PDF_set_info_title(), PDF_set_info_subject().
PDF_open -- 새 pdf 문서를 연다.
int pdf_open
(int file, int info);
The PDF_open() function opens a new pdf document. The corresponding file has to be opened with fopen() and the file descriptor passed as argument file. info is the info structure that has to be created with pdf_get_info(). The info structure will be deleted within this function.
Note: The return value is needed as the first parameter in all other functions writing to the pdf document.
Note: This function does not allow the second parameter if pdflib 2.0 support is activated.
See also fopen(), PDF_get_info(), PDF_close().
PDF_close -- pdf 문서를 닫는다.
void pdf_close
(int pdf document);
The PDF_close() function closes the pdf document.
Note: Due to an unclean implementation of the pdflib 0.6 the internal closing of the document also closes the file. This should not be done because pdflib did not open the file, but expects an already open file when PDF_open() is called. Consequently it shouldn't close the file. In order to fix this just take out line 190 of the file p_basic.c in the pdflib 0.6 source distribution until the next release of pdflib will fix this.
Note: This function works properly without any patches to pdflib if pdflib 2.0 support is activated.
See also PDF_open(), fclose().
PDF_begin_page -- 새 페이지를 시작한다.
void pdf_begin_page
(int pdf document, double height, double width);
The PDF_begin_page() function starts a new page with height height and width width.
See also PDF_end_page().
PDF_end_page -- 페이지를 끝낸다.
void pdf_end_page
(int pdf document);
The PDF_end_page() function ends a page. Once a page is ended it cannot be modified anymore.
See also PDF_begin_page().
PDF_show -- 현재 위치에 text를 출력한다.
void pdf_show
(int pdf document, string text);
The PDF_show() function outputs the string text at the current position using the current font.
See also PDF_show_xy(), PDF_show_boxed(), PDF_set_text_pos(), PDF_set_font().
int pdf_show_boxed
(int
pdf document, string text, double x-coor, double y-coor, double width, double
height, string mode)
The PDF_show_boxed() function outputs the string text in a box with its lower left position at (x-coor, y-coor). The boxes dimension is height by width. The parameter mode determines how the text is type set. If width and height are zero, the mode can be "left", "right" or "center". If width or height is unequal zero it can also be "justify" and "fulljustify".
Returns the number of characters that could not be processed because they did not fit into the box.
See also PDF_show(), PDF_show_xy()
PDF_show_xy -- 지정한 위치에 text를 출력한다.
void pdf_show_xy
(int pdf document, string text, double x-koor, double y-koor);
The PDF_show_xy() function outputs the string text at position (x-koor, y-koor).
See also PDF_show().
PDF_set_font -- 사용할 font 모양과 크기를 선택한다.
void pdf_set_font
(int
pdf document, string font name, double size, string encoding [, int embed])
The PDF_set_font() function sets the current font face, font size and encoding. If you use pdflib 0.6 you will need to provide the Adobe Font Metrics (afm-files) for the font in the font path (default is ./fonts). If you use php3 or a version of pdflib older than 2.20 the fourth parameter encoding can take the following values: 0 = builtin, 1 = pdfdoc, 2 = macroman, 3 = macexpert, 4 = winansi. An encoding greater than 4 and less than 0 will default to winansi. winansi is often a good choice. If you use php4 and a version of pdflib >= 2.20 the encoding parameter has changed to a string. Use 'winansi', 'builtin' etc. instead. If the last parameter is set to 1 the font is embedded into the pdf document otherwise it is not. To embed a font is usually a good idea if the font is not widely spread and you cannot ensure that the person watching your document has access on fonts in the document. I font is only embedded once even if you call PDF_set_font() several times.
Note: This function has to be called after PDF_begin_page() in order to create a valid pdf document.
Note: If you reference a font in a .upr file make sure the name in the afm file and the font name are the same. Otherwise, the font will be embedded several times (Thanks to Paul Haddon for finding this.)
PDF_set_leading -- 줄 간격을 설정한다.
void pdf_set_leading
(int pdf document, double distance)
The PDF_set_leading() function sets the distance between text lines. This will be used if text is output by PDF_continue_text().
See also PDF_continue_text().
void pdf_set_parameter
(int pdf document, string name, string value)
The PDF_set_parameter() function sets several parameters of pdflib.
PDF_set_text_rendering -- text를 출력할 방식을 결정한다.(Determines how text is rendered)
void pdf_set_text_rendering
(int pdf document, int mode);
The PDF_set_text_rendering() function determines how text is rendered. The possible values for mode are 0=fill text, 1=stroke text, 2=fill and stroke text, 3=invisible, 4=fill text and add it to cliping path, 5=stroke text and add it to clipping path, 6=fill and stroke text and add it to cliping path, 7=add it to clipping path.
PDF_set_horiz_scaling -- text의 수평 확대 비율을 정한다.
void pdf_set_horiz_scaling
(int pdf document, double scale);
The PDF_set_horiz_scaling() function sets the horizontal scaling to scale percent.
PDF_set_text_rise -- text를 rise하게 표시되도록 설정한다.
void pdf_set_text_rise
(int pdf document, double value);
The PDF_set_text_rise() function sets the text rising to value points.
PDF_set_text_matrix -- text를 matrix 형태로 지정한다.
void pdf_set_text_matrix
(int pdf document, array matrix);
The PDF_set_text_matrix() function sets a matrix which describes a transformation applied on the current text font. The matrix has to passed as an array with six elements.
PDF_set_text_pos -- text의 위치를 설정한다.
void pdf_set_text_pos
(int pdf document, double x-koor, double y-koor);
The PDF_set_text_pos() function sets the position of text for the next pdf_show() function call.
See also PDF_show(), PDF_show_xy().
PDF_set_char_spacing -- 글자 사이의 간격을 지정한다.
void pdf_set_char_spacing
(int pdf document, double space);
The PDF_set_char_spacing() function sets the spacing between characters.
See also PDF_set_word_spacing(), PDF_set_leading().
PDF_set_word_spacing -- 단어 사이의 간격을 지정한다.
void pdf_set_word_spacing
(int pdf document, double space);
The PDF_set_word_spacing() function sets the spacing between words.
See also PDF_set_char_spacing(), PDF_set_leading().
void pdf_skew
(int pdf
document, double alpha, double beta)
The PDF_skew() function skew the coordinate system by alpha (x) and beta (y) degrees. alpha and beta may not be 90 or 270 degrees.
PDF_continue_text -- 새 줄에 text를 출력한다.
void pdf_continue_text
(int pdf document, string text);
The PDF_continue_text() function outputs the string in text in the next line. The distance between the lines can be set with PDF_set_leading().
See also PDF_show_xy(), PDF_set_leading(), PDF_set_text_pos().
PDF_stringwidth -- 현재 사용중인 font의 넓이를 구한다.
double pdf_stringwidth
(int pdf document, string text);
The PDF_stringwidth() function returns the width of the string in text. It requires a font to be set before.
See also PDF_set_font().
PDF_save -- 현재 환경을 저장한다.
void pdf_save
(int pdf document);
The PDF_save() function saves the current environment. It works like the postscript command gsave. Very useful if you want to translate or rotate an object without effecting other objects. PDF_save() should always be followed by PDF_restore().
See also PDF_restore().
PDF_restore -- 전에 저장해 두었던 환경으로 복귀한다.
void pdf_restore
(int pdf document);
The PDF_restore() function restores the environment saved with PDF_save(). It works like the postscript command grestore. Very useful if you want to translate or rotate an object without effecting other objects.
Example 1. Save and Restore <?php PDF_save($pdf); // do all kinds of rotations, transformations, ... PDF_restore($pdf) ?> |
See also PDF_save().
PDF_translate -- koordinate system의 기준이되는 원점을 정한다.
void pdf_translate
(int pdf document, double x-koor, double y-koor);
The PDF_translate() function set the origin of coordinate system to the point (x-koor, y-koor). The following example draws a line from (0, 0) to (200, 200) relative to the initial coordinate system. You have to set the current point after PDF_translate() and before you start drawing more objects.
Example 1. Translation <?php PDF_moveto($pdf, 0, 0); PDF_lineto($pdf, 100, 100); PDF_stroke($pdf); PDF_translate($pdf, 100, 100); PDF_moveto($pdf, 0, 0); PDF_lineto($pdf, 100, 100); PDF_stroke($pdf); ?> |
PDF_scale -- scaling을 설정한다.
void pdf_scale
(int pdf document, double x-scale, double y-scale);
The PDF_scale() function set the scaling factor in both directions. The following example scales x and y direction by 72. The following line will therefore be drawn one inch in both directions.
Example 1. Scaling <?php PDF_scale($pdf, 72.0, 72.0); PDF_lineto($pdf, 1, 1); PDF_stroke($pdf); ?> |
PDF_rotate -- 회전율을 정한다.
void pdf_rotate
(int pdf document, double angle);
The PDF_rotate() function set the rotation in degress to angle.
PDF_setflat -- flatness를 정한다.
void pdf_setflat
(int pdf document, double value);
The PDF_setflat() function set the flatness to a value between 0 and 100.
PDF_setlinejoin -- linejoin parameter를 정한다.
void pdf_setlinejoin
(int pdf document, long value);
The PDF_setlinejoin() function set the linejoin parameter between a value of 0 and 2.
PDF_setlinecap -- linecap aparameter를 정한다.
void pdf_setlinecap
(int pdf document, int value);
The PDF_setlinecap() function set the linecap parameter between a value of 0 and 2.
PDF_setmiterlimit -- miter limit을 정한다.
void pdf_setmiterlimit
(int pdf document, double value);
The PDF_setmiterlimit() function set the miter limit to a value greater of equal than 1.
PDF_setlinewidth -- 한 라인의 폭을 정한다.
void pdf_setlinewidth
(int pdf document, double width);
The PDF_setlinewidth() function set the line width to width.
PDF_setdash -- 점선의 무늬를 정한다.
void pdf_setdash
(int pdf document, double white, double black);
The PDF_setdash() function set the dash pattern white white points and black black points. If both are 0 a solid line is set.
PDF_moveto -- 현재 위치를 바꾼다.
void pdf_moveto
(int pdf document, double x-koor, double y-koor);
The PDF_moveto() function set the current point to the coordinates x-koor and y-koor.
PDF_curveto -- 곡선을 그린다.
void pdf_curveto
(int pdf document, double x1, double y1, double x2, double y2, double x3, double y3);
The PDF_curveto() function draws a Bezier curve from the current point to the point (x3, y3) using (x1, y1) and (x2, y2) as control points.
See also PDF_moveto(), PDF_lineto(), PDF_stroke().
PDF_lineto -- 직선을 그린다.
void pdf_lineto
(int pdf document, double x-koor, double y-koor);
The PDF_lineto() function draws a line from the current point to the point with coordinates (x-koor, y-koor).
See also PDF_moveto(), PDF_curveto(), PDF_stroke().
PDF_circle -- 원을 그린다.
void pdf_circle
(int pdf document, double x-koor, double y-koor, double radius);
The PDF_circle() function draws a circle with center at point (x-koor, y-koor) and radius radius.
See also PDF_arc(), PDF_stroke().
PDF_arc -- 원호를 그린다.
void pdf_arc
(int pdf document, double x-koor, double y-koor, double radius, double start, double end);
The PDF_arc() function draws an arc with center at point (x-koor, y-koor) and radius radius, starting at angle start and ending at angle end.
See also PDF_circle(), PDF_stroke().
PDF_rect -- 사각형을 그린다.
void pdf_rect
(int pdf document, double x-koor, double y-koor, double width, double height);
The PDF_rect() function draws a rectangle with its lower left corner at point (x-koor, y-koor). This width is set to widgth. This height is set to height.
See also PDF_stroke().
PDF_closepath -- path를 닫는다.
void pdf_closepath
(int pdf document);
The PDF_closepath() function closes the current path. This means, it draws a line from current point to the point where the first line was started. Many functions like PDF_moveto(), PDF_circle() and PDF_rect() start a new path.
PDF_stroke -- path를 따라 선을 그린다.
void pdf_stroke
(int pdf document);
The PDF_stroke() function draws a line along current path. The current path is the sum of all line drawing. Without this function the line would not be drawn.
See also PDF_closepath(), PDF_closepath_stroke().
PDF_closepath_stroke -- path를 따라 선을 그리고 path를 닫는다.
void pdf_closepath_stroke
(int pdf document);
The PDF_closepath_stroke() function is a combination of PDF_closepath() and PDF_stroke(). Than clears the path.
See also PDF_closepath(), PDF_stroke().
PDF_fill -- 현재 path안을 칠한다.
void pdf_fill
(int pdf document);
The PDF_fill() function fills the interior of the current path with the current fill color.
See also PDF_closepath(), PDF_stroke(), PDF_setgray_fill(), PDF_setgray(), PDF_setrgbcolor_fill(), PDF_setrgbcolor().
PDF_fill_stroke -- 현재 path의 안쪽을 칠하고, 현재 path를 따라 그린다.
void pdf_fill_stroke
(int pdf document);
The PDF_fill_stroke() function fills the interior of the current path with the current fill color and draws current path.
See also PDF_closepath(), PDF_stroke(), PDF_fill(), PDF_setgray_fill(), PDF_setgray(), PDF_setrgbcolor_fill(), PDF_setrgbcolor().
PDF_closepath_fill_stroke -- 현재 path의 안쪽을 칠하고, 현재 path를 따라 그린 후, path를 닫는다.
void pdf_closepath_fill_stroke
(int pdf document);
The PDF_closepath_fill_stroke() function closes, fills the interior of the current path with the current fill color and draws current path.
See also PDF_closepath(), PDF_stroke(), PDF_fill(), PDF_setgray_fill(), PDF_setgray(), PDF_setrgbcolor_fill(), PDF_setrgbcolor().
PDF_endpath -- 현재 path를 종료한다.
void pdf_endpath
(int pdf document);
The PDF_endpath() function ends the current path but does not close it.
See also PDF_closepath().
PDF_clip -- 현재 path를 clip한다.
void pdf_clip
(int pdf document);
The PDF_clip() function clips all drawing to the current path.
PDF_setgray_fill -- 칠하는 색을 회색톤으로 설정한다.
void pdf_setgray_fill
(int pdf document, double value);
The PDF_setgray_fill() function sets the current gray value to fill a path.
See also PDF_setrgbcolor_fill().
PDF_setgray_stroke -- 그리는 색을 회색톤으로 설정한다.
void pdf_setgray_stroke
(int pdf document, double gray value);
The PDF_setgray_stroke() function sets the current drawing color to the given gray value.
See also PDF_setrgbcolor_stroke().
PDF_setgray -- 칠하고 그리는 색을 회색톤으로 설정한다.
void pdf_setgray
(int pdf document, double gray value);
The PDF_setgray_stroke() function sets the current drawing and filling color to the given gray value.
See also PDF_setrgbcolor_stroke(), PDF_setrgbcolor_fill().
PDF_setrgbcolor_fill -- 칠하는 색을 rgb color로 설정한다.
void pdf_setrgbcolor_fill
(int pdf document, double red value, double green value, double blue value);
The PDF_setrgbcolor_fill() function sets the current rgb color value to fill a path.
See also PDF_setrgbcolor_fill().
PDF_setrgbcolor_stroke -- 그리는 색을 rgb color로 설정한다.
void pdf_setrgbcolor_stroke
(int pdf document, double red value, double green value, double blue value);
The PDF_setrgbcolor_stroke() function sets the current drawing color to the given rgb color value.
See also PDF_setrgbcolor_stroke().
PDF_setrgbcolor -- 칠하고 그리는 색을 rgb color로 설정한다.
void pdf_setrgbcolor
(int pdf document, double red value, double green value, double blue value);
The PDF_setrgbcolor_stroke() function sets the current drawing and filling color to the given rgb color value.
See also PDF_setrgbcolor_stroke(), PDF_setrgbcolor_fill().
PDF_add_outline -- 현재 페이지에 bookmark를 추가한다.
void pdf_add_outline
(int pdf document, string text);
The PDF_add_outline() function adds a bookmark with text text that points to the current page.
Unfortunately pdflib does not make a copy of the string, which forces PHP to allocate the memory. Currently this piece of memory is not been freed by any PDF function but it will be taken care of by the PHP memory manager.
PDF_set_transition -- 페이지간의 transition을 지정한다.
void pdf_set_transition
(int pdf document, int transition);
The PDF_set_transition() function set the transition between following pages. The value of transition can be
0 for none, |
1 for two lines sweeping across the screen reveal the page, |
2 for multiple lines sweeping across the screen reveal the page, |
3 for a box reveals the page, |
4 for a single line sweeping across the screen reveals the page, |
5 for the old page dissolves to reveal the page, |
6 for the dissolve effect moves from one screen edge to another, |
7 for the old page is simply replaced by the new page (default) |
See also PDF_set_duration().
PDF_set_duration -- page간의 duration을 지정한다.
void pdf_set_duration
(int pdf document, double duration);
The PDF_set_duration() function set the duration between following pages in seconds.
See also PDF_set_transition().
PDF_open_gif -- GIF 이미지를 연다.
int pdf_open_gif
(int pdf document, string filename);
The PDF_open_gif() function opens an image stored in the file with the name filename. The format of the image has to be gif. The function returns a pdf image identifier.
Example 1. Including a gif image <?php $im = PDF_open_gif($pdf, "test.gif"); pdf_place_image($pdf, $im, 100, 100, 1); pdf_close_image($pdf, $im); ?> |
See also PDF_close_image(), PDF_open_jpeg(), PDF_open_png(), PDF_open_memory_image(), PDF_execute_image(), PDF_place_image(), PDF_put_image().
int pdf_open_png
(int
pdf, string png_file)
The PDF_open_png() function opens an image stored in the file with the name filename. The format of the image has to be png. The function returns a pdf image identifier.
Example 1. Including a PNG image
|
See also PDF_close_image(), PDF_open_jpeg(), PDF_open_gif(), PDF_open_memory_image(), PDF_execute_image(), PDF_place_image(), PDF_put_image().
PDF_open_memory_image -- PHP의 image 함수로 만든 image를 연다.
int pdf_open_memory_image
(int pdf document, string int image);
The PDF_open_memory_image() function takes an image created with the PHP's image functions and makes it available for the pdf document. The function returns a pdf image identifier.
Example 1. Including a memory image <?php $im = ImageCreate(100, 100); $col = ImageColorAllocate($im, 80, 45, 190); ImageFill($im, 10, 10, $col); $pim = PDF_open_memory_image($pdf, $im); ImageDestroy($im); pdf_place_image($pdf, $pim, 100, 100, 1); pdf_close_image($pdf, $pim); ?> |
See also PDF_close_image(), PDF_open_jpeg(), PDF_open_gif(), PDF_execute_image(), PDF_place_image(), PDF_put_image().
PDF_open_jpeg -- JPEG image를 연다.
int pdf_open_jpeg
(int pdf document, string filename);
The PDF_open_jpeg() function opens an image stored in the file with the name filename. The format of the image has to be jpeg. The function returns a pdf image identifier.
See also PDF_close_image(), PDF_open_gif(), PDF_open_png(), PDF_open_memory_image(), PDF_execute_image(), PDF_place_image(), PDF_put_image().
PDF_close_image -- image를 닫는다.
void pdf_close_image
(int image);
The PDF_close_image() function closes an image which has been opened with any of the PDF_open_xxx() functions.
See also PDF_open_jpeg(), PDF_open_gif(), PDF_open_png(), PDF_open_memory_image().
PDF_place_image -- image를 page에 위치시킨다.
void pdf_place_image
(int pdf document, int image, double x-koor, double y-koor, double scale);
The PDF_place_image() function places an image on the page at postion (x-koor, x-koor). The image can be scaled at the same time.
See also PDF_put_image().
PDF_put_image -- 나중에 쓰기 위해 image를 PDF에 저장한다.
void pdf_put_image
(int
pdf document, int image)
The PDF_put_image() function places an image in the PDF file without showing it. The stored image can be displayed with the PDF_execute_image() function as many times as needed. This is useful when using the same image multiple times in order to keep the file size small. Using PDF_put_image() and PDF_execute_image() is highly recommended for larger images (several kb) if they show up more than once in the document.
Note: This function has become meaningless with version 2.01 of pdflib. It will just output a warning.
See also PDF_put_image(), PDF_place_image(), PDF_execute_image().
PDF_execute_image -- 저장된 image를 page에 위치시킨다.
void pdf_execute_image
(int pdf document, int image, double x-coor, double y-coor, double scale);
The PDF_execute_image function displays an image that has been put in the PDF file with the PDF_put_image() function on the current page at the given coordinates.
The image can be scaled while displaying it. A scale of 1.0 will show the image in the original size.
Example 1. Multiple show of an image <?php $im = ImageCreate(100, 100); $col1 = ImageColorAllocate($im, 80, 45, 190); ImageFill($im, 10, 10, $col1); $pim = PDF_open_memory_image($pdf, $im); pdf_put_image($pdf, $pim); pdf_execute_image($pdf, $pim, 100, 100, 1); pdf_execute_image($pdf, $pim, 200, 200, 2); pdf_close_image($pdf, $pim); ?> |
pdf_add_annotation -- 주석을 첨가한다.
void pdf_add_annotation
(int pdf document, double llx, double lly, double urx, double ury, string title, string content);
The pdf_add_annotation() adds a note with the lower left corner at (llx, lly) and the upper right corner at (urx, ury).
이 함수들은 Perl Compatible Regular Expressions와 함께 동작하도록 만들어졌다.
이 함수들에서 사용하는 패턴의 문법은 Perl과 매우 유사하다. 표현식은 반드시 두 개의 구획문자(예를들어 슬래시(/)같은)로 둘러싸여 있어야 한다. 알파벳이나 숫자 혹은 백슬래시(\)를 제외한 어떤 문자도 구획문자가 될 수 있다. 만약 구획문자로 사용된 문자를 표현식 내에 사용하고 싶다면 백슬래시로 escape해 주면 된다.(앞에 백슬래시를 붙이면 된다.)
종료를 나타내는 구획문자 뒤에는 매칭에 관련된 여러 옵션을 붙여줄 수 있다. 자세한 것은 Pattern Modifiers를 보자.
Example 1. Examples of valid patterns /<\/\w+>/ |(\d{3})-\d+|Sm /^(?I)php[34]/ |
Example 2. Examples of invalid patterns /href='(.*)' - missing ending delimiter /\w+\s*\w+/J - unknown option 'J' 1-\d3-\d3-\d4| - missing starting delimiter |
Note: 이 펄 호환 정규 표현식 함수들은 PHP 4 와 PHP 3.0.9 이상에서 동작한다.
preg_match -- 정규 표현식 검색을 수행한다.
int preg_match
(string
pattern, string subject [, array matches])
Searches subject for a match to the regular expression given in pattern.
If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that match the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.
Returns true if a match for pattern was found in the subject string, or false if not match was found or an error occurred.
Example 1. Getting the page number out of a string
|
See also preg_match_all(), preg_replace(), and preg_split().
preg_match_all -- 전역적인 정규 표현식 검색을 수행한다.
int preg_match_all
(string pattern, string subject, array matches [, int order])
Searches subject for all matches to the regular expression given in pattern and puts them in matches in the order specified by order.
After the first match is found, the subsequent searches are continued on from end of the last match.
order can be one of two things:
Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on.
1 2 preg_match_all("|<[^>]+>(.*)</[^>]+>|U", "<b>example: </b><div align=left>a test</div>", $out, PREG_PATTERN_ORDER); 3 print $out[0][0].", ".$out[0][1]."\n"; 4 print $out[1][0].", ".$out[1][1]."\n" 5 |
This example will produce:
1 2 <b>example: </b>, <div align=left>this is a test</div> 3 example: , this is a test 4 |
So, $out[0] contains array of strings that matched full pattern, and $out[1] contains array of strings enclosed by tags.
Orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on.
1 2 preg_match_all("|<[^>]+>(.*)</[^>]+>|U", "<b>example: </b><div align=left>a test</div>", $out, PREG_SET_ORDER); 3 print $out[0][0].", ".$out[0][1]."\n"; 4 print $out[1][0].", ".$out[1][1]."\n" 5 |
This example will produce:
1 2 <b>example: </b>, example: 3 <div align=left>this is a test</div>, this is a test 4 |
If order is not specified, it is assumed to be PREG_PATTERN_ORDER.
Returns the number of full pattern matches, or false if no match is found or an error occurred.
Example 1. Getting all phone numbers out of some text.
|
See also preg_match(), preg_replace(), and preg_split().
preg_replace -- 정규 표현식의 검색과 바꾸기를 수행한다.
mixed preg_replace
(mixed pattern, mixed replacement, mixed subject)
Searches subject for matches to pattern and replaces them with replacement .
replacement may contain references of the form \\n. Every such reference will be replaced by the text captured by the n'th parenthesized pattern. n can be from 0 to 99, and \\0 refers to the text matched by the whole pattern. Opening parentheses are counted from left to right (starting from 1) to obtain the number of the capturing subpattern.
If no matches are found in subject, then it will be returned unchanged.
Every parameter to preg_replace() can be an array.
If subject is an array, then the search and replace is performed on every entry of subject, and the return value is an array as well.
If pattern and replacement are arrays, then preg_replace() takes a value from each array and uses them to do search and replace on subject. If replacement has fewer values than pattern, then empty string is used for the rest of replacement values. If pattern is an array and replacement is a string; then this replacement string is used for every value of pattern. The converse would not make sense, though.
/e modifier makes preg_replace() treat the replacement parameter as PHP code after the appropriate references substitution is done. Tip: make sure that replacement constitutes a valid PHP code string, otherwise PHP will complain about a parse error at the line containing preg_replace().
Note: This modifier was added in PHP 4.0.
Example 1. Replacing several values
|
This example will produce:
1 2 $startDate = 5/27/1999 3 |
Example 2. Using /e modifier
This would capitalize all HTML tags in the input text. |
See also preg_match(), preg_match_all(), and preg_split().
preg_split -- 정규 표현식에 따른 문자열 나누기를 한다.
array preg_split
(string pattern, string
subject [, int limit [, int flags]])
Note: Parameter flags was added in PHP Beta 3.
Returns an array containing substrings of subject split along boundaries matched by pattern.
If limit is specified, then only substrings up to limit are returned.
If flags is PREG_SPLIT_NO_EMPTY then only non-empty pieces will be by preg_split().
Example 1. Getting parts of search string
|
See also preg_match(), preg_match_all(), and preg_replace().
preg_quote -- 정규 표현식에 사용되는 문자들을 backslash가 붙은 문자로 전환(quote)한다.
string preg_quote
(string str)
preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.
The special regular expression characters are:
. \\ + * ? [ ^ ] $ ( ) { } = ! < > | : |
Note: This function was added in PHP 3.0.9.
preg_grep -- 배열에서 패턴에 맞는 원소들을 반환한다.
array preg_grep
(string
pattern, array input)
preg_grep() returns the array consisting of the elements of the input array that match the given pattern.
Example 1. preg_grep() example
|
Note: This function was added in PHP 4.0.
Pattern Modifiers -- regex 패턴의 가능한 변경자(modifier)를 기술한다.
현재 PCRE에서 가능한 변경자(modifier)들은 아래 나와있다. 괄호안의 이름은 해당 옵션에 대하여 PCRE 내부에서 사용하는 이름이다.
- i (PCRE_CASELESS)
- 이 옵션이 설정되어 있으면, 패턴의 문자는 대소문자를 가리지 않고 모두 매칭된다.
- m (PCRE_MULTILINE)
- 기본적으로, PCRE는 (비록 안에 개향 문자가 있어도) 해당 문자열을 한줄로 취급한다. 따라서, "줄 시작"을 나타내는 메타 캐릭터(^)는 해당 문자열의 시작에만 매칭되고, "줄 끝"을 나타내는 메타 캐릭터($)는 문자열의 끝이나, (E option이 설정되어 있지 않다면) newline이 끝나기 전에 매칭된다. 이것은 Perl과 동일하다.
- 만약 이 옵션이 설정되면, "줄 시작"과 "줄 끝"이 해당 문자열의 모든 개개의 newline의 시작과 끝에 매칭되도록 한다. 이것은 Perl의 /m 옵션과 동일하다. 해당하는 문자열에 "\n"문자가 없거나 패턴에 ^나 $가 없다면 이 옵션은 아무 의미가 없게된다.
- s (PCRE_DOTALL)
- 이 옵션이 설정되어 있으면, 패턴의 점 메타 캐릭터(.)는 개행문자를 포함한 어떤 문자에도 매칭된다. 이 옵션이 없다면 개행문자는 제외된다. 이 옵션은 Perl의 /s 옵션과 동일하다. [^a]같은 negative class는 이 옵션에 관계없이 언제나 개행문자에 매칭된다.
- x (PCRE_EXTENDED)
- 이 옵션이 설정되어 있으면, 패턴의 공백문자는 완전히 무시된다. 단, escape되어 있거나, character class안에 있는 경우는 유효하다. 또한 character class밖에 있는 unescaped # 과 다음 개행문자 사이에 있는 문자들도 무시된다.
- 이 옵션은 Perl의 /x 옵션과 동일하고, 복잡한 패턴의 안에 주석문을 넣어두는 것을 가능하게 한다. 주의할점은 이것이 단지 데이터 문자들에 대해서만 작용한다는 것이다. 공백 문자들은 패턴에서의 특별한 문자 sequence 사이에는 나타날 수 없다. 예를들어 conditional subpattern인 (?( sequence 사이에서는 나타날 수 없다.
- e
- 이 옵션이 설정되어 있으면, preg_replace()는 교체 문자열에 있는 \\에 대해 PHP 코드에서 하는 일반적인 치환을 먼저 하고, 그 결과를 탐색 문자열로 사용한다. (If this option is set, preg_replace() does normal substitution of \\ references in the replacement string, evaluates it as PHP code, and uses the result for replacing the search string.)
이 옵션은 오직 preg_replace()에서만 사용된다. 다른 PCRE 함수들에서는 이 옵션이 무시된다.- A (PCRE_ANCHORED)
- 이 옵션이 설정되어 있으면, 패턴이 "anchored"되어 있다고 강제로 설정한다. 이것은 탐색되는 문자열("subject string")의 시작에서만 매칭되도록 강제한다. This effect can also be achieved by appropriate constructs in the pattern itself, which is the only way to do it in Perl.
- E (PCRE_DOLLAR_ENDONLY)
- 이 옵션이 설정되어 있으면 $ 메타 캐릭터는 해당 문자열의 맨 마지막과 매칭된다. 이 옵션이 사용되지 않으면, $는 마지막 문자가 newline이면 이 문자 앞과 매칭된다.(모든 newline의 앞이 아니다.) 이 옵션은 m 옵션이 설정되어 있으면 무시된다. Perl에서 동일한 옵션은 없다.
- S
- 패턴이 여러번 사용된다면, 매칭을 검사하는 것보다 더 많은 시간이 패턴을 분석하는데 사용될 수 있다. 이 옵션이 설정되어 있으면 별도의 분석이 수행된다. 요즘에 이 패턴 studying은 한 개의 고정된 시작 문자를 가지지 않는 non-anchored 패턴에 대해서만 유용하게 사용된다.
- U (PCRE_UNGREEDY)
- 이 옵션은 수량 기호의 "greediness"를 반전시킨다. 따라서 디폴트로 greedy 하지 않도록 한다. 그러나 "?"다음에 사용되는 경우는 greedy하도록 한다. 이점은 Perl과 호환이 되지 않는다. 또한 이것은 패턴안에 (?U) 옵션을 설정하여 설정할 수도 있다.
- X (PCRE_EXTRA)
- 이 옵션은 PCRE의 Perl과 비호환되는 추가적인 기능을 활성화 한다. 패턴에거 백슬래시 뒤에 나오는 문자중에 특별한 의미가 없는 것은 에러를 발생시킨다. 이것은 후에 확장을 위해서이다. 기본적으로 Perl에서는 백슬래시 뒤에 나오는 의미없는 문자들은 일반 문자로 취급된다. 이 옵션에 의해 설정되는 내용은 현재 이것 뿐이다.
Pattern Syntax -- describes PCRE regex syntax
The PCRE library is a set of functions that implement regular
expression pattern matching using the same syntax and semantics
as Perl 5, with just a few differences (see below). The current
implementation corresponds to Perl 5.005.
The differences described here are with respect to Perl
5.005.
1. By default, a whitespace character is any character that
the C library function isspace() recognizes, though it is
possible to compile PCRE with alternative character type
tables. Normally isspace() matches space, formfeed, newline,
carriage return, horizontal tab, and vertical tab. Perl 5 no
longer includes vertical tab in its set of whitespace char-
acters. The \v escape that was in the Perl documentation for
a long time was never in fact recognized. However, the char-
acter itself was treated as whitespace at least up to 5.002.
In 5.004 and 5.005 it does not match \s.
2. PCRE does not allow repeat quantifiers on lookahead
assertions. Perl permits them, but they do not mean what you
might think. For example, (?!a){3} does not assert that the
next three characters are not "a". It just asserts that the
next character is not "a" three times.
3. Capturing subpatterns that occur inside negative looka-
head assertions are counted, but their entries in the
offsets vector are never set. Perl sets its numerical vari-
ables from any such patterns that are matched before the
assertion fails to match something (thereby succeeding), but
only if the negative lookahead assertion contains just one
branch.
4. Though binary zero characters are supported in the sub-
ject string, they are not allowed in a pattern string
because it is passed as a normal C string, terminated by
zero. The escape sequence "\0" can be used in the pattern to
represent a binary zero.
5. The following Perl escape sequences are not supported:
\l, \u, \L, \U, \E, \Q. In fact these are implemented by
Perl's general string-handling and are not part of its pat-
tern matching engine.
6. The Perl \G assertion is not supported as it is not
relevant to single pattern matches.
7. Fairly obviously, PCRE does not support the (?{code})
construction.
8. There are at the time of writing some oddities in Perl
5.005_02 concerned with the settings of captured strings
when part of a pattern is repeated. For example, matching
"aba" against the pattern /^(a(b)?)+$/ sets $2 to the value
"b", but matching "aabbaa" against /^(aa(bb)?)+$/ leaves $2
unset. However, if the pattern is changed to
/^(aa(b(b))?)+$/ then $2 (and $3) get set.
In Perl 5.004 $2 is set in both cases, and that is also true
of PCRE. If in the future Perl changes to a consistent state
that is different, PCRE may change to follow.
9. Another as yet unresolved discrepancy is that in Perl
5.005_02 the pattern /^(a)?(?(1)a|b)+$/ matches the string
"a", whereas in PCRE it does not. However, in both Perl and
PCRE /^(a)?a/ matched against "a" leaves $1 unset.
10. PCRE provides some extensions to the Perl regular
expression facilities:
(a) Although lookbehind assertions must match fixed length
strings, each alternative branch of a lookbehind assertion
can match a different length of string. Perl 5.005 requires
them all to have the same length.
(b) If PCRE_DOLLAR_ENDONLY is set and PCRE_MULTILINE is not
set, the $ meta- character matches only at the very end of
the string.
(c) If PCRE_EXTRA is set, a backslash followed by a letter
with no special meaning is faulted.
(d) If PCRE_UNGREEDY is set, the greediness of the repeti-
tion quantifiers is inverted, that is, by default they are
not greedy, but if followed by a question mark they are.
The syntax and semantics of the regular expressions sup-
ported by PCRE are described below. Regular expressions are
also described in the Perl documentation and in a number of
other books, some of which have copious examples. Jeffrey
Friedl's "Mastering Regular Expressions", published by
O'Reilly (ISBN 1-56592-257-3), covers them in great detail.
The description here is intended as reference documentation.
A regular expression is a pattern that is matched against a
subject string from left to right. Most characters stand for
themselves in a pattern, and match the corresponding charac-
ters in the subject. As a trivial example, the pattern
The quick brown fox
matches a portion of a subject string that is identical to
itself. The power of regular expressions comes from the
ability to include alternatives and repetitions in the pat-
tern. These are encoded in the pattern by the use of meta-
characters, which do not stand for themselves but instead
are interpreted in some special way.
There are two different sets of meta-characters: those that
are recognized anywhere in the pattern except within square
brackets, and those that are recognized in square brackets.
Outside square brackets, the meta-characters are as follows:
\ general escape character with several uses
^ assert start of subject (or line, in multiline
mode)
$ assert end of subject (or line, in multiline mode)
. match any character except newline (by default)
[ start character class definition
| start of alternative branch
( start subpattern
) end subpattern
? extends the meaning of (
also 0 or 1 quantifier
also quantifier minimizer
* 0 or more quantifier
+ 1 or more quantifier
{ start min/max quantifier
Part of a pattern that is in square brackets is called a
"character class". In a character class the only meta-
characters are:
\ general escape character
^ negate the class, but only if the first character
- indicates character range
] terminates the character class
The following sections describe the use of each of the
meta-characters.
BACKSLASH
The backslash character has several uses. Firstly, if it is
followed by a non-alphameric character, it takes away any
special meaning that character may have. This use of
backslash as an escape character applies both inside and
outside character classes.
For example, if you want to match a "*" character, you write
"\*" in the pattern. This applies whether or not the follow-
ing character would otherwise be interpreted as a meta-
character, so it is always safe to precede a non-alphameric
with "\" to specify that it stands for itself. In particu-
lar, if you want to match a backslash, you write "\\".
If a pattern is compiled with the PCRE_EXTENDED option, whi-
tespace in the pattern (other than in a character class) and
characters between a "#" outside a character class and the
next newline character are ignored. An escaping backslash
can be used to include a whitespace or "#" character as part
of the pattern.
A second use of backslash provides a way of encoding non-
printing characters in patterns in a visible manner. There
is no restriction on the appearance of non-printing charac-
ters, apart from the binary zero that terminates a pattern,
but when a pattern is being prepared by text editing, it is
usually easier to use one of the following escape sequences
than the binary character it represents:
\a alarm, that is, the BEL character (hex 07)
\cx "control-x", where x is any character
\e escape (hex 1B)
\f formfeed (hex 0C)
\n newline (hex 0A)
\r carriage return (hex 0D)
\t tab (hex 09)
\xhh character with hex code hh
\ddd character with octal code ddd, or backreference
The precise effect of "\cx" is as follows: if "x" is a lower
case letter, it is converted to upper case. Then bit 6 of
the character (hex 40) is inverted. Thus "\cz" becomes hex
1A, but "\c{" becomes hex 3B, while "\c;" becomes hex 7B.
After "\x", up to two hexadecimal digits are read (letters
can be in upper or lower case).
After "\0" up to two further octal digits are read. In both
cases, if there are fewer than two digits, just those that
are present are used. Thus the sequence "\0\x\07" specifies
two binary zeros followed by a BEL character. Make sure you
supply two digits after the initial zero if the character
that follows is itself an octal digit.
The handling of a backslash followed by a digit other than 0
is complicated. Outside a character class, PCRE reads it
and any following digits as a decimal number. If the number
is less than 10, or if there have been at least that many
previous capturing left parentheses in the expression, the
entire sequence is taken as a back reference. A description
of how this works is given later, following the discussion
of parenthesized subpatterns.
Inside a character class, or if the decimal number is
greater than 9 and there have not been that many capturing
subpatterns, PCRE re-reads up to three octal digits follow-
ing the backslash, and generates a single byte from the
least significant 8 bits of the value. Any subsequent digits
stand for themselves. For example:
\040 is another way of writing a space
\40 is the same, provided there are fewer than 40
previous capturing subpatterns
\7 is always a back reference
\11 might be a back reference, or another way of
writing a tab
\011 is always a tab
\0113 is a tab followed by the character "3"
\113 is the character with octal code 113 (since there
can be no more than 99 back references)
\377 is a byte consisting entirely of 1 bits
\81 is either a back reference, or a binary zero
followed by the two characters "8" and "1"
Note that octal values of 100 or greater must not be intro-
duced by a leading zero, because no more than three octal
digits are ever read.
All the sequences that define a single byte value can be
used both inside and outside character classes. In addition,
inside a character class, the sequence "\b" is interpreted
as the backspace character (hex 08). Outside a character
class it has a different meaning (see below).
The third use of backslash is for specifying generic charac-
ter types:
\d any decimal digit
\D any character that is not a decimal digit
\s any whitespace character
\S any character that is not a whitespace character
\w any "word" character
\W any "non-word" character
Each pair of escape sequences partitions the complete set of
characters into two disjoint sets. Any given character
matches one, and only one, of each pair.
A "word" character is any letter or digit or the underscore
character, that is, any character which can be part of a
Perl "word". The definition of letters and digits is con-
trolled by PCRE's character tables, and may vary if locale-
specific matching is taking place (see "Locale support"
above). For example, in the "fr" (French) locale, some char-
acter codes greater than 128 are used for accented letters,
and these are matched by \w.
These character type sequences can appear both inside and
outside character classes. They each match one character of
the appropriate type. If the current matching point is at
the end of the subject string, all of them fail, since there
is no character to match.
The fourth use of backslash is for certain simple asser-
tions. An assertion specifies a condition that has to be met
at a particular point in a match, without consuming any
characters from the subject string. The use of subpatterns
for more complicated assertions is described below. The
backslashed assertions are
\b word boundary
\B not a word boundary
\A start of subject (independent of multiline mode)
\Z end of subject or newline at end (independent of
multiline mode)
\z end of subject (independent of multiline mode)
These assertions may not appear in character classes (but
note that "\b" has a different meaning, namely the backspace
character, inside a character class).
A word boundary is a position in the subject string where
the current character and the previous character do not both
match \w or \W (i.e. one matches \w and the other matches
\W), or the start or end of the string if the first or last
character matches \w, respectively.
The \A, \Z, and \z assertions differ from the traditional
circumflex and dollar (described below) in that they only
ever match at the very start and end of the subject string,
whatever options are set. They are not affected by the
PCRE_NOTBOL or PCRE_NOTEOL options. The difference between
\Z and \z is that \Z matches before a newline that is the
last character of the string as well as at the end of the
string, whereas \z matches only at the end.
CIRCUMFLEX AND DOLLAR
Outside a character class, in the default matching mode, the
circumflex character is an assertion which is true only if
the current matching point is at the start of the subject
string. Inside a character class, circumflex has an entirely
different meaning (see below).
Circumflex need not be the first character of the pattern if
a number of alternatives are involved, but it should be the
first thing in each alternative in which it appears if the
pattern is ever to match that branch. If all possible alter-
natives start with a circumflex, that is, if the pattern is
constrained to match only at the start of the subject, it is
said to be an "anchored" pattern. (There are also other con-
structs that can cause a pattern to be anchored.)
A dollar character is an assertion which is true only if the
current matching point is at the end of the subject string,
or immediately before a newline character that is the last
character in the string (by default). Dollar need not be the
last character of the pattern if a number of alternatives
are involved, but it should be the last item in any branch
in which it appears. Dollar has no special meaning in a
character class.
The meaning of dollar can be changed so that it matches only
at the very end of the string, by setting the
PCRE_DOLLAR_ENDONLY option at compile or matching time. This
does not affect the \Z assertion.
The meanings of the circumflex and dollar characters are
changed if the PCRE_MULTILINE option is set. When this is
the case, they match immediately after and immediately
before an internal "\n" character, respectively, in addition
to matching at the start and end of the subject string. For
example, the pattern /^abc$/ matches the subject string
"def\nabc" in multiline mode, but not otherwise. Conse-
quently, patterns that are anchored in single line mode
because all branches start with "^" are not anchored in mul-
tiline mode. The PCRE_DOLLAR_ENDONLY option is ignored if
PCRE_MULTILINE is set.
Note that the sequences \A, \Z, and \z can be used to match
the start and end of the subject in both modes, and if all
branches of a pattern start with \A is it always anchored,
whether PCRE_MULTILINE is set or not.
FULL STOP (PERIOD, DOT)
Outside a character class, a dot in the pattern matches any
one character in the subject, including a non-printing
character, but not (by default) newline. If the PCRE_DOTALL
option is set, then dots match newlines as well. The han-
dling of dot is entirely independent of the handling of cir-
cumflex and dollar, the only relationship being that they
both involve newline characters. Dot has no special meaning
in a character class.
SQUARE BRACKETS
An opening square bracket introduces a character class, ter-
minated by a closing square bracket. A closing square
bracket on its own is not special. If a closing square
bracket is required as a member of the class, it should be
the first data character in the class (after an initial cir-
cumflex, if present) or escaped with a backslash.
A character class matches a single character in the subject;
the character must be in the set of characters defined by
the class, unless the first character in the class is a cir-
cumflex, in which case the subject character must not be in
the set defined by the class. If a circumflex is actually
required as a member of the class, ensure it is not the
first character, or escape it with a backslash.
For example, the character class [aeiou] matches any lower
case vowel, while [^aeiou] matches any character that is not
a lower case vowel. Note that a circumflex is just a con-
venient notation for specifying the characters which are in
the class by enumerating those that are not. It is not an
assertion: it still consumes a character from the subject
string, and fails if the current pointer is at the end of
the string.
When caseless matching is set, any letters in a class
represent both their upper case and lower case versions, so
for example, a caseless [aeiou] matches "A" as well as "a",
and a caseless [^aeiou] does not match "A", whereas a case-
ful version would.
The newline character is never treated in any special way in
character classes, whatever the setting of the PCRE_DOTALL
or PCRE_MULTILINE options is. A class such as [^a] will
always match a newline.
The minus (hyphen) character can be used to specify a range
of characters in a character class. For example, [d-m]
matches any letter between d and m, inclusive. If a minus
character is required in a class, it must be escaped with a
backslash or appear in a position where it cannot be inter-
preted as indicating a range, typically as the first or last
character in the class.
It is not possible to have the literal character "]" as the
end character of a range. A pattern such as [W-]46] is
interpreted as a class of two characters ("W" and "-") fol-
lowed by a literal string "46]", so it would match "W46]" or
"-46]". However, if the "]" is escaped with a backslash it
is interpreted as the end of range, so [W-\]46] is inter-
preted as a single class containing a range followed by two
separate characters. The octal or hexadecimal representation
of "]" can also be used to end a range.
Ranges operate in ASCII collating sequence. They can also be
used for characters specified numerically, for example
[\000-\037]. If a range that includes letters is used when
caseless matching is set, it matches the letters in either
case. For example, [W-c] is equivalent to [][\^_`wxyzabc],
matched caselessly, and if character tables for the "fr"
locale are in use, [\xc8-\xcb] matches accented E characters
in both cases.
The character types \d, \D, \s, \S, \w, and \W may also
appear in a character class, and add the characters that
they match to the class. For example, [\dABCDEF] matches any
hexadecimal digit. A circumflex can conveniently be used
with the upper case character types to specify a more res-
tricted set of characters than the matching lower case type.
For example, the class [^\W_] matches any letter or digit,
but not underscore.
All non-alphameric characters other than \, -, ^ (at the
start) and the terminating ] are non-special in character
classes, but it does no harm if they are escaped.
VERTICAL BAR
Vertical bar characters are used to separate alternative
patterns. For example, the pattern
gilbert|sullivan
matches either "gilbert" or "sullivan". Any number of alter-
natives may appear, and an empty alternative is permitted
(matching the empty string). The matching process tries
each alternative in turn, from left to right, and the first
one that succeeds is used. If the alternatives are within a
subpattern (defined below), "succeeds" means matching the
rest of the main pattern as well as the alternative in the
subpattern.
INTERNAL OPTION SETTING
The settings of PCRE_CASELESS, PCRE_MULTILINE, PCRE_DOTALL,
and PCRE_EXTENDED can be changed from within the pattern by
a sequence of Perl option letters enclosed between "(?" and
")". The option letters are
i for PCRE_CASELESS
m for PCRE_MULTILINE
s for PCRE_DOTALL
x for PCRE_EXTENDED
For example, (?im) sets caseless, multiline matching. It is
also possible to unset these options by preceding the letter
with a hyphen, and a combined setting and unsetting such as
(?im-sx), which sets PCRE_CASELESS and PCRE_MULTILINE while
unsetting PCRE_DOTALL and PCRE_EXTENDED, is also permitted.
If a letter appears both before and after the hyphen, the
option is unset.
The scope of these option changes depends on where in the
pattern the setting occurs. For settings that are outside
any subpattern (defined below), the effect is the same as if
the options were set or unset at the start of matching. The
following patterns all behave in exactly the same way:
(?i)abc
a(?i)bc
ab(?i)c
abc(?i)
which in turn is the same as compiling the pattern abc with
PCRE_CASELESS set. In other words, such "top level" set-
tings apply to the whole pattern (unless there are other
changes inside subpatterns). If there is more than one set-
ting of the same option at top level, the rightmost setting
is used.
If an option change occurs inside a subpattern, the effect
is different. This is a change of behaviour in Perl 5.005.
An option change inside a subpattern affects only that part
of the subpattern that follows it, so
(a(?i)b)c
matches abc and aBc and no other strings (assuming
PCRE_CASELESS is not used). By this means, options can be
made to have different settings in different parts of the
pattern. Any changes made in one alternative do carry on
into subsequent branches within the same subpattern. For
example,
(a(?i)b|c)
matches "ab", "aB", "c", and "C", even though when matching
"C" the first branch is abandoned before the option setting.
This is because the effects of option settings happen at
compile time. There would be some very weird behaviour oth-
erwise.
The PCRE-specific options PCRE_UNGREEDY and PCRE_EXTRA can
be changed in the same way as the Perl-compatible options by
using the characters U and X respectively. The (?X) flag
setting is special in that it must always occur earlier in
the pattern than any of the additional features it turns on,
even when it is at top level. It is best put at the start.
SUBPATTERNS
Subpatterns are delimited by parentheses (round brackets),
which can be nested. Marking part of a pattern as a subpat-
tern does two things:
1. It localizes a set of alternatives. For example, the pat-
tern
cat(aract|erpillar|)
matches one of the words "cat", "cataract", or "caterpil-
lar". Without the parentheses, it would match "cataract",
"erpillar" or the empty string.
2. It sets up the subpattern as a capturing subpattern (as
defined above). When the whole pattern matches, that por-
tion of the subject string that matched the subpattern is
passed back to the caller via the ovector argument of
pcre_exec(). Opening parentheses are counted from left to
right (starting from 1) to obtain the numbers of the captur-
ing subpatterns.
For example, if the string "the red king" is matched against
the pattern
the ((red|white) (king|queen))
the captured substrings are "red king", "red", and "king",
and are numbered 1, 2, and 3.
The fact that plain parentheses fulfil two functions is not
always helpful. There are often times when a grouping sub-
pattern is required without a capturing requirement. If an
opening parenthesis is followed by "?:", the subpattern does
not do any capturing, and is not counted when computing the
number of any subsequent capturing subpatterns. For example,
if the string "the white queen" is matched against the
pattern
the ((?:red|white) (king|queen))
the captured substrings are "white queen" and "queen", and
are numbered 1 and 2. The maximum number of captured sub-
strings is 99, and the maximum number of all subpatterns,
both capturing and non-capturing, is 200.
As a convenient shorthand, if any option settings are
required at the start of a non-capturing subpattern, the
option letters may appear between the "?" and the ":". Thus
the two patterns
(?i:saturday|sunday)
(?:(?i)saturday|sunday)
match exactly the same set of strings. Because alternative
branches are tried from left to right, and options are not
reset until the end of the subpattern is reached, an option
setting in one branch does affect subsequent branches, so
the above patterns match "SUNDAY" as well as "Saturday".
REPETITION
Repetition is specified by quantifiers, which can follow any
of the following items:
a single character, possibly escaped
the . metacharacter
a character class
a back reference (see next section)
a parenthesized subpattern (unless it is an assertion -
see below)
The general repetition quantifier specifies a minimum and
maximum number of permitted matches, by giving the two
numbers in curly brackets (braces), separated by a comma.
The numbers must be less than 65536, and the first must be
less than or equal to the second. For example:
z{2,4}
matches "zz", "zzz", or "zzzz". A closing brace on its own
is not a special character. If the second number is omitted,
but the comma is present, there is no upper limit; if the
second number and the comma are both omitted, the quantifier
specifies an exact number of required matches. Thus
[aeiou]{3,}
matches at least 3 successive vowels, but may match many
more, while
\d{8}
matches exactly 8 digits. An opening curly bracket that
appears in a position where a quantifier is not allowed, or
one that does not match the syntax of a quantifier, is taken
as a literal character. For example, {,6} is not a quantif-
ier, but a literal string of four characters.
The quantifier {0} is permitted, causing the expression to
behave as if the previous item and the quantifier were not
present.
For convenience (and historical compatibility) the three
most common quantifiers have single-character abbreviations:
* is equivalent to {0,}
+ is equivalent to {1,}
? is equivalent to {0,1}
It is possible to construct infinite loops by following a
subpattern that can match no characters with a quantifier
that has no upper limit, for example:
(a?)*
Earlier versions of Perl and PCRE used to give an error at
compile time for such patterns. However, because there are
cases where this can be useful, such patterns are now
accepted, but if any repetition of the subpattern does in
fact match no characters, the loop is forcibly broken.
By default, the quantifiers are "greedy", that is, they
match as much as possible (up to the maximum number of per-
mitted times), without causing the rest of the pattern to
fail. The classic example of where this gives problems is in
trying to match comments in C programs. These appear between
the sequences /* and */ and within the sequence, individual
* and / characters may appear. An attempt to match C com-
ments by applying the pattern
/\*.*\*/
to the string
/* first command */ not comment /* second comment */
fails, because it matches the entire string due to the
greediness of the .* item.
However, if a quantifier is followed by a question mark,
then it ceases to be greedy, and instead matches the minimum
number of times possible, so the pattern
/\*.*?\*/
does the right thing with the C comments. The meaning of the
various quantifiers is not otherwise changed, just the pre-
ferred number of matches. Do not confuse this use of ques-
tion mark with its use as a quantifier in its own right.
Because it has two uses, it can sometimes appear doubled, as
in
\d??\d
which matches one digit by preference, but can match two if
that is the only way the rest of the pattern matches.
If the PCRE_UNGREEDY option is set (an option which is not
available in Perl) then the quantifiers are not greedy by
default, but individual ones can be made greedy by following
them with a question mark. In other words, it inverts the
default behaviour.
When a parenthesized subpattern is quantified with a minimum
repeat count that is greater than 1 or with a limited max-
imum, more store is required for the compiled pattern, in
proportion to the size of the minimum or maximum.
If a pattern starts with .* or .{0,} and the PCRE_DOTALL
option (equivalent to Perl's /s) is set, thus allowing the .
to match newlines, then the pattern is implicitly anchored,
because whatever follows will be tried against every charac-
ter position in the subject string, so there is no point in
retrying the overall match at any position after the first.
PCRE treats such a pattern as though it were preceded by \A.
In cases where it is known that the subject string contains
no newlines, it is worth setting PCRE_DOTALL when the pat-
tern begins with .* in order to obtain this optimization, or
alternatively using ^ to indicate anchoring explicitly.
When a capturing subpattern is repeated, the value captured
is the substring that matched the final iteration. For exam-
ple, after
(tweedle[dume]{3}\s*)+
has matched "tweedledum tweedledee" the value of the cap-
tured substring is "tweedledee". However, if there are
nested capturing subpatterns, the corresponding captured
values may have been set in previous iterations. For exam-
ple, after
/(a|(b))+/
matches "aba" the value of the second captured substring is
"b".
BACK REFERENCES
Outside a character class, a backslash followed by a digit
greater than 0 (and possibly further digits) is a back
reference to a capturing subpattern earlier (i.e. to its
left) in the pattern, provided there have been that many
previous capturing left parentheses.
However, if the decimal number following the backslash is
less than 10, it is always taken as a back reference, and
causes an error only if there are not that many capturing
left parentheses in the entire pattern. In other words, the
parentheses that are referenced need not be to the left of
the reference for numbers less than 10. See the section
entitled "Backslash" above for further details of the han-
dling of digits following a backslash.
A back reference matches whatever actually matched the cap-
turing subpattern in the current subject string, rather than
anything matching the subpattern itself. So the pattern
(sens|respons)e and \1ibility
matches "sense and sensibility" and "response and responsi-
bility", but not "sense and responsibility". If caseful
matching is in force at the time of the back reference, then
the case of letters is relevant. For example,
((?i)rah)\s+\1
matches "rah rah" and "RAH RAH", but not "RAH rah", even
though the original capturing subpattern is matched case-
lessly.
There may be more than one back reference to the same sub-
pattern. If a subpattern has not actually been used in a
particular match, then any back references to it always
fail. For example, the pattern
(a|(bc))\2
always fails if it starts to match "a" rather than "bc".
Because there may be up to 99 back references, all digits
following the backslash are taken as part of a potential
back reference number. If the pattern continues with a digit
character, then some delimiter must be used to terminate the
back reference. If the PCRE_EXTENDED option is set, this can
be whitespace. Otherwise an empty comment can be used.
A back reference that occurs inside the parentheses to which
it refers fails when the subpattern is first used, so, for
example, (a\1) never matches. However, such references can
be useful inside repeated subpatterns. For example, the pat-
tern
(a|b\1)+
matches any number of "a"s and also "aba", "ababaa" etc. At
each iteration of the subpattern, the back reference matches
the character string corresponding to the previous itera-
tion. In order for this to work, the pattern must be such
that the first iteration does not need to match the back
reference. This can be done using alternation, as in the
example above, or by a quantifier with a minimum of zero.
ASSERTIONS
An assertion is a test on the characters following or
preceding the current matching point that does not actually
consume any characters. The simple assertions coded as \b,
\B, \A, \Z, \z, ^ and $ are described above. More compli-
cated assertions are coded as subpatterns. There are two
kinds: those that look ahead of the current position in the
subject string, and those that look behind it.
An assertion subpattern is matched in the normal way, except
that it does not cause the current matching position to be
changed. Lookahead assertions start with (?= for positive
assertions and (?! for negative assertions. For example,
\w+(?=;)
matches a word followed by a semicolon, but does not include
the semicolon in the match, and
foo(?!bar)
matches any occurrence of "foo" that is not followed by
"bar". Note that the apparently similar pattern
(?!foo)bar
does not find an occurrence of "bar" that is preceded by
something other than "foo"; it finds any occurrence of "bar"
whatsoever, because the assertion (?!foo) is always true
when the next three characters are "bar". A lookbehind
assertion is needed to achieve this effect.
Lookbehind assertions start with (?<= for positive asser-
tions and (?<! for negative assertions. For example,
(?<!foo)bar
does find an occurrence of "bar" that is not preceded by
"foo". The contents of a lookbehind assertion are restricted
such that all the strings it matches must have a fixed
length. However, if there are several alternatives, they do
not all have to have the same fixed length. Thus
(?<=bullock|donkey)
is permitted, but
(?<!dogs?|cats?)
causes an error at compile time. Branches that match dif-
ferent length strings are permitted only at the top level of
a lookbehind assertion. This is an extension compared with
Perl 5.005, which requires all branches to match the same
length of string. An assertion such as
(?<=ab(c|de))
is not permitted, because its single top-level branch can
match two different lengths, but it is acceptable if rewrit-
ten to use two top-level branches:
(?<=abc|abde)
The implementation of lookbehind assertions is, for each
alternative, to temporarily move the current position back
by the fixed width and then try to match. If there are
insufficient characters before the current position, the
match is deemed to fail. Lookbehinds in conjunction with
once-only subpatterns can be particularly useful for match-
ing at the ends of strings; an example is given at the end
of the section on once-only subpatterns.
Several assertions (of any sort) may occur in succession.
For example,
(?<=\d{3})(?<!999)foo
matches "foo" preceded by three digits that are not "999".
Furthermore, assertions can be nested in any combination.
For example,
(?<=(?<!foo)bar)baz
matches an occurrence of "baz" that is preceded by "bar"
which in turn is not preceded by "foo".
Assertion subpatterns are not capturing subpatterns, and may
not be repeated, because it makes no sense to assert the
same thing several times. If an assertion contains capturing
subpatterns within it, these are always counted for the pur-
poses of numbering the capturing subpatterns in the whole
pattern. Substring capturing is carried out for positive
assertions, but it does not make sense for negative asser-
tions.
Assertions count towards the maximum of 200 parenthesized
subpatterns.
ONCE-ONLY SUBPATTERNS
With both maximizing and minimizing repetition, failure of
what follows normally causes the repeated item to be re-
evaluated to see if a different number of repeats allows the
rest of the pattern to match. Sometimes it is useful to
prevent this, either to change the nature of the match, or
to cause it fail earlier than it otherwise might, when the
author of the pattern knows there is no point in carrying
on.
Consider, for example, the pattern \d+foo when applied to
the subject line
123456bar
After matching all 6 digits and then failing to match "foo",
the normal action of the matcher is to try again with only 5
digits matching the \d+ item, and then with 4, and so on,
before ultimately failing. Once-only subpatterns provide the
means for specifying that once a portion of the pattern has
matched, it is not to be re-evaluated in this way, so the
matcher would give up immediately on failing to match "foo"
the first time. The notation is another kind of special
parenthesis, starting with (?> as in this example:
(?>\d+)bar
This kind of parenthesis "locks up" the part of the pattern
it contains once it has matched, and a failure further into
the pattern is prevented from backtracking into it. Back-
tracking past it to previous items, however, works as nor-
mal.
An alternative description is that a subpattern of this type
matches the string of characters that an identical stan-
dalone pattern would match, if anchored at the current point
in the subject string.
Once-only subpatterns are not capturing subpatterns. Simple
cases such as the above example can be thought of as a max-
imizing repeat that must swallow everything it can. So,
while both \d+ and \d+? are prepared to adjust the number of
digits they match in order to make the rest of the pattern
match, (?>\d+) can only match an entire sequence of digits.
This construction can of course contain arbitrarily compli-
cated subpatterns, and it can be nested.
Once-only subpatterns can be used in conjunction with look-
behind assertions to specify efficient matching at the end
of the subject string. Consider a simple pattern such as
abcd$
when applied to a long string which does not match it.
Because matching proceeds from left to right, PCRE will look
for each "a" in the subject and then see if what follows
matches the rest of the pattern. If the pattern is specified
as
^.*abcd$
then the initial .* matches the entire string at first, but
when this fails, it backtracks to match all but the last
character, then all but the last two characters, and so on.
Once again the search for "a" covers the entire string, from
right to left, so we are no better off. However, if the pat-
tern is written as
^(?>.*)(?<=abcd)
then there can be no backtracking for the .* item; it can
match only the entire string. The subsequent lookbehind
assertion does a single test on the last four characters. If
it fails, the match fails immediately. For long strings,
this approach makes a significant difference to the process-
ing time.
CONDITIONAL SUBPATTERNS
It is possible to cause the matching process to obey a sub-
pattern conditionally or to choose between two alternative
subpatterns, depending on the result of an assertion, or
whether a previous capturing subpattern matched or not. The
two possible forms of conditional subpattern are
(?(condition)yes-pattern)
(?(condition)yes-pattern|no-pattern)
If the condition is satisfied, the yes-pattern is used; oth-
erwise the no-pattern (if present) is used. If there are
more than two alternatives in the subpattern, a compile-time
error occurs.
There are two kinds of condition. If the text between the
parentheses consists of a sequence of digits, then the con-
dition is satisfied if the capturing subpattern of that
number has previously matched. Consider the following pat-
tern, which contains non-significant white space to make it
more readable (assume the PCRE_EXTENDED option) and to
divide it into three parts for ease of discussion:
( \( )? [^()]+ (?(1) \) )
The first part matches an optional opening parenthesis, and
if that character is present, sets it as the first captured
substring. The second part matches one or more characters
that are not parentheses. The third part is a conditional
subpattern that tests whether the first set of parentheses
matched or not. If they did, that is, if subject started
with an opening parenthesis, the condition is true, and so
the yes-pattern is executed and a closing parenthesis is
required. Otherwise, since no-pattern is not present, the
subpattern matches nothing. In other words, this pattern
matches a sequence of non-parentheses, optionally enclosed
in parentheses.
If the condition is not a sequence of digits, it must be an
assertion. This may be a positive or negative lookahead or
lookbehind assertion. Consider this pattern, again contain-
ing non-significant white space, and with the two alterna-
tives on the second line:
(?(?=[^a-z]*[a-z])
\d{2}[a-z]{3}-\d{2} | \d{2}-\d{2}-\d{2} )
The condition is a positive lookahead assertion that matches
an optional sequence of non-letters followed by a letter. In
other words, it tests for the presence of at least one
letter in the subject. If a letter is found, the subject is
matched against the first alternative; otherwise it is
matched against the second. This pattern matches strings in
one of the two forms dd-aaa-dd or dd-dd-dd, where aaa are
letters and dd are digits.
COMMENTS
The sequence (?# marks the start of a comment which
continues up to the next closing parenthesis. Nested
parentheses are not permitted. The characters that make up a
comment play no part in the pattern matching at all.
If the PCRE_EXTENDED option is set, an unescaped # character
outside a character class introduces a comment that contin-
ues up to the next newline character in the pattern.
PERFORMANCE
Certain items that may appear in patterns are more efficient
than others. It is more efficient to use a character class
like [aeiou] than a set of alternatives such as (a|e|i|o|u).
In general, the simplest construction that provides the
required behaviour is usually the most efficient. Jeffrey
Friedl's book contains a lot of discussion about optimizing
regular expressions for efficient performance.
When a pattern begins with .* and the PCRE_DOTALL option is
set, the pattern is implicitly anchored by PCRE, since it
can match only at the start of a subject string. However, if
PCRE_DOTALL is not set, PCRE cannot make this optimization,
because the . metacharacter does not then match a newline,
and if the subject string contains newlines, the pattern may
match from the character immediately following one of them
instead of from the very start. For example, the pattern
(.*) second
matches the subject "first\nand second" (where \n stands for
a newline character) with the first captured substring being
"and". In order to do this, PCRE has to retry the match
starting after every newline in the subject.
If you are using such a pattern with subject strings that do
not contain newlines, the best performance is obtained by
setting PCRE_DOTALL, or starting the pattern with ^.* to
indicate explicit anchoring. That saves PCRE from having to
scan along the subject looking for a newline to restart at.
error_log -- 에러 메세지를 지정한 곳에 보낸다.
int error_log
(string message, int message_type, string [destination], string [extra_headers]);
Sends an error message to the web server's error log, a TCP port or to a file. The first parameter, message, is the error message that should be logged. The second parameter, message_type says where the message should go:
Table 1. error_log() log types
0 |
message is sent to PHP's system logger, using the Operating System's system logging mechanism or a file, depending on what the error_log configuration directive is set to. |
1 |
message is sent by email to the address in the destination parameter. This is the only message type where the fourth parameter, extra_headers is used. This message type uses the same internal function as Mail() does. |
2 |
message is sent through the PHP debugging connection. This option is only available if remote debugging has been enabled. In this case, the destination parameter specifies the host name or IP address and optionally, port number, of the socket receiving the debug information. |
3 |
message is appended to the file destination. |
Example 1. error_log() examples // Send notification through the server log if we can not // connect to the database. if (!Ora_Logon($username, $password)) { error_log("Oracle database not available!", 0); } // Notify administrator by email if we run out of FOO if (!($foo = allocate_new_foo()) { error_log("Big trouble, we're all out of FOOs!", 1, "operator@mydomain.com"); } // other ways of calling error_log(): error_log("You messed up!", 2, "127.0.0.1:7000"); error_log("You messed up!", 2, "loghost"); error_log("You messed up!", 3, "/var/tmp/my-errors.log"); |
error_reporting -- report 될 PHP 에러들을 정한다.
int error_reporting
(int [level]);
Sets PHP's error reporting level and returns the old level. The error reporting level is a bitmask of the following values (follow the links for the internal values to get their meanings):
Table 1. error_reporting() bit values
value |
internal name |
---|---|
1 |
|
2 |
|
4 |
|
8 |
|
16 |
|
32 |
extension_loaded -- 어떤 extension이 load되어 있는지 알려준다.
bool extension_loaded
(string name);
Returns true if the extension identified by name is loaded. You can see the names of various extensions by using phpinfo().
See also phpinfo().
Note: This function was added in 3.0.10.
getenv -- 환경 변수(environment variable)의 값을 구한다.
string getenv
(string varname);
Returns the value of the environment variable varname, or false on an error.
$ip = getenv("REMOTE_ADDR"); // get the ip number from the user
get_cfg_var -- PHP 설정 옵션(configuration option)의 값을 구한다.
string get_cfg_var
(string varname);
Returns the current value of the PHP configuration variable specified by varname, or false if an error occurs.
It will not return configuration information set when the PHP was compiled, or read from an Apache configuration file (using the php3_configuration_option directives).
To check whether the system is using a php3.ini file, try retrieving the value of the cfg_file_path configuration setting. If this is available, a php3.ini file is being used.
get_current_user -- 현 PHP script의 owner 이름을 구한다.
string get_current_user(void);
Returns the name of the owner of the current PHP script.
See also getmyuid(), getmypid(), getmyinode(), and getlastmod().
get_magic_quotes_gpc -- magic quotes gpc의 현재 설정 상태를 얻는다.
long get_magic_quotes_gpc
(void);
Returns the current active configuration setting of magic_quotes_gpc. (0 for off, 1 for on)
See also get_magic_quotes_runtime(), set_magic_quotes_runtime().
get_magic_quotes_runtime -- magic_quotes_runtime의 현재 설정 상태를 얻는다.
long get_magic_quotes_runtime
(void);
Returns the current active configuration setting of magic_quotes_runtime. (0 for off, 1 for on)
See also get_magic_quotes_gpc(), set_magic_quotes_runtime().
getlastmod -- 현 문서를 마지막으로 수정한 시간을 구한다.
int getlastmod(void);
Returns the time of the last modification of the current page. The value returned is a Unix timestamp, suitable for feeding to date(). Returns false on error.
Example 1. getlastmod() example // outputs e.g. 'Last modified: March 04 1998 20:43:59.' echo "Last modified: ".date( "F d Y H:i:s.", getlastmod() ); |
See alse date(), getmyuid(), get_current_user(), getmyinode(), and getmypid().
getmyinode -- 현 script의 inode를 구한다.
int getmyinode(void);
Returns the current script's inode, or false on error.
See also getmyuid(), get_current_user(), getmypid(), and getlastmod().
getmypid -- PHP의 process ID를 구한다.
int getmypid(void);
Returns the current PHP process ID, or false on error.
Note that when running as a server module, separate invocations of the script are not guaranteed to have distinct pids.
See also getmyuid(), get_current_user(), getmyinode(), and getlastmod().
getmyuid -- PHP script의 owner의 UID 값을 구한다..
int getmyuid(void);
Returns the user ID of the current script, or false on error.
See also getmypid(), get_current_user(), getmyinode(), and getlastmod().
getrusage -- 현재 자원의 사용 현황을 얻는다.
array getrusage
(int [who]);
This is an interface to getrusage(2). It returns an associative array containing the data returned from the system call. If who is 1, getrusage will be called with RUSAGE_CHILDREN. All entries are accessible by using their documented field names.
Example 1. Getrusage Example $dat = getrusage(); echo $dat["ru_nswap"]; # number of swaps echo $dat["ru_majflt"]; # number of page faults echo $dat["ru_utime.tv_sec"]; # user time used (seconds) echo $dat["ru_utime.tv_usec"]; # user time used (microseconds) |
See your system's man page for more details.
phpinfo -- 여러가지의 PHP information을 출력한다.
int phpinfo(void);
Outputs a large amount of information about the current state of PHP. This includes information about PHP compilation options and extensions, the PHP version, server information and environment (if compiled as a module), the PHP environment, OS version information, paths, master and local values of configuration options, HTTP headers, and the GNU Public License.
See also phpversion().
phpversion -- 현 PHP version을 구한다.
string phpversion(void);
Returns a string containing the version of the currently running PHP parser.
Example 1. phpversion() example // prints e.g. 'Current PHP version: 3.0rel-dev' echo "Current PHP version: ".phpversion(); |
See also phpinfo().
(PHP4 >= 4.0b4)
php_logo_guid -- logo guid를 얻는다.string php_logo_guid
(void)
Note: This funcionality was added in PHP4 Beta 4.
putenv -- 환경 변수(environment variable)의 값을 설정한다.
void putenv
(string
setting)
Adds setting to the environment.
Example 1. Setting an Environment Variable
|
set_magic_quotes_runtime -- Set the current active configuration setting of magic_quotes_runtime.
long set_magic_quotes_runtime
(int new_setting);
Set the current active configuration setting of magic_quotes_runtime. (0 for off, 1 for on)
See also get_magic_quotes_gpc(), get_magic_quotes_runtime().
set_time_limit -- 실행에 걸리는 시간을 한정시킨다. (limit the maximum execution time)
void set_time_limit
(int seconds);
Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in php3.ini. If seconds is set to zero, no time limit is imposed.
When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit( 20 ) is made, the script will run for a total of 45 seconds before timing out.
(PHP4 >= 4.0b4)
zend_logo_guid -- zend guid를 얻는다.string zend_logo_guid
(void)
Note: This funcionality was added in PHP4 Beta 4.
이 모듈은 IEEE 1003.1 (POSIX.1) 표준 문서에 정의되어 있는 함수중에 다른 방법으로는 지원되지 않는 함수에 대한 인터페이스를 포함한다. 예를들어 POSIX.1에는 open(), read(), write(), close() 등의 함수가 포함되어 있느나 이 함수들은 PHP3에서 이전부터 지원하던 것이므로 이 모듈에 포함되지 않는다. 이전에는 시스템에 관련된 많은 함수를 사용하지 못하였으나, 이 모듈은 이 함수들을 쉽게 사용할 수 있도록 도와줄 것이다.
posix_kill -- 특정 프로세스에 신호(signal)을 준다.
bool posix_kill
(int pid, int sig);
Send the signal sig to the process with the process identifier pid. Returns FALSE, if unable to send the signal, TRUE otherwise.
See also the kill(2) manual page of your POSIX system, which contains additional information about negative process identifiers, the special pid 0, the special pid -1, and the signal number 0.
posix_getpid -- 현재 프로세스의 ID를 반환한다.
int posix_getpid
(void );
Return the process identifier of the current process.
posix_getppid -- 부모 프로세스의 ID를 반환한다.
int posix_getppid
(void );
Return the process identifier of the parent process of the current process.
posix_getuid -- 현재 프로세스의 real user ID를 반환한다.
int posix_getuid
(void );
Return the numeric real user ID of the current process. See also posix_getpwuid() for information on how to convert this into a useable username.
posix_geteuid -- 현재 프로세스의 effective user ID를 반환한다.
int posix_geteuid
(void );
Return the numeric effective user ID of the current process. See also posix_getpwuid() for information on how to convert this into a useable username.
posix_getgid -- 현재 프로세스의 real group ID를 반환한다.
int posix_getgid
(void );
Return the numeric real group ID of the current process. See also posix_getgrgid() for information on how to convert this into a useable group name.
posix_getegid -- 현재 프로세스의 effective group ID를 반환한다.
int posix_getegid
(void );
Return the numeric effective group ID of the current process. See also posix_getgrgid() for information on how to convert this into a useable group name.
posix_setuid -- 현재 프로세스의 effective UID를 새로 설정한다.
bool posix_setuid
(int uid);
Set the real user ID of the current process. This is a privileged function and you need appropriate privileges (usually root) on your system to be able to perform this function.
Returns TRUE on success, FALSE otherwise. See also posix_setgid().
posix_setgid -- 현재 프로세스의 effective GID를 새로 설정한다.
bool posix_setgid
(int gid);
Set the real group ID of the current process. This is a privileged function and you need appropriate privileges (usually root) on your system to be able to perform this function. The appropriate order of function calls is posix_setgid() first, posix_setuid() last.
Returns TRUE on success, FALSE otherwise.
posix_getgroups -- 현재 프로세스의 group set을 반환한다.
array posix_getgroups
(void );
Returns an array of integers containing the numeric group ids of the group set of the current process. See also posix_getgrgid() for information on how to convert this into useable group names.
posix_getlogin -- login name을 반환한다.
string posix_getlogin
(void );
Returns the login name of the user owning the current process. See posix_getpwnam() for information how to get more information about this user.
posix_getpgrp -- 현재 프로세스의 group ID를 반환한다.
int posix_getpgrp
(void );
Return the process group identifier of the current process. See POSIX.1 and the getpgrp(2) manual page on your POSIX system for more information on process groups.
posix_setsid -- 현재 프로세스를 session leader로 만든다.
int posix_setsid
(void );
Make the current process a session leader. See POSIX.1 and the setsid(2) manual page on your POSIX system for more informations on process groups and job control. Returns the session id.
posix_setpgid -- 특정 프로세스에 프로세스 group ID를 설정한다.
int posix_setpgid
(int pid, int pgid);
Let the process pid join the process group pgid. See POSIX.1 and the setsid(2) manual page on your POSIX system for more informations on process groups and job control. Returns TRUE on success, FALSE
posix_getpgid -- 특정 프로세스의 프로세스 group ID를 얻는다.
int posix_getpgid
(int pid);
Returns the process group identifier of the process pid.
This is not a POSIX function, but is common on BSD and System V systems. If your system does not support this function at system level, this PHP function will always return FALSE.
posix_getsid -- 특정프로세스의 현재 sid를 얻는다.
int posix_getsid
(int pid);
Return the sid of the process pid. If pid is 0, the sid of the current process is returned.
This is not a POSIX function, but is common on System V systems. If your system does not support this function at system level, this PHP function will always return FALSE.
posix_uname -- system name을 얻는다.
array posix_uname
(void );
Returns a hash of strings with information about the system. The indices of the hash are
Posix requires that you must not make any assumptions about the format of the values, e.g. you cannot rely on three digit version numbers or anything else returned by this function.
posix_times -- process times을 얻는다.
array posix_times
(void );
Returns a hash of strings with information about the current process CPU usage. The indices of the hash are
posix_ctermid -- controlling terminal의 path 이름을 얻는다.
string posix_ctermid
(void );
Needs to be written.
posix_ttyname -- 지정된 파일 descriptor의 terminal 장치(device) 이름을 결정한다.
string posix_ttyname
(int fd);
Needs to be written.
posix_isatty -- 지정된 파일 descriptor가 interactive terminal 인가 결정한다.
bool posix_isatty
(int fd);
Needs to be written.
posix_getcwd -- 현재 디렉토리의 Pathname
string posix_getcwd
(void );
Needs to be written ASAP
posix_mkfifo -- fifo special file (a named pipe)을 만든다.
bool posix_getcwd
(string pathname, int mode);
Needs to be written ASAP..
posix_getgrnam -- 그룹명을 사용하여 그룹에 대한 정보를 가져온다.
array posix_getgrnam
(string name);
Needs to be written.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
posix_getgrgid -- 그룹 ID를 사용하여 그룹에 대한 정보를 가져온다.array posix_getgrgid
(int gid)
Needs to be written.
posix_getpwnam -- 사용자명을 사용하여 사용자에 대한 정보를 가져온다.
array posix_getpwnam
(string username);
Returns an associative array containing information about a user referenced by an alphanumeric username, passed in the username parameter.
The array elements returned are:
Table 1. The user information array
Element | Description |
---|---|
name | The name element contains the username of the user. This is a short, usually less than 16 character "handle" of the user, not her real, full name. This should be the same as the username parameter used when calling the function, and hence redundant. |
passwd | The passwd element contains the user's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead. |
uid | User ID of the user in numeric form. |
gid | The group ID of the user. Use the function posix_getgrgid() to resolve the group name and a list of its members. |
gecos | GECOS is an obsolete term that refers to the finger information field on a Honeywell batch processing system. The field, however, lives on, and its contents have been formalized by POSIX. The field contains a comma separated list containing the user's full name, office phone, office number, and home phone number. On most systems, only the user's full name is available. |
dir | This element contains the absolute path to the home directory of the user. |
shell | The shell element contains the absolute path to the executable of the user's default shell. |
posix_getpwuid -- 사용자 ID를 사용하여 사용자에 대한 정보를 가져온다.
array posix_getpwuid
(int uid);
Returns an associative array containing information about a user referenced by a numeric user ID, passed in the uid parameter.
The array elements returned are:
Table 1. The user information array
Element | Description |
---|---|
name | The name element contains the username of the user. This is a short, usually less than 16 character "handle" of the user, not her real, full name. |
passwd | The passwd element contains the user's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead. |
uid | User ID, should be the same as the uid parameter used when calling the function, and hence redundant. |
gid | The group ID of the user. Use the function posix_getgrgid() to resolve the group name and a list of its members. |
gecos | GECOS is an obsolete term that refers to the finger information field on a Honeywell batch processing system. The field, however, lives on, and its contents have been formalized by POSIX. The field contains a comma separated list containing the user's full name, office phone, office number, and home phone number. On most systems, only the user's full name is available. |
dir | This element contains the absolute path to the home directory of the user. |
shell | The shell element contains the absolute path to the executable of the user's default shell. |
posix_getrlimit -- system 자원의 limit에 대한 정보를 반환한다.
array posix_getrlimit
(void );
Needs to be written ASAP.
UC Berkeley Computer Science Department에서 처음 개발된 Postgres는 이제는 일부 상용 database에서 가능한 object-relational 개념의 많은 것을 개척하였다. 이것은 SQL92/SQL3 언어를 지원하고, transaction integrity와 type 확장가능성을 제공한다. PostgreSQL은 public-domain이고, original Berkeley code의 발전된 소스를 제공한다.
PostgreSQL은 무료로 사용가능하다. 현재 버젼은 6.3.3까지 나와있고, www.postgreSQL.org에서 찾을 수 있다.
version 6.3 (03/02/1998)이후로 PostgreSQL은 unix domain socket을 사용하고, 이 기능을 위해 table이 주어진다. 이 소켓은 /tmp/.s.PGSQL.5432에서 찾을 수 있다. 이 옵션은 postmaster에 '-i' flag를 주어서 enable시킬 수 있는데, 이것은 "TCP/IP sockets뿐 아니라 Unix domain socket의 요청도 받아들여라."는 의미이다.
Table 1. Postmaster and PHP
Postmaster |
PHP |
Status |
---|---|---|
postmaster & |
pg_connect("", "", "", "", "dbname"); |
OK |
postmaster -i & |
pg_connect("", "", "", "", "dbname"); |
OK |
postmaster & |
pg_connect("localhost", "", "", "", "dbname"); |
PostgreSQL server에 연결할 수 없음: connectDB() failed: Is the postmaster running and accepting TCP/IP (with -i) connection at 'localhost' on port '5432'? in /path/to/file.php3 on line 20. |
postmaster -i & |
pg_connect("localhost", "", "", "", "dbname"); |
OK |
다음과 같은 하나의 파라메터만으로도 연결을 설정할 수 있다. : $conn = pg_Connect("host=localhost port=5432 dbname=chris");
large object (lo) interface를 사용하려면 transaction block으로 둘러 싸는 것이 필요하다. transaction block은 begin으로 시작하고, transaction이확실하다면 commit이나 end로 끝낸다. 만약 transaction이 오류가있거나 실패하면 transaction block은 abort나 rollback으로 끝내야 할 것이다.
Example 1. Using Large Objects
|
Table of Contents
pg_Close -- PostgreSQL connection을 닫는다.
void pg_close(int connection);
Returns false if connection is not a valid connection index, true otherwise. Closes down the connection to a PostgreSQL database associated with the given connection index.
pg_cmdTuples -- 해당하는 tuple의 개수를 구한다.
int pg_cmdtuples(int result_id);
pg_cmdTuples() returns the number of tuples (instances) affected by INSERT, UPDATE, and DELETE queries. If no tuple is affected the function will return 0.
Example 1. pg_cmdtuples <?php $result = pg_exec($conn, "INSERT INTO verlag VALUES ('Autor')"); $cmdtuples = pg_cmdtuples($result); echo $cmdtuples . " <- cmdtuples affected."; ?> |
pg_Connect -- connection을 연다.
int pg_connect(string host, string port, string options, string tty, string dbname);
Returns a connection index on success, or false if the connection could not be made. Opens a connection to a PostgreSQL database. Each of the arguments should be a quoted string, including the port number. The options and tty arguments are optional and can be left out. This function returns a connection index that is needed by other PostgreSQL functions. You can have multiple connections open at once.
A connection can also established with the following command: $conn = pg_connect("dbname=marliese port=5432"); Other parameters besides dbname and port are host, tty and options.
See also pg_pConnect().
pg_DBname -- database 이름
string pg_dbname(int connection);
Returns the name of the database that the given PostgreSQL connection index is connected to, or false if connection is not a valid connection index.
pg_ErrorMessage -- 에러 메세지
string pg_errormessage(int connection);
Returns a string containing the error message, false on failure. Details about the error probably cannot be retrieved using the pg_errormessage() function if an error occured on the last database action for which a valid connection exists, this function will return a string containing the error message generated by the backend server.
pg_Exec -- 질의를 실행한다.
int pg_exec(int connection, string query);
Returns a result index if query could be executed, false on failure or if connection is not a valid connection index. Details about the error can be retrieved using the pg_ErrorMessage() function if connection is valid. Sends an SQL statement to the PostgreSQL database specified by the connection index. The connection must be a valid index that was returned by pg_Connect(). The return value of this function is an index to be used to access the results from other PostgreSQL functions.
Note: PHP/FI returned 1 if the query was not expected to return data (inserts or updates, for example) and greater than 1 even on selects that did not return anything. No such assumption can be made in PHP.
pg_Fetch_Array -- row를 배열로 가져온다.
array pg_fetch_array
(int result, int row, int [result_type] );
Returns: An array that corresponds to the fetched row, or false if there are no more rows.
pg_fetch_array() is an extended version of pg_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.
The third optional argument result_type in pg_fetch_array() is a constant and can take the following values: PGSQL_ASSOC, PGSQL_NUM, and PGSQL_BOTH.
Note: Result_type was added in PHP 4.0.
An important thing to note is that using pg_fetch_array() is NOT significantly slower than using pg_fetch_row(), while it provides a significant added value.
For further details, also see pg_fetch_row()
Example 1. PostgreSQL fetch array <?php $conn = pg_pconnect("","","","","publisher"); if (!$conn) { echo "An error occured.\n"; exit; } $result = pg_Exec ($conn, "SELECT * FROM authors"); if (!$result) { echo "An error occured.\n"; exit; } $arr = pg_fetch_array ($result, 0); echo $arr[0] . " <- array\n"; $arr = pg_fetch_array ($result, 1); echo $arr["author"] . " <- array\n"; ?> |
pg_Fetch_Object -- row를 object로 가져온다.
object pg_fetch_object
(int result, int row, int [result_type] );
Returns: An object with properties that correspond to the fetched row, or false if there are no more rows.
pg_fetch_object() is similar to pg_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).
The third optional argument result_type in pg_fetch_object() is a constant and can take the following values: PGSQL_ASSOC, PGSQL_NUM, and PGSQL_BOTH.
Note: Result_type was added in PHP 4.0.
Speed-wise, the function is identical to pg_fetch_array(), and almost as quick as pg_fetch_row() (the difference is insignificant).
See also: pg_fetch_array() and pg_fetch_row().
Example 1. Postgres fetch object <?php $database = "verlag"; $db_conn = pg_connect ("localhost", "5432", "", "", $database); if (!$db_conn): ?> <H1>Failed connecting to postgres database <? echo $database ?></H1> <? exit; endif; $qu = pg_exec ($db_conn, "SELECT * FROM verlag ORDER BY autor"); $row = 0; // postgres needs a row counter other dbs might not while ($data = pg_fetch_object ($qu, $row)): echo $data->autor." ("; echo $data->jahr ."): "; echo $data->titel."<BR>"; $row++; endwhile; ?> <PRE><?php $fields[] = Array ("autor", "Author"); $fields[] = Array ("jahr", " Year"); $fields[] = Array ("titel", " Title"); $row= 0; // postgres needs a row counter other dbs might not while ($data = pg_fetch_object ($qu, $row)): echo "----------\n"; reset ($fields); while (list (,$item) = each ($fields)): echo $item[1].": ".$data->$item[0]."\n"; endwhile; $row++; endwhile; echo "----------\n"; ?> </PRE> <?php pg_freeResult ($qu); pg_close ($db_conn); ?> |
pg_Fetch_Row -- row를 배열(enumerated array)로 가져온다.
array pg_fetch_row
(int result, int row);
Returns: An array that corresponds to the fetched row, or false if there are no more rows.
pg_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
Subsequent call to pg_fetch_row() would return the next row in the result set, or false if there are no more rows.
See also: pg_fetch_array(), pg_fetch_object(), pg_result().
Example 1. Postgres fetch row <?php $conn = pg_pconnect("","","","","publisher"); if (!$conn) { echo "An error occured.\n"; exit; } $result = pg_Exec ($conn, "SELECT * FROM authors"); if (!$result) { echo "An error occured.\n"; exit; } $row = pg_fetch_row ($result, 0); echo $row[0] . " <- row\n"; $row = pg_fetch_row ($result, 1); echo $row[0] . " <- row\n"; $row = pg_fetch_row ($result, 2); echo $row[1] . " <- row\n"; ?> |
pg_FieldIsNull -- field가 NULL인가 검사한다.
int pg_fieldisnull(int result_id, int row, mixed field);
Test if a field is NULL or not. Returns 0 if the field in the given row is not NULL. Returns 1 if the field in the given row is NULL. Field can be specified as number or fieldname. Row numbering starts at 0.
pg_FieldName -- field의 이름을 반환한다.
string pg_fieldname(int result_id, int field_number);
pg_FieldName() will return the name of the field occupying the given column number in the given PostgreSQL result identifier. Field numbering starts from 0.
pg_FieldNum -- column의 개수를 반환한다.
string pg_fieldnum(int result_id, int field_name);
pg_FieldNum() will return the number of the column slot that corresponds to the named field in the given PosgreSQL result identifier. Field numbering starts at 0. This function will return -1 on error.
pg_FieldPrtLen -- 프린드될 길이(문자 개수)를 구한다.
int pg_fieldprtlen(int result_id, int row_number, string field_name);
pg_FieldPrtLen() will return the actual printed length (number of characters) of a specific value in a PostgreSQL result. Row numbering starts at 0. This function will return -1 on an error.
pg_FieldSize -- 지정된 field의 저장을 위해 할당된 공간(internal storage)의 크기
int pg_fieldsize
(int result_id, string field_name);
pg_FieldSize() will return the internal storage size (in bytes) of the named field in the given PostgreSQL result. A field size of -1 indicates a variable length field. This function will return false on error.
pg_FieldType -- 해당 필드 번호에 대응하는 type이름을 반환한다.
int pg_fieldtype(int result_id, int field_number);
pg_FieldType() will return a string containing the type name of the given field in the given PostgreSQL result identifier. Field numbering starts at 0.
pg_FreeResult -- result memory를 해제한다.
int pg_freeresult
(int result_id);
pg_FreeResult() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script is finished. But, if you are sure you are not going to need the result data anymore in a script, you may call pg_FreeResult() with the result identifier as an argument and the associated result memory will be freed.
pg_GetLastOid -- 최근의 object identifier를 반환한다.
int pg_getlastoid
(int result_id);
pg_GetLastOid() can be used to retrieve the Oid assigned to an inserted tuple if the result identifier is used from the last command sent via pg_Exec() and was an SQL INSERT. This function will return a positive integer if there was a valid Oid. It will return -1 if an error occured or the last command sent via pg_Exec() was not an INSERT.
pg_Host -- host 이름을 반환한다.
string pg_host(int connection_id);
pg_Host() will return the host name of the given PostgreSQL connection identifier is connected to.
pg_loclose -- large object를 닫는다.
void pg_loclose(int fd);
pg_loclose() closes an Inversion Large Object. fd is a file descriptor for the large object from pg_loopen().
pg_locreate -- large object를 생성한다.
int pg_locreate(int conn);
pg_locreate() creates an Inversion Large Object and returns the oid of the large object. conn specifies a valid database connection. PostgreSQL access modes INV_READ, INV_WRITE, and INV_ARCHIVE are not supported, the object is created always with both read and write access. INV_ARCHIVE has been removed from PostgreSQL itself (version 6.3 and above).
void pg_loexport
(int
oid, int file [, int connection_id])
The oid argument specifies the object id of the large object to export and the filename argument specifies the pathname of the file. Returns FALSE if an error occurred, TRUE otherwise. Remember that handling large objects in PostgreSQL must happen inside a transaction.
void pg_loimport
(int
file [, int connection_id])
The filename argument specifies the pathname of the file to be imported as a large object. Returns FALSE if an error occurred, object id of the just created large object otherwise. Remember that handling large objects in PostgreSQL must happen inside a transaction.
pg_loopen -- large object를 연다.
int pg_loopen(int conn, int objoid, string mode);
pg_loopen() open an Inversion Large Object and returns file descriptor of the large object. The file descriptor encapsulates information about the connection. Do not close the connection before closing the large object file descriptor. objoid specifies a valid large object oid and mode can be either "r", "w", or "rw".
pg_loread -- large object를 읽는다.
string pg_loread
(int fd, int len);
pg_loread() reads at most len bytes from a large object and returns it as a string. fd specifies a valid large object file descriptor andlen specifies the maximum allowable size of the large object segment.
pg_loreadall -- large object 전체를 읽는다.
void pg_loreadall(int fd);
pg_loreadall() reads a large object and passes it straight through to the browser after sending all pending headers. Mainly intended for sending binary data like images or sound.
pg_lounlink -- large object를 지운다.
void pg_lounlink(int conn, int lobjid);
pg_lounlink() deletes a large object with the lobjid identifier for that large object.
pg_lowrite -- large object에 쓴다.
int pg_lowrite
(int fd, string buf);
pg_lowrite() writes at most to a large object from a variable buf and returns the number of bytes actually written, or false in the case of an error. fd is a file descriptor for the large object from pg_loopen().
pg_NumFields -- field의 개수를 반환한다.
int pg_numfields(int result_id);
pg_NumFields() will return the number of fields (columns) in a PostgreSQL result. The argument is a valid result identifier returned by pg_Exec(). This function will return -1 on error.
pg_NumRows -- row의 개수를 반환한다.
int pg_numrows
(int result_id);
pg_NumRows() will return the number of rows in a PostgreSQL result. The argument is a valid result identifier returned by pg_Exec(). This function will return -1 on error.
pg_Options -- option들을 반환한다.
string pg_options(int connection_id);
pg_Options() will return a string containing the options specified on the given PostgreSQL connection identifier.
pg_pConnect -- 영구적인 database connection을 만든다.
int pg_pconnect
(string host, string port, string options, string tty, string dbname);
Returns a connection index on success, or false if the connection could not be made. Opens a persistent connection to a PostgreSQL database. Each of the arguments should be a quoted string, including the port number. The options and tty arguments are optional and can be left out. This function returns a connection index that is needed by other PostgreSQL functions. You can have multiple persistent connections open at once. See also pg_Connect().
A connection can also established with the following command: $conn = pg_pconnect("dbname=marliese port=5432"); Other parameters besides dbname and port are host, tty and options.
pg_Port -- port 번호를 반환한다.
int pg_port(int connection_id);
pg_Port() will return the port number that the given PostgreSQL connection identifier is connected to.
pg_Result -- result identifier로 부터 값들을 구한다.
mixed pg_result(int result_id, int row_number, mixed fieldname);
pg_Result() will return values from a result identifier produced by pg_Exec(). The row_number and fieldname sepcify what cell in the table of results to return. Row numbering starts from 0. Instead of naming the field, you may use the field index as an unquoted number. Field indices start from 0.
PostgreSQL has many built in types and only the basic ones are directly supported here. All forms of integer, boolean and oid types are returned as integer values. All forms of float, and real types are returned as double values. All other types, including arrays are returned as strings formatted in the same default PostgreSQL manner that you would see in the psql program.
bool pg_trace
(string
filename [, string mode [, int connection]])
Enables tracing of the PostgreSQL frontend/backend communication to a debugging file. To fully understand the results one needs to be familiar with the internals of PostgreSQL communication protocol. For those who are not, it can still be useful for tracing errors in queries sent to the server, you could do for example 'grep '^To backend' trace.log' and see what queriew actually were sent to the PostgreSQL server.
filename and mode are the same as in fopen() (mode defaults to 'w'), connection specifies the connection to trace and defaults to the last one opened.
Returns TRUE if filename could be opened for logging, FALSE otherwise.
See also fopen() and pg_untrace().
pg_tty -- tty 이름을 반환한다.
string pg_tty(int connection_id);
pg_tty() will return the tty name that server side debugging output is sent to on the given PostgreSQL connection identifier.
bool pg_untrace
([int
connection])
Stop tracing started by pg_trace(). connection specifies the connection that was traced and defaults to the last one opened.
Returns always TRUE.
See also pg_trace().
escapeshellcmd -- shell의 metacharacter들을 escape한 다.
string escapeshellcmd
(string
command)EscapeShellCmd() escapes any characters in a string that might be used to trick a shell command into executing arbitrary commands. This function should be used to make sure that any data coming from user input is escaped before this data is passed to the exec() or system() functions. A standard use would be:
1 2 system(EscapeShellCmd($cmd)) 3 |
See also exec(), popen(), system(), and the backtick operator.
exec -- 외부 program을 실행한다.
string exec
(string command [,
string array [, int return_var]])Exec executes the given command, however it does not output anything. It simply returns the last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the PassThru() function.
If the array argument is present, then the specified array will be filled with every line of output from the command. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().
If the return_var argument is present along with the array argument, then the return status of the executed command will be written to this variable.
Note that if you are going to allow data coming from user input to be passed to this function, then you should be using EscapeShellCmd() to make sure that users cannot trick the system into executing arbitrary commands.
Note also that if you start a program using this function and want to leave it running in the background, you have to make sure that the output of that program is redirected to a file or some other output stream or else PHP will hang until the execution of the program ends.
See also system(), PassThru(), popen(), EscapeShellCmd(), and the backtick operator.
passthru -- 외부 프로그램을 실행하고 그 결과를 직접 (지체없이) 출력한다.
void passthru
(string command
[, int return_var])The passthru() function is similar to the Exec() function in that it executes a command. If the return_var argument is present, the return status of the Unix command will be placed here. This function should be used in place of Exec() or System() when the output from the Unix command is binary data which needs to be passed directly back to the browser. A common use for this is to execute something like the pbmplus utilities that can output an image stream directly. By setting the content-type to image/gif and then calling a pbmplus program to output a gif, you can create PHP scripts that output images directly.
Note that if you start a program using this function and want to leave it running in the background, you have to make sure that the output of that program is redirected to a file or some other output stream or else PHP will hang until the execution of the program ends.See also exec(), system(), popen(), EscapeShellCmd(), and the backtick operator.
system -- 외부 program을 실행하고 그 결과를 출력한다.
string system
(string command
[, int return_var])System() is just like the C version of the function in that it executes the given command and outputs the result. If a variable is provided as the second argument, then the return status code of the executed command will be written to this variable.
Note, that if you are going to allow data coming from user input to be passed to this function, then you should be using the EscapeShellCmd() function to make sure that users cannot trick the system into executing arbitrary commands.
Note also that if you start a program using this function and want to leave it running in the background, you have to make sure that the output of that program is redirected to a file or some other output stream or else PHP will hang until the execution of the program ends.
The System() call also tries to automatically flush the web server's output buffer after each line of output if PHP is running as a server module.
Returns the last line of the command output on success, and false on failure.If you need to execute a command and have all the data from the command passed directly back without any interference, use the PassThru() function.
See also exec(), PassThru(), popen(), EscapeShellCmd(), and the backtick operator.
이 모듈은 GNU Recode 라이브러리(version 3.5)의 인터페이스를 포함한다. 이 모듈에 있는 함수를 사용하고자 한다면, PHP를 컴파일 할 때 --with-recode 옵션을 주고 컴파일하여야 한다. 이를 위해서는 당연히 시스템에 GNU Recode 3.5 이상이 설치되어 있어야 한다.
GNU Recode 라이브러리는 파일을 여러 가지 다른 character sets 과 surface encodings로 변환한다. 만약 이 변환이 정확하게 이루어질 수 없게 되면, 오류가 있는 문자로의 변환을 하지 않고, 최대한 비슷한 것으로 대체하게된다.이 라이브러리는 약 150가지의 서로 다른 character sets을 인식하고 만들어 낼 수 있고, 이들간의 대부분의 조합을 사용하여 변환이 가능하다. RFC 1345 character sets 거의 전부를 지원한다.
(PHP3 >= 3.0.13, PHP4 >= 4.0RC1)
recode_string -- recode 요구에 따라 문자열을 Recode한다.string recode_string
(string request, string string)
Recode the string string according to the recode request request. Returns FALSE, if unable to comply, TRUE otherwise.
A simple recode request may be "lat1..iso646-de". See also the GNU Recode documentation of your installation for detailed instructions about recode requests.
(PHP4 >= 4.0RC1)
recode -- recode 요구에 따라 문자열을 Recode한다.string recode_string
(string request, string string)
Note: This is an alias for recode_string(). It has been added in PHP4.
(PHP3 >= 3.0.13, PHP4 >= 4.0RC1)
recode_file -- recode 요구에 따라 파일을 Recode한다.bool recode_file
(int
input, int output)
Recode the file referenced by file handle input into the file referenced by file handle output according to the recode request. Returns FALSE, if unable to comply, TRUE otherwise.
This function does not currently process filehandles referencing remote files (URLs). Both filehandles must refer to local files.
Regular expression은 PHP에서 복잡한 문자열 조작을 위해 사용한다. regular expression을 지원하기 위해 다음의 함수가 사용된다. :
위의 함수들은 regular expression 문자열을 첫 인수(argument)로 가진다. PHP는 Posix 1003.2에서 정의된 Posix 확장 regular expression을 사용한다. Posix regular expressions에 대한 자세한 설명은 PHP distribution의 regex디렉토리에 있는 regex man page를 참조하기 바란다. 이것은 manpage 형태를 하고 있으므로 man /usr/local/src/regex/regex.7 과 같은 명령을 사용하여 읽을 수 있다.
Example 1. Regular expression examples
|
ereg -- regular expression 이 주어진 패턴에 맞는지 검사한다.
int ereg
(string pattern, string string, array [regs]);
Searchs string for matches to the regular expression given in pattern.
If matches are found for parenthesized substrings of pattern and the function is called with the third argument regs, the matches will be stored in the elements of regs. $regs[1] will contain the substring which starts at the first left parenthesis; $regs[2] will contain the substring starting at the second, and so on. $regs[0] will contain a copy of string.
Searching is case sensitive.
Returns true if a match for pattern was found in string, or false if no matches were found or an error occurred.
The following code snippet takes a date in ISO format (YYYY-MM-DD) and prints it in DD.MM.YYYY format:
Example 1. ereg() example if ( ereg( "([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $date, $regs ) ) { echo "$regs[3].$regs[2].$regs[1]"; } else { echo "Invalid date format: $date"; } |
See also eregi(), ereg_replace(), and eregi_replace().
ereg_replace -- regular expression의 문장을 대치한다.
string ereg_replace
(string pattern, string replacement, string string);
This function scans string for matches to pattern, then replaces the matched text with replacement.
The modified string is returned. (Which may mean that the original string is returned if there are no matches to be replaced.)
If pattern contains parenthesized substrings, replacement may contain substrings of the form \\digit, which will be replaced by the text matching the digit'th parenthesized substring; \\0 will produce the entire contents of string. Up to nine substrings may be used. Parentheses may be nested, in which case they are counted by the opening parenthesis.
If no matches are found in string, then string will be returned unchanged.
For example, the following code snippet prints "This was a test" three times:
Example 1. ereg_replace() example $string = "This is a test"; echo ereg_replace( " is", " was", $string ); echo ereg_replace( "( )is", "\\1was", $string ); echo ereg_replace( "(( )is)", "\\2was", $string ); |
See also ereg(), eregi(), and eregi_replace().
eregi -- regular expression 이 주어진 패턴에 맞는지 대,소문자 가리지 않고 검사한다.
int eregi
(string pattern, string string, array [regs]);
This function is identical to ereg() save that this ignores case distinction when matching alphabetic characters.
See also ereg(), ereg_replace(), and eregi_replace().
eregi_replace -- regular expression의 문장을 대,소문자 가리지 않고 대치한다.
string eregi_replace(string pattern, string replacement, string string);
This function is identical to ereg_replace() save that this ignores case distinction when matching alphabetic characters.
See also ereg(), eregi(), and ereg_replace().
split -- 문자열을 regular expression에 의해 나눈다.
array split
(string pattern, string string, int [limit]);
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by pattern. If an error occurs, returns false.
To get the first five fields from a line from /etc/passwd:
Example 1. split() example $passwd_list = split( ":", $passwd_line, 5 ); |
Note that pattern is case-sensitive.
See also explode() and implode().
sql_regcase -- 대,소문자 가리지 않는 검사를 위한 regular expression을 만든다.
string sql_regcase
(string string)
Returns a valid regular expression which will match string, ignoring case. This expression is string with each character converted to a bracket expression; this bracket expression contains that character's uppercase and lowercase form if applicable, otherwise it contains the original character twice.
Example 1. sql_regcase() example
|
prints
[Ff][Oo][Oo][ ][Bb][Aa][Rr] |
This can be used to achieve case insensitive pattern matching in products which support only case sensitive regular expressions.
이 모듈은 System V 세마포어를 사용하는 세마포어 함수를 제공한다. 세마포어는 보통 현재 컴퓨터의 자원(resources)에 대해 배타적으로 접근하거나, 한 자원에 동시에 사용 가능한 프로세스의 수를 제한 할 때 사용한다.
또한 이모듈은 System V 공유 메모리를 사용하는 공유 메모리 함수를 제공한다. 공유 메모리(Shared memory)는 전역 변수에 접근하기위해 사용된다. 다른점은 httpd-daemon이나 심지어 Perl이나 C로 작성된 다른 프로그램에서도 이 변수에 접근할 수 있으므로 광범위한 데이터 교환이 가능하다. 주의할 점은 공유 메모리는 동시에 두군데서 접근하는 것에 대해 절대로 안전하지 않다. 따라서 이를 방지하기위해 세마포어를 사용하여 동기화(synchronize)하여야 한다.
Table 1. Limits of shared memory by the Unix OS
SHMMAX |
max size of shared memory, normally 131072 bytes |
SHMMIN |
minimum size of shared memory, normally 1 byte |
SHMMNI |
max amount of shared memory segments, normally 100 |
SHMSEG |
max amount of shared memory per process, normally 6 |
sem_get -- semaphore id를 얻는다.
int sem_get
(int key [,
int max_acquire [, int perm]])
Returns: A positive semaphore identifier on success, or false on error.
Sem_get() returns an id that can be used to access the System V semaphore with the given key. The semaphore is created if necessary using the permission bits specified in perm (defaults to 0666). The number of processes that can acquire the semaphore simultaneously is set to max_acquire (defaults to 1). Actually this value is set only if the process finds it is the only process currently attached to the semaphore.
A second call to sem_get() for the same key will return a different semaphore identifier, but both identifiers access the same underlying semaphore.
See also: sem_acquire() and sem_release().
sem_acquire -- semaphore를 얻는다.
int sem_acquire
(int
sem_identifier)
Returns: true on success, false on error.
Sem_acquire() blocks (if necessary) until the semaphore can be acquired. A process attempting to acquire a semaphore which it has already acquired will block forever if acquiring the semaphore would cause its max_acquire value to be exceeded.
After processing a request, any semaphores acquired by the process but not explicitly released will be released automatically and a warning will be generated.
See also: sem_get() and sem_release().
sem_release -- semaphore를 풀어준다.
int sem_release
(int
sem_identifier)Returns: true on success, false on error
sem_release() releases the semaphore if it is currently acquired by the calling process, otherwise a warning is generated.
After releasing the semaphore, sem_acquire() may be called to re-acquire it.
See also: sem_get() and sem_acquire().
shm_attach -- 공유 메모리의 segment를 만들거나 연다.
int shm_attach
(int key
[, int memsize [, int perm]])
Shm_attach() returns an id that that can be used to access the System V shared memory with the given key, the first call creates the shared memory segment with mem_size (default: sysvshm.init_mem in the configuration file, otherwise 10000 bytes) and the optional perm-bits (default: 0666).
A second call to shm_attach() for the same key will return a different shared memory identifier, but both identifiers access the same underlying shared memory. Memsize and perm will be ignored.
shm_detach -- 공유 메모리 세그먼트와의 연결을 끊는다.
int shm_detach
(int
shm_identifier)shm_detach() disconnects from the shared memory given by the shm_identifier created by shm_attach(). Remember, that shared memory still exist in the Unix system and the data is still present.
shm_remove -- Unix 시스템에서 공유 메모리를 제거한다.
int shm_remove
(int shm_identifier);
Removes shared memory from Unix systems. All data will be destroyed.
shm_put_var -- 공유 메모리안에 변수를 삽입하거나 변수 값을 변경한다.
int shm_put_var
(int
shm_identifier, int variable_key, mixed variable)
Inserts or updates a variable with a given variable_key. All variable-types (double, int, string, array) are supported.
shm_get_var -- 공유 메모리의 변수를 반환한다.
mixed shm_get_var
(int
id, int variable_key)
Shm_get_var() returns the variable with a given variable_key. The variable is still present in the shared memory.
shm_remove_var -- 공유 메모리로부터 변수를 제거한다.
int shm_remove_var
(int
id, int variable_key)
Removes a variable with a given variable_key and frees the occupied memory.
PHP에서 지원하는 세션은 특정 데이터를 연이은 접속에서 사용할 수 있도록 저장하는 방법을 제공한다. 이것은 여러분에게 좀더 사용자에게 친근한 어플리케이션을 만들 수 있도록 해 주고, 여러분의 웹 사이트를 더욱 흥미롭게 만들 수 있게 해 준다.
만약 여러분이 PHPLIB의 세션 관리에 대해 잘 알고 있다면, 이것의 많은 개념들이 PHP의 세션 지원과 비슷하다는 것을 알 게 될 것이다.
여러분의 웹사이트를 방문한 방문자는 유일한 ID 하나를 배정받게 되는데, 이것이 세션 ID이다. 이 세션 ID는 사용자측에 쿠키로 저장될 수도 있고, URL의 일부로 붙어다닐 수도 있다.
세션은 서버에 대한 요구(request)들에 공통적으로 저장되고 사용될 여러개의 변수를 등록할 수 있게 해 준다. 방문자가 여러분의 사이트를 접근하면, PHP는 자동적으로(session.auto_start 가 1로 설정되어 있는 경우), 혹은 여러분의 요구가 있는 경우(이것만을 하는 session_start() 함수나, 이 기능도 포함하는 session_register() 함수를 사용) 해당 요구(request)와 함께 특정 세션 ID가 전송되었는가 여부를 판단한다. 이런 이유라면 이전에 저장되었던 환경으로 다시 복구된다.
이 요구(request) 동작이 끝나면 모든 등록한 변수들이 순서대로 나열된다. 정의되어(defined) 있지 않은 등록한(registered) 변수는 현재 등록되지 않았다고 표시된다. 연이은 접속에서, 이런 변수들은 사용자가 나중에 정의하지 않는 한 세션 모듈에 의해 정의되지는 않는다.
track_vars 와 gpc_globals 설정은 세션 변수들이 어떻게 복구되는가에 영향을 준다. track_vars이 enable 되어있으면, 저장된 세션 변수들을 $HTTP_STATE_VARS라는 전역 associative 배열을 사용하여 접근할 수 있다. gpc_globals가 enable 되어 있으면, 세션 변수들은 각각의 전역 변수로 복원된다. 두가지 모두 설정되어 있으면, 전역변수와 $HTTP_STATE_VARS 모두에 같은 값으로 복원된다.
세션 ID를 전달하는 방법은 다음 두가지가 있다. :
세션 모듈은 두가지 방법 모두를 지원한다. 쿠키가 좀더 이상적인 방법이기는 해도, 사용자의 브라우저가 쿠키를 지원하지 않을 수도 있고, 쿠키 데이터를 받아들인다는 보장이 없기 때문에 신뢰성이 떨어진다. 두 번째 방법은 세션 ID를 URL에 직접 포함시키는 방법이다.
PHP는 --enable-trans-sid 옵션을 주어 컴파일 하면 이 기능을 자동으로 해 준다. 만약 여러분이 이 옵션을 설정하면, 상대적(relative) URI들은 모두 자동적으로 세션 ID를 포함하도록 바뀐다. 다른 대안으로, 사용자의 브라우저가 적절한 쿠키를 보내지 못한다면, 미리 정의된 SID라는 상수를 사용할 수도 있다. SID 는 session_name=session_id의 형태나, 빈 문자열이 된다.
다음 예제는 변수를 등록하고, SID를 사용하여 다른 페이지로 연결하는 예를 보여준다.
Example 1. Counting the number of hits of a single user
|
데이터베이스 공간을 사용하기 위해서는, 약간의 PHP 코드와 session_set_save_handler() 이라는 사용자 레벨 함수가 필요하다. MySQL 이나 다른 데이터베이스를 이용하기 위해서는 아마도 다음 함수들을 잘 활용해야 할 것이다.
Example 2. Usage of session_set_save_handler()
|
위의 예제는 다음과 같은 결과를 만들어 낸다. :
1 2 $ ./php save_handler.php 3 Content-Type: text/html 4 Set-cookie: PHPSESSID=f08b925af0ecb52bdd2de97d95cdbe6b 5 6 open (/tmp, PHPSESSID) 7 read (f08b925af0ecb52bdd2de97d95cdbe6b) 8 write (f08b925af0ecb52bdd2de97d95cdbe6b, foo|i:2;) 9 close 10 |
--enable-trans-sid 로 컴파일된 PHP에서는, <?=SID?> 가 필요 없다.
세션 관리 시스템은 php.ini 파일에서 설정가능한 많은 설정 옵션을 지원한다. 이것들에 대해 간단히 살펴보자.
Note: Session handling은 PHP 4.0에서 추가되었다.
session_start -- session 데이타를 초기화한다.
bool session_start
(void);
session_start() creates a session (or resumes the current one based on the session id being passed via a GET variable or a cookie).
This function always returns true.
Note: This function was added in PHP 4.0.
session_destroy -- session에 등록된 모든 데이타를 제거한다.
bool session_destroy
(void);
session_destroy() destroys all of the data associated with the current session.
This function always returns true.
Note: This function was added in PHP 4.0.
session_name -- 현재 session의 이름을 얻거나, 설정한다.
string session_name
([string name])
session_name() returns the name of the current session. If name is specified, the name of the current session is changed to its value.
The session name references the session id in cookies and URLs. It should contain only alphanumeric characters; it should be short and descriptive (i.e. for users with enabled cookie warnings). The session name is resetted to the default value stored in session.name at request startup time. Thus, you need to call session_name() for every request (and before session_start() or session_register() are called).
Example 1. session_name() examples
|
Note: This function was added in PHP 4.0.
session_module_name -- 현재 session 모듈의 이름을 얻거나, 설정한다.
string session_module_name
([string module])
session_module_name() returns the name of the current session module. If module is specified, that module will be used instead.
Note: This function was added in PHP 4.0.
session_save_path -- 현재 session 데이타가 저장된 path를 얻거나, 설정한다.
string session_save_path
([string path])
session_save_path() returns the path of the current directory used to save session data. If path is specified, the path to which data is saved will be changed.
Note: On some operating systems, you may want to specify a path on a filesystem that handles lots of small files efficiently. For example, on Linux, reiserfs may provide better performance than ext2fs.
Note: This function was added in PHP 4.0.
session_id -- 현재 session의 ID를 얻거나, 설정한다.
string session_id
([string id])
session_id() returns the session id for the current session. If id is specified, it will replace the current session id.
directory used to save session data. If path is specified, the path to which data is saved will be changed.
The constant SID can also be used to retrieve the current name and session id as a string suitable for adding to URLs.
Note: This function was added in PHP 4.0.
session_register -- 현재 session에 변수를 등록한다.
bool session_register
(mixed name [, mixed ...])
session_register() variable number of arguments, any of which can be either a string holding the variable name or an array consisting of such variable names or other arrays. For each encountered variable name, session_register() registers the global variable named by it with the current session.
This function returns true when the variable is successfully registered with the session.
Note: This function was added in PHP 4.0.
session_unregister -- 현재 session에 등록된 변수를 삭제한다.
bool session_unregister
(string name)
session_unregister() unregisters (forgets) the global variable named name from the current session.
This function returns true when the variable is successfully unregistered from the session.
Note: This function was added in PHP 4.0.
(PHP4 >= 4.0b4)
session_unset -- 모든 session 변수들을 해제한다.void session_unset
(void);
The session_unset() function free's all session variables currently registered.
session_is_registered -- 해당 변수가 session에 등록되어 있는가 확인한다.
bool session_is_registered
(string name)
session_is_registered() returns true if there is a variable with the name name registered in the current session.
Note: This function was added in PHP 4.0.
(PHP4 >= 4.0RC2)
session_get_cookie_params -- session cookie 파라메터를 구한다.array session_get_cookie_params
(void);
The session_get_cookie_params() function returns an array with the current session cookie information, the array contains the following items:
(PHP4 >= 4.0b4)
session_set_cookie_params -- session cookie 파라메터를 설정한다.void session_set_cookie_params
(int lifetime [, string path [, string domain]])
Set cookie parameters defined in the php.ini file. The effect of this function only lasts for the duration of the script.
session_decode -- 문자열에서 session 데이타로 decode한다.
bool session_decode
(string data)
session_decode() decodes the session data in data, setting variables stored in the session.
Note: This function was added in PHP 4.0.
session_encode -- 현재 session의 데이타를 문자열로 encode한다.
bool session_encode
(void);
session_encode() returns a string with the contents of the current session encoded within.
Note: This function was added in PHP 4.0.
이 SNMP 함수들을 사용하려면 ucd-snmp package를 설치하여야 한다. 최신버전이 있는 곳에 대해서는 PHP FAQ를 참조하도록한다. Windows에서 이 함수들은 NT환경에서만 동작하며 Win95/98에서는 동작하지 않는다.
주의사항 : UCD SNMP 패키지를 사용하려면, 이 패키지를 컴파일 하기 전에 NO_ZEROLENGTH_COMMUNITY를 1로 설정해야 한다. UCD SNMP를 configure 한 후에 config.h의 NO_ZEROLENGTH_COMMUNITY 값을 손으로 직접 고쳐 주어야 한다. #define 라인의 comment를 없애주면 된다. 즉, 다음과 같이 만들면 되는 것이다.
1 2 #define NO_ZEROLENGTH_COMMUNITY 1 3 |
만약 SNMP 명령 사용중에 이상한 segmentation faults를 만나면, 위의 작업을 안한 것이다. 만약 UCD SNMP를 다시 컴파일하고 싶지 않다면 PHP를 컴파일할 때 --enable-ucd-snmp-hack 스위치를 주고 컴파일하면 되기는 하지만 문제가 있을 수도 있다.
snmpget -- SNMP object를 가져온다.
string snmpget
(string
hostname, string community, string object_id [, int timeout [, int retries]])
Returns SNMP object value on success and false on error.
The snmpget() function is used to read the value of an SNMP object specified by the object_id. SNMP agent is specified by the hostname and the read community is specified by the community parameter.
1 2 $syscontact = snmpget("127.0.0.1", "public", "system.SysContact.0"); 3 |
snmpset -- SNMP object를 설정한다.
bool snmpset
(string
hostname, string community, string object_id, string type, mixed value [, int
timeout [, int retries]])
Sets the specified SNMP object value, returning true on success and false on error.
The snmpset() function is used to set the value of an SNMP object specified by the object_id. SNMP agent is specified by the hostname and the read community is specified by the community parameter.
snmpwalk -- agent로 부터 모든 SNMP object들을 가져온다.
array snmpwalk
(string
hostname, string community, string object_id [, int timeout [, int retries]])
Returns an array of SNMP object values starting from the object_id() as root and false on error.
snmpwalk() function is used to read all the values from an SNMP agent specified by the hostname. Community specifies the read community for that agent. A null object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array. If object_id is specified, all the SNMP objects below that object_id are returned.
1 2 $a = snmpwalk("127.0.0.1", "public", ""); 3 |
Above function call would return all the SNMP objects from the SNMP agent running on localhost. One can step through the values with a loop
1 2 for ($i=0; $i<count($a); $i++) { 3 echo $a[$i]; 4 } 5 |
snmpwalkoid -- 네트웍 entity에 대한 정보 tree를 질의한다.
array snmpwalkoid
(string hostname, string community, string object_id [, int timeout [, int
retries]])
Returns an associative array with object ids and their respective object value starting from the object_id as root and false on error.
snmpwalkoid() function is used to read all object ids and their respective values from an SNMP agent specified by the hostname. Community specifies the read community for that agent. A null object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array. If object_id is specified, all the SNMP objects below that object_id are returned.
The existence of snmpwalkoid() and snmpwalk() has historical reasons. Both functions are provided for backward compatibility.
1 2 $a = snmpwalkoid("127.0.0.1", "public", ""); 3 |
Above function call would return all the SNMP objects from the SNMP agent running on localhost. One can step through the values with a loop
1 2 for (reset($a); $i = key($a); next($a)) { 3 echo "$i: $a[$i]<br>\n"; 4 } 5 |
snmp_get_quick_print -- UCD SNMP library의 현재 quick_print setting 값을 가져온다.
boolean snmp_get_quick_print
(void )
Returns the current value stored in the UCD Library for quick_print. quick_print is off by default.
1 2 $quickprint = snmp_get_quick_print(); 3 |
Above function call would return false if quick_print is on, and true if quick_print is on.
snmp_get_quick_print() is only available when using the UCD SNMP library. This function is not available when using the Windows SNMP library.
See: snmp_set_quick_print() for a full description of what quick_print does.
snmp_set_quick_print -- UCD SNMP library의 quick_print의 값을 설정한다.
void snmp_set_quick_print
(boolean quick_print)
Sets the value of quick_print within the UCD SNMP library. When this is set (1), the SNMP library will return 'quick printed' values. This means that just the value will be printed. When quick_print is not enabled (default) the UCD SNMP library prints extra information including the type of the value (i.e. IpAddress or OID). Additionally, if quick_print is not enabled, the library prints additional hex values for all strings of three characters or less.
Setting quick_print is often used when using the information returned rather then displaying it.
1 2 snmp_set_quick_print(0); 3 $a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1"); 4 echo "$a<BR>\n"; 5 snmp_set_quick_print(1); 6 $a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1"); 7 echo "$a<BR>\n"; 8 |
The first value printed might be: 'Timeticks: (0) 0:00:00.00', whereas with quick_print enabled, just '0:00:00.00' would be printed.
By default the UCD SNMP library returns verbose values, quick_print is used to return only the value.
Currently strings are still returned with extra quotes, this will be corrected in a later release.
snmp_set_quick_print() is only available when using the UCD SNMP library. This function is not available when using the Windows SNMP library.
이 함수들은 문자열을 다루는 함수들이다. 더 자세한 사항은 regular expression 이나 URL handling 절에 설명된 부분을 참조하라.
string addcslashes
(string str, string charlist)
Returns a string with backslashes before characters that are listed in charlist parameter. It escapes \n, \r etc. in C-like style, characters with ASCII code lower than 32 and higher than 126 are converted to octal representation. Be carefull when escaping alphanumeric characters. You can specify a range in charlist like "\0..\37", which would escape all characters with ASCII code between 0 and 31.
Example 1. Addcslashes() example
|
Note: Added in PHP4b3-dev.
See also stripcslashes(), stripslashes(), htmlspecialchars() and quotemeta().
AddSlashes -- 필요한 곳을 backslash로 감싼다.
string addslashes
(string str);
Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the null byte).
See also stripcslashes(), stripslashes(), htmlspecialchars() and quotemeta().
bin2hex -- 이진 데이터를 16진수 표시로 바꾼다.
string bin2hex
(string str);
Returns an ASCII string containing the hexadecimal representation of str. The conversion is done byte-wise with the high-nibble first.
Chop -- 뒤쪽의 여백를 삭제한다.
string chop
(string str)
Returns the argument string without trailing whitespace, including newlines.
Example 1. Chop() example
|
Chr -- 지정된 문자를 반환한다.
string chr
(int ascii)
Returns a one-character string containing the character specified by ascii.
Example 1. Chr() example
|
This function complements ord(). See also sprintf() with a format string of %c.
chunk_split -- 문자열을 비슷한 크기로 나눈다.
string chunk_split
(string string [, int chunklen [, string end]])
Can be used to split a string into smaller chunks which is useful for e.g. converting base64_encode output to match RFC 2045 semantics. It inserts every chunklen (defaults to 76) chars the string end (defaults to "\r\n"). It returns the new string leaving the original string untouched.
Example 1. Chunk_split() example
|
This function is significantly faster than ereg_replace().
convert_cyr_string -- 문자열을 특정 Cyrillic 문자에서 다른 것으로 바꾼다.
string convert_cyr_string
(string str, string from, string to);
This function converts the given string from one Cyrillic character set to another. The from and to arguments are single characters that represent the source and target Cyrillic character sets. The supported types are:
(PHP4 >= 4.0b4)
count_chars -- 문자열에 사용된 문자들에 대한 정보를 반환한다.mixed count_chars
(string string [, mode])
Counts the number of occurances of every byte-value (0..255) in string and returns it in various ways. The optional parameter Mode default to 0. Depending on mode count_chars() returns one of the following:
Note: This function was added in PHP 4.0.
crypt -- 문자열을 DES encryption방법으로 변환(encrypt)한다.
string crypt
(string str
[, string salt])
crypt() will encrypt a string using the standard Unix DES encryption method. Arguments are a string to be encrypted and an optional two-character salt string to base the encryption on. See the Unix man page for your crypt function for more information.
If the salt argument is not provided, it will be randomly generated by PHP.
Some operating systems support more than one type of encryption. In fact, sometimes the standard DES encryption is replaced by an MD5 based encryption algorithm. The encryption type is triggered by the salt argument. At install time, PHP determines the capabilities of the crypt function and will accept salts for other encryption types. If no salt is provided, PHP will auto-generate a standard 2-character DES salt by default unless the default encryption type on the system is MD5 in which case a random MD5-compatible salt is generated. PHP sets a constant named CRYPT_SALT_LENGTH which tells you whether a regular 2-character salt applies to your system or the longer 12-char MD5 salt is applicable.
The standard DES encryption crypt() contains the salt as the first two characters of the output.
On systems where the crypt() function supports multiple encryption types, the following constants are set to 0 or 1 depending on whether the given type is available:
There is no decrypt function, since crypt() uses a one-way algorithm.
echo -- 하나 이상의 문자열을 출력한다.
echo
(string arg1,
string [argn]...)
Outputs all parameters.
Echo() is not actually a function (it is a language construct) so you are not required to use parantheses with it.
Example 1. Echo() example
|
Note: In fact, if you want to pass more than one parameter to echo, you must not enclose the parameters within parentheses.
See also: print(), printf(), and flush()
explode -- 문자열을 문자열 기준으로 나눈다.
array explode
(string
separator, string string [, int limit])
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delim. If limit is set, the returned array will contaion a maximum of limit elements with the last element containing the whole rest of string.
Example 1. Explode() example
|
flush -- output buffer를 Flush한다.
void flush
(void);
Flushes the output buffers of PHP and whatever backend PHP is using (CGI, a web server, etc.) This effectively tries to push all the output so far to the user's browser.
(PHP4 >= 4.0b4)
get_html_translation_table -- htmlspecialchars()와 htmlentities() 함수에서 사용하는 변환 테이블을 반환한다.string get_html_translation_table
(int table)
get_html_translation_table() will return the translation table that is used internally for htmlspecialchars() and htmlentities(). Ther are two new defines (HTML_ENTITIES, HTML_SPECIALCHARS) that allow you to specify the table you want.
Example 1. Translation Table Example
|
The $encoded variable will now contain: "Hallo & <Frau> & Krämer".
The cool thing is using array_flip() to change the direction of the translation.
1 2 $trans = array_flip ($trans); 3 $original = strtr ($str, $trans); 4 |
The content of $original would be: "Hallo & <Frau> & Krämer".
Note: This function was added in PHP 4.0.
See also: htmlspecialchars(), htmlentities(), strtr(), and array_flip().
get_meta_tags -- 파일에서 모든 meta tag의 content 속성을 추출하여 배열에 저장한다.
array get_meta_tags
(string filename [, int use_include_path])
Opens filename and parses it line by line for <meta> tags of the form
Example 1. Meta Tags Example
|
(pay attention to line endings - PHP uses a native function to parse the input, so a Mac file won't work on Unix).
The value of the name property becomes the key, the value of the content property becomes the value of the returned array, so you can easily use standard array functions to traverse it or access single values. Special characters in the value of the name property are substituted with '_', the rest is converted to lower case.
Setting use_include_path to 1 will result in PHP trying to open the file along the standard include path.
htmlentities -- 모든 가능한 문자들을 HTML entity로 바꾼다.
string htmlentities
(string
string)This function is identical to htmlspecialchars() in all ways, except that all characters which have HTML entity equivalents are translated into these entities.
At present, the ISO-8859-1 character set is used.
See also htmlspecialchars() and nl2br().
htmlspecialchars -- 특수문자들을 HTML entity로 변환한다.
string htmlspecialchars
(string
string)Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with these conversions made.
This function is useful in preventing user-supplied text from containing HTML markup, such as in a message board or guest book application.
At present, the translations that are done are:
'&' (ampersand) becomes '&'
'"' (double quote) becomes '"'
'<' (less than) becomes '<'
'>' (greater than) becomes '>'
Note that this functions does not translate anything beyond what is listed above. For full entity translation, see htmlentities().
See also htmlentities() and nl2br().
implode -- 배열의 원소들을 문자열을 사용해 연결한다.
string implode
(string
glue, array pieces)
Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.
Example 1. Implode() example
|
See also explode(), join(), and split().
join -- 배열의 원소들을 문자열을 사용해 연결한다
string join
(string
glue, array pieces)
join() is an alias to implode(), and is identical in every way.
See also explode(), implode(), and split().
(PHP3 CVS only, PHP4 CVS only)
levenshtein -- 두 문자열간의 Levenshtein 거리를 계산한다.int levenshtein
(string
str1, string str2)
This function return the Levenshtein-Distance between the two argument strings or -1, if one of the argument strings is longer than the limit of 255 characters.
The Levenshtein distance is defined as the minimal number of characters you have to replace, insert or delete to transform str1 into str2. The complexity of the algorithm is O(m*n), where n and m are the length of str1 and str2 (rather good when compared to similar_text(), which is O(max(n,m)**3), but still expensive).
See also soundex(), similar_text() and metaphone().
ltrim -- 문자열의 앞 여백을 제거한다.
string ltrim
(string
str)
This function strips whitespace from the start of a string and returns the stripped string. The whitespace characters it currently strips are: "\n", "\r", "\t", "\v", "\0", and a plain space.
md5 -- 문자열의 md5 hash 값을 계산한다.
string md5
(string str)Calculates the MD5 hash of str using the RSA Data Security, Inc. MD5 Message-Digest Algorithm.
( 역자주 : MD5 algorithm에 관한자세한 설명은 RFC 1321을 보세요.)
string metaphone
(string
str)
Calculates the metaphone key of str.
Similar to soundex() metaphone creates the same key for similar sounding words. It's more accurate than soundex() as it knows the basic rules of English pronunciation. The metaphone generated keys are of variable length.
Metaphone was developed by Lawrence Philips <lphilips@verity.com>. It is described in ["Practical Algorithms for Programmers", Binstock & Rex, Addison Wesley, 1995].
Note: This function was added in PHP 4.0.
nl2br -- newline을 HTML line break로 변환한다.
string nl2br
(string
string)
Returns string with '<BR>' inserted before all newlines.
See also htmlspecialchars() and htmlentities().
Ord -- 문자의 ASCII 값을 구한다.
int ord
(string string)
Returns the ASCII value of the first character of string. This function complements chr().
Example 1. Ord() example
|
See also chr().
parse_str -- 문자열을 변수로 해석(parse)한다.
void parse_str
(string
str)
Parses str as if it were the query string passed via an URL and sets variables in the current scope.
Example 1. Using parse_str()
|
print -- 문자열을 출력한다.
print
(string arg)Outputs arg.
See also: echo(), printf() and flush()
printf -- 문자열을 format하여 출력한다.
int printf
(string format [,
mixed args...])Produces output according to format, which is described in the documentation for sprintf().
See also: print(), sprintf(), and flush().
quoted_printable_decode -- quoted-printable 문자열을 8 bit 문자열로 바꾼다.
string quoted_printable_decode
(string str)This function returns an 8-bit binary string corresponding to the decoded quoted printable string. This function is similar to imap_qprint(), except this one does not require the IMAP module to work.
QuoteMeta -- meta character들을 backslash가 붙은 문자로 전환한다.
string quotemeta
(string
str)
Returns a version of str with a backslash character (\) before every character that is among these:
. \\ + * ? [ ^ ] ( $ ) |
See also addslashes(), htmlentities(), htmlspecialchars(), nl2br(), and stripslashes().
rawurldecode -- URL-encoded 문자열을 decode한다.
string rawurldecode
(string str)
Returns a string in which the sequences with percent (%) signs followed by two hex digits have been replaced with literal characters. For example, the string
foo%20bar%40baz |
decodes into
foo bar@baz |
See also rawurlencode().
rawurlencode -- RFC1738을 따라 URL-encode한다.
string rawurlencode
(string str)
Returns a string in which all non-alphanumeric characters except
-_. |
have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in RFC1738 for protecting literal characters from being interpreted as special URL delimiters, and for protecting URL's from being mangled by transmission media with character conversions (like some email systems). For example, if you want to include a password in an ftp url:
Example 1. Rawurlencode() example 1
|
Or, if you pass information in a path info component of the url:
Example 2. Rawurlencode() example 2
|
See also rawurldecode().
setlocale -- locale information을 설정한다.
string setlocale
(string
category, string locale)category is a string specifying the category of the functions affected by the locale setting:
If locale is the empty string "", the locale names will be set from the values of environment variables with the same names as the above categories, or from "LANG".
If locale is zero or "0", the locale setting is not affected, only the current setting is returned.
Setlocale returns the new current locale, or false if the locale functionality is not implemented in the plattform, the specified locale does not exist or the category name is invalid. An invalid category name also causes a warning message.
similar_text -- 두 문자열 간의 비슷한 정도를 계산한다.
int similar_text
(string first,
string second [, double percent])This calculates the similarity between two strings as described in Oliver [1993]. Note that this implementation does not use a stack as in Oliver's pseudo code, but recursive calls which may or may not speed up the whole process. Note also that the complexity of this algorithm is O(N**3) where N is the length of the longest string.
By passing a reference as third argument, similar_text() will calculate the similarity in percent for you. It returns the number of matching chars in both strings.
soundex -- 문자열의 soundex key를 구한다.(역자주: 비슷한 발음을 찾기 위해 사용, 영어만 가능)
string soundex
(string
str)
Calculates the soundex key of str.
Soundex keys have the property that words pronounced similarly produce the same soundex key, and can thus be used to simplify searches in databases where you know the pronunciation but not the spelling. This soundex function returns a string 4 characters long, starting with a letter.
This particular soundex function is one described by Donald Knuth in "The Art Of Computer Programming, vol. 3: Sorting And Searching", Addison-Wesley (1973), pp. 391-392.
Example 1. Soundex Examples
|
sprintf -- format된 문자열을 반환한다.
string sprintf
(string
format [, mixed args...])
Returns a string produced according to the formatting string format.
The format string is composed by zero or more directives: ordinary characters (excluding %) that are copied directly to the result, and conversion specifications, each of which results in fetching its own parameter. This applies to both sprintf() and printf().
Each conversion specification consists of these elements, in order:
% - a literal percent character. No argument is required. |
b - the argument is treated as an integer, and presented as a binary number. |
c - the argument is treated as an integer, and presented as the character with that ASCII value. |
d - the argument is treated as an integer, and presented as a decimal number. |
f - the argument is treated as a double, and presented as a floating-point number. |
o - the argument is treated as an integer, and presented as an octal number. |
s - the argument is treated as and presented as a string. |
x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters). |
X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters). |
See also: printf(), number_format()
Example 1. Sprintf(): zero-padded integers
|
Example 2. Sprintf(): formatting currency
|
(PHP3 >= 3.0.2, PHP4 )
strcasecmp -- binary 방식(safe)의 대,소문자 구별 없는 문자열 비교int strcasecmp
(string
str1, string str2)
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
Example 1. strcasecmp() example
|
See also ereg(), strcmp(), substr(), stristr(), and strstr().
strchr -- 해당 문자가 처음 나타나는 곳을 찾는다.
string strchr
(string
haystack, string needle)This function is an alias for strstr(), and is identical in every way.
strcmp -- binary 방식(safe)의 문자열 비교
int strcmp
(string str1,
string str2)
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
Note that this comparison is case sensitive.
See also ereg(), substr(), and strstr().
strcspn -- mask에 맞지 않는 initial segment의 길이를 구한다.
int strcspn
(string
str1, string str2)Returns the length of the initial segment of str1 which does not contain any of the characters in str2.
See also strspn().
(PHP3 >= 3.0.8, PHP4 >= 4.0b2)
strip_tags -- 문자열에서 HTML과 PHP 테그들을 제거한다.
string strip_tags
(string str [, string allowable_tags])
This function tries to strip all HTML and PHP tags from the given string. It errors on the side of caution in case of incomplete or bogus tags. It uses the same tag stripping state machine as the fgetss() function.
You can use the optional second parameter to specify tags which should not be stripped.
Note: Allowable_tags was added in PHP 3.0.13, PHP4B3.
string stripcslashes
(string str)
Returns a string with backslashes stripped off. Recognizes C-like \n, \r ..., octal and hexadecimal representation.
Note: Added in PHP4b3-dev.
See also addcslashes().
StripSlashes -- addslashes로 quote된 문자열을 un-quote한다.
string stripslashes
(string str)
Returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes are made into a single backslash.
See also addslashes().
(PHP3 >= 3.0.6, PHP4 )
stristr -- 대,소문자를 구분하지 않는 strstr()string stristr
(string
haystack, string needle)
Returns all of haystack from the first occurrence of needle to the end. needle and haystack are examined in a case-insensitive manner.
If needle is not found, returns false.
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
strlen -- 문자열의 길이를 구한다.
int strlen
(string str)Returns the length of string.
strpos -- 해당 문자열이 나타나는 첫 위치를 구한다.
int strpos
(string
haystack, string needle [, int offset])
Returns the numeric position of the first occurrence of needle in the haystack string. Unlike the strrpos(), this function can take a full string as the needle parameter and the entire string will be used.
If needle is not found, returns false.
Note: It is easy to mistake the return values for "character found at position 0" and "character not found". Here's how to detect the difference:
1 2 // in PHP 4.0b3 and newer: 3 $pos = strpos ("b", $mystring); 4 if ($pos === false) { // note: three equal signs 5 // not found... 6 } 7 8 // in versions older than 4.0b3: 9 $pos = strpos ("b", $mystring); 10 if (is_string ($pos) && !$pos) { 11 // not found... 12 } 13
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
The optional offset parameter allows you to specify which character in haystack to start searching. The position returned is still relative to the the beginning of haystack.
See also strrpos(), strrchr(), substr(), and strstr().
strrchr -- 문자가 마지막으로 나타나는 위치를 구한다.
string strrchr
(string
haystack, string needle)
This function returns the portion of haystack which starts at the last occurrence of needle and goes until the end of haystack.
Returns false if needle is not found.
If needle contains more than one character, the first is used.
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
Example 1. Strrchr() example
|
See also substr() and strstr().
(PHP4 >= 4.0b4)
str_repeat -- 문자열을 반복한다.string str_repeat
(string input, int multiplier)
Returns input_str repeated multiplier times. multiplier has to be greater than 0.
Example 1. Str_repeat() example
|
This will output "-=-=-=-=-=-=-=-=-=-=".
Note: This function was added in PHP 4.0.
strrev -- 문자열을 Reverse한다.
string strrev
(string
string)Returns string, reversed.
strrpos -- 문자열에서 해당 문자가 나타나는 제일 마지막 위치를 구한다.
int strrpos
(string
haystack, char needle)
Returns the numeric position of the last occurrence of needle in the haystack string. Note that the needle in this case can only be a single character. If a string is passed as the needle, then only the first character of that string will be used.
If needle is not found, returns false.
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
See also strpos(), strrchr(), substr(), stristr() and strstr().
strspn -- mask에 맞는 initial segment의 길이를 구한다.
int strspn
(string str1,
string str2)
Returns the length of the initial segment of str1 which consists entirely of characters in str2
See also strcspn().
strstr -- 문자열이 처음 나타나는 위치의 문자열을 반환한다.
string strstr
(string
haystack, string needle)
Returns all of haystack from the first occurrence of needle to the end.
If needle is not found, returns false.
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
Example 1. Strstr() example
|
See also stristr(), strrchr(), substr(), and ereg().
strtok -- 문자열을 token화 한다.
string strtok
(string
arg1, string arg2)
strtok() is used to tokenize a string. That is, if you have a string like "This is an example string" you could tokenize this string into its individual words by using the space character as the token.
Example 1. Strtok() example
|
Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use, as it keeps track of where it is in the current string. To start over, or to tokenize a new string you simply call strtok with the string argument again to initialize it. Note that you may put multiple tokens in the token parameter. The string will be tokenized when any one of the characters in the argument are found.
Also be careful that your tokens may be equal to "0". This evaluates to false in conditional expressions.
See also split() and explode().
strtolower -- 소문자로 만든다.
string strtolower
(string str)
Returns string with all alphabetic characters converted to lowercase.
Note that 'alphabetic' is determined by the current locale. This means that in i.e. the default "C" locale, characters such as umlaut-A (Ä) will not be converted.
Example 1. Strtolower() example
|
See also strtoupper() and ucfirst().
strtoupper -- 대문자로 만든다.
string strtoupper
(string string)
Returns string with all alphabetic characters converted to uppercase.
Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.
Example 1. Strtoupper() example
|
See also strtolower() and ucfirst().
str_replace -- Replace all occurrences of needle in haystack with str
string str_replace
(string needle, string str, string haystack)
This function replaces all occurences of needle in haystack with the given str. If you don't need fancy replacing rules, you should always use this function instead of ereg_replace().
Example 1. Str_replace() example
|
This function is binary safe.
Note: Str_replace() was added in PHP 3.0.6, but was buggy up until PHP 3.0.8.
See also ereg_replace() and strtr()
strtr -- 특정 문자열을 대치(translate)한다.
string strtr
(string
str, string from, string to)
This function operates on str, translating all occurrences of each character in from to the corresponding character in to and returning the result.
If from and to are different lengths, the extra characters in the longer of the two are ignored.
Example 1. Strtr() example
|
strtr() can be called with only two arguments. If called with two arguments it behaves in a new way: from then has to be an array that contains string -> string pairs that will be replaced in the source string. strtr() will always look for the longest possible match first and will *NOT* try to replace stuff that it has already worked on.
Examples:
1 2 $trans = array ("hello" => "hi", "hi" => "hello"); 3 echo strtr("hi all, I said hello", $trans) . "\n"; 4 |
Note: This feature (two arguments) was added in PHP 4.0.
See also : ereg_replace().
substr -- 문자열의 일부분을 반환한다.
string substr
(string
string, int start [, int length])
Substr returns the portion of string specified by the start and length parameters.
If start is positive, the returned string will start at the start'th character of string.
Examples:
1 2 $rest = substr ("abcdef", 1); // returns "bcdef" 3 $rest = substr ("abcdef", 1, 3); // returns "bcd" 4 |
If start is negative, the returned string will start at the start'th character from the end of string.
Examples:
1 2 $rest = substr ("abcdef", -1); // returns "f" 3 $rest = substr ("abcdef", -2); // returns "ef" 4 $rest = substr ("abcdef", -3, 1); // returns "d" 5 |
If length is given and is positive, the string returned will end length characters from start. If this would result in a string with negative length (because the start is past the end of the string), then the returned string will contain the single character at start.
If length is given and is negative, the string returned will end length characters from the end of string. If this would result in a string with negative length, then the returned string will contain the single character at start.
Examples:
1 2 $rest = substr ("abcdef", 1, -1); // returns "bcde" 3 |
See also strrchr() and ereg().
(PHP4 >= 4.0b4)
substr_replace -- 문자열의 특정 위치의 text를 치환한다.string substr_replace
(string string, string replacement, int start [, int length])
substr_replace() replaces the part of string delimited by the start and (optionally) length parameters with the string given in replacement. The result is returned.
If start is positive, the replacing will begin at the start'th offset into string.
If start is negative, the replacing will begin at the start'th character from the end of string.
If length is given and is positive, it represents the length of the portion of string which is to be replaced. If it is negative, it represents the number of characters from the end of string at which to stop replacing. If it is not given, then it will default to strlen( string ); i.e. end the replacing at the end of string.
Example 1. Substr_replace() example
|
See also str_replace() and substr().
Note: Substr_replace() was added in PHP 4.0.
trim -- 문자열의 앞,뒤 여백 모두를 제거한다.
string trim
(string str)
This function strips whitespace from the start and the end of a string and returns the stripped string. The whitespace characters it currently strips are: "\n", "\r", "\t", "\v", "\0", and a plain space
ucfirst -- 문자열의 처음 문자를 대문자로 만든다.
string ucfirst
(string
str)
Capitalizes the first character of str if that character is alphabetic.
Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.
Example 1. ucfirst() example
|
See also strtoupper() and strtolower().
ucwords -- 문자열내의 각 단어의 첫 번째 문자를 대문자로 만든다.
string ucwords
(string
str)
Capitalizes the first character of each word in str if that character is alphabetic.
Example 1. ucwords() example
|
See also strtoupper(), strtolower() and ucfirst().
PHP는 Paul Haeberli의 libswf 모듈을 통해 Shockwave Flash 파일을 만드는 기능을 제공한다. libswf는 http://reality.sgi.com/grafica/flash/에서 얻을 수 있다. libswf 가 있다면 PHP 설정시에 --with-swf[=DIR] 옵션을 주고 설정하여야 한다. (DIR은 include와 lib 디렉토리를 포함하고 있는 디렉토리이다.) include 디렉토리에는 swf.h 파일이 있어야 하고, lib 디렉토리에는 libswf.a 파일이 있어야 한다. 만약 여러분이 libswf 배포본을 풀었는데 이 두 파일이 같은 디렉토리에 있다면, include와 lib 디렉토리를 직접 만들어 이 두 파일을 적합한 위치에 옮겨 두어야 한다.
PHP를 Shockwave Flash 지원으로 설치하였다면, 이제 PHP에서 Shockwave 파일을 만들 수 있다. 이제 무엇을 할 수 있는지 놀랄 것이다. 다음의 코드를 살펴보자. :
Example 1. SWF example
|
위의 예제는 이 url에서 볼 수 있는 동영상을 만들어 낸다.
Note: SWF 지원은 PHP4 RC2에서 추가되었다.
(PHP4 >= 4.0RC2)
swf_openfile -- Open a new Shockwave Flash filevoid swf_openfile
(string filename, float width, float height, float framerate, float r,
float g, float b)
The swf_openfile() function opens a new file named filename with a width of width and a height of height a frame rate of framerate and background with a red color of r a green color of g and a blue color of b.
The swf_openfile() must be the first function you call, otherwise your script will cause a segfault. If you want to send your output to the screen make the filename: "php://stdout" (support for this is in 4.0.1 and up).
(PHP4 >= 4.0RC2)
swf_closefile -- Close the current Shockwave Flash file(PHP4 >= 4.0RC2)
swf_labelframe -- Label the current framevoid swf_labelframe
(string name)
Label the current frame with the name given by the name parameter.
(PHP4 >= 4.0RC2)
swf_showframe -- Display the current framevoid swf_showframe
(void);
The swf_showframe function will output the current frame.
(PHP4 >= 4.0RC2)
swf_setframe -- Switch to a specified framevoid swf_setframe
(int
framenumber)
The swf_setframe() changes the active frame to the frame specified by framenumber.
(PHP4 >= 4.0RC2)
swf_getframe -- Get the frame number of the current frameint swf_getframe
(void);
The swf_getframe() function gets the number of the current frame.
(PHP4 >= 4.0RC2)
swf_mulcolor -- Sets the global multiply color to the rgba value specifiedvoid swf_mulcolor
(float
r, float g, float b, float a)
The swf_mulcolor() function sets the global multiply color to the rgba color specified. This color is then used (implicitly) by the swf_placeobject(), swf_modifyobject() and the swf_addbuttonrecord() functions. The color of the object will be multiplied by the rgba values when the object is written to the screen.
Note: The rgba values can be either positive or negative.
(PHP4 >= 4.0RC2)
swf_addcolor -- Set the global add color to the rgba value specifiedvoid swf_addcolor
(float
r, float g, float b, float a)
The swf_addcolor() function sets the global add color to the rgba color specified. This color is then used (implicitly) by the swf_placeobject(), swf_modifyobject() and the swf_addbuttonrecord() functions. The color of the object will be add by the rgba values when the object is written to the screen.
Note: The rgba values can be either positive or negative.
(PHP4 >= 4.0RC2)
swf_placeobject -- Place an object onto the screenvoid swf_placeobject
(int objid, int depth)
Places the object specified by objid in the current frame at a depth of depth. The objid parameter and the depth must be between 1 and 65535.
This uses the current mulcolor (specified by swf_mulcolor()) and the current addcolor (specified by swf_addcolor()) to color the object and it uses the current matrix to position the object.
Note: Full RGBA colors are supported.
(PHP4 >= 4.0RC2)
swf_modifyobject -- Modify an objectvoid swf_modifyobject
(int depth, int how)
Updates the position and/or color of the object at the specified depth, depth. The parameter how determines what is updated. how can either be the constant MOD_MATRIX or MOD_COLOR or it can be a combination of both (MOD_MATRIX|MOD_COLOR).
MOD_COLOR uses the current mulcolor (specified by the function swf_mulcolor()) and addcolor (specified by the function swf_addcolor()) to color the object. MOD_MATRIX uses the current matrix to position the object.
(PHP4 >= 4.0RC2)
swf_removeobject -- Remove an objectvoid swf_removeobject
(int depth)
Removes the object at the depth specified by depth.
(PHP4 >= 4.0RC2)
swf_nextid -- Returns the next free object idint swf_nextid
(void);
The swf_nextid() function returns the next available object id.
(PHP4 >= 4.0RC2)
swf_startdoaction -- Start a description of an action list for the current framevoid swf_startdoaction
(void);
The swf_startdoaction() function starts the description of an action list for the current frame. This must be called before actions are defined for the current frame.
(PHP4 >= 4.0RC2)
swf_actiongotoframe -- Play a frame and then stopvoid swf_actiongotoframe
(int framenumber)
The swf_actionGotoFrame() function will go to the frame specified by framenumber, play it, and then stop.
(PHP4 >= 4.0RC2)
swf_actiongeturl -- Get a URL from a Shockwave Flash movievoid swf_actiongeturl
(string url, string target)
The swf_actionGetUrl() function gets the URL specified by the parameter url with the target target.
(PHP4 >= 4.0RC2)
swf_actionnextframe -- Go foward one framevoid swf_actionnextframe
(void);
Go foward one frame.
(PHP4 >= 4.0RC2)
swf_actionprevframe -- Go backwards one framevoid swf_actionprevframe
(void);(PHP4 >= 4.0RC2)
swf_actionplay -- Start playing the flash movie from the current framevoid swf_actionplay
(void);
Start playing the flash movie from the current frame.
(PHP4 >= 4.0RC2)
swf_actionstop -- Stop playing the flash movie at the current framevoid swf_actionstop
(void);
Stop playing the flash movie at the current frame.
(PHP4 >= 4.0RC2)
swf_actiontogglequality -- Toggle between low and high qualityvoid swf_actiontogglequality
(void);
Toggle the flash movie between high and low quality.
(PHP4 >= 4.0RC2)
swf_actionwaitforframe -- Skip actions if a frame has not been loadedvoid swf_actionwaitforframe
(int framenumber, int skipcount)
The swf_actionWaitForFrame() function will check to see if the frame, specified by the framenumber parameter has been loaded, if not it will skip the number of actions specified by the skipcount parameter. This can be useful for "Loading..." type animations.
(PHP4 >= 4.0RC2)
swf_actionsettarget -- Set the context for actionsvoid swf_actionsettarget
(string target)
The swf_actionSetTarget() function sets the context for all actions. You can use this to control other flash movies that are currently playing.
(PHP4 >= 4.0RC2)
swf_actiongotolabel -- Display a frame with the specified labelvoid swf_actiongotolabel
(string label)
The swf_actionGotoLabel() function displays the frame with the label given by the label parameter and then stops.
(PHP4 >= 4.0RC2)
swf_enddoaction -- End the current actionvoid swf_enddoaction
(void);
Ends the current action started by the swf_startdoaction() function.
(PHP4 >= 4.0RC2)
swf_defineline -- Define a linevoid swf_defineline
(int
objid, float x1, float y1, float x2, float y2, float width)
The swf_defineline() defines a line starting from the x coordinate given by x1 and the y coordinate given by y1 parameter. Up to the x coordinate given by the x2 parameter and the y coordinate given by the y2 parameter. It will have a width defined by the width parameter.
(PHP4 >= 4.0RC2)
swf_definerect -- Define a rectanglevoid swf_definerect
(int
objid, float x1, float y1, float x2, float y2, float width)
The swf_definerect() defines a rectangle with an upper left hand coordinate given by the x, x1, and the y, y1. And a lower right hand coordinate given by the x coordinate, x2, and the y coordinate, y2 . Width of the rectangles border is given by the width parameter, if the width is 0.0 then the rectangle is filled.
(PHP4 >= 4.0.0)
swf_definepoly -- Define a polygonvoid swf_definepoly
(int
objid, array coords, int npoints, float width)
The swf_definepoly() function defines a polygon given an array of x, y coordinates (the coordinates are defined in the parameter coords). The parameter npoints is the number of overall points that are contained in the array given by coords. The width is the width of the polygon's border, if set to 0.0 the polygon is filled.
(PHP4 >= 4.0RC2)
swf_startshape -- Start a complex shapevoid swf_startshape
(int
objid)
The swf_startshape() function starts a complex shape, with an object id given by the objid parameter.
(PHP4 >= 4.0RC2)
swf_shapelinesolid -- Set the current line stylevoid swf_shapelinesolid
(float r, float g, float b, float a, float width)
The swf_shapeLineSolid() function sets the current line style to the color of the rgba parameters and width to the width parameter. If 0.0 is given as a width then no lines are drawn.
(PHP4 >= 4.0RC2)
swf_shapefilloff -- Turns off fillingvoid swf_shapefilloff
(void);
The swf_shapeFillOff() function turns off filling for the current shape.
(PHP4 >= 4.0RC2)
swf_shapefillsolid -- Set the current fill style to the specified colorvoid swf_shapefillsolid
(float r, float g, float b, float a)
The swf_shapeFillSolid() function sets the current fill style to solid, and then sets the fill color to the values of the rgba parameters.
(PHP4 >= 4.0RC2)
swf_shapefillbitmaptile -- Set current fill mode to clipped bitmapvoid swf_shapefillbitmapclip
(int bitmapid)
Sets the fill to bitmap clipped, empty spaces will be filled by the bitmap given by the bitmapid parameter
(PHP4 >= 4.0RC2)
swf_shapefillbitmaptile -- Set current fill mode to tiled bitmapvoid swf_shapefillbitmaptile
(int bitmapid)
Sets the fill to bitmap tile, empty spaces will be filled by the bitmap given by the bitmapid parameter (tiled).
(PHP4 >= 4.0RC2)
swf_shapemoveto -- Move the current positionvoid swf_shapemoveto
(float x, float y)
The swf_shapeMoveTo() function moves the current position to the x coordinate given by the x parameter and the y position given by the y parameter.
(PHP4 >= 4.0RC2)
swf_shapelineto -- Draw a linevoid swf_shapelineto
(float x, float y)
The swf_shapeLineTo() draws a line to the x,y coordinates given by the x parameter & the y parameter. The current position is then set to the x,y parameters.
(PHP4 >= 4.0RC2)
swf_shapecurveto -- Draw a quadratic bezier curve between two pointsvoid swf_shapecurveto
(float x1, float y1, float x2, float y2)
The swf_shapecurveto() function draws a quadratic bezier curve from the x coordinate given by x1 and the y coordinate given by y1 to the x coordinate given by x2 and the y coordinate given by y2. The current position is then set to the x,y coordinates given by the x2 and y2 parameters
(PHP4 >= 4.0RC2)
swf_shapecurveto3 -- Draw a cubic bezier curvevoid swf_shapecurveto3
(float x1, float y1, float x2, float y2, float x3, float y3)
Draw a cubic bezier curve using the x,y coordinate pairs x1, y1 and x2,y2 as off curve control points and the x,y coordinate x3, y3 as an endpoint. The current position is then set to the x,y coordinate pair given by x3,y3.
(PHP4 >= 4.0RC2)
swf_shapearc -- Draw a circular arcvoid swf_shapearc
(float
x, float y, float r, float ang1, float ang2)
The swf_shapeArc() function draws a circular arc from angle A given by the ang1 parameter to angle B given by the ang2 parameter. The center of the circle has an x coordinate given by the x parameter and a y coordinate given by the y, the radius of the circle is given by the r parameter.
(PHP4 >= 4.0RC2)
swf_endshape -- Completes the definition of the current shapevoid swf_endshape
(void);
The swf_endshape() completes the definition of the current shape.
(PHP4 >= 4.0RC2)
swf_definefont -- Defines a fontvoid swf_definefont
(int
fontid, string fontname)
The swf_definefont() function defines a font given by the fontname parameter and gives it the id specified by the fontid parameter. It then sets the font given by fontname to the current font.
(PHP4 >= 4.0RC2)
swf_setfont -- Change the current fontvoid swf_setfont
(int
fontid)
The swf_setfont() sets the current font to the value given by the fontid parameter.
(PHP4 >= 4.0RC2)
swf_fontsize -- Change the font sizevoid swf_fontsize
(float
size)
The swf_fontsize() function changes the font size to the value given by the size parameter.
(PHP4 >= 4.0RC2)
swf_fontslant -- Set the font slantvoid swf_fontslant
(float slant)
Set the current font slant to the angle indicated by the slant parameter. Positive values create a foward slant, negative values create a negative slant.
(PHP4 >= 4.0RC2)
swf_fonttracking -- Set the current font trackingvoid swf_fonttracking
(float tracking)
Set the font tracking to the value specified by the tracking parameter. This function is used to increase the spacing between letters and text, positive values increase the space and negative values decrease the space between letters.
(PHP4 >= 4.0RC2)
swf_getfontinfo -- The height in pixels of a capital A and a lowercase xarray swf_getfontinfo
(void);
The swf_getfontinfo() function returns an associative array with the following parameters:
(PHP4 >= 4.0RC2)
swf_definetext -- Define a text stringvoid swf_definetext
(int
objid, string str, int docenter)
Define a text string (the str parameter) using the current font and font size. The docenter is where the word is centered, if docenter is 1, then the word is centered in x.
(PHP4 >= 4.0RC2)
swf_textwidth -- Get the width of a stringfloat swf_textwidth
(string str)
The swf_textwidth() function gives the width of the string, str, in pixels, using the current font and font size.
(PHP4 >= 4.0RC2)
swf_definebitmap -- Define a bitmapvoid swf_definebitmap
(int objid, string image_name)
The swf_definebitmap() function defines a bitmap given a GIF, JPEG, RGB or FI image. The image will be converted into a Flash JPEG or Flash color map format.
(PHP4 >= 4.0RC2)
swf_getbitmapinfo -- Get information about a bitmaparray swf_getbitmapinfo
(int bitmapid)
The swf_getbitmapinfo() function returns an array of information about a bitmap given by the bitmapid parameter. The returned array has the following elements:
(PHP4 >= 4.0RC2)
swf_startsymbol -- Define a symbolvoid swf_startsymbol
(int objid)
Define an object id as a symbol. Symbols are tiny flash movies that can be played simultaneously. The objid parameter is the object id you want to define as a symbol.
(PHP4 >= 4.0RC2)
swf_endsymbol -- End the definition of a symbolvoid swf_endsymbol
(void);
The swf_endsymbol() function ends the definition of a symbol that was started by the swf_startsymbol() function.
(PHP4 >= 4.0RC2)
swf_startbutton -- Start the definition of a buttonvoid swf_startbutton
(int objid, int type)
The swf_startbutton() function starts off the definition of a button. The type parameter can either be TYPE_MENUBUTTON or TYPE_PUSHBUTTON. The TYPE_MENUBUTTON constant allows the focus to travel from the button when the mouse is down, TYPE_PUSHBUTTON does not allow the focus to travel when the mouse is down.
(PHP4 >= 4.0RC2)
swf_addbuttonrecord -- Controls location, appearance and active area of the current buttonvoid swf_addbuttonrecord
(int states, int shapeid, int depth)
The swf_addbuttonrecord() function allows you to define the specifics of using a button. The first parameter, states, defines what states the button can have, these can be any or all of the following constants: BSHitTest, BSDown, BSOver or BSUp. The second parameter, the shapeid is the look of the button, this is usually the object id of the shape of the button. The depth parameter is the placement of the button in the current frame.
Example 1. Swf_addbuttonrecord() function example
|
(PHP4 >= 4.0RC2)
swf_oncondition -- Describe a transition used to trigger an action listvoid swf_oncondition
(int transition)
The swf_onCondition() function describes a transition that will trigger an action list. There are several types of possible transitions, the following are for buttons defined as TYPE_MENUBUTTON:
For TYPE_PUSHBUTTON there are the following options:
(PHP4 >= 4.0RC2)
swf_endbutton -- End the definition of the current buttonvoid swf_endbutton
(void);
The swf_endButton() function ends the definition of the current button.
(PHP4 >= 4.0RC2)
swf_viewport -- Select an area for future drawingvoid swf_viewport
(double xmin, double xmax, double ymin, double ymax)
The swf_viewport() function selects an area for future drawing for xmin to xmax and ymin to ymax, if this function is not called the area defaults to the size of the screen.
(PHP4 CVS only)
swf_ortho -- Defines an orthographic mapping of user coordinates onto the current viewportvoid swf_ortho
(double
xmin, double xmax, double ymin, double ymax, double zmin, double zmax)
The swf_ortho() funcion defines a orthographic mapping of user coordinates onto the current viewport.
(PHP4 >= 4.0RC2)
swf_ortho2 -- Defines 2D orthographic mapping of user coordinates onto the current viewportvoid swf_ortho2
(double
xmin, double xmax, double ymin, double ymax)
The swf_ortho2() function defines a two dimensional orthographic mapping of user coordinates onto the current viewport, this defaults to one to one mapping of the area of the Flash movie. If a perspective transformation is desired, the swf_perspective () function can be used.
(PHP4 >= 4.0RC2)
swf_perspective -- Define a perspective projection transformationvoid swf_perspective
(double fovy, double aspect, double near, double far)
The swf_perspective() function defines a perspective projection transformation. The fovy parameter is field-of-view angle in the y direction. The aspect parameter should be set to the aspect ratio of the viewport that is being drawn onto. The near parameter is the near clipping plane and the far parameter is the far clipping plane.
Note: Various distortion artifacts may appear when performing a perspective projection, this is because Flash players only have a two dimensional matrix. Some are not to pretty.
(PHP4 >= 4.0RC2)
swf_polarview -- Define the viewer's position with polar coordinatesvoid swf_polarview
(double dist, double azimuth, double incidence, double twist)
The swf_polarview() function defines the viewer's position in polar coordinates. The dist parameter gives the distance between the viewpoint to the world space origin. The azimuth parameter defines the azimuthal angle in the x,y coordinate plane, measured in distance from the y axis. The incidence parameter defines the angle of incidence in the y,z plane, measured in distance from the z axis. The incidence angle is defined as the angle of the viewport relative to the z axis. Finally the twist specifies the amount that the viewpoint is to be rotated about the line of sight using the right hand rule.
(PHP4 >= 4.0RC2)
swf_lookat -- Define a viewing transformationvoid swf_lookat
(double
view_x, double view_y, double view_z, double reference_x, double reference_y,
double reference_z, double twist)
The swf_lookat() function defines a viewing transformation by giving the viewing position (the parameters view_x, view_y, and view_z) and the coordinates of a reference point in the scene, the reference point is defined by the reference_x, reference_y , and reference_z parameters. The twist controls the rotation along with viewer's z axis.
(PHP4 >= 4.0RC2)
swf_pushmatrix -- Push the current transformation matrix back unto the stackvoid swf_pushmatrix
(void);
The swf_pushmatrix() function pushes the current transformation matrix back onto the stack.
(PHP4 >= 4.0RC2)
swf_popmatrix -- Restore a previous transformation matrixvoid swf_popmatrix
(void);
The swf_popmatrix() function pushes the current transformation matrix back onto the stack.
(PHP4 >= 4.0RC2)
swf_scale -- Scale the current transformationvoid swf_scale
(double
x, double y, double z)
The swf_scale() scales the x coordinate of the curve by the value of the x parameter, the y coordinate of the curve by the value of the y parameter, and the z coordinate of the curve by the value of the z parameter.
(PHP4 >= 4.0RC2)
swf_translate -- Translate the current transformationsvoid swf_translate
(double x, double y, double z)
The swf_translate() function translates the current transformation by the x, y, and z values given.
(PHP4 >= 4.0RC2)
swf_rotate -- Rotate the current transformationvoid swf_rotate
(double
angle, string axis)
The swf_rotate() rotates the current transformation by the angle given by the angle parameter around the axis given by the axis parameter. Valid values for the axis are 'x' (the x axis), 'y' (the y axis) or 'z' (the z axis).
(PHP4 >= 4.0RC2)
swf_posround -- Enables or Disables the rounding of the translation when objects are placed or movedvoid swf_posround
(int
round)
The swf_posround() function enables or disables the rounding of the translation when objects are placed or moved, there are times when text becomes more readable because rounding has been enabled. The round is whether to enable rounding or not, if set to the value of 1, then rounding is enabled, if set to 0 then rounding is disabled.
sybase_affected_rows -- 최근 질의에 영향을 받는 row의 개수를 구한다.
int sybase_affected_rows
(int [link_identifier] );
Returns: The number of affected rows by the last query.
sybase_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or DELETE query on the server associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.
This command is not effective for SELECT statements, only on statements which modify records. To retrieve the number of rows returned from a SELECT, use sybase_num_rows().
Note: This function is only available using the CT library interface to Sybase, and not the DB library.
sybase_close -- Sybase connection을 닫는다.
int sybase_close(int link_identifier);
Returns: true on success, false on error
sybase_close() closes the link to a Sybase database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.
Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
sybase_close() will not close persistent links generated by sybase_pconnect().
See also: sybase_connect(), sybase_pconnect().
sybase_connect -- Sybase server connection을 연다.
int sybase_connect(string servername, string username, string password);
Returns: A positive Sybase link identifier on success, or false on error.
sybase_connect() establishes a connection to a Sybase server. The servername argument has to be a valid servername that is defined in the 'interfaces' file.
In case a second call is made to sybase_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.
The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling sybase_close().
See also sybase_pconnect(), sybase_close().
sybase_data_seek -- internal row pointer를 옮긴다.
int sybase_data_seek(int result_identifier, int row_number);
Returns: true on success, false on failure
sybase_data_seek() moves the internal row pointer of the Sybase result associated with the specified result identifier to pointer to the specifyed row number. The next call to sybase_fetch_row() would return that row.
See also: sybase_data_seek().
sybase_fetch_array -- row를 배열로 가져온다.
int sybase_fetch_array(int result);
Returns: An array that corresponds to the fetched row, or false if there are no more rows.
sybase_fetch_array() is an extended version of sybase_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.
An important thing to note is that using sybase_fetch_array() is NOT significantly slower than using sybase_fetch_row(), while it provides a significant added value.
For further details, also see sybase_fetch_row()
sybase_fetch_field -- 필드 정보를 구한다.
object sybase_fetch_field(int result, int field_offset);
Returns an object containing field information.
sybase_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retreived by sybase_fetch_field() is retreived.
The properties of the object are:
name - column name. if the column is a result of a function, this property is set to computed#N, where #N is a serial number.
column_source - the table from which the column was taken
max_length - maximum length of the column
numeric - 1 if the column is numeric
See also sybase_field_seek()
sybase_fetch_object -- row를 객체(Object)로 가져온다.
int sybase_fetch_object(int result);
Returns: An object with properties that correspond to the fetched row, or false if there are no more rows.
sybase_fetch_object() is similar to sybase_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).
Speed-wise, the function is identical to sybase_fetch_array(), and almost as quick as sybase_fetch_row() (the difference is insignificant).
See also: sybase_fetch-array() and sybase_fetch-row().
sybase_fetch_row -- row를 배열(enumerated array)로 가져온다.
array sybase_fetch_row(int result);
Returns: An array that corresponds to the fetched row, or false if there are no more rows.
sybase_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
Subsequent call to sybase_fetch_rows() would return the next row in the result set, or false if there are no more rows.
See also: sybase_fetch_array(), sybase_fetch_object(), sybase_data_seek(), sybase_fetch_lengths(), and sybase_result().
sybase_field_seek -- 필드의 offset을 설정한다.
int sybase_field_seek(int result, int field_offset);
Seeks to the specified field offset. If the next call to sybase_fetch_field() won't include a field offset, this field would be returned.
See also: sybase_fetch_field().
sybase_free_result -- result memory를 풀어준다.
int sybase_free_result
(int result);
sybase_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script, you may call sybase_free_result() with the result identifier as an argument and the associated result memory will be freed.
sybase_num_fields -- result의 field 개수를 구한다.
int sybase_num_fields(int result);
sybase_num_fields() returns the number of fields in a result set.
See also: sybase_db_query(), sybase_query(), sybase_fetch_field(), sybase_num_rows().
sybase_num_rows -- result의 row 개수를 구한다.
int sybase_num_rows(string result);
sybase_num_rows() returns the number of rows in a result set.
See also: sybase_db_query(), sybase_query() and, sybase_fetch_row().
sybase_pconnect -- 영구적인 Sybase 접속을 연다.
int sybase_pconnect(string servername, string username, string password);
Returns: A positive Sybase persistent link identifier on success, or false on error
sybase_pconnect() acts very much like sybase_connect() with two major differences.
First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (sybase_close() will not close links established by sybase_pconnect()).
This type of links is therefore called 'persistent'.
sybase_query -- Sybase 질의를 전송한다.
int sybase_query(string query, int link_identifier);
Returns: A positive Sybase result identifier on success, or false on error.
sybase_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if sybase_connect() was called, and use it.
See also: sybase_db_query(), sybase_select_db(), and sybase_connect().
sybase_result -- result data를 구한다.
int sybase_result(int result, int i, mixed field);
Returns: The contents of the cell at the row and offset in the specified Sybase result set.
sybase_result() returns the contents of one cell from a Sybase result set. The field argument can be the field's offset, or the field's name, or the field's table dot field's name (fieldname.tablename). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.
When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than sybase_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.
Recommended high-performance alternatives: sybase_fetch_row(), sybase_fetch_array(), and sybase_fetch_object().
sybase_select_db -- Sybase database를 선택한다.
int sybase_select_db(string database_name, int link_identifier);
Returns: true on success, false on error
sybase_select_db() sets the current active database on the server that's associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if sybase_connect() was called, and use it.
Every subsequent call to sybase_query() will be made on the active database.
See also: sybase_connect(), sybase_pconnect(), and sybase_query()
base64_decode -- MIME base64로 encode된 문자열을 decode 한다.
string base64_decode
(string
encoded_data)base64_decode() decodes encoded_data and returns the original data. The returned data may be binary.
See also: base64_encode(), RFC-2045 section 6.8.
base64_encode -- MIME base64 방식으로 encode한다.
string base64_encode
(string
data)base64_encode() returns data encoded with base64. This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.
Base64-encoded data takes about 33% more space than the original data.
See also: base64_decode(), chunk_split(), RFC-2045 section 6.8.
parse_url -- PHP가 form data를 해석하듯이 query string을 해석(parse)한다.
array parse_url
(string
url)
This function returns an associative array returning any of the various components of the URL that are present. This includes the "scheme", "host", "port", "user", "pass", "path", "query", and "fragment".
urldecode -- URL-encode된 문자열을 decode한다.
string urldecode
(string
str)
Decodes any %## encoding in the given string. The decoded string is returned.
Example 1. Urldecode() example
|
See also urlencode()
urlencode -- 문자열을 URL-encode한다.
string urlencode
(string
str)
Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. This differs from the RFC1738 encoding (see rawurlencode()) in that for historical reasons, spaces are encoded as plus (+) signs. This function is convenient when encoding a string to be used in a query part of an URL, as a convenient way to pass variables to the next page:
Example 1. Urlencode() example
|
See also urldecode()
(PHP3 >= 3.0.3, PHP4 )
call_user_func -- 첫 번째 파라메터로 주어진 사용자 함수를 호출한다.mixed call_user_func
(string function_name [, mixed parameters*])
Call a user defined function given by the function_name parameter. Take the following:
1 2 function barber ($type) { 3 print "You wanted a $type haircut, no problem"; 4 } 5 call_user_func('barber', "mushroom"); 6 call_user_func('barber', "shave"); 7 |
doubleval -- 변수의 실수(double)값을 구한다.
double doubleval
(mixed
var)
Returns the double (floating point) value of var.
Var may be any scalar type. You cannot use doubleval() on arrays or objects.
1 2 $var = '122.34343The'; 3 $double_value_of_var = doubleval ($var); 4 print $double_value_of_var; // prints 122.34343 5 |
See also intval(), strval(), settype() and Type juggling.
empty -- 변수가 값이 비어 있는가 검사한다.
int empty
(mixed var)
Returns false if var is set and has a non-empty or non-zero value; true otherwise.
1 2 $var = 0; 3 if (empty($var)) { #evaluates true 4 print '$var is either 0 or not at all set'; 5 } 6 if (!isset($var)) { // evaluates false 7 print 'The $var is not set at all'; 8 } 9 |
Note that this is meaningless when used on anything which isn't a variable; i.e. empty (addslashes ($name)) has no meaning since it would be checking whether something which isn't a variable is a variable with a false value.
gettype -- 변수의 type을 구한다.
string gettype
(mixed
var)
Returns the type of the PHP variable var.
Possibles values for the returned string are:
See also settype().
intval -- 변수의 정수값을 구한다.
int intval
(mixed var [,
int base])
Returns the integer value of var, using the specified base for the conversion (the default is base 10).
Var may be any scalar type. You cannot use intval() on arrays or objects.
See also doubleval(), strval(), settype() and Type juggling.
is_array -- 변수가 배열인가 검사한다.
int is_array
(mixed var)
Returns true if var is an array, false otherwise.
See also is_bool(), is_double(), is_float(), is_int(), is_integer(), is_real(), is_string(), is_long(), and is_object().
(PHP4 >= 4.0b4)
is_bool -- 변수가 불린형인가 검사한다.int is_bool
(mixed var)
Returns true if the var parameter is a boolean.
See also is_array(), is_double(), is_float(), is_int(), is_integer(), is_real(), is_string(), is_long(), and is_object().
is_double -- 변수가 실수인가 검사한다.
int is_double
(mixed var);Returns true if var is a double, false otherwise.
See also is_array(), is_bool(), is_float(), is_int(), is_integer(), is_real(), is_string(), is_long(), and is_object().
is_float -- 변수가 실수인가 검사한다.
int is_float
(mixed var);This function is an alias for is_double().
See also is_bool(), is_double(), is_real(), is_int(), is_integer(), is_string(), is_object(), is_array(), and is_long().
is_int -- 변수가 정수인가 검사한다.
int is_int
(mixed var);This function is an alias for is_long().
See also is_bool(), is_double(), is_float(), is_integer(), is_string(), is_real(), is_object(), is_array(), and is_long().
is_integer -- 변수가 정수인가 검사한다.
int is_integer
(mixed var);This function is an alias for is_long().
See also is_bool(), is_double(), is_float(), is_int(), is_string(), is_real(), is_object(), is_array(), and is_long().
is_long -- 변수가 정수인가 검사한다.
int is_long
(mixed var);Returns true if var is an integer (long), false otherwise.
See also is_bool(), is_double(), is_float(), is_int(), is_real(), is_string(), is_object(), is_array(), and is_integer().
(PHP4 >= 4.0RC1)
is_numeric -- 변수가 숫자 혹은 숫자를 표현하는 문자열인가 검사한다.int is_numeric
(mixed
var)
Returns true if var is a number or a numeric string, false otherwise.
See also is_bool(), is_double(), is_float(), is_int(), is_real(), is_string(), is_object(), is_array(), and is_integer().
is_object -- 변수가 객체(object)인가 검사한다.
int is_object
(mixed
var)
Returns true if var is an object, false otherwise.
See also is_bool(), is_long(), is_int(), is_integer(), is_float(), is_double(), is_real(), is_string(), and is_array().
is_real -- 변수가 실수인가 검사한다.
int is_real
(mixed var)This function is an alias for is_double().
See also is_bool(), is_long(), is_int(), is_integer(), is_float(), is_double(), is_object(), is_string(), and is_array().
(PHP4 >= 4.0b4)
is_resource -- 변수가 자원(resource)을 가지고 있는가 검사한다.int is_resource
(mixed
var)
is_resource() returns true if the variable given by the var parameter is a resource, otherwise it returns false.
Resources are things like file or database result handles that are allocated and freed by internal PHP functions and that may need some cleanup when they are no longer in use but haven't been freed by user code.
is_string -- 변수가 문자열인가 검사한다.
int is_string
(mixed
var)Returns true if var is a string, false otherwise.
See also is_bool(), is_long(), is_int(), is_integer(), is_float(), is_double(), is_real(), is_object(), and is_array().
isset -- 변수에 값이 있는가 검사한다.
int isset
(mixed var)
Returns true if var exists; false otherwise.
If a variable has been unset with unset(), it will no longer be isset().
1 2 $a = "test"; 3 echo isset ($a); // true 4 unset ($a); 5 echo isset ($a); // false 6 |
(PHP4 )
print_r -- 변수값을 사람이 읽을 수 있는 형태로 바꾸어 출력한다.
void print_r
(mixed
expression)
This function displays information about the values of variables in a way that's readable by humans. If given a string, integer or double, the value itself will be printed. If given an array, values will be presented in a format that shows keys and elements. Similar notation is used for objects.
Compare print_r() to var_dump().
1 2 <?php 3 $a = array (1, 2, array ("a", "b", "c")); 4 print_r ($a); 5 ?> 6 |
Warning |
This function will continue forever if given an array or object that contains a direct or indirect reference to itself or that contains an array or object on a deepre level that does so. This is especially true for print_r($GLOBALS), as $GLOBALS is itself a global variable and contains a reference to itself as such. |
settype -- 변수의 type을 설정한다.
int settype
(string var,
string type)Set the type of variable var to type.
Possibles values of type are:
Returns true if successful; otherwise returns false.
See also gettype().
strval -- 변수의 값을 문자열로 만든다.
string strval
(mixed
var)Returns the string value of var.
var may be any scalar type. You cannot use strval() on arrays or objects.
See also doubleval(), intval(), settype() and Type juggling.
unset -- 변수를 Unset한다.
int unset
(mixed var)
unset() destroys the specified variable and returns true.
Example 1. Unset() example
|
(PHP3 >= 3.0.5, PHP4 )
var_dump -- Dumps information about a variablevoid var_dump
(mixed
expression)
This function returns structured information about an expression that includes its type and value. Arrays are explored recursively with values indented to show structure.
Compare var_dump() to print_r().
1 2 <pre> 3 <?php 4 $a = array (1, 2, array ("a", "b", "c")); 5 var_dump ($a); 6 ?> 7 </pre> 8 |
이 함수들은 QMAIL (www.qmail.org) 과 vmailmgr 패키지를 필요로 한다. 이 패키지는 Bruce Guenter에 의해 제공되고 있고 http://www.qcc.sk.ca/~bguenter/distrib/vmailmgr/ 에서 찾을 수 있다.
아래의 함수들에서는 두 개의 변수가 정의되어 있다 : 여러분의 가상 domain (vdomain.com)의 도메인 이름을 값으로 가지는 vdomain이라는 string 변수와, 가상 user들을 가지고 있는 '진짜(real)' user의 password를 값으로 가지는 basepwd라는 string 변수이다.
가상 user들의 password는 8자까지만 인식되고 그 이후는 무시된다.
모든 함수들의 return 상태는 response.h 에 다음과 같이 정의되어 있다.
O ok |
1 bad |
2 error |
3 error connecting |
알려진 문제들: vm_deluser()는 사용자의 directory를 지우지 않는다. vm_addalias()는 현재 제대로 동작하지 않는다.
1 2 <?php 3 dl("php3_vmailmgr.so"); //load the shared library 4 $vdomain="vdomain.com"; 5 $basepwd="password"; 6 ?> 7 |
vm_adduser -- 주어진 password로 새 virtual user를 만든다.
int vm_adduser
(string vdomain,
string basepwd, string newusername, string newuserpassword)Add a new virtual user with a password. newusername is the email login name and newuserpassword the password for this user.
vm_addalias -- virtual user에 alias를 추가한다.
int vm_addalias
(string vdomain, string basepwd, string username, string alias);
Add an alias to a virtual user. username is the email login name and alias is an alias for this vuser.
vm_passwd -- virtual user의 password를 변경한다.
int vm_passwd
(string
vdomain, string username, string password, string newpassword)
Changes a virtual users password. username is the email login name, password the old password for the vuser, and newpassword the new password.
vm_delalias -- alias를 지운다.
int vm_delalias
(string
vdomain, string basepwd, string alias)Removes an alias.
vm_deluser -- virtual user를 삭제한다.
int vm_deluser
(string
vdomain, string username)Removes a virtual user.
이 함수들은 WDDX와 함께 동작하도록 되어있다.
변수를 나열(serialize)하는 모든 함수들은, 배열의 첫 번째 원소로 해당 배열이 다른 배열로 나열(serialize)될 것인지, 구조체(structure)로 나열될 것인가를 결정한다. 첫번째 원소가 문자열 키를 가지고 있으면 구조체로 나열되고, 그렇지 않다면 배열로 나열된다.
Note that all the functions that serialize variables use the first element of an array to determine whether the array is to be serialized into an array or structure. If the first element has string key, then it is serialized into a structure, otherwise, into an array.
Example 1. Serializing a single value
|
위의 예제는 다음과 같은 내용을 출력한다.:
1 2 <wddxPacket version='0.9'><header comment='PHP packet'/><data> 3 <string>PHP to WDDX packet example</string></data></wddxPacket> 4 |
Example 2. Using incremental packets
|
위의 예제는 다음과 같은 내용을 출력한다.:
1 2 <wddxPacket version='0.9'><header comment='PHP'/><data><struct> 3 <var name='pi'><number>3.1415926</number></var><var name='cities'> 4 <array length='3'><string>Austin</string><string>Novato</string> 5 <string>Seattle</string></array></var></struct></data></wddxPacket> 6 |
wddx_serialize_value -- WDDX 패켓에 단일 값을 serialize 한다.
string wddx_serialize_value
(mixed var, string [comment]);
wddx_serialize_value() is used to create a WDDX packet from a single given value. It takes the value contained in var, and an optional comment string that appears in the packet header, and returns the WDDX packet.
wddx_serialize_vars -- WDDX 패켓에 여러 변수를 serialize 한다.
string wddx_serialize_vars
(mixed var_name [, mixed ...])
wddx_serialize_vars() is used to create a WDDX packet with a structure that contains the serialized representation of the passed variables.
wddx_serialize_vars() takes a variable number of arguments, each of which can be either a string naming a variable or an array containing strings naming the variables or another array, etc.
Example 1. wddx_serialize_vars example
|
The above example will produce:
1 2 <wddxPacket version='0.9'><header/><data><struct><var name='a'><number>1</number></var> 3 <var name='b'><number>5.5</number></var><var name='c'><array length='3'> 4 <string>blue</string><string>orange</string><string>violet</string></array></var> 5 <var name='d'><string>colors</string></var></struct></data></wddxPacket> 6 |
wddx_packet_start -- 내부에 있는 구조대로 새로운 WDDX 패켓을 만든다.
int wddx_packet_start
(string [comment]);
Use wddx_packet_start() to start a new WDDX packet for incremental addition of variables. It takes an optional comment string and returns a packet ID for use in later functions. It automatically creates a structure definition inside the packet to contain the variables.
wddx_packet_end -- 지정된 ID의 WDDX 패켓을 종료한다.
int wddx_packet_end
(int packet_id);
wddx_packet_end() ends the WDDX packet specified by the packet_id and returns the string with the packet.
wddx_add_vars -- 해당하는 패켓에 추가로 변수들을 serialize한다.
wddx_add_vars
(int packet_id, ...);
wddx_add_vars() is used to serialize passed variables and add the result to the packet specified by the packet_id. The variables to be serialized are specified in exactly the same way as wddx_serialize_vars().
wddx_deserialize -- WDDX 패켓을 deserialize 한다.
mixed wddx_deserialize
(string packet);
wddx_deserialized() takes a packet string and deserializes it. It returns the result which can be string, number, or array. Note that structures are deserialized into associative arrays.
XML(eXtensible Markup Language)이란 웹에서 교환되는 문서를 위한 데이터 포맷의 하나이다. 이것은 W3C(World Wide Web consortium)에 의해 규정된 표준이다. XML에 대한 정보와 그에 관련된 기술들은 http://www.w3.org/XML/에서 찾아볼 수 있을 것이다.
이 확장은 http://www.jclark.com/xml/에서 찾을 수 있는 expat라는 것을 사용하고 있다. expact와 함께 따라오는 Makefile은 그대로는 라이브러리를 만들어 내지 못한다. 다음과 같은 make rule을 사용해야 가능해 진다. :
1 2 libexpat.a: $(OBJS) 3 ar -rc $@ $(OBJS) 4 ranlib $@ 5 |
expact의 소스 RPM 패키지는 http://www.guardian.no/~ssb/phpxml.html에서 찾을 수 있다.
유닉스에서는 configure를 --with-xml 옵션을 주어 실행한다. expat 라이브러리는 여러분의 컴파일러가 기본적으로 찾을 수 있는 곳에 설치되어 있어야 한다. 만약 설치한 expact가 컴파일러가 찾을 수 없는 곳에 있다면 configure를 실행하기 전에 환경변수 CPPFLAGS와 LDFLAGS를 여러분의 환경에서 해당 값으로 설정할 필요가 있다.
이제 PHP를 컴파일하면 된다.
이 확장은 PHP에서 James Clark의 expat를 지원하도록 해 준다. 이 Toolkit은 여러분이 XML을 해석(parse)하도록 하지만, 유효한가(validate)는 확인하지 않는다. 이 확장은 PHP가 제공하는 세가지 문자 형태(character encodings)를 지원한다. US-ASCII와 ISO-8859-1, UTF-8이 가능하다. UTF-16은 지원하지 않는다.
이 확장으로 여러분은 XML 파서를 만들고(create XML parsers), 서로다른 XML event에 대해 handlers를 정의한다. 각각의 XML 파서는 여러분이 조정가능한 몇 개의 parameters를 가지고 있다.
제공되는 XML event handlers는 다음과 같다. :
Table 1. Supported XML handlers
PHP function to set handler |
Event description |
---|---|
Element events are issued whenever the XML parser encounters start or end tags. There are separate handlers for start tags and end tags. |
|
Character data is roughly all the non-markup contents of XML documents, including whitespace between tags. Note that the XML parser does not add or remove any whitespace, it is up to the application (you) to decide whether whitespace is significant. |
|
PHP programmers should be familiar with processing instructions (PIs) already. <?php ?> is a processing instruction, where php is called the "PI target". The handling of these are application-specific, except that all PI targets starting with "XML" are reserved. |
|
What goes not to another handler goes to the default handler. You will get things like the XML and document type declarations in the default handler. |
|
This handler will be called for declaration of an unparsed (NDATA) entity. |
|
This handler is called for declaration of a notation. |
|
This handler is called when the XML parser finds a reference to an external parsed general entity. This can be a reference to a file or URL, for example. See the external entity example for a demonstration. |
element handler 함수들은 그들의 요소를 case-folded하게 얻는다. Case-folding은 XML 표준에 다음과 같이 정의되어 있다. : "a process applied to a sequence of characters, in which those identified as non-uppercase are replaced by their uppercase equivalents" (일련의 문자들에서 대문자가 아닌 글자들을 대문자와 동일하게 다루는 방법). 다른 말로 하면 case-folding이란 단순히 uppercasing을 의미한다.
기본적으로, handler 함수에 전달되는 모든 요소들의 이름은 case-folded하다. case-folded 설정은 xml_parser_get_option()과 xml_parser_set_option() 함수로 XML 파서에 대해 질의하거나 원하는 대로 설정할 수 있다.
다음의 상수들이 XML 에러 코드로 정의되어 있다. (xml_parse()의 반환값이다.)
XML_ERROR_NONE |
XML_ERROR_NO_MEMORY |
XML_ERROR_SYNTAX |
XML_ERROR_NO_ELEMENTS |
XML_ERROR_INVALID_TOKEN |
XML_ERROR_UNCLOSED_TOKEN |
XML_ERROR_PARTIAL_CHAR |
XML_ERROR_TAG_MISMATCH |
XML_ERROR_DUPLICATE_ATTRIBUTE |
XML_ERROR_JUNK_AFTER_DOC_ELEMENT |
XML_ERROR_PARAM_ENTITY_REF |
XML_ERROR_UNDEFINED_ENTITY |
XML_ERROR_RECURSIVE_ENTITY_REF |
XML_ERROR_ASYNC_ENTITY |
XML_ERROR_BAD_CHAR_REF |
XML_ERROR_BINARY_ENTITY_REF |
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF |
XML_ERROR_MISPLACED_XML_PI |
XML_ERROR_UNKNOWN_ENCODING |
XML_ERROR_INCORRECT_ENCODING |
XML_ERROR_UNCLOSED_CDATA_SECTION |
XML_ERROR_EXTERNAL_ENTITY_HANDLING |
PHP의 XML 확장은 서로 다른 character encoding들을 위해 Unicode character set을 지원한다. character encoding에는 source encoding과 target encoding의 두가지 유형이 있다. 참고로 PHP는 내부적으로 모든 문서를 UTF-8으로 encode하고 있다.
Source encoding은 XML 문서가 해석(parse)될 때 일어난다. XML 파서를 만들 때(Upon creating an XML parser), source encoding은 지정될 수 있다. (이 encoding은 해당 XML 파서가 없어질 때 까지 변경될 수 없다.) 지원되는 source encoding은 ISO-8859-1와 US-ASCII, UTF-8의 세가지 이다. 앞의 두가지는 single-byte encoding이다. 이것은 각각의 문자가 1개의 byte로 표현된다는 의미이다. UTF-8은 1 바이트에서 4 바이트(21비트)까지 변경가능한 수의 비트수로 구성된 문자로 encode한다. PHP에서 기본 source encoding은 ISO-8859-1이다.
Target encoding은 PHP가 XML handler 함수로 데이터를 넘겨줄 때 일어난다. XML 파서가 생성될 때 target encoding은 source encoding과 같은 값으로 설정되지만, 그 값은 나중에 언제라도 바꿀 수 있다. target encoding은 문자 데이터뿐 아니라, tag 이름이나 processing instruction targets에도 적용된다.
만약 XML 파서가 그것의 source encoding이 표현할 수 없는 범위에 있는 문자를 만난다면, 파서는 에러를 반환한다.
PHP가 해석된(parsed) 문서중에서 선택된 target encoding안에서 표현이 불가능한 문자를 만났다면, 이 문제가 된 문자를 "demoted"한다. 현재 그런 문자들은 물음표(?)로 대치된다.
여기에 XML 문서를 해석하는 PHP 스크립트 예제가 있다.
문서에서 시작 요소들의 구조를 indentation하여 표시하는 예제. :
Example 1. Show XML Element Structure
|
Example 2. Map XML to HTML 이 예제는 XML문서의 택을 직접적으로 HTML 택으로 map한다. "map array"에서 찾을 수 없는 요소는 무시된다. 물론, 이 예제는 특정한 문서 타입에서만 동작한다.
|
이 예제는 XML 코드의 하이라이트이다. 이것은 다른 문서를 포함(include)하고 해석(parse)하기 위해 external entity reference handler를 어떻게 사용하는가 보여주고, 어떻게 PI(processing instruction)가 수행되고, PI가 담고 있는 코드의 "신뢰(trust)"를 결정하는 가에 대한 방법을 보여준다.
이 예제를 사용하기 위한 XML 문서는 아래 예제에서 찾을 수 있다. (xmltest.xml와 xmltest2.xml.)
Example 3. External Entity Example
|
Example 4. xmltest.xml
|
이 파일은 xmltest.xml에 포함(include)된다.
Example 5. xmltest2.xml
|
xml_parser_create -- XML parser를 만든다.
int xml_parser_create
([string
encoding])
encoding (optional)
Which character encoding the parser should use. The following character encodings are supported:
ISO-8859-1 (default) |
US-ASCII |
UTF-8 |
This function creates an XML parser and returns a handle for use by other XML functions. Returns false on failure.
(PHP4 >= 4.0b4)
xml_set_object -- object에 대한 XML Parser를 사용한다. (Use XML Parser within an object)void xml_set_object
(int
parser, object &object)
This function makes parser useable from within object. All callback functions settet via xml_set_element_handler() etc are assumed to be methods of object.
1 2 <?php 3 class xml { 4 var $parser; 5 6 function xml() { 7 $this->parser = xml_parser_create(); 8 xml_set_object($this->parser,&$this); 9 xml_set_element_handler($this->parser,"tag_open","tag_close"); 10 xml_set_character_data_handler($this->parser,"cdata"); 11 } 12 13 function parse($data) { 14 xml_parse($this->parser,$data); 15 } 16 17 function tag_open($parser,$tag,$attributes) { 18 var_dump($parser,$tag,$attributes); 19 } 20 21 function cdata($parser,$cdata) { 22 var_dump($parser,$cdata); 23 } 24 25 function tag_close($parser,$tag) { 26 var_dump($parser,$tag); 27 } 28 29 } // end of class xml 30 31 $xml_parser = new xml(); 32 $xml_parser->parse("<A ID=\"hallo\">PHP</A>"); 33 ?> 34 |
Note: xml_set_object() handling was added in PHP 4.0.
xml_set_element_handler -- 시작 element handlers와 끝 element handlers를 설정한다.
int xml_set_element_handler
(int parser, string startElementHandler, string endElementHandler);
Sets the element handler functions for the XML parser parser. startElementHandler and endElementHandler are strings containing the names of functions that must exist when xml_parse() is called for parser.
The function named by startElementHandler must accept three parameters:
startElementHandler
(int parser, string name, string attribs);
The function named by endElementHandler must accept two parameters:
endElementHandler
(int parser, string name);
If a handler function is set to an empty string, or false, the handler in question is disabled.
True is returned if the handlers are set up, false if parser is not a parser.
There is currently no support for object/method handlers.
xml_set_character_data_handler -- character data handler를 설정한다.
int xml_set_character_data_handler
(int parser, string handler);
Sets the character data handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
The function named by handler must accept two parameters:
handler
(int parser, string data);
If a handler function is set to an empty string, or false, the handler in question is disabled.
True is returned if the handler is set up, false if parser is not a parser.
There is currently no support for object/method handlers.
xml_set_processing_instruction_handler -- processing instruction (PI) handler를 설정한다.
int xml_set_processing_instruction_handler
(int parser, string handler);
Sets the processing instruction (PI) handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
A processing instruction has the following format:
<?target data?>
You can put PHP code into such a tag, but be aware of one limitation: in an XML PI, the PI end tag (?>) can not be quoted, so this character sequence should not appear in the PHP code you embed with PIs in XML documents. If it does, the rest of the PHP code, as well as the "real" PI end tag, will be treated as character data.
The function named by handler must accept three parameters:
handler
(int parser, string target, string data);
If a handler function is set to an empty string, or false, the handler in question is disabled.
True is returned if the handler is set up, false if parser is not a parser.
There is currently no support for object/method handlers.
xml_set_default_handler -- 기본 handler를 설정한다.
int xml_set_default_handler
(int parser, string handler);
Sets the default handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
The function named by handler must accept two parameters:
handler
(int parser, string data);
If a handler function is set to an empty string, or false, the handler in question is disabled.
True is returned if the handler is set up, false if parser is not a parser.
There is currently no support for object/method handlers.
xml_set_unparsed_entity_decl_handler -- unparsed entity declaration handler를 설정한다.
int xml_set_unparsed_entity_decl_handler
(int parser, string handler);
Sets the unparsed entity declaration handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
This handler will be called if the XML parser encounters an external entity declaration with an NDATA declaration, like the following:
<!ENTITY name {publicId | systemId} NDATA notationName>
See section 4.2.2 of the XML 1.0 spec for the definition of notation declared external entities.
The function named by handler must accept six parameters:
handler
(int parser, string entityName, string base, string systemId, string publicId, string notationName);
If a handler function is set to an empty string, or false, the handler in question is disabled.
True is returned if the handler is set up, false if parser is not a parser.
There is currently no support for object/method handlers.
xml_set_notation_decl_handler -- notation declaration handler를 설정한다.
int xml_set_notation_decl_handler
(int parser, string handler);
Sets the notation declaration handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
A notation declaration is part of the document's DTD and has the following format:
<!NOTATION name {systemId | publicId}>
See section 4.7 of the XML 1.0 spec for the definition of notation declarations.
The function named by handler must accept five parameters:
handler
(int parser, string notationName, string base, string systemId, string publicId);
If a handler function is set to an empty string, or false, the handler in question is disabled.
True is returned if the handler is set up, false if parser is not a parser.
There is currently no support for object/method handlers.
xml_set_external_entity_ref_handler -- external entity reference handler를 설정한다.
int xml_set_external_entity_ref_handler
(int parser, string handler);
Sets the notation declaration handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
The function named by handler must accept five parameters, and should return an integer value. If the value returned from the handler is false (which it will be if no value is returned), the XML parser will stop parsing and xml_get_error_code() will return XML_ERROR_EXTERNAL_ENTITY_HANDLING.
int
handler
(int parser, string openEntityNames, string base, string systemId, string publicId);
If a handler function is set to an empty string, or false, the handler in question is disabled.
True is returned if the handler is set up, false if parser is not a parser.
There is currently no support for object/method handlers.
xml_parse -- XML document의 해석(parsing)을 시작한다.
int xml_parse
(int parser, string data, int [isFinal]);
When the XML document is parsed, the handlers for the configured events are called as many times as necessary, after which this function returns true or false.
True is returned if the parse was successful, false if it was not successful, or if parser does not refer to a valid parser. For unsuccessful parses, error information can be retrieved with xml_get_error_code(), xml_error_string(), xml_get_current_line_number(), xml_get_current_column_number() and xml_get_current_byte_index().
xml_get_error_code -- XML parser error code를 얻는다.
int xml_get_error_code
(int parser);
This function returns false if parser does not refer to a valid parser, or else it returns one of the error codes listed in the error codes section.
xml_error_string -- XML parser error 문자열을 얻는다.
string xml_error_string
(int code);
Returns a string with a textual description of the error code code, or false if no description was found.
xml_get_current_line_number -- XML parser의 현재 line number를 얻는다.
int xml_get_current_line_number
(int parser);
This function returns false if parser does not refer to a valid parser, or else it returns which line the parser is currently at in its data buffer.
xml_get_current_column_number -- XML parser의 현재 column number를 얻는다.
int xml_get_current_column_number
(int parser);
This function returns false if parser does not refer to a valid parser, or else it returns which column on the current line (as given by xml_get_current_line_number()) the parser is currently at.
xml_get_current_byte_index -- XML parser의 현재 byte index를 얻는다.
int xml_get_current_byte_index
(int parser);
This function returns false if parser does not refer to a valid parser, or else it returns which byte index the parser is currently at in its data buffer (starting at 0).
xml_parser_free -- XML parser를 해제(free)한다.
string xml_parser_free
(int parser);
This function returns false if parser does not refer to a valid parser, or else it frees the parser and returns true.
xml_parser_set_option -- XML parser의 옵션을 설정한다.
int xml_parser_set_option
(int parser, int option, mixed value);
This function returns false if parser does not refer to a valid parser, or if the option could not be set. Else the option is set and true is returned.
The following options are available:
Table 1. XML parser options
Option constant |
Data type |
Description |
---|---|---|
XML_OPTION_CASE_FOLDING |
integer |
Controls whether case-folding is enabled for this XML parser. Enabled by default. |
XML_OPTION_TARGET_ENCODING |
string |
Sets which target encoding to use in this XML parser. By default, it is set to the same as the source encoding used by xml_parser_create(). Supported target encodings are ISO-8859-1, US-ASCII and UTF-8. |
xml_parser_get_option -- XML parser의 옵션을 구한다.
mixed xml_parser_get_option
(int parser, int option);
This function returns false if parser does not refer to a valid parser, or if the option could not be set. Else the option's value is returned.
See xml_parser_set_option() for the list of options.
utf8_decode -- UTF-8으로 encode된 ISO-8859-1 문자열을 1바이트의 ISO-8859-1로 변환한다.
string utf8_decode
(string data);
This function decodes data, assumed to be UTF-8 encoded, to ISO-8859-1.
See utf8_encode() for an explaination of UTF-8 encoding.
utf8_encode -- ISO-8859-1로 encode된 문자열을 UTF-8으로 변환한다.
string utf8_encode
(string data);
This function encodes the string data to UTF-8, and returns the encoded version. UTF-8 is a standard mechanism used by Unicodefor encoding wide character values into a byte stream. UTF-8 is transparent to plain ASCII characters, is self-synchronized (meaning it is possible for a program to figure out where in the bytestream characters start) and can be used with normal string comparison functions for sorting and such. PHP encodes UTF-8 characters in up to four bytes, like this:
Table 1. UTF-8 encoding
bytes |
bits |
representation |
---|---|---|
1 |
7 |
0bbbbbbb |
2 |
11 |
110bbbbb 10bbbbbb |
3 |
16 |
1110bbbb 10bbbbbb 10bbbbbb |
4 |
21 |
11110bbb 10bbbbbb 10bbbbbb 10bbbbbb |
Each b represents a bit that can be used to store character data.
(역자주: 이부분은 별로 이용되지 않을 것으로 생각되므로 번역을 생략한다.)
PHP 3.0 is rewritten from the ground up. It has a proper parser that is much more robust and consistent than 2.0's. 3.0 is also significantly faster, and uses less memory. However, some of these improvements have not been possible without compatibility changes, both in syntax and functionality.
In addition, PHP's developers have tried to clean up both PHP's syntax and semantics in version 3.0, and this has also caused some incompatibilities. In the long run, we believe that these changes are for the better.
This chapter will try to guide you through the incompatibilities you might run into when going from PHP/FI 2.0 to PHP 3.0 and help you resolve them. New features are not mentioned here unless necessary.
A conversion program that can automatically convert your old PHP/FI 2.0 scripts exists. It can be found in the convertor subdirectory of the PHP 3.0 distribution. This program only catches the syntax changes though, so you should read this chapter carefully anyway.
The first thing you probably will notice is that PHP's start and end tags have changed. The old <? > form has been replaced by three new possible forms:
Example 0-1. Migration: old start/end tags <? echo "This is PHP/FI 2.0 code.\n"; > |
As of version 2.0, PHP/FI also supports this variation:
Example 0-2. Migration: first new start/end tags <? echo "This is PHP 3.0 code!\n"; ?> |
Notice that the end tag now consists of a question mark and a greater-than character instead of just greater-than. However, if you plan on using XML on your server, you will get problems with the first new variant, because PHP may try to execute the XML markup in XML documents as PHP code. Because of this, the following variation was introduced:
Example 0-3. Migration: second new start/end tags <?php echo "This is PHP 3.0 code!\n"; ?> |
Some people have had problems with editors that don't understand the processing instruction tags at all. Microsoft FrontPage is one such editor, and as a workaround for these, the following variation was introduced as well:
Example 0-4. Migration: third new start/end tags <script language="php"> echo "This is PHP 3.0 code!\n"; </script> |
The `alternative' way to write if/elseif/else statements, using if(); elseif(); else; endif; cannot be efficiently implemented without adding a large amount of complexity to the 3.0 parser. Because of this, the syntax has been changed:
Example 0-5. Migration: old if..endif syntax if ($foo); echo "yep\n"; elseif ($bar); echo "almost\n"; else; echo "nope\n"; endif; |
Example 0-6. Migration: new if..endif syntax if ($foo): echo "yep\n"; elseif ($bar): echo "almost\n"; else: echo "nope\n"; endif; |
Notice that the semicolons have been replaced by colons in all statements but the one terminating the expression (endif).
Just like with if..endif, the syntax of while..endwhile has changed as well:
Example 0-7. Migration: old while..endwhile syntax while ($more_to_come); ... endwhile; |
Example 0-8. Migration: new while..endwhile syntax while ($more_to_come): ... endwhile; |
Warning |
If you use the old while..endwhile syntax in PHP 3.0, you will get a never-ending loop. |
PHP/FI 2.0 used the left side of expressions to determine what type the result should be. PHP 3.0 takes both sides into account when determining result types, and this may cause 2.0 scripts to behave unexpectedly in 3.0.
Consider this example:
$a[0]=5; $a[1]=7; $key = key($a); while ("" != $key) { echo "$keyn"; next($a); }
In PHP/FI 2.0, this would display both of $a's indices. In PHP 3.0, it wouldn't display anything. The reason is that in PHP 2.0, because the left argument's type was string, a string comparison was made, and indeed "" does not equal "0", and the loop went through. In PHP 3.0, when a string is compared with an integer, an integer comparison is made (the string is converted to an integer). This results in comparing atoi("") which is 0, and variablelist which is also 0, and since 0==0, the loop doesn't go through even once.
The fix for this is simple. Replace the while statement with:
while ((string)$key != "") {
PHP 3.0's error messages are usually more accurate than 2.0's were, but you no longer get to see the code fragment causing the error. You will be supplied with a file name and a line number for the error, though.
In PHP 3.0 boolean evaluation is short-circuited. This means that in an expression like (1 || test_me()), the function test_me() would not be executed since nothing can change the result of the expression after the 1.
This is a minor compatibility issue, but may cause unexpected side-effects.
Most internal functions have been rewritten so they return TRUE when successful and FALSE when failing, as opposed to 0 and -1 in PHP/FI 2.0, respectively. The new behaviour allows for more logical code, like $fp = fopen("/your/file") or fail("darn!");. Because PHP/FI 2.0 had no clear rules for what functions should return when they failed, most such scripts will probably have to be checked manually after using the 2.0 to 3.0 convertor.
Example 0-9. Migration from 2.0: return values, old code $fp = fopen($file, "r"); if ($fp == -1); echo("Could not open $file for reading<br>\n"); endif; |
Example 0-10. Migration from 2.0: return values, new code $fp = @fopen($file, "r") or print("Could not open $file for reading<br>\n"); |
The PHP 3.0 Apache module no longer supports Apache versions prior to 1.2. Apache 1.2 or later is required.
echo() no longer supports a format string. Use the printf() function instead.
In PHP/FI 2.0, an implementation side-effect caused $foo[0] to have the same effect as $foo. This is not true for PHP 3.0.
Reading arrays with $array[] is no longer supported
That is, you cannot traverse an array by having a loop that does $data = $array[]. Use current() and next() instead.
Also, $array1[] = $array2 does not append the values of $array2 to $array1, but appends $array2 as the last entry of $array1. See also multidimensional array support.
"+" is no longer overloaded as a concatenation operator for strings, instead it converts it's arguments to numbers and performs numeric addition. Use "." instead.
Example 0-11. Migration from 2.0: concatenation for strings echo "1" + "1"; In PHP 2.0 this would echo 11, in PHP 3.0 it would echo 2. Instead use: echo "1"."1"; $a = 1; $b = 1; echo $a + $b; This would echo 2 in both PHP 2.0 and 3.0. $a = 1; $b = 1; echo $a.$b; This will echo 11 in PHP 3.0. |
모든 함수는 다음과 같은 모양을 취한다. :
void php3_foo(INTERNAL_FUNCTION_PARAMETERS) { }
비록 함수가 어떤 인수(argument)도 가지고 있지 않아도, 이런 방식으로 호출된다.
인수(Argument)는 한상 pval type이다. 이 type은 argument의 actual type을 가진 union을 포함하고 있다. 따라서, 만약 함수가 두 개의 argument를 가진다면, 함수의 맨 처음에서 다음과 같은 동작을 취한다. :
Example 0-1. Fetching function arguments pval *arg1, *arg2; if (ARG_COUNT(ht) != 2 || getParameters(ht,2,&arg1,&arg2)==FAILURE) { WRONG_PARAM_COUNT; } |
NOTE: argument는 by value와 by reference의 방식중에 하나로 전달된다. 두 방식 모두 getParameters에 &(pval *)을 전달할 필요가 있다. 만역 여러분이 n번째 parameter가 by reference로 전달되었는가를 검사하려면, ParameterPassedByReference(ht,n) 함수를 사용한다. 이 함수는 1이나 0을 반환한다.
When you change any of the passed parameters, whether they are sent by reference or by value, you can either start over with the parameter by calling pval_destructor on it, or if it's an ARRAY you want to add to, you can use functions similar to the ones in internal_functions.h which manipulate return_value as an ARRAY.
Also if you change a parameter to IS_STRING make sure you first assign the new estrdup()'ed string and the string length, and only later change the type to IS_STRING. If you change the string of a parameter which already IS_STRING or IS_ARRAY you should run pval_destructor on it first.
A function can take a variable number of arguments. If your function can take either 2 or 3 arguments, use the following:
Example 0-2. Variable function arguments pval *arg1, *arg2, *arg3; int arg_count = ARG_COUNT(ht); if (arg_count < 2 || arg_count > 3 || getParameters(ht,arg_count,&arg1,&arg2,&arg3)==FAILURE) { WRONG_PARAM_COUNT; } |
개별 argument의 type은 pval type 필드에 저장된다. 이 type은 다음중 한 개다. :
Table 0-1. PHP Internal Types
IS_STRING |
String |
IS_DOUBLE |
Double-precision floating point |
IS_LONG |
Long integer |
IS_ARRAY |
Array |
IS_EMPTY |
None |
IS_USER_FUNCTION |
?? |
IS_INTERNAL_FUNCTION |
?? (if some of these cannot be passed to a function - delete) |
IS_CLASS |
?? |
IS_OBJECT |
?? |
If you get an argument of one type and would like to use it as another, or if you just want to force the argument to be of a certain type, you can use one of the following conversion functions:
convert_to_long(arg1); convert_to_double(arg1); convert_to_string(arg1); convert_to_boolean_long(arg1); /* If the string is "" or "0" it becomes 0, 1 otherwise */ convert_string_to_number(arg1); /* Converts string to either LONG or DOUBLE depending on string */
These function all do in-place conversion. They do not return anything.
The actual argument is stored in a union; the members are:
IS_STRING: arg1->value.str.val
IS_LONG: arg1->value.lval
IS_DOUBLE: arg1->value.dval
함수가 필요한 모든 메모리는 emalloc()이나 estrdup()을 사용해서 확보한다. 이 함수들은 일반적인 malloc(), strdup()과 비슷하게 느껴지는 추상적인 메모리 관리 함수이다. 이 메모리는 efree()함수를 사용하여 해제(free)된다.
프로그램에서는 다음과 같은 두 종류의 종류의 메모리가 사용된다. : 변수에서 사용하여 파서에 돌려지는 메모리와, 여러분의 내부 함수(internal function)에서 임시 저장 공간으로 필요한 메모리. 만약 여러분이 문자열을 파서에 돌려줄 변수에 저장하려 한다면, 이 변수는 우선 emalloc()이나 estrdup()의 함수를 사용하여 메모리의 공간을 확보할 필요가 있다. 이 메모리는 절대 여러분이 풀어줄 수 없다. 단지, 후에 같은 함수내에서 원래의 대입된 값을 바꾸어 줄 수 있을 뿐이다.
여러분이 함수나 라이브러리에서 필요한 어떠한 임시/영구적인 메모리에 대해서도, 여러분은 emalloc()과 estrdup(), efree()의 3개의 함수를 사용해야 한다. 이 함수들은 반드시 그것에 대응되는 함수들과 함께 작동해야 한다. emalloc()이나 estrdup()을 사용한 메모리에는, 이 메모리가 프로그램이 종료될 때까지 필요한 것이 아닌 한, 반드시 efree()가 필요하다. 만약 그렇게 하지 않으면 메모리 누설(leak)이 발생한다. "그 함수가 그것에 대응되는 함수와 함께 작동해야 한다"는 것의 의미는, emalloc()이나 estrdup()없이 efree()를 사용한다면 여러분은 segment fault 오류를 만나게 될 것이다. 그러므로 필요없는 메모리에 대한 해제는 충분한 주의를 기울여야 할 것이다.
PHP을 "-DDEBUG"를 주고 컴파일하였다면, PHP는 emalloc()이나 estrdup()에 의해 확보된 모든 메모리의 list를 표시할 것이다. 그러나, efree()함수를 사용해도 해제되지 않고, 해당 프로그램이 종료될 때 해제된다.
symbol table에 변수를 설정하기 쉽게하기 위해 다음과 같은 몇 개의 macro가 있다. :
SET_VAR_STRING(name,value) [1]
SET_VAR_DOUBLE(name,value)
SET_VAR_LONG(name,value)
PHP 3.0의 Symbol tables은 hash table의 형태로 되어 있다. 언제나 &symbol_table은 'main' symbol table을 가리키고 있고, active_symbol_table은 현재 active된 symbol table을 가리키고 있다. (이 두가지는 시작(startup)시는 같지만, 함수안에서는 달라진다.)
The following examples use 'active_symbol_table'. You should replace it with &symbol_table if you specifically want to work with the 'main' symbol table. Also, the same functions may be applied to arrays, as explained below.
Example 0-3. Checking whether $foo exists in a symbol table if (hash_exists(active_symbol_table,"foo",sizeof("foo"))) { exists... } else { doesn't exist } |
Example 0-4. Finding a variable's size in a symbol table hash_find(active_symbol_table,"foo",sizeof("foo"),&pvalue); check(pvalue.type); |
Arrays in PHP 3.0 are implemented using the same hashtables as symbol tables. This means the two above functions can also be used to check variables inside arrays.
If you want to define a new array in a symbol table, you should do the following.
First, you may want to check whether it exists and abort appropiately, using hash_exists() or hash_find().
Next, initialize the array:
Example 0-5. Initializing a new array pval arr; if (array_init(&arr) == FAILURE) { failed... }; hash_update(active_symbol_table,"foo",sizeof("foo"),&arr,sizeof(pval),NULL); |
This code declares a new array, named $foo, in the active symbol table. This array is empty.
Here's how to add new entries to it:
Example 0-6. Adding entries to a new array pval entry; entry.type = IS_LONG; entry.value.lval = 5; /* defines $foo["bar"] = 5 */ hash_update(arr.value.ht,"bar",sizeof("bar"),&entry,sizeof(pval),NULL); /* defines $foo[7] = 5 */ hash_index_update(arr.value.ht,7,&entry,sizeof(pval),NULL); /* defines the next free place in $foo[], * $foo[8], to be 5 (works like php2) */ hash_next_index_insert(arr.value.ht,&entry,sizeof(pval),NULL); |
If you'd like to modify a value that you inserted to a hash, you must first retrieve it from the hash. To prevent that overhead, you can supply a pval ** to the hash add function, and it'll be updated with the pval * address of the inserted element inside the hash. If that value is NULL (like in all of the above examples) - that parameter is ignored.
hash_next_index_insert() uses more or less the same logic as "$foo[] = bar;" in PHP 2.0.
If you are building an array to return from a function, you can initialize the array just like above by doing:
if (array_init(return_value) == FAILURE) { failed...; }
...and then adding values with the helper functions:
add_next_index_long(return_value,long_value); add_next_index_double(return_value,double_value); add_next_index_string(return_value,estrdup(string_value));
Of course, if the adding isn't done right after the array initialization, you'd probably have to look for the array first:
pval *arr; if (hash_find(active_symbol_table,"foo",sizeof("foo"),(void **)&arr)==FAILURE) { can't find... } else { use arr->value.ht... }
Note that hash_find receives a pointer to a pval pointer, and not a pval pointer.
Just about any hash function returns SUCCESS or FAILURE (except for hash_exists(), which returns a boolean truth value).
함수에서 쉽게 값을 반환하기 위해 다음과 같은 몇 개의 매크로가 있다. :
모든 RETURN_* 매크로들은 return값을 설정하고, 해당 함수로부터 복귀한다. :
RETURN
RETURN_FALSE
RETURN_TRUE
RETURN_LONG(l)
RETURN_STRING(s,dup) If dup is true, duplicates the string
RETURN_STRINGL(s,l,dup) Return string (s) specifying length (l).
RETURN_DOUBLE(d)
모든 RETVAL_* 매크로들은 return값을 설정하지만, 해당 함수로부터 복귀하지는 않는다. :
RETVAL_FALSE
RETVAL_TRUE
RETVAL_LONG(l)
RETVAL_STRING(s,dup) If dup is true, duplicates the string
RETVAL_STRINGL(s,l,dup) Return string (s) specifying length (l).
RETVAL_DOUBLE(d)
The string macros above will all estrdup() the passed 's' argument, so you can safely free the argument after calling the macro, or alternatively use statically allocated memory.
If your function returns boolean success/error responses, always use RETURN_TRUE and RETURN_FALSE respectively.
함수는 object나 array같은 complex data도 반환할 수 있다.
Returning an object:
Call object_init(return_value).
Fill it up with values. The functions available for this purpose are listed below.
Possibly, register functions for this object. In order to obtain values from the object, the function would have to fetch "this" from the active_symbol_table. Its type should be IS_OBJECT, and it's basically a regular hash table (i.e., you can use regular hash functions on .value.ht). The actual registration of the function can be done using:
add_method( return_value, function_name, function_ptr );
The functions used to populate an object are:
add_property_long( return_value, property_name, l ) - Add a property named 'property_name', of type long, equal to 'l'
add_property_double( return_value, property_name, d ) - Same, only adds a double
add_property_string( return_value, property_name, str ) - Same, only adds a string
add_property_stringl( return_value, property_name, str, l ) - Same, only adds a string of length 'l'
Returning an array:
Call array_init(return_value).
Fill it up with values. The functions available for this purpose are listed below.
The functions used to populate an array are:
add_assoc_long(return_value,key,l) - add associative entry with key 'key' and long value 'l'
add_assoc_double(return_value,key,d)
add_assoc_string(return_value,key,str)
add_assoc_stringl(return_value,key,str,length) specify the string length
add_index_long(return_value,index,l) - add entry in index 'index' with long value 'l'
add_index_double(return_value,index,d)
add_index_string(return_value,index,str)
add_index_stringl(return_value,index,str,length) - specify the string length
add_next_index_long(return_value,l) - add an array entry in the next free offset with long value 'l'
add_next_index_double(return_value,d)
add_next_index_string(return_value,str)
add_next_index_stringl(return_value,str,length) - specify the string length
PHP 3.0은 여러 자원의 가지 형태를 다루는 표준적인 방법을 가지고 있다. 이것은 PHP 2.0의 모든 지역적인 linked list를 대체한다.
Available functions:
php3_list_insert(ptr, type) - returns the 'id' of the newly inserted resource
php3_list_delete(id) - delete the resource with the specified id
php3_list_find(id,*type) - returns the pointer of the resource with the specified id, updates 'type' to the resource's type
Typically, these functions are used for SQL drivers but they can be used for anything else; for instance, maintaining file descriptors.
Typical list code would look like this:
Example 0-7. Adding a new resource RESOURCE *resource; /* ...allocate memory for resource and acquire resource... */ /* add a new resource to the list */ return_value->value.lval = php3_list_insert((void *) resource, LE_RESOURCE_TYPE); return_value->type = IS_LONG; |
Example 0-8. Using an existing resource pval *resource_id; RESOURCE *resource; int type; convert_to_long(resource_id); resource = php3_list_find(resource_id->value.lval, &type); if (type != LE_RESOURCE_TYPE) { php3_error(E_WARNING,"resource index %d has the wrong type",resource_id->value.lval); RETURN_FALSE; } /* ...use resource... */ |
Example 0-9. Deleting an existing resource pval *resource_id; RESOURCE *resource; int type; convert_to_long(resource_id); php3_list_delete(resource_id->value.lval); |
The resource types should be registered in php3_list.h, in enum list_entry_type. In addition, one should add shutdown code for any new resource type defined, in list.c's list_entry_destructor() (even if you don't have anything to do on shutdown, you must add an empty case).
PHP 3.0은 영구적인 자원(persistent resources; i.e., resources that are kept in between hits)을 저장하는 표준적인 방법을 가지고 있다. 이 방법은 MySQL 모듈에서 처음사용되었고, mSQL도 이것을 따르고 있다. 따라서 persistent resource를 어떻게 사용하는가에 대해 알고 싶다면 우선 mysql.c를 읽어보도록하자. 주의해서 볼 함수들은 다은과 같다. :
php3_mysql_do_connect |
php3_mysql_connect() |
php3_mysql_pconnect() |
persistence 모듈의 일반적인 idea는 다음과 같다. :
Code all of your module to work with the regular resource list mentioned in section (9).
Code extra connect functions that check if the resource already exists in the persistent resource list. If it does, register it as in the regular resource list as a pointer to the persistent resource list (because of 1., the rest of the code should work immediately). If it doesn't, then create it, add it to the persistent resource list AND add a pointer to it from the regular resource list, so all of the code would work since it's in the regular resource list, but on the next connect, the resource would be found in the persistent resource list and be used without having to recreate it. You should register these resources with a different type (e.g. LE_MYSQL_LINK for non-persistent link and LE_MYSQL_PLINK for a persistent link).
If you read mysql.c, you'll notice that except for the more complex connect function, nothing in the rest of the module has to be changed.
The very same interface exists for the regular resource list and the persistent resource list, only 'list' is replaced with 'plist':
php3_plist_insert(ptr, type) - returns the 'id' of the newly inserted resource
php3_plist_delete(id) - delete the resource with the specified id
php3_plist_find(id,*type) - returns the pointer of the resource with the specified id, updates 'type' to the resource's type
However, it's more than likely that these functions would prove to be useless for you when trying to implement a persistent module. Typically, one would want to use the fact that the persistent resource list is really a hash table. For instance, in the MySQL/mSQL modules, when there's a pconnect() call (persistent connect), the function builds a string out of the host/user/passwd that were passed to the function, and hashes the SQL link with this string as a key. The next time someone calls a pconnect() with the same host/user/passwd, the same key would be generated, and the function would find the SQL link in the persistent list.
Until further documented, you should look at mysql.c or msql.c to see how one should use the plist's hash table abilities.
One important thing to note: resources going into the persistent resource list must *NOT* be allocated with PHP's memory manager, i.e., they should NOT be created with emalloc(), estrdup(), etc. Rather, one should use the regular malloc(), strdup(), etc. The reason for this is simple - at the end of the request (end of the hit), every memory chunk that was allocated using PHP's memory manager is deleted. Since the persistent list isn't supposed to be erased at the end of a request, one mustn't use PHP's memory manager for allocating resources that go to it.
When you register a resource that's going to be in the persistent list, you should add destructors to it both in the non-persistent list and in the persistent list. The destructor in the non-persistent list destructor shouldn't do anything. The one in the persistent list destructor should properly free any resources obtained by that type (e.g. memory, SQL links, etc). Just like with the non-persistent resources, you *MUST* add destructors for every resource, even it requires no destructotion and the destructor would be empty. Remember, since emalloc() and friends aren't to be used in conjunction with the persistent list, you mustn't use efree() here either.
많은 PHP의 기능(feature)들이 실행중에 설정 가능하다. 이 설정 지시자(configuration directives)는 php3.ini에 설정되거나, Apache 모듈의 경우 .conf 파일에 설정가능하도록 되어 있다. Apache .conf 파일에 설정하는 것의 장점은 디렉토리별로 설정을 다르게 할 수 있다는 점이다. 이것은 예를들어 어떤 디렉토리가 다른 디렉토리를 가지고 있어도, 해당하는 한 디렉토리에만 safemodeexecdir 설정을 할 수 있다는 것이다. 이 개별 설정 기능은 서버가 multiple virtual hosts를 지원할 때 무척 유용하다.
The steps required to add a new directive:
Add directive to php3_ini_structure struct in mod_php3.h.
In main.c, edit the php3_module_startup function and add the appropriate cfg_get_string() or cfg_get_long() call.
Add the directive, restrictions and a comment to the php3_commands structure in mod_php3.c. Note the restrictions part. RSRC_CONF are directives that can only be present in the actual Apache .conf files. Any OR_OPTIONS directives can be present anywhere, include normal .htaccess files.
In either php3take1handler() or php3flaghandler() add the appropriate entry for your directive.
In the configuration section of the _php3_info() function in functions/info.c you need to add your new directive.
And last, you of course have to use your new directive somewhere. It will be addressable as php3_ini.directive.
내부 함수(internal function)에서 사용자 함수를 부르려면, call_user_function() 함수를 사용하여야 한다.
call_user_function() returns SUCCESS on success, and FAILURE in case the function cannot be found. You should check that return value! If it returns SUCCESS, you are responsible for destroying the retval pval yourself (or return it as the return value of your function). If it returns FAILURE, the value of retval is undefined, and you mustn't touch it.
All internal functions that call user functions must be reentrant. Among other things, this means they must not use globals or static variables.
call_user_function() takes six arguments:
This is the hash table in which the function is to be looked up.
This is a pointer to an object on which the function is invoked. This should be NULL if a global function is called. If it's not NULL (i.e. it points to an object), the function_table argument is ignored, and instead taken from the object's hash. The object *may* be modified by the function that is invoked on it (that function will have access to it via $this). If for some reason you don't want that to happen, send a copy of the object instead.
The name of the function to call. Must be a pval of type IS_STRING with function_name.str.val and function_name.str.len set to the appropriate values. The function_name is modified by call_user_function() - it's converted to lowercase. If you need to preserve the case, send a copy of the function name instead.
A pointer to a pval structure, into which the return value of the invoked function is saved. The structure must be previously allocated - call_user_function() does NOT allocate it by itself.
The number of parameters being passed to the function.
An array of pointers to values that will be passed as arguments to the function, the first argument being in offset 0, the second in offset 1, etc. The array is an array of pointers to pval's; The pointers are sent as-is to the function, which means if the function modifies its arguments, the original values are changed (passing by reference). If you don't want that behavior, pass a copy instead.
내부 함수에서 에러를 report할 때는 php3_error()함수를 사용하는 것이 좋다. 이 함수는 최소 두개의 인수를 가지고 호출된다. 첫번째는 에러의 level이고, 다른 하나는 에러 메세지를 위한 format string( printf()에서 사용되는 것과 같은 형태) 이다. 그리고 그 나머지는 주어진 format string의 parameter가 된다. 에러 level은 다음과 같다. :
Notice는 기본적으로는 출력되지 않는다. 이것은 스크립트가 뭔가 에러를 감지했지만, 그것이 정상적인 상황에서 발생하는 것이라는 의미이다. 예를들어 설정되지 않은 변수를 사용하려 했거나, 존재하지 않는 파일에 stat() 함수를 호출하는 것 등이다.
Warning은 기본적으로 출력된다. 그러나, 스크립트의 실행을 멈추지는 않는다. 이것은 호출이 완료되기 전에 스크립트에 의해 잡혀져야 하는 문제를 가리킨다. 예를들어 잘못된 regular expression으로 ereg()를 호출하는 것 등이다.
Error도 기본적으로 출력된다. 그리고, 함수의 실행이 완료된 직후, 스크립트의 실행을 멈춘다. 이것은 memory allocation 문제같은 복구가 불가능한 에러를 의미한다.
Parse error는 오직 Parser만이 생성가능하다. code가 list된다.
PHP의 core에의해 생성된다는 점을 제외하고는 E_ERROR와 동일하다. 일반 함수로는 이 형태의 에러를 만들지 못한다.
PHP의 core에의해 생성된다는 점을 제외하고는 E_WARNING와 동일하다. 일반 함수로는 이 형태의 에러를 만들지 못한다.
PHP의 내장 디버거는 파악하기 힘든 버그를 찾아내는데 매우 유용한 도구이다. 디버거는 PHP가 시작될 때마다 TCP 포트에 접속하여 동작한다. 요구에 대한 모든 에러 메세지가 이 점속을 통해 전달된다. This information is intended for "debugging server" that can run inside an IDE or programmable editor (such as Emacs).
debugger 설정 방법:
이제, 모든 warning과 notice 등이 listener socket에 표시될 것이다. 만약 여러분이 error_reporting()를 사용해서 report하지 못하도록 해도 이 레포트는 동작한다.
debugger protocol은 라인 단위이다. 각 라인은 type을 가지고 있고, 여러라인이 하나의 메세지를 구성한다. 각 메세지는 start type 으로 시작하고, end type으로 끝난다. PHP는 동시에 여러 다른 메세지의 라인을 보낼 수도 있다.
한 줄은 다음과 같은 format으로 되어 있다.:
date time
host(pid)
type:
message-data
Table C-1. Debugger Line Types
Name |
Meaning |
---|---|
start |
Tells the receiving program that a debugger message starts here. The contents of data will be the type of error message, listed below. |
message |
The PHP error message. |
location |
File name and line number where the error occured. The first location line will always contain the top-level location. data will contain file:line. There will always be a location line after message and after every function. |
frames |
Number of frames in the following stack dump. If there are four frames, expect information about four levels of called functions. If no "frames" line is given, the depth should be assumed to be 0 (the error occured at top-level). |
function |
Name of function where the error occured. Will be repeated once for every level in the function call stack. |
end |
Tells the receiving program that a debugger message ends here. |
Table C-2. Debugger Error Types
Debugger |
PHP Internal |
---|---|
warning |
E_WARNING |
error |
E_ERROR |
parse |
E_PARSE |
notice |
E_NOTICE |
core-error |
E_CORE_ERROR |
core-warning |
E_CORE_WARNING |
unknown |
(any other) |
Example C-1. Example Debugger Message 1998-04-05 23:27:400966 lucifer.guardian.no(20481) start: notice |
Be careful here. The value part must be malloc'ed manually because the memory management code will try to free this pointer later. Do not pass statically allocated memory into a SET_VAR_STRING. |