PHP 매뉴얼

by:
Mehdi Achour
Friedhelm Betz
Antony Dovgal
Nuno Lopes
Hannes Magnusson
Georg Richter
Damien Seguy
Jakub Vrana
2009-07-24
Edited By: Philip Olson
by:
LEE Yun-young
Jin Tae-young
Joong-yeon Choi
Lee Seung Hwan
Bong-woon Suk

저작권

Copyright © 1997 - 2009 by the PHP Documentation Group. 이 저작물은 Creative Commons Attribution 3.0 이상의 사용허가 조항 및 제약에 따를 경우에 배포할 수 있습니다. Creative Commons Attribution 3.0 라이센스 사본은 매뉴얼과 함께 배포됩니다. 최신 버전은 » http://creativecommons.org/licenses/by/3.0/에서 확인할 수 있습니다.

변경 여부에 관계 없이, 이 문서의 전체나 부분에 대한 재배포나 출판에 관심이 있을 경우 저작권자(» doc-license@lists.php.net)에게 문의하십시오. 주의: 이 주소는 공개적으로 기록되는 메일링 리스트입니다.



PHP 매뉴얼


서문

PHP는 하이퍼텍스트 전처리기("PHP: Hypertext Preprocessor")를 의미하며, 널리 쓰이는 오픈 소스 일반 스크립트 언어입니다. 특히 웹 개발에 적합하고 HTML에 삽입할 수 있습니다. 문법은 C, Java, Perl과 흡사하여 배우기 쉽습니다. 주 목표는 웹 개발자가 동적으로 생성되는 웹 페이지를 빠르게 개발할 수 있게 하는 것이지만, PHP로 할 수 있는 일은 훨씬 많습니다.

이 메뉴얼은 본래 함수 레퍼런스이지만, 문법 레퍼런스 및 PHP의 주요 기능과 기타 추가 정보를 수록하고 있습니다.

다양한 형태의 매뉴얼을 » http://www.php.net/download-docs.php에서 받을 수 있습니다. 부록 메뉴얼에 관하여에서 매뉴얼이 어떻게 개발되는지 찾아 볼 수 있습니다. PHP의 역사에 관심이 있으면, 해당 부록을 참고하십시오.

저자와 공헌자

현재 가장 활발한 사람을 매뉴얼 첫 페이지에 표시하지만, 그 외에도 현재 작업을 돕는, 또는 과거에 프로젝트에 많은 양의 도움을 준 공헌자들이 많이 있습니다. 많은 수의 이름이 남지 않은 매뉴얼 페이지의 사용자 노트는 계속하여 참조되어지고, 매우 고마운 일입니다. 아래의 모든 목록은 알파벳 순입니다.

저자와 편집자

다음 공헌자들은 매뉴얼에 많은 콘텐트를 추가한 영향을 인정합니다: Bill Abt, Jouni Ahto, Alexander Aulbach, Daniel Beckham, Stig Bakken, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall, Simone Cortesi, Markus Fischer, Wez Furlong, Sara Golemon, Rui Hirokawa, Brad House, Pierre-Alain Joye, Etienne Kneuss, Moriyoshi Koizumi, Rasmus Lerdorf, Andrew Lindeman, Stanislav Malyshev, Rafael Martinez, Rick McGuire, Yasuo Ohgaki, Derick Rethans, Rob Richards, Sander Roobol, Egon Schmid, Thomas Schoefbeck, Sascha Schumann, Dan Scott, Masahiro Takagi, Michael Wallner, Lars Torben Wilson, Jim Winstead, Jeroen van Wolffelaar 그리고 Andrei Zmievski.

다음 공헌자들은 매뉴얼 편집에 많은 도움을 주었습니다: Stig Bakken, Gabor Hojtsy, Hartmut Holzgraefe 그리고 Egon Schmid.

사용자 노트 관리자

현재 가장 활동중인 관리자: Daniel Brown, Nuno Lopes, Felipe Pena, Thiago Pojda 그리고 Maciek Sokolewicz.

이 사람들은 사용자 노트 관리에 많은 노력을 했습니다: Mehdi Achour, Daniel Beckham, Friedhelm Betz, Victor Boivie, Jesus M. Castagnetto, Nicolas Chaillan, Ron Chmara, Sean Coates, James Cox, Vincent Gevers, Sara Golemon, Zak Greant, Szabolcs Heilig, Oliver Hinckel, Hartmut Holzgraefe, Etienne Kneuss, Rasmus Lerdorf, Matthew Li, Andrew Lindeman, Aidan Lister, Hannes Magnusson, Maxim Maletsky, Bobby Matthis, James Moore, Philip Olson, Sebastian Picklum, Derick Rethans, Sander Roobol, Damien Seguy, Jason Sheets, Tom Sommer, Jani Taskinen, Yasuo Ohgaki, Jakub Vrana, Lars Torben Wilson, Jim Winstead, Jared Wyles 그리고 Jeroen van Wolffelaar.




시작하기


소개

Table of Contents


PHP란?

PHP(정식 명칭 "PHP: Hypertext Preprocessor")는 범용성을 지닌 널리 사용되는 오픈 소스 스크립트 언어입니다. 특히, 웹 개발 및 HTML에 포함하기에 적합합니다.

좋습니다, 그려면 어떤 의미일까요? 다음 예제를 봅시다:

Example #1 소개용 예제

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>예제</title>
    </head>
    <body>

        <?php
            
echo "안녕, 나는 PHP 스크립트야!"
        
?>

    </body>
</html>

(C나 펄처럼) HTML을 출력하기 위해서 많은 명령을 쓰는 대신, PHP 페이지는 "무언가"(여기서는, "안녕, 나는 PHP 스크립트야!"를 출력)를 하는 추가적인 코드를 가진 HTML입니다. PHP 코드는 "PHP 모드"로 들어가는 특수한 프로세싱 시말 지시 <??> 사이에 들어가 있습니다.

PHP가 클라이언트측 자바스크립트 등과 구별되는 점은 이 코드는 서버에서 실행하여, HTML 생성하여 전송하는 점입니다. 클라이언트는 스크립트 실행 결과만을 받게 되고, 그 코드의 모양은 알 수 없습니다. 웹 서버를 설정하여 모든 HTML 파일을 PHP가 처리하게 할 수 있으며, 그러면 사용자가 무엇으로 처리하는 지 알 방법은 없습니다.

PHP를 사용하는 가장 큰 이득은 초보에게는 매우 쉽고, 전문가에게는 많은 고급 기능을 제공한다는 점입니다. PHP 기능의 긴 리스트를 읽는 것을 두려워하지 마십시오. 그저 시작해 보면 짧은 시간 안에 간단한 스크립트를 작성할 수 있을 것입니다.

PHP의 개발은 서버측 스크립팅에 초점이 맞추어져 있지만, 그보다 더 많은 것들을 할 수 있습니다. PHP로 할 수 있는 것들 섹션을 참고하거나, 웹 프로그래밍에만 관심이 있다면 간단한 튜토리얼로 넘어가십시오.



PHP로 할 수 있는 것들

PHP로 무엇이든지 할 수 있습니다. PHP는 서버측 스크립팅에 중점을 두고 있어, 다른 종류의 CGI 프로그램이 하는 모든 것을 할 수 있습니다. 예를 들면, 폼 데이터를 수집하거나, 동적인 페이지 콘텐츠를 만들거나 쿠키를 보내고 받을 수 있습니다. 그리고 PHP는 더 많은 것들을 할 수 있습니다.

PHP 스크립트가 사용되는 세가지 중점적인 영역이 있습니다.

  • 서버측 스크립팅. 이것은 PHP에서 가장 오래되고, 중점적인 영역입니다. 이 일을 위해서는 세가지가 필요합니다. PHP 파서 (CGI나 서버 모듈), 웹서버, 그리고 웹 브라우저. PHP가 설치된 웹서버를 실행시킬 필요가 있습니다. 웹 브라우저로 서버에 있는 PHP 페이지를 보는 것으로 PHP 프로그램 출력에 접근하게 됩니다. 단순히 PHP 프로그래밍을 경험해보고 싶다면, 당신의 집에 있는 머신으로도 가능합니다. 더 많은 정보는 설치 안내 섹션을 참고하십시오.
  • 커맨드 라인 스크립팅. 어떠한 서버나 브라우저 없이 PHP 스크립트를 실행하게 할 수 있습니다. 이 때에는 PHP 파서만 있으면 됩니다. 이런 사용법은 스크립트를 cron(*nix나 Linux에서)이나 작업 관리자(윈도우에서)를 사용해 실행하는 것과 동일합니다. 이런 스크립트들은 간단한 텍스트 처리 작업에 사용될 수도 있습니다. 더 많은 정보를 위해서는 PHP의 커맨드 라인 사용법 섹션을 참고하십시오.
  • 데스크톱 어플리케이션의 작성. PHP는 그래픽 유저 인터페이스를 가지는 데스크탑 어플리케이션을 작성하기에 최적의 언어는 아니지만, PHP를 잘 이해하고 있고, 고급의 PHP 기능을 클라이언트측 어플리케이션에 사용하고 싶다면, 그러한 프로그램을 위해 PHP-GTK를 사용할 수 있습니다. 또한, 이러한 방법으로 플래폼에 상관 없이 작동하는 어플리케이션을 작성할 수도 있습니다. PHP-GTK는 PHP의 확장으로, 배포판에는 포함되어 있지 않습니다. PHP-GTK에 흥미가 있다면, » PHP-GTK 웹사이트를 방문해 보십시오.

PHP는 리눅스, 많은 유닉스 계열 (HP-UX, Solaris와 OpenBSD를 포함), 마이크로소프트 윈도우, 맥 OS X, RISC OS 등과 같은 모든 유명한 OS에서 사용할 수 있습니다. 또한, PHP는 오늘날의 대부분의 웹 서버를 지원합니다. 이것에는 아파치, Microsoft Internet Information Server, Personal Web Server, Netscape and iPlanet servers, Oreilly, Website Pro server, Caudium, Xitami, OmniHTTPd, 그 외의 많은 서버들을 포함합니다. 유명한 서버에 대해서는 PHP 모듈이 있으며, 다른 것에 대해서는 CGI 표준을 지원한다면, PHP는 CGI 프로세서로 동작할 수 있습니다.

그러므로 PHP라면, OS와 웹서버를 선택하는 것에서 자유로워 질 수 있습니다. 추가로, 함수 지향형이나 객체 지향형, 또는 그 둘을 섞은 형태로 프로그램을 할 수 있습니다. 비록 PHP 4는 모든 표준 OOP 기능을 포함하고 있지 않지만, 많은 코드 라이브러리와 커다란 애플리케이션들(PEAR 라이브러리를 포함하여)이 OOP 코드만을 이용하여 작성되고 있습니다. PHP 5는 PHP 4에서의 객체 관련 취약점을 보완하고, 완전한 객체 모델을 지원하고 있습니다.

PHP는 HTML을 출력하는 것에만 제한되지 않습니다. PHP의 능력은 이미지, PDF 파일, 심지어 플래시 무비(libswf와 Ming를 사용하여)까지 만들어서 출력할 수 있습니다. 또한 XHTML이나 다른 종류의 XML 파일과 같은 어떠한 텍스트 파일이라도 쉽게 출력할 수 있습니다. PHP로 출력을 하는 대신, 자동적으로 만들어진 파일들을 파일 시스템에 저장하여 동적 컨텐츠에 대한 서버측 캐시를 구현할 수도 있습니다.

PHP의 가장 강력하고 인상적인 기능 중 하나는 넓은 범위의 데이터베이스에 대한 지원입니다. 데이터베이스를 이용하는 웹 페이지를 작성하는것은 매우 간단합니다. 현재 다음과 같은 데이터베이스를 지원하고 있습니다:

  • Adabas D
  • dBase
  • Empress
  • FilePro (read-only)
  • Hyperwave
  • IBM DB2
  • Informix
  • Ingres
  • InterBase
  • FrontBase
  • mSQL
  • Direct MS-SQL
  • MySQL
  • ODBC
  • Oracle (OCI7 and OCI8)
  • Ovrimos
  • PostgreSQL
  • SQLite
  • Solid
  • Sybase
  • Velocis
  • Unix dbm

또한 데이터베이스 추상 확장(이름은 PDO)은 이 확장이 지원하는 어떠한 데이터베이스라도 투명하게 사용할 수 있게 합니다. 추가로 PHP는 공개 데이터베이스 접속 표준(ODBC)을 지원하기 때문에, 이 세계 표준을 지원하는 어떤 데이터베이스라도 연결할 수 있습니다.

또한 PHP는 LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (윈도우에서), 그리고 셀 수 없는 여러가지 프로토콜들을 이용해서 다른 서비스와 연계할 수 있도록 지원합니다. 또한 비어있는 네트워크 소켓을 열수도 있기에 어떤 프로토콜과도 연계해서 실행할 수 있습니다. PHP는 WDDX complex data exchange between virtually all Web programming languages를 지원합니다. 이를 통한 연계로, PHP는 자바 객체를 그대로 PHP 객체로 옮겨서 이용할 수 있습니다. 또한 원거리 객체 접근을 위해 CORBA 익스텐션을 이용할 수도 있습니다.

PHP는 극도로 유용한 텍스트 처리 기능을 가지고 있습니다. POSIX 확장 정규표현식이나 펄 정규표현식을 가지고 있고, XML 문서 처리를 위하여 PHP 4는 SAX와 DOM 표준을 지원하고, XML 문서를 변형하기 위해 XSLT 확장을 사용할 수 있습니다. PHP 5는 모든 XML 확장을 libxml2의 튼튼한 기반 위에 표준화하고, SimpleXML과 XMLReader 지원을 추가하여 기능을 확장하였습니다.

마지막으로, 하지만 적지 않게 (At last but not least), 많은 또다른 재미있는 확장들이 있습니다. mnoGoSearch 검색 엔진 함수, IRC 게이트웨이 함수, 많은 압축 유틸리티 (gzip, bz2, zip), 달력 변환, 번역...

이 페이지만을 보는 것으로는 PHP가 제공할 수 있는 모든 기능과 이득을 알기에는 충분하지 않습니다. PHP 설치하기 섹션을 읽어보고, 이곳에 언급된 확장들에 대한 함수 레퍼런스를 참고하십시오.




짧고 간단한 튜토리얼로 PHP의 가장 기초가 되는 부분을 보여드립니다. PHP는 웹페이지를 만들 때만 사용하는 것은 아니지만, 여기서는 PHP로 동적 웹페이지를 만드는 내용에 대해서만 다룹니다. PHP로 할 수 있는 것들 섹션에서 더 많은 정보를 얻을 수 있습니다.

PHP를 포함한 웹 페이지는 보통의 HTML 페이지와 같이 취급합니다. 그러므로, 보통의 HTML 페이지를 만드는 것과 같은 방법으로 작성할 수 있습니다.


무엇이 필요한가?

이 튜토리얼은 서버가 PHP를 지원하고, .php 확장자를 가지는 모든 파일을 PHP로 다루고 있다고 가정합니다. 대부분의 서버에서 이는 PHP의 기본 확장자입니다만, 확인하기 위해서 서버 관리자에게 문의해보십시오. 서버가 PHP를 지원하고 있다면, 더 이상 준비할 것은 없습니다. 단순히 .php 파일을 만들어서 웹 디렉토리에 넣으면, 서버가 자동적으로 처리합니다. 컴파일할 필요도 없고, 별도의 툴을 설치할 필요도 없습니다. PHP를 포함한 파일을, 모든 일을 할 수 있는 마법의 태그를 가진 단순한 HTML 파일이라고 생각하십시오. 대부분의 웹 호스트는 PHP를 지원하지만, 지원하지 않을 경우에는 » PHP 링크 섹션에서 PHP를 지원하는 웹 호스트에 대한 정보를 얻을 수 있습니다.

대역폭을 보존하기 위해 로컬 영역에서 개발하고 싶을 수도 있습니다. 이 경우에는, » 아파치 등의 웹 서버와 함께 » PHP를 설치할 수 있습니다. 원한다면 » MySQL 등의 데이터베이스를 설치할 수도 있습니다.

이들은 개별적으로 설치하거나, 보다 간단한 방법을 이용할 수 있습니다. 매뉴얼에는 PHP 설치 안내(이미 설치한 몇몇 웹 서버를 따라서)가 있습니다. 이 경우, PHP 설치시에 문제가 있다면, » 설치 메일링 리스트를 통하여 질문을 할 수 있습니다. 보다 간단한 길을 간다면, 사용하는 OS를 위한 » 미리 설정된 패키지를 사용하여, 이 모든 것을 간단한 마우스 클릭만으로 설치할 수 있습니다. MacOSX, 리눅스, 윈도우를 포함하여, 어떠한 운영 체제 아래에서도 간단히 PHP를 지원하는 웹 서버를 설정합니다. 리눅스에서는, » rpmfind» PBone이 RPM을 찾을 때 유용합니다. » apt-get에서 데비안 패키지를 찾을 수 있습니다.



첫번째 PHP 실행 페이지

다음에 쓰여진 내용으로 hello.php를 만들고, 웹서버의 루트 디렉토리(DOCUMENT_ROOT)에 놓습니다.

Example #1 첫번째 PHP 스크립트: hello.php

<html>
 <head>
  <title>PHP 테스트</title>
 </head>
 <body>
 <?php echo '<p>Hello World</p>'?> 
 </body>
</html>

웹 브라우저를 이용해서 "/hello.php"에 접근합니다. 로컬에서 개발한다면 URL은 보통 http://localhost/hello.php이나 http://127.0.0.1/hello.php일 것이지만, 이는 웹 서버 설정에 따라 달리집니다. 모두 제대로 되었다면, 이 파일은 PHP에 의해 처리되어 다음 출력을 브라우저로 전송합니다:

<html>
 <head>
  <title>PHP 테스트</title>
 </head>
 <body>
 <p>Hello World</p> 
 </body>
</html>

이 프로그램은 매우 간단해서, 실제로 이런 페이지를 만들기 위해서 PHP를 사용할 필요는 없습니다. 이 프로그램은 Hello World를 PHP echo() 표현으로 보여주기만 할 뿐입니다. 파일에 실행 권한을 줄 필요도 없고, 어떠한 특별한 처리를 할 필요도 없습니다. 서버는 ".php" 확장을 사용하였기 때문에, 이 파일을 PHP를 통해 처리해야 한다고 인식합니다. 이를 많은 일들을 가능하게 하는 특별한 태그를 가진 일반적인 HTML 파일로 생각하십시오.

이 예제를 실행했을 때, 아무것도 출력하지 않거나, 다운로드 할 것인지 묻거나, 모든 내용이 텍스트 문서처럼 보였다면, 그 서버에서 PHP가 작동하지 않거나 제대로 설정되지 않은 것입니다. 서버 관리자에게 매뉴얼의 설치 장을 참고하여 PHP를 사용할 수 있게 해달라고 요청하십시오. http를 통하여, 서버가 출력을 제공하도록 접근하고 있는지 확인하십시오. 단순히 파일 시스템에서 읽어들인다면, PHP를 통하여 처리되지 않습니다. 문제가 계속된다면, 망설이지 말고 » PHP 지원을 이용하십시오.

예제의 초점은 특별한 PHP 태그를 보여주는 것입니다. 이 예제에서 <?php가 PHP 태그의 시작을 알립니다. 그러면 PHP 상태로 돌입하게 되고, 종료 태그인 ?>에 의해 PHP 모드를 떠나게 됩니다. HTML 파일 어디에서라도 이런 방법으로 PHP 모드로 들어가고, 나올 수 있습니다. 더 자세한 내용은 매뉴얼에서 기본 PHP 문법 섹션을 읽어보십시오.

Note: 줄바꿈에 대한 주의
HTML에서 줄바꿈은 약간의 의미를 가지지만, 줄바꿈을 넣어서 HTML을 깔끔하게 보이게 하는 건 좋은 생각입니다. ?> 바로 뒤에 따라오는 줄바꿈은 PHP가 제거합니다. 이는 많은 PHP 블록을 쓰거나, 아무것도 출력하지 않는 PHP 파일을 포함할 때 매우 유용합니다. 반면, 약간 혼동할 수도 있습니다. ?>로 닫은 뒤에 공백을 하나 둠으로써, 공백과 줄바꿈을 출력하게 하거나, PHP 블록 안에서 마지막 echo/print에 명시적으로 줄바꿈을 넣을 수 있습니다.

Note: 텍스트 편집기에 대한 참고
PHP를 만들고, 수정하고, 관리할 수 있는 많은 텍스트 편집기와 IDE가 있습니다. 이러한 도구에 대한 부분적인 목록은 » PHP 편집기 목록에서 관리하고 있습니다. 편집기를 추천하려면, 위 페이지를 방문해서 페이지 관리자에게 그 편집기를 목록에 추가해달라고 하십시오. 구문 하이라이팅이 있는 편집기는 도움이 될 것입니다.

Note: 워드 프로세서에 대한 주의
StarOffice Writer, Microsoft Word, Abiword 등의 워드 프로세서는 PHP 파일을 수정하는데에는 최적화되어 있지 않습니다. 이들을 텍스트 스크립트에 이용하기 위해서는, 꼭 plain text로 저장해야만 하며, 그렇지 않으면 PHP는 그 스크립트를 읽을 수가 없고 실행할 수 없습니다.

Note: 윈도우 메모장에 대한 주의
PHP 스크립트를 윈도우 메모장을 이용해서 작성할때는, 파일이 .php 확장자를 가지도록 주의해야합니다. (메모장은 다음과 같은 절차를 거치지 않으면 자동적으로 .txt 확장자를 붙입니다) 파일을 저장할 때, 파일 이름을 묻는 부분에서 파일 이름을 따옴표로 감싸줘야 합니다. (예: "hello.php") 또는, '저장' 창에서 '텍스트 문서' 드롭다운 메뉴를 클릭해서 "모든 파일"로 설정을 바꿀 수 있습니다. 이 경우에는 따옴표를 쓰지 않아도 됩니다.

작동하는 PHP 스크립트를 성공적으로 만들었다면, 가장 유명한 PHP 스크립트를 작성할 차례입니다! phpinfo() 함수를 호출하여, 사용 가능한 예약 정의 변수, 불러진 PHP 모듈들, 설정 등 시스템과 설정에 관련한 수많은 유용한 정보를 볼 수 있습니다. 잠깐의 시간을 들여서 중요한 정보들을 확인해보십시오.

Example #2 PHP에서 시스템 정보 얻기

<?php phpinfo(); ?>



유용한 기능들

이제 더 유용한 무언가를 해봅시다. 방문자가 사용하는 브라우저의 종류를 확인할 것입니다. 이를 위해서, 브라우저가 HTTP 요청의 부분으로 보내는 user agent 문자열을 확인합니다. 이 정보는 변수에 기록되어 있습니다. PHP에서 변수는 항상 달러표시($)로 시작합니다. 여기서 다룰 변수는 $_SERVER['HTTP_USER_AGENT']입니다.

Note: $_SERVER는 모든 웹 서버 정보를 포함하기 위해 특별히 예약된 PHP 변수입니다. 이것은 자동전역이라고 부릅니다. 더 많은 정보는 자동전역과 관련한 매뉴얼 페이지를 참고하십시오. 이 특별한 변수들은 PHP » 4.1.0에서 소개되었습니다. 이전에는 $HTTP_SERVER_VARS 등의 $HTTP_*_VARS 배열을 이용하였습니다. 배제되었지만, 이 구형의 변수들은 아직 존재합니다. (예전의 코드에 관한 노트를 참고하십시오)

이 변수를 표시하기 위해서는, 간단히 다음과 같이 하면 됩니다:

Example #1 변수 출력하기 (배열 원소)

<?php
echo $_SERVER['HTTP_USER_AGENT'];
?>

이 스크립트의 출력 예제는 다음과 같습니다:


Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)

PHP에는 많은 변수의 이 존재합니다. 위 예제에서는 배열 원소를 출력했습니다. 배열은 매우 유용합니다.

$_SERVER는 PHP가 자동적으로 생성하는 변수 중의 하나에 불과합니다. 매뉴얼의 예약 정의 변수를 보거나, 이전 섹션의 예제에서 사용한 phpinfo() 함수의 출력에서 전체 목록을 얻을 수 있습니다.

PHP 태그 안쪽으로 하나의 echo뿐이 아닌 여러개의 PHP문을 넣어서 작은 코드 블럭을 만들 수 있습니다. 예를 들면, Internet Explorer를 체크하고 싶다면 다음과 같이 할 수 있습니다:

Example #2 제어문함수를 사용하는 예제

<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
       echo 
'Internet Explorer를 사용하고 있습니다.<br />';
}
?>

이 스크립트의 출력 예제:

Internet Explorer를 사용하고 있습니다.<br />

여기서 두가지 새로운 컨셉을 소개합니다. PHP에는 if문이 있습니다. C 언어에서 사용하는 기본 문법에 친숙하다면, 이것은 매우 논리적으로 보일 것입니다. 그렇지 않으면, PHP 소개서를 구해서 첫부분을 읽어보거나, 매뉴얼의 언어 레퍼런스 부분을 읽어보십시오.

두번째 컨셉은 strpos() 함수 호출입니다. strpos()는 하나의 문자열을 다른 문자열에서 찾아내는 PHP 내장 함수입니다. 여기서는 $_SERVER['HTTP_USER_AGENT'](haystack이라고 합니다) 안에서 'MSIE'(needle이라고 합니다)를 찾아봅시다. haystack 안에서 needle을 발견하면, 이 함수는 haystack의 첫번째 문자로부터 needle의 위치를 반환합니다. 발견하지 못했다면 FALSE를 반환합니다. FALSE를 반환하지 않았다면, if문은 TRUE로 판단하고 {중괄호} 안에 있는 코드를 실행합니다. 그렇지 않으면, 코드를 실행하지 않습니다. if, else, 그리고 strtoupper()strlen() 등의 함수를 사용하는 비슷한 예제도 쉽게 작성할 수 있습니다. 관련된 매뉴얼 페이지들은 예제를 포함하고 있습니다. 어떻게 함수를 사용하는지를 모르겠다면, 매뉴얼의 함수 정의를 읽는 방법PHP 함수 섹션을 읽어보십시오.

한걸음 더 나아가서, PHP 블록 안에서 어떻게 PHP 모드를 드나드는지 알아봅시다:

Example #3 HTML과 PHP 모드 섞기

<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
?>
<h3>strpos()는 false가 아닌 것을 반환했습니다.</h3>
<p>Internet Explorer를 사용하고 있습니다.</p>
<?php
} else {
?>
<h3>strpos()는 false를 반환했습니다.</h3>
<p>Internet Explorer를 사용하고 있지 않습니다.</p>
<?php
}
?>

이 스크립트의 출력 예제:

<h3>strpos()는 false가 아닌 것을 반환했습니다.</h3>
<p>Internet Explorer를 사용하고 있습니다.</p>

PHP echo문을 이용한 출력 방법 대신, PHP 모드를 빠져나가서 직접 HTML을 전송할 수 있습니다. 여기서 주의해야할 중요하고 강력한 점은 스크립트의 논리적 흐름이 유지되고 있는 점입니다. strpos()의 결과값에 따라서 오직 하나의 HTML 블록만이 보여지게 됩니다. 즉, MSIE의 발견 여부에 따르게 됩니다.



폼 다루기

PHP의 매우 강력한 기능의 하나는 HTML 폼을 다루는 방법입니다. 이를 이해하는데에 중요한 기본적인 컨셉은 어떤 폼 요소라도 자동적으로 PHP 스크립트에서 사용 가능하다는 점입니다. PHP로 폼을 이용하는 많은 정보와 예제를 위해서 매뉴얼의 외부 변수 섹션을 읽어보십시오. 다음은 HTML 폼의 예제입니다:

Example #1 간단한 HTML 폼

<form action="action.php" method="post">
 <p>이름: <input type="text" name="name" /></p>
 <p>연령: <input type="text" name="age" /></p>
 <p><input type="submit" /></p>
</form>

이 폼에는 특별한 것은 아무것도 없습니다. 어떠한 특별한 태그도 가지지 않는 단순한 HTML 폼입니다. 유저가 이 폼을 채우고 submit 버튼을 누르면, action.php 페이지가 호출됩니다. 이 파일은 다음처럼 작성할 수 있습니다:

Example #2 폼에서 온 데이터 출력하기

<?php echo htmlspecialchars($_POST['name']); ?>씨 안녕하세요.
당신은 <?php echo (int)$_POST['age']; ?>세입니다.

이 스크립트의 출력 예제:

홍길동씨 안녕하세요. 당신은 22세입니다.

htmlspecialchars()(int) 부분을 제외하면, 이 소스가 어떤 일을 하는지는 명백합니다. htmlspecialchars()는 HTML에서 특별한 의미를 가지는 문자들을 정확히 인코딩하게 하여, HTML 태그나 자바스크립트를 페이지에 삽입할 수 없도록 합니다. age 필드에 대해서는, 숫자이여야 함을 알고 있으므로 간단히 integer변환하여 다른 문자들을 제거합니다. 이러한 작업은 필터 확장을 이용하여 PHP가 자동으로 하도록 할 수 있습니다. $_POST['name']$_POST['age'] 변수는 PHP가 자동적으로 사용할수 있도록 설정합니다. 위에서 자동전역 $_SERVER를 사용했듯이, 이번에는 모든 POST 데이터를 포함하는 $_POST 자동전역을 소개합니다. 폼에서 method를 POST로 설정한 점에 주의하십시오. 폼에서 GET method로 지정하면, 폼 정보는 $_GET 자동전역이 가집니다. 요청한 데이터가 어떤 소스인지를 신경쓰지 않을 때는 $_REQUEST 자동전역을 사용할 수 있습니다. 이는 GET, POST, COOKIE 데이터를 포함합니다. import_request_variables() 함수를 참고하십시오.

한동안은 잘 지원되는 HTML 폼에 만족할 수도 있지만, PHP에서는 XForms 입력을 다룰 수도 있습니다. XForms로 작업하는 것은 초보자를 위한 것은 아니지만, 흥미를 가질 것입니다. 기능 섹션에서 XForms로 받은 데이터를 다루는 짧은 안내를 참고하십시오.



새 버전의 PHP에서 예전의 코드를 사용하기

PHP는 유명한 스크립트 언어로 성장했고, 재사용 할 수 있는 많은 양의 저장소와 라이브러리 코드 자원이 존재합니다. PHP 개발자는 하위 호환을 유지하기 위해 많이 노력했기 때문에, 이전 버전에서 작성한 스크립트라도 아무런 변경 없이 새버전의 PHP에서 (완벽하게) 작동합니다. 그렇지만, 실제 상황에선 몇가지 변경이 필요할 수도 있습니다.

예전의 코드에 영향을 주는 최근의 중요한 두가지 변경점:

  • (함수나 메쏘드 안에서 사용할 때 global 선언을 필요로 하는) 이전의 $HTTP_*_VARS 배열의 배제. PHP » 4.1.0에서 소개한 자동전역 배열을 사용하십시오. 그 종류는 $_GET, $_POST, $_COOKIE, $_SERVER, $_FILES, $_ENV, $_REQUEST, $_SESSION입니다. $HTTP_POST_VARS 등, 이전 형태의 $HTTP_*_VARS 배열도 존재합니다. PHP 5.0.0부터, 긴 형태의 PHP 예약 변수 배열을 register_long_arrays 지시어로 제거할 수 있습니다.
  • 기본값으로, 외부 변수를 더 이상 전역 변수로 등록하지 않습니다. 즉, PHP » 4.2.0부터 php.ini에서의 PHP 설정 register_globals의 기본값이 off가 되었습니다. 이 값들에의 접근은 위에서 언급한 자동전역 배열을 이용하는 것을 권장합니다. 예전의 스크립트, 책, 그리고 튜토리얼은 이 설정을 on이라고 생각합니다. 예를 들어, 이 설정이 on이라면 누군가가 $id를 URL http://www.example.com/foo.php?id=42처럼 사용할 수 있습니다. on/off에 관계 없이, $_GET['id']는 사용할 수 있습니다.

이 변화에 대한 자세한 내용은 예약 정의 변수 섹션과 그 안의 링크들을 참고하십시오.



다음은?

새로운 지식으로 매뉴얼과 예제 아카이브의 수많은 예제 스크립트의 대부분을 이해할 수 있을 것입니다. php.net 사이트의 또다른 예제들을 다음 링크 섹션에서 찾아볼 수 있습니다: » http://www.php.net/links.php.

PHP로 할 수 있는 많은 일들에 대한 다양한 슬라이드 프리젠테이션을 PHP 컨퍼런스 자료 사이트를 참고하십시오: » http://talks.php.net/





설치와 설정


일반적인 설치 고려사항

설치하기에 앞서, 먼저 PHP를 무엇에 사용해야 할지를 알아야 합니다. PHP로 할 수 있는 것들 섹션에 PHP를 사용하여 할수 있는것들이 설명되어 있습니다.:

  • 웹사이트와 웹어플리케이션 (서버측 스크립팅)
  • 커맨드 라인 스크립팅
  • 데스크탑(GUI) 어플리케이션

이를 위한 첫번째와 대부분의 일반적인 형식으로, 3가지가 필요 합니다.: PHP 그자체와, 웹서버와 웹브라우저가 필요합니다. 아마도 당신은 당신의 운영체제에 의존하는 웹브라우저를 이미 가지고 있을것이며, 어쩌면 웹서버 또한 가지고 있을지도 모릅니다. (e.g. Linux상의 Apache 와 MacOS X; Window상의 IIS). 웹호스팅 회사로부터 웹호스팅을 받고 있을지도 모릅니다. 이경우에는 아무것도 설치할 필요가 없으며, 그냥 PHP 스크립트를 작성하여 웹호스팅을 받고 있는 서버에 업로드 하고, 그 결과를 웹브라우저로 확인만 하면 됩니다.

PHP와 웹서버를 직접 설치하는 경우라면 PHP를 웹서버에 연결하는데에는 두가지 방법을 선택할 수 있습니다. 많은 웹서버들은 다이렉트 모듈 인터페이스를 지원하고 있습니다.(SAPI라고 부르는). Apache, Microsoft Internet Information Server, Netscape and iPlanet server 가 이에 속합니다. 그 외의 많은 웹서버들은 ISAPI를 비롯하여, Microsoft module interface 를 지원합니다. (예를 들어 OmniHTTPd). 웹서버가 PHP모듈을 지원하지 못한다면, 언제든지 CGI나 FastCGI 프로세서를 사용할 수 있습니다. 이것은 서버상의 모든 PHP 파일 요청을 처리하기 위해 웹서버는 PHP CGI 가 실행될수 있도록 설치할 수 있음을 의미합니다.

PHP를 커맨드라인 스크립팅에 사용하는것에 관심이 있다면 (e.g. 오프라인 상태에서 어떤 이미지를 생성하는 스크립트 라던가 어떤 인수를 넘겨받아 텍스트 파일을 조작하는것과 같은), 커맨드 라인 실행기가 필요할 것입니다. 더 많은 정보를 원한다면 커맨드 라인에서 PHP 사용하기 섹션을 읽어보기 바랍니다. 이 경우에는 웹서버와 웹브라우저가 필요하지 않습니다.

PHP-GTK 확장을 사용하면 PHP로 데스크탑 GUI어플리케이션을 작성할 수 있습니다. 이것은 웹페이지를 작성하는것과는 완전히 틀린방식이며, 어떤 HTML도 생성해 낼수 없지만, 대신에 윈도우와 오브젝트들을 관리해야 합니다. PHP-GTK에 대한 더 많은 정보를 원한다면, » 이 확장을 위한 독립적인 사이트에 방문해 보시기 바랍니다. PHP-GTK 는 공식적인 PHP 배포판에는 포함되지 않습니다.

지금부터, 이 섹션은 유닉스나 윈도우상의 웹서버에 PHP를 서버 모듈 인터페이스와 CGI 실행방식으로 설치하는 방법을 다룰것입니다. 또한 다음 섹션에서 커맨드 라인 실행방식에 대한 정보도 찾을 수 있을 것입니다.

PHP 소스코드와 윈도우 바이너리 배포판들은 » http://www.php.net/downloads.php 에서 찾을 수 있습니다. 배포판을 다운로드 하기 위해서 가까운 » mirror 사이트를 사용할 것을 권장합니다.



유닉스 시스템에 설치

Table of Contents

이 섹션은 유닉스 시스템에 대한 PHP의 일반적인 설정과 설치에 대해서 안내합니다. 진행하기 전에 플래폼 및 웹서버의 사양을 확인하십시오.

일반적인 설치 고려 장에서 나온 매뉴얼 아웃라인에 따라, 이 장에서는 주로 PHP를 웹 중심으로 설정을 합니다. 물론, 명령줄 사용을 위한 PHP 설정도 포함하고 있습니다.

유닉스 플래폼에 PHP를 설치하는 방법은 여러가지가 있습니다. configure 및 컴파일 프로세스를 거치거나, 미리 작성된 패키지 방법 등이 있습니다. 이 문서는 주로 configure와 컴파일을 통한 작업에 맞추어져 있습니다. 많은 유닉스 호환 시스템은 몇몇 패키지 설치 시스템을 갖추고 있습니다. 이는 일반적인 설정에는 도움을 줄 수 있지만, 다른 기능을 필요로 할 경우에는 (보안 서버나, 다른 데이터베이스 드라이버 등), PHP와 웹 서버를 빌드할 필요가 있습니다. 소프트웨어의 컴파일과 빌드에 익숙하지 않다면, 필요한 기능이 들어있는 PHP 패키지를 찾아보는 것도 좋을 것입니다.

컴파일을 위해 필요한 지식과 소프트웨어:

  • 기본적인 유닉스 기술 (C 컴파일러와 "make"를 실행할 수 있어야 함)
  • ANSI C 컴파일러
  • flex: 버전 2.5.4
  • bison: 버전 1.28 (선호됨), 1.35, 또는 1.75
  • 웹 서버
  • 모듈 특정 컴포넌트 (gd, pdf libs 등등)

PHP 설정의 첫 작업은 configure 스크립트의 명령줄 옵션을 통해서 조정합니다. 사용할 수 있는 옵션 목록과 그에 대한 짧은 설명은 ./configure --help를 실행하여 얻을 수 있습니다. 매뉴얼은 여러 옵션을 나누어 다루고 있습니다. 부록에서 코어 옵션을 볼 수 있고, 홧장 전용 옵션은 레퍼런스 페이지에 설명이 있습니다.

PHP가 설정되면, 바로 모듈과 확장을 빌드할 수 있습니다. make 명령이 이를 수행합니다. 이 명령이 실패하고, 원인을 찾을 수 없다면, 문제 장을 참고하십시오.


Apache 1.3.x on Unix systems

This section contains notes and hints specific to Apache installs of PHP on Unix platforms. We also have instructions and notes for Apache 2 on a separate page.

You can select arguments to add to the configure on line 10 below from the list of core configure options and from extension specific options described at the respective places in the manual. The version numbers have been omitted here, to ensure the instructions are not incorrect. You will need to replace the 'xxx' here with the correct values from your files.

Example #1 Installation Instructions (Apache Shared Module Version) for PHP

1.  gunzip apache_xxx.tar.gz
2.  tar -xvf apache_xxx.tar
3.  gunzip php-xxx.tar.gz
4.  tar -xvf php-xxx.tar
5.  cd apache_xxx
6.  ./configure --prefix=/www --enable-module=so
7.  make
8.  make install
9.  cd ../php-xxx

10. Now, configure your PHP.  This is where you customize your PHP
    with various options, like which extensions will be enabled.  Do a
    ./configure --help for a list of available options.  In our example
    we'll do a simple configure with Apache 1 and MySQL support.  Your
    path to apxs may differ from our example.

      ./configure --with-mysql --with-apxs=/www/bin/apxs

11. make
12. make install

    If you decide to change your configure options after installation,
    you only need to repeat the last three steps. You only need to 
    restart apache for the new module to take effect. A recompile of
    Apache is not needed.
  
    Note that unless told otherwise, 'make install' will also install PEAR,
    various PHP tools such as phpize, install the PHP CLI, and more.

13. Setup your php.ini file:

      cp php.ini-dist /usr/local/lib/php.ini

    You may edit your .ini file to set PHP options.  If you prefer your
    php.ini in another location, use --with-config-file-path=/some/path in
    step 10. 
    
    If you instead choose php.ini-recommended, be certain to read the list
    of changes within, as they affect how PHP behaves.

14. Edit your httpd.conf to load the PHP module.  The path on the right hand
    side of the LoadModule statement must point to the path of the PHP
    module on your system.  The make install from above may have already
    added this for you, but be sure to check.
        
    For PHP 4:
            
      LoadModule php4_module libexec/libphp4.so

    For PHP 5:
                      
      LoadModule php5_module libexec/libphp5.so
      
15. And in the AddModule section of httpd.conf, somewhere under the
    ClearModuleList, add this:
    
    For PHP 4:
    
      AddModule mod_php4.c
      
    For PHP 5:
    
      AddModule mod_php5.c

16. Tell Apache to parse certain extensions as PHP.  For example,
    let's have Apache parse the .php extension as PHP.  You could
    have any extension(s) parse as PHP by simply adding more, with
    each separated by a space.  We'll add .phtml to demonstrate.

      AddType application/x-httpd-php .php .phtml

    It's also common to setup the .phps extension to show highlighted PHP
    source, this can be done with:
    
      AddType application/x-httpd-php-source .phps

17. Use your normal procedure for starting the Apache server. (You must
    stop and restart the server, not just cause the server to reload by
    using a HUP or USR1 signal.)

Alternatively, to install PHP as a static object:

Example #2 Installation Instructions (Static Module Installation for Apache) for PHP

1.  gunzip -c apache_1.3.x.tar.gz | tar xf -
2.  cd apache_1.3.x
3.  ./configure
4.  cd ..

5.  gunzip -c php-5.x.y.tar.gz | tar xf -
6.  cd php-5.x.y
7.  ./configure --with-mysql --with-apache=../apache_1.3.x
8.  make
9.  make install

10. cd ../apache_1.3.x

11. ./configure --prefix=/www --activate-module=src/modules/php5/libphp5.a
    (The above line is correct! Yes, we know libphp5.a does not exist at this
    stage. It isn't supposed to. It will be created.)

12. make
    (you should now have an httpd binary which you can copy to your Apache bin dir if
    it is your first install then you need to "make install" as well)

13. cd ../php-5.x.y
14. cp php.ini-dist /usr/local/lib/php.ini

15. You can edit /usr/local/lib/php.ini file to set PHP options.
    Edit your httpd.conf or srm.conf file and add:
    AddType application/x-httpd-php .php

Note: Replace php-5 by php-4 and php5 by php4 in PHP 4.

Depending on your Apache install and Unix variant, there are many possible ways to stop and restart the server. Below are some typical lines used in restarting the server, for different apache/unix installations. You should replace /path/to/ with the path to these applications on your systems.

Example #3 Example commands for restarting Apache

1. Several Linux and SysV variants:
/etc/rc.d/init.d/httpd restart

2. Using apachectl scripts:
/path/to/apachectl stop
/path/to/apachectl start

3. httpdctl and httpsdctl (Using OpenSSL), similar to apachectl:
/path/to/httpsdctl stop
/path/to/httpsdctl start

4. Using mod_ssl, or another SSL server, you may want to manually
stop and start:
/path/to/apachectl stop
/path/to/apachectl startssl

The locations of the apachectl and http(s)dctl binaries often vary. If your system has locate or whereis or which commands, these can assist you in finding your server control programs.

Different examples of compiling PHP for apache are as follows:

./configure --with-apxs --with-pgsql

This will create a libphp5.so (or libphp4.so in PHP 4) shared library that is loaded into Apache using a LoadModule line in Apache's httpd.conf file. The PostgreSQL support is embedded into this library.

./configure --with-apxs --with-pgsql=shared

This will create a libphp4.so shared library for Apache, but it will also create a pgsql.so shared library that is loaded into PHP either by using the extension directive in php.ini file or by loading it explicitly in a script using the dl() function.

./configure --with-apache=/path/to/apache_source --with-pgsql

This will create a libmodphp5.a library, a mod_php5.c and some accompanying files and copy this into the src/modules/php5 directory in the Apache source tree. Then you compile Apache using --activate-module=src/modules/php5/libphp5.a and the Apache build system will create libphp5.a and link it statically into the httpd binary (replace php5 by php4 in PHP 4). The PostgreSQL support is included directly into this httpd binary, so the final result here is a single httpd binary that includes all of Apache and all of PHP.

./configure --with-apache=/path/to/apache_source --with-pgsql=shared

Same as before, except instead of including PostgreSQL support directly into the final httpd you will get a pgsql.so shared library that you can load into PHP from either the php.ini file or directly using dl().

When choosing to build PHP in different ways, you should consider the advantages and drawbacks of each method. Building as a shared object will mean that you can compile apache separately, and don't have to recompile everything as you add to, or change, PHP. Building PHP into apache (static method) means that PHP will load and run faster. For more information, see the Apache » web page on DSO support.

Note: Apache's default httpd.conf currently ships with a section that looks like this:

User nobody
Group "#-1"

Unless you change that to "Group nogroup" or something like that ("Group daemon" is also very common) PHP will not be able to open files.

Note: Make sure you specify the installed version of apxs when using --with-apxs=/path/to/apxs. You must NOT use the apxs version that is in the apache sources but the one that is actually installed on your system.



유닉스 시스템 아파치 2.0

이 섹션은 유닉스 시스템 아파치 2.0에 특화된 PHP 설치에 관한 정보와 힌트를 담고 있습니다.

Warning

제품 환경에서 아파치 2 쓰레드 MPM 사용을 권하지 않습니다. prefork MPM을 사용하거나, Apache 1을 사용하십시오. 이유는 관련 FAQ 아파치2 쓰레드 MPM 사용하기를 읽어보십시오.

아파치 2.0 서버에 대한 이해를 위하여 » 아파치 문서를 살펴보길 권합니다.

Note: PHP와 아파치 2.0.x 호환 노트
다음 버전의 PHP가 최신 버전의 아파치 2.0.x에서 작동합니다:

위 PHP 버전은 아파치 2.0.40 이후에 호환됩니다.
아파치 2.0 SAPI 지원은 PHP 4.2.0부터 시작했습니다. PHP 4.2.3은 아파치 2.0.39에서 작동하며, PHP 4.2.3과 다른 아파치 버전을 사용하지 마십시오. 그러나, 권장하는 설정은 최신 버전의 아파치2와 PHP 4.3.0 이후를 사용하는 것입니다.
언급한 모든 PHP 버전은 아파치 1.3.x에서 잘 동작합니다.

최신 버전의 » 아파치 2.0과 위에서 언급한 위치에서 적합한 PHP 버전을 내려받습니다. 이 빠른 가이드는 아파치 2.0과 PHP를 시작하는 기본적인 내용만 다루고 있습니다. 자세한 정보는 » 아파치 문서를 읽으십시오. 지시가 틀리지 않기 위해서, 여기에서 버전 번호는 제거했습니다. 'NN'을 적합한 값으로 변경해야 합니다.

Example #1 설치 안내 (아파치 2 공유 모듈 버전)

1.  gzip -d httpd-2_0_NN.tar.gz
2.  tar xvf httpd-2_0_NN.tar
3.  gunzip php-NN.tar.gz
4.  tar -xvf php-NN.tar
5.  cd httpd-2_0_NN
6.  ./configure --enable-so
7.  make
8.  make install

    이제 /usr/local/apache2 아래 모듈 적재 지원과 표준 MPM
    prefork로 설정한 아파치 2.0.NN이 존재합니다.
    설치를 테스트하려면 일반적인 아파치 서버 시작 절차를
    사용합니다. 즉:
    /usr/local/apache2/bin/apachectl start
    그리고 PHP 설정을 위하여 서버를 중단합니다:
    /usr/local/apache2/bin/apachectl stop.

9.  cd ../php-NN

10. 이제, PHP를 설정합니다. 여기에서 확장을 활성화 하는 등,
    PHP를 다양한 다양한 옵션으로 커스터마이즈합니다. 
    ./configure --help 를 실행하여 가능한 옵션 목록을 확인할 수 있습니다.
    예제에서는 아파치 2와 MySQL 지원으로 간단히 설정합니다. 실제 apxs
    경로는 다를 수 있습니다. 시스템에 따라서 apxs2로 존재하는 경우도
    있습니다.
    
      ./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql

11. make
12. make install

    설치 후에 설정 옵션을 바꾸려면, 마지막 세 단계만
    반복하면 됩니다. 그리고 새 모듈이 효과를 발휘하도록
    아파치를 재시작하면 됩니다. 아파치를 다시 컴파일할
    필요는 없습니다.

    특별히 언급이 없는 한, 'make install'은 PEAR, phpize 같은 다양한
    PHP 도구, PHP CLI 등을 함께 설치합니다.
    
13. php.ini 설치
    
    cp php.ini-dist /usr/local/lib/php.ini

    PHP 옵션을 설정하기 위하여 .ini 파일을 수정할 수 있습니다. php.ini를
    다른 위치에 놓으려면, 10번째 단계에서 --with-config-file-paht=/some/path
    를 사용합니다.

    php.ini-recommended를 선택한다면, 안에서 변경 목록을 읽어서,
    어떤 PHP 행동에 영향을 주는지 확인하십시오.

14. httpd.conf를 수정하여 PHP 모듈을 적재합니다. LoadModule
    구문 우측에서는 시스템의 PHP 모듈 경로를 가르켜야 합니다.
    위에서 make install이 이미 이를 추가했을 수도 있지만,
    꼭 확인해보십시오.

    For PHP 4:
  
      LoadModule php4_module modules/libphp4.so
      
    For PHP 5:
    
      LoadModule php5_module modules/libphp5.so
 
15. 어떠한 확장자를 PHP로 해석할지 아파치에 알려줍니다. 예를 들어,
    아파치가 .php 파일을 PHP로 해석하게 합시다. 단순히 아파치
    AddType 지시어를 사용하는 대신, exploit.php.jpg 등의 파일이
    업로드되어 PHP로 실행되는 것을 막습니다. 이 예제를 사용하여,
    PHP로 해석할 어떠한 확장자라도 단순히 추가할 수 있습니다.
    예시를 위해 .phtml을 추가하겠습니다.

      <FilesMatch \.php$>
          SetHandler application/x-httpd-php
      </FilesMatch>

    또는, .php, .php2, .php3, .php4, .php6, .phtml 파일을 PHP로 실행하게
    할 수 있습니다. 이렇게 하면 됩니다:

      <FilesMatch "\.ph(p[2-6]?|tml)$">
          SetHandler application/x-httpd-php
      </FilesMatch>

    .phps 파일을 PHP 소스 파일로 실행하려면, 다음을 추가합니다:

      <FilesMatch "\.phps$">
          SetHandler application/x-httpd-php-source
      </FilesMatch>

16. 아파치 서버를 시작하는 정상 절차를 사용합니다, 즉:
   
      /usr/local/apache2/bin/apachectl start

          - 또는 -

      service httpd restart
   

위 단계를 따라하면 아파치2 웹 서버를 PHP SAPI 모듈로 실행하게 됩니다. 물론, 아파치와 PHP에는 많은 설정 옵션이 존재합니다. 자세한 정보는 해당 소스 트리에서 ./configuration --help를 쳐 보십시오. 멀티쓰레드 버전의 아파치2를 빌드하려면, 표준 MPM 모듈 preforkworkerperchild로 덮어써야 합니다. 이를 위해서는 위의 6번째 단계에서 --with-mpm=worker--with-mpm=perchild 옵션을 추가해야 합니다. 이를 하기 전에, 최소한 이 일이 어떻게 작동하는지와 장단점을 파악하십시오. 자세한 정보는 » MPM 모듈에 관한 아파치 문서를 읽어보십시오.

Note: 내용 협상을 사용하려면, 아파치 MultiViews FAQ를 읽어보십시오.

Note: 아파치 멀티쓰레드 버전을 빌드하려면, 시스템이 쓰레드를 지원해야 합니다. 이 경우 PHP를 실험적인 Zend Thread Safety (ZTS)로 빌드하게 합니다. 그러므로 모든 확장을 사용할 수 없습니다. 권장하는 설치는 아파치를 표준 prefork MPM 모듈로 빌드하는 것입니다.



Lighttpd 1.4 on Unix systems

This section contains notes and hints specific to Lighttpd 1.4 installs of PHP on Unix systems.

Please use the » Lighttpd trac to learn how to install Lighttpd properly before continuing.

Fastcgi is the preferred SAPI to connect PHP and Lighttpd. Fastcgi is automagically enabled in php-cgi in PHP 5.3, but for older versions configure PHP with --enable-fastcgi. To confirm that PHP has fastcgi enabled, php -v should contain PHP 5.2.5 (cgi-fcgi) Before PHP 5.2.3, fastcgi was enabled on the php binary (there was no php-cgi).

Letting Lighttpd spawn php processes

To configure Lighttpd to connect to php and spawn fastcgi processes, edit lighttpd.conf. Sockets are preferred to connect to fastcgi processes on the local system.

Example #1 Partial lighttpd.conf

server.modules += ( "mod_fastcgi" )

fastcgi.server = ( ".php" =>
  ((
    "socket" => "/tmp/php.socket",
    "bin-path" => "/usr/local/bin/php-cgi",
    "bin-environment" => (
      "PHP_FCGI_CHILDREN" => "16",
      "PHP_FCGI_MAX_REQUESTS" => "10000"
    ),
    "min-procs" => 1,
    "max-procs" => 1,
    "idle-timeout" => 20
  ))
)

The bin-path directive allows lighttpd to spawn fastcgi processes dynamically. PHP will spawn children according to the PHP_FCGI_CHILDREN environment variable. The "bin-environment" directive sets the environment for the spawned processes. PHP will kill a child process after the number of requests specified by PHP_FCGI_MAX_REQUESTS is reached. The directives "min-procs" and "max-procs" should generally be avoided with PHP. PHP manages its own children and opcode caches like APC will only share among children managed by PHP. If "min-procs" is set to something greater than 1, the total number of php responders will be multiplied PHP_FCGI_CHILDREN (2 min-procs * 16 children gives 32 responders).

Spawning with spawn-fcgi

Lighttpd provides a program called spawn-fcgi to ease the process of spawning fastcgi processes easier.

Spawning php-cgi

It is possible to spawn processes without spawn-fcgi, though a bit of heavy-lifting is required. Setting the PHP_FCGI_CHILDREN environment var controls how many children PHP will spawn to handle incoming requests. Setting PHP_FCGI_MAX_REQUESTS will determine how long (in requests) each child will live. Here's a simple bash script to help spawn php responders.

Example #2 Spawning FastCGI Responders

#!/bin/sh

# Location of the php-cgi binary
PHP=/usr/local/bin/php-cgi

# PID File location
PHP_PID=/tmp/php.pid

# Binding to an address
#FCGI_BIND_ADDRESS=10.0.1.1:10000
# Binding to a domain socket
FCGI_BIND_ADDRESS=/tmp/php.sock

PHP_FCGI_CHILDREN=16
PHP_FCGI_MAX_REQUESTS=10000

env -i PHP_FCGI_CHILDREN=$PHP_FCGI_CHILDREN \
       PHP_FCGI_MAX_REQUESTS=$PHP_FCGI_MAX_REQUESTS \
       $PHP -b $FCGI_BIND_ADDRESS &

echo $! > "$PHP_PID"

Connecting to remote FCGI instances

Fastcgi instances can be spawned on multiple remote machines in order to scale applications.

Example #3 Connecting to remote php-fastcgi instances

fastcgi.server = ( ".php" =>
   (( "host" => "10.0.0.2", "port" => 1030 ),
    ( "host" => "10.0.0.3", "port" => 1030 ))
)


Caudium

PHP can be built as a Pike module for the » Caudium webserver. Follow the simple instructions below to install PHP for Caudium.

Example #1 Caudium Installation Instructions

1.  Make sure you have Caudium installed prior to attempting to
    install PHP 4. For PHP 4 to work correctly, you will need Pike
    7.0.268 or newer. For the sake of this example we assume that
    Caudium is installed in /opt/caudium/server/.
2.  Change directory to php-x.y.z (where x.y.z is the version number).
3.  ./configure --with-caudium=/opt/caudium/server
4.  make
5.  make install
6.  Restart Caudium if it's currently running.
7.  Log into the graphical configuration interface and go to the
    virtual server where you want to add PHP 4 support.
8.  Click Add Module and locate and then add the PHP 4 Script Support module.
9.  If the documentation says that the 'PHP 4 interpreter isn't
    available', make sure that you restarted the server. If you did
    check /opt/caudium/logs/debug/default.1 for any errors related to
    PHP4.so. Also make sure that 
    caudium/server/lib/[pike-version]/PHP4.so
    is present.
10. Configure the PHP Script Support module if needed.

You can of course compile your Caudium module with support for the various extensions available in PHP 4. See the reference pages for extension specific configure options.

Note: When compiling PHP 4 with MySQL support you must make sure that the normal MySQL client code is used. Otherwise there might be conflicts if your Pike already has MySQL support. You do this by specifying a MySQL install directory the --with-mysql option.



fhttpd 관련 노트

PHP를 fttpd 모듈로 빌드하려면, fttpd 소스 기반 디렉토리를 지정하고 "Build as an fhttpd module?"에 "yes"로 답하십시오. (configure에 --with-fhttpd=DIR 옵션을 줍니다) 기본 디렉토리는 /usr/local/src/fhttpd입니다. fhttpd를 사용한다면, PHP를 모듈로 빌드하는 것이 더욱 좋은 퍼포먼스와 많은 조작, 원격 실행을 가능하게 합니다.

Note: PHP 4.3.0부터 fhttpd를 지원하지 않습니다.



Sun, iPlanet and Netscape servers on Sun Solaris

This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Sun Solaris.

From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to generate custom directory listings and error pages. Additional functions for Apache compatibility are also available. For support in current web servers read the note about subrequests.

You can find more information about setting up PHP for the Netscape Enterprise Server (NES) here: » http://benoit.noss.free.fr/php/install-php4.html

To build PHP with Sun JSWS/Sun ONE WS/iPlanet/Netscape web servers, enter the proper install directory for the --with-nsapi=[DIR] option. The default directory is usually /opt/netscape/suitespot/. Please also read /php-xxx-version/sapi/nsapi/nsapi-readme.txt.

  1. Install the following packages from » http://www.sunfreeware.com/ or another download site:

    • autoconf-2.13
    • automake-1.4
    • bison-1_25-sol26-sparc-local
    • flex-2_5_4a-sol26-sparc-local
    • gcc-2_95_2-sol26-sparc-local
    • gzip-1.2.4-sol26-sparc-local
    • m4-1_4-sol26-sparc-local
    • make-3_76_1-sol26-sparc-local
    • mysql-3.23.24-beta (if you want mysql support)
    • perl-5_005_03-sol26-sparc-local
    • tar-1.13 (GNU tar)

  2. Make sure your path includes the proper directories PATH=.:/usr/local/bin:/usr/sbin:/usr/bin:/usr/ccs/bin and make it available to your system export PATH .
  3. gunzip php-x.x.x.tar.gz (if you have a .gz dist, otherwise go to 4).
  4. tar xvf php-x.x.x.tar
  5. Change to your extracted PHP directory: cd ../php-x.x.x
  6. For the following step, make sure /opt/netscape/suitespot/ is where your netscape server is installed. Otherwise, change to the correct path and run:

    ./configure --with-mysql=/usr/local/mysql \
    --with-nsapi=/opt/netscape/suitespot/ \
    --enable-libgcc

  7. Run make followed by make install.

After performing the base install and reading the appropriate readme file, you may need to perform some additional configuration steps.

Configuration Instructions for Sun/iPlanet/Netscape

Firstly you may need to add some paths to the LD_LIBRARY_PATH environment for the server to find all the shared libs. This can best done in the start script for your web server. The start script is often located in: /path/to/server/https-servername/start. You may also need to edit the configuration files that are located in: /path/to/server/https-servername/config/.

  1. Add the following line to mime.types (you can do that by the administration server):

    type=magnus-internal/x-httpd-php exts=php
    

  2. Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following, shlib will vary depending on your system, it will be something like /opt/netscape/suitespot/bin/libphp4.so. You should place the following lines after mime types init.

    Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="/opt/netscape/suitespot/bin/libphp4.so"
    Init fn="php4_init" LateInit="yes" errorString="Failed to initialize PHP!" [php_ini="/path/to/php.ini"]
    

    (PHP >= 4.3.3) The php_ini parameter is optional but with it you can place your php.ini in your web server config directory.

  3. Configure the default object in obj.conf (for virtual server classes [version 6.0+] in their vserver.obj.conf):

    <Object name="default">
    .
    .
    .
    .#NOTE this next line should happen after all 'ObjectType' and before all 'AddLog' lines
    Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...]
    .
    .
    </Object>
    

    (PHP >= 4.3.3) As additional parameters you can add some special php.ini-values, for example you can set a docroot="/path/to/docroot" specific to the context php4_execute is called. For boolean ini-keys please use 0/1 as value, not "On","Off",... (this will not work correctly), e.g. zlib.output_compression=1 instead of zlib.output_compression="On"

  4. This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):

    <Object name="x-httpd-php">
    ObjectType fn="force-type" type="magnus-internal/x-httpd-php"
    Service fn=php4_execute [inikey=value inikey=value ...]
    </Object>
    

    After that you can configure a directory in the Administration server and assign it the style x-httpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming files to .html.

  5. Setup of authentication: PHP authentication cannot be used with any other authentication. ALL AUTHENTICATION IS PASSED TO YOUR PHP SCRIPT. To configure PHP Authentication for the entire server, add the following line to your default object:

    <Object name="default">
    AuthTrans fn=php4_auth_trans
    .
    .
    .
    </Object>
    

  6. To use PHP Authentication on a single directory, add the following:

    <Object ppath="d:\path\to\authenticated\dir\*">
    AuthTrans fn=php4_auth_trans
    </Object>
    

Note: The stacksize that PHP uses depends on the configuration of the web server. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").

CGI environment and recommended modifications in php.ini

Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the web server itself) and this space has only one environment. If you want to get CGI variables like PATH_INFO, HTTP_HOST etc. it is not the correct way to try this in the old PHP way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running web server without any valid CGI variables!

Note: Why are there (invalid) CGI variables in the environment?
Answer: This is because you started the web server process from the admin server which runs the startup script of the web server, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started web server has some CGI environment variables in it. You can test this by starting the web server not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.

Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):

variables_order = "GPCS"
register_globals = On

Special use for error pages or self-made directory listings (PHP >= 4.3.3)

You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:

Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...]

where XXX is the HTTP error code. Please delete any other Error directives which could interfere with yours. If you want to place a page for all errors that could exist, leave the code parameter out. Your script can get the HTTP status code with $_SERVER['ERROR_TYPE'].

Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:

Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...]

For both error and directory listing pages the original URI and translated URI are in the variables $_SERVER['PATH_INFO'] and $_SERVER['PATH_TRANSLATED'].

Note about nsapi_virtual() and subrequests (PHP >= 4.3.3)

The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the web server and insert the result in the web page. This function uses some undocumented features from the NSAPI library. On Unix the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.

Note: But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!



CGI and command line setups

The default is to build PHP as a CGI program. This creates a command line interpreter, which can be used for CGI processing, or for non-web-related PHP scripting. If you are running a web server PHP has module support for, you should generally go for that solution for performance reasons. However, the CGI version enables users to run different PHP-enabled pages under different user-ids.

Warning

CGI 설정을 사용할 때, 서버가 여러 공격에 노출됩니다. 그러한 공격을 막기 위해 CGI 보안 섹션을 읽어보십시오.

As of PHP 4.3.0, some important additions have happened to PHP. A new SAPI named CLI also exists and it has the same name as the CGI binary. What is installed at {PREFIX}/bin/php depends on your configure line and this is described in detail in the manual section named Using PHP from the command line. For further details please read that section of the manual.

Testing

If you have built PHP as a CGI program, you may test your build by typing make test. It is always a good idea to test your build. This way you may catch a problem with PHP on your platform early instead of having to struggle with it later.

Using Variables

Some server supplied environment variables are not defined in the current » CGI/1.1 specification. Only the following variables are defined there: AUTH_TYPE, CONTENT_LENGTH, CONTENT_TYPE, GATEWAY_INTERFACE, PATH_INFO, PATH_TRANSLATED, QUERY_STRING, REMOTE_ADDR, REMOTE_HOST, REMOTE_IDENT, REMOTE_USER, REQUEST_METHOD, SCRIPT_NAME, SERVER_NAME, SERVER_PORT, SERVER_PROTOCOL, and SERVER_SOFTWARE. Everything else should be treated as 'vendor extensions'.



HP-UX specific installation notes

This section contains notes and hints specific to installing PHP on HP-UX systems.

There are two main options for installing PHP on HP-UX systems. Either compile it, or install a pre-compiled binary.

Official pre-compiled packages are located here: » http://software.hp.com/

Until this manual section is rewritten, the documentation about compiling PHP (and related extensions) on HP-UX systems has been removed. For now, consider reading the following external resource: » Building Apache and PHP on HP-UX 11.11



OpenBSD installation notes

This section contains notes and hints specific to installing PHP on » OpenBSD 3.6.

Using Binary Packages

Using binary packages to install PHP on OpenBSD is the recommended and simplest method. The core package has been separated from the various modules, and each can be installed and removed independently from the others. The files you need can be found on your OpenBSD CD or on the FTP site.

The main package you need to install is php4-core-4.3.8.tgz, which contains the basic engine (plus gettext and iconv). Next, take a look at the module packages, such as php4-mysql-4.3.8.tgz or php4-imap-4.3.8.tgz. You need to use the phpxs command to activate and deactivate these modules in your php.ini.

Example #1 OpenBSD Package Install Example

# pkg_add php4-core-4.3.8.tgz
# /usr/local/sbin/phpxs -s
# cp /usr/local/share/doc/php4/php.ini-recommended /var/www/conf/php.ini
  (add in mysql)
# pkg_add php4-mysql-4.3.8.tgz
# /usr/local/sbin/phpxs -a mysql
  (add in imap)
# pkg_add php4-imap-4.3.8.tgz
# /usr/local/sbin/phpxs -a imap
  (remove mysql as a test)
# pkg_delete php4-mysql-4.3.8
# /usr/local/sbin/phpxs -r mysql
  (install the PEAR libraries)
# pkg_add php4-pear-4.3.8.tgz

Read the » packages(7) manual page for more information about binary packages on OpenBSD.

Using Ports

You can also compile up PHP from source using the » ports tree. However, this is only recommended for users familiar with OpenBSD. The PHP 4 port is split into two sub-directories: core and extensions. The extensions directory generates sub-packages for all of the supported PHP modules. If you find you do not want to create some of these modules, use the no_* FLAVOR. For example, to skip building the imap module, set the FLAVOR to no_imap.

Common Problems

  • The default install of Apache runs inside a » chroot(2) jail, which will restrict PHP scripts to accessing files under /var/www. You will therefore need to create a /var/www/tmp directory for PHP session files to be stored, or use an alternative session backend. In addition, database sockets need to be placed inside the jail or listen on the localhost interface. If you use network functions, some files from /etc such as /etc/resolv.conf and /etc/services will need to be moved into /var/www/etc. The OpenBSD PEAR package automatically installs into the correct chroot directories, so no special modification is needed there. More information on the OpenBSD Apache is available in the » OpenBSD FAQ.
  • The OpenBSD 3.6 package for the » gd extension requires XFree86 to be installed. If you do not wish to use some of the font features that require X11, install the php4-gd-4.3.8-no_x11.tgz package instead.

Older Releases

Older releases of OpenBSD used the FLAVORS system to compile up a statically linked PHP. Since it is hard to generate binary packages using this method, it is now deprecated. You can still use the old stable ports trees if you wish, but they are unsupported by the OpenBSD team. If you have any comments about this, the current maintainer for the port is Anil Madhavapeddy (avsm at openbsd dot org).



Solaris specific installation tips

This section contains notes and hints specific to installing PHP on Solaris systems.

Required software

Solaris installs often lack C compilers and their related tools. Read this FAQ for information on why using GNU versions for some of these tools is necessary. The required software is as follows:

  • gcc (recommended, other C compilers may work)
  • make
  • flex
  • bison
  • m4
  • autoconf
  • automake
  • perl
  • gzip
  • tar
  • GNU sed

In addition, you will need to install (and possibly compile) any additional software specific to your configuration, such as Oracle or MySQL.

Using Packages

You can simplify the Solaris install process by using pkgadd to install most of your needed components.



Debian GNU/Linux installation notes

This section contains notes and hints specific to installing PHP on » Debian GNU/Linux.

While the instructions for building PHP on Unix apply to Debian as well, this manual page contains specific information for other options, such as using either the apt-get or aptitude commands. This manual page uses these two commands interchangeably.

Using APT

First, note that other related packages may be desired like libapache2-mod-php5 to integrate with Apache 2, and php-pear for PEAR.

Second, before installing a package, it's wise to ensure the package list is up to date. Typically, this is done by running the command apt-get update.

Example #1 Debian Install Example with Apache 2

# apt-get install php5-common libapache2-mod-php5 php5-cli

APT will automatically install the PHP 5 module for Apache 2 and all of its dependencies, and then activate it. Apache should be restarted in order for the changes take place. For example:

Example #2 Stopping and starting Apache once PHP is installed

# /etc/init.d/apache2 stop
# /etc/init.d/apache2 start

Better control of configuration

In the last section, PHP was installed with only core modules. It's very likely that additional modules will be desired, such as MySQL, cURL, GD, etc. These may also be installed via the apt-get command.

Example #3 Methods for listing additional PHP 5 packages

# apt-cache search php5
# aptitude search php5
# aptitude search php5 |grep -i mysql

The examples will show a lot of packages including several PHP specific ones like php5-cgi, php5-cli and php5-dev. Determine which are needed and install them like any other with either apt-get or aptitude. And because Debian performs dependency checks, it'll prompt for those so for example to install MySQL and cURL:

Example #4 Install PHP with MySQL, cURL

# apt-get install php5-mysql php5-curl

APT will automatically add the appropriate lines to the different php.ini related files like /etc/php5/apache2/php.ini, /etc/php5/conf.d/pdo.ini, etc. and depending on the extension will add entries similar to extension=foo.so. However, restarting the web server (like Apache) is required before these changes take affect.

Common Problems

  • If the PHP scripts are not parsing via the web server, then it's likely that PHP was not added to the web server's configuration file, which on Debian may be /etc/apache2/apache2.conf or similar. See the Debian manual for further details.
  • If an extension was seemingly installed yet the functions are undefined, be sure that the appropriate ini file is being loaded and/or the web server was restarted after installation.
  • There are two basic commands for installing packages on Debian (and other linux variants): apt-get and aptitude. However, explaining the subtle differences between these commands goes beyond the scope of this manual.



Mac OS X에 설치

Table of Contents

이 장은 Mac OS X에 PHP를 설치하기 위해 필요한 정보와 힌트를 포함하고 있습니다. Mac OS X에는 클라이언트와 서버의 두가지 다른 버전이 존재합니다만, 매뉴얼은 양쪽의 시스템을 모두 다룹니다. MacOS 9 이전 버전에서는 PHP를 사용할 수 없는 점에 주의하십시오.


패키지 사용하기

Mac OS X를 위해 미리 컴파일 하여 패키지 된 몇몇 PHP 버전이 존재합니다. 이는 일반적인 설정으로 간편하게 설치할 수 있지만, 특별한 기능(보안 서버나 특정 데이터베이스 드라이버)이 필요할 경우에는 직접 PHP를 빌드해야 합니다. 소프트웨어를 컴파일하고 빌드하는 작업에 익숙하지 않다면, 누군가가 필요한 기능을 포함한 PHP 버전을 패키지로 만들어 두었는지 확인해 보는 것도 좋습니다.

PHP를 MacOS에 쉽게 설치할 수 있는 패키지와 컴파일된 바이너리입니다:



Using the bundled PHP

PHP has come standard with Macs since OS X version 10.0.0. Enabling PHP with the default web server requires uncommenting a few lines in the Apache configuration file httpd.conf whereas the CGI and/or CLI are enabled by default (easily accessible via the Terminal program).

Enabling PHP using the instructions below is meant for quickly setting up a local development environment. It's highly recommended to always upgrade PHP to the newest version. Like most live software, newer versions are created to fix bugs and add features and PHP being is no different. See the appropriate MAC OS X installation documentation for further details. The following instructions are geared towards a beginner with details provided for getting a default setup to work. All users are encouraged to compile, or install a new packaged version.

The standard installation type is using mod_php, and enabling the bundled mod_php on Mac OS X for the Apache web server (the default web server, that is accessible via System Preferences) involves the following steps:

  1. Locate and open the Apache configuration file. By default, the location is as follows: /private/etc/apache2/httpd.conf Using Finder or Spotlight to find this file may prove difficult as by default it's private and owned by the root user.

    Note: One way to open this is by using a Unix based text editor in the Terminal, for example nano, and because the file is owned by root we'll use the sudo command to open it (as root) so for example type the following into the Terminal Application (after, it will prompt for a password): sudo nano /private/etc/apache2/httpd.conf Noteworthy nano commands: ^w (search), ^o (save), and ^x (exit) where ^ represents the Ctrl key.

    Note: Versions of Mac OS X prior to 10.5 were bundled with older versions of PHP and Apache. As such, the Apache configuration file on legacy machines may be /etc/httpd/httpd.conf.

  2. With a text editor, uncomment the lines (by removing the #) that look similar to the following (these two lines are often not together, locate them both in the file):

    # LoadModule php5_module libexec/httpd/libphp5.so
    
    # AddModule mod_php5.c
    
    Notice the location/path. When building PHP in the future, the above files should be replaced or commented out.

  3. Be sure the desired extensions will parse as PHP (examples: .php .html and .inc)

    Due to the following statement already existing in httpd.conf (as of Mac Panther), once PHP is enabled the .php files will automatically parse as PHP.

    <IfModule mod_php5.c>
        # If php is turned on, we respect .php and .phps files.
        AddType application/x-httpd-php .php
        AddType application/x-httpd-php-source .phps
    
        # Since most users will want index.php to work we
        # also automatically enable index.php
        <IfModule mod_dir.c>
            DirectoryIndex index.html index.php
        </IfModule>
    </IfModule>
    

    Note: Before OS X 10.5 (Leopard), PHP 4 was bundled instead of PHP 5 in which case the above instructions will differ slightly by changing 5's to 4's.

  4. Be sure the DirectoryIndex loads the desired default index file This is also set in httpd.conf. Typically index.php and index.html are used. By default index.php is enabled because it's also in the PHP check shown above. Adjust accordingly.
  5. Set the php.ini location or use the default A typical default location on Mac OS X is /usr/local/php/php.ini and a call to phpinfo() will reveal this information. If a php.ini is not used, PHP will use all default values. See also the related FAQ on finding php.ini.
  6. Locate or set the DocumentRoot This is the root directory for all the web files. Files in this directory are served from the web server so the PHP files will parse as PHP before outputting them to the browser. A typical default path is /Library/WebServer/Documents but this can be set to anything in httpd.conf. Alternatively, the default DocumentRoot for individual users is /Users/yourusername/Sites
  7. Create a phpinfo() file

    The phpinfo() function will display information about PHP. Consider creating a file in the DocumentRoot with the following PHP code:

    <?php phpinfo(); ?>

  8. Restart Apache, and load the PHP file created above To restart, either execute sudo apachectl graceful in the shell or stop/start the "Personal Web Server" option in the OS X System Preferences. By default, loading local files in the browser will have an URL like so: http://localhost/info.php Or using the DocumentRoot in the user directory is another option and would end up looking like: http://localhost/~yourusername/info.php

The CLI (or CGI in older versions) is appropriately named php and likely exists as /usr/bin/php. Open up the terminal, read the command line section of the PHP manual, and execute php -v to check the PHP version of this PHP binary. A call to phpinfo() will also reveal this information.



Compiling for OS X Server

Mac OS X Server install

  1. Get the latest distributions of Apache and PHP.
  2. Untar them, and run the configure program on Apache like so.

    ./configure --exec-prefix=/usr \
    --localstatedir=/var \
    --mandir=/usr/share/man \
    --libexecdir=/System/Library/Apache/Modules \
    --iconsdir=/System/Library/Apache/Icons \
    --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \
    --enable-shared=max \
    --enable-module=most \
    --target=apache

  3. If you want the compiler to do some optimization, you may also want to add this line:

    setenv OPTIM=-O2

  4. Next, go to the PHP 4 source directory and configure it.

    ./configure --prefix=/usr \
        --sysconfdir=/etc \
        --localstatedir=/var \
        --mandir=/usr/share/man \
        --with-xml \
        --with-apache=/src/apache_1.3.12

    If you have any other additions (MySQL, GD, etc.), be sure to add them here. For the --with-apache string, put in the path to your apache source directory, for example /src/apache_1.3.12.

  5. Type make and make install. This will add a directory to your Apache source directory under src/modules/php4.
  6. Now, reconfigure Apache to build in PHP 4.

    ./configure --exec-prefix=/usr \
    --localstatedir=/var \
    --mandir=/usr/share/man \
    --libexecdir=/System/Library/Apache/Modules \
    --iconsdir=/System/Library/Apache/Icons \
    --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \
    --enable-shared=max \
    --enable-module=most \
    --target=apache \
    --activate-module=src/modules/php4/libphp4.a

    You may get a message telling you that libmodphp4.a is out of date. If so, go to the src/modules/php4 directory inside your Apache source directory and run this command: ranlib libmodphp4.a. Then go back to the root of the Apache source directory and run the above configure command again. That'll bring the link table up to date. Run make and make install again.

  7. Copy and rename the php.ini-dist file to your bin directory from your PHP 4 source directory: cp php.ini-dist /usr/local/bin/php.ini or (if your don't have a local directory) cp php.ini-dist /usr/bin/php.ini .



Installing for Apache on MacOS X Client

The following instructions will help you install a PHP module for the Apache web server included in MacOS X using the MacOS GUI. This version includes MySQL, PostgreSQL, and iODBC database support, cURL, GD, PDFLib, LDAP, and more. These instructions are graciously provided by » Marc Liyanage.

Warning

Be sure you know what you're doing before advancing beyond this point! You can cause irreparable harm to your Apache installation otherwise.

Note: These instructions will only work with the original Apache web server as shipped by Apple. If you re-built or upgraded your Apache, you will have to build your own PHP module.

To install:

  1. For Apache 1.3, download: http://www2.entropy.ch/download/entropy-php-5.2.4-1.tar.gz
  2. For Apache 2, download: wget http://www2.entropy.ch/download/entropy-php-5.2.4-1-apache2.tar.gz
  3. Unpack the compressed .tar.gz file, but DO NOT USE StuffIt Expander. Instead, use Apple's BOMArchiveHelper or the command line.
  4. Double-click the installer package and follow the directions of the installer application.

That's all! PHP should now be up and running. You can test it by dropping a file named test.php into your Sites folder in your home directory. Into that file, write this line: <?php phpinfo() ?>.

Now open up 127.0.0.1/~your_username/test.php in your web browser. You should see a status table with information about the PHP module.




윈도우 시스템에 인스톨하기

Table of Contents

본 섹션은 윈도우 98/Me와 윈도우 NT/2000/XP/2003에 해당합니다. PHP는 윈도우 3.1 같은 16비트 플랫폼상에서는 동작하지 않고 때때로 지원되는 윈도우 플랫폼이 Win32에 의존합니다. 윈도우 95는 PHP 4.3.0과 같은것은 더이상 지원되지 않습니다.

Note: PHP 5.3.0부터 윈도우 98/ME/NT4를 지원하지 않습니다.

Note: PHP 4.3.0부터 윈도우 95를 지원하지 않습니다.

윈도우에 PHP를 인스톨하는데에는 크게 두가지 방법이 있습니다. 수동설치 를 하거나 설치관리자 를 사용하는 것입니다.

Microsoft Visual Studio 를 가지고 있다면, 원본 소스코드로 부터 PHP를 빌드 할 수가 있습니다.

일단 PHP를 설치 했다면, 기능을 추가시키기 위해 몇가지 확장모듈을 적재 하기를 원할수도 있을 것입니다.

Warning

인터넷에 몇가지의 올인원(all-in-one) 설치관리자가 나돌지만, 어떤것도 PHP.net으로부터 승인된 것은 없으며, » http://www.php.net/downloads.php 으로부터 제공되는 공식 윈도우 패키지를 사용하는것이 시스템을 안전하고 최적화되게 하는 최선의 선택이라고 생각합니다.


Windows Installer (PHP 5.1.0 and earlier)

The Windows PHP installer is available from the downloads page at » http://www.php.net/downloads.php. This installs the CGI version of PHP and for IIS, PWS, and Xitami, it configures the web server as well. The installer does not include any extra external PHP extensions (php_*.dll) as you'll only find those in the Windows Zip Package and PECL downloads.

Note: While the Windows installer is an easy way to make PHP work, it is restricted in many aspects as, for example, the automatic setup of extensions is not supported. Use of the installer isn't the preferred method for installing PHP.

First, install your selected HTTP (web) server on your system, and make sure that it works.

Run the executable installer and follow the instructions provided by the installation wizard. Two types of installation are supported - standard, which provides sensible defaults for all the settings it can, and advanced, which asks questions as it goes along.

The installation wizard gathers enough information to set up the php.ini file, and configure certain web servers to use PHP. One of the web servers the PHP installer does not configure for is Apache, so you'll need to configure it manually.

Once the installation has completed, the installer will inform you if you need to restart your system, restart the server, or just start using PHP.

Warning

Be aware, that this setup of PHP is not secure. If you would like to have a secure PHP setup, you'd better go on the manual way, and set every option carefully. This automatically working setup gives you an instantly working PHP installation, but it is not meant to be used on online servers.



Windows Installer (PHP 5.2 and later)

The Windows PHP installer for later versions of PHP is built using MSI technology using the Wix Toolkit (» http://wix.sourceforge.net/). It will install and configure PHP and all the built-in and PECL extensions, as well as configure many of the popular web servers such as IIS, Apache, and Xitami.

First, install your selected HTTP (web) server on your system, and make sure that it works. Then proceed with one of the following install types.

Normal Install

Run the MSI installer and follow the instructions provided by the installation wizard. You will be prompted to select the Web Server you wish to configure first, along with any configuration details needed.

You will then be prompted to select which features and extensions you wish to install and enable. By selecting "Will be installed on local hard drive" in the drop-down menu for each item you can trigger whether to install the feature or not. By selecting "Entire feature will be installed on local hard drive", you will be able to install all sub-features of the included feature ( for example by selecting this options for the feature "PDO" you will install all PDO Drivers ).

Warning

It is not recommended to install all extensions by default, since many other them require dependencies from outside PHP in order to function properly. Instead, use the Installation Repair Mode that can be triggered thru the 'Add/Remove Programs' control panel to enable or disable extensions and features after installation.

The installer then sets up PHP to be used in Windows and the php.ini file, and configures certain web servers to use PHP. The installer will currently configure IIS, Apache, Xitami, and Sambar Server; if you are using a different web server you'll need to configure it manually.

Silent Install

The installer also supports a silent mode, which is helpful for Systems Administrators to deploy PHP easily. To use silent mode:

       
msiexec.exe /i php-VERSION-win32-install.msi /q

You can control the install directory by passing it as a parameter to the install. For example, to install to e:\php:

       
msiexec.exe /i php-VERSION-win32-install.msi /q INSTALLDIR=e:\php
You can also use the same syntax to specify the Apache Configuration Directory (APACHEDIR), the Sambar Server directory (SAMBARDIR), and the Xitami Server directory (XITAMIDIR).

You can also specify what features to install. For example, to install the mysqli extension and the CGI executable:

       
msiexec.exe /i php-VERSION-win32-install.msi /q ADDLOCAL=cgi,ext_php_mysqli

The current list of Features to install is as follows:

 
MainExecutable - php.exe executable
ScriptExecutable - php-win.exe executable
ext_php_* - the various extensions ( for example: ext_php_mysql for MySQL )
apache13 - Apache 1.3 module
apache20 - Apache 2.0 module
apache22 - Apache 2,2 module
apacheCGI - Apache CGI executable
iis4ISAPI - IIS ISAPI module
iis4CGI - IIS CGI executable
iis4FastCGI - IIS CGI executable
NSAPI - Sun/iPlanet/Netscape server module
netserve - NetServe Web Server CGI executable
Xitami - Xitami CGI executable
Sambar - Sambar Server ISAPI module
CGI - php-cgi.exe executable
PEAR - PEAR installer
Manual - PHP Manual in CHM Format

For more information on installing MSI installers from the command line, visit » http://msdn.microsoft.com/en-us/library/aa367988.aspx

Upgrading PHP with the Install

To upgrade, run the installer either graphically or from the command line as normal. The installer will read your current install options, remove your old installation, and reinstall PHP with the same options as before. It is recommended that you use this method of keeping PHP updated instead of manually replacing the files in the installation directory.



Manual Installation Steps

This install guide will help you manually install and configure PHP with a web server on Microsoft Windows. To get started you'll need to download the zip binary distribution from the downloads page at » http://www.php.net/downloads.php.

Although there are many all-in-one installation kits, and we also distribute a PHP installer for Microsoft Windows, we recommend you take the time to setup PHP yourself as this will provide you with a better understanding of the system, and enables you to install PHP extensions easily when needed.

Note: Upgrading from a previous PHP version
Previous editions of the manual suggest moving various ini and DLL files into your SYSTEM (i.e. C:\WINDOWS) folder and while this simplifies the installation procedure it makes upgrading difficult. We advise you remove all of these files (like php.ini and PHP related DLLs from the Windows SYSTEM folder) before moving on with a new PHP installation. Be sure to backup these files as you might break the entire system. The old php.ini might be useful in setting up the new PHP as well. And as you'll soon learn, the preferred method for installing PHP is to keep all PHP related files in one directory and have this directory available to your systems PATH.

Note: MDAC requirements
If you use Microsoft Windows 98/NT4 download the latest version of the Microsoft Data Access Components (MDAC) for your platform. MDAC is available at » http://msdn.microsoft.com/data/. This requirement exists because ODBC is built into the distributed Windows binaries.

The following steps should be completed on all installations before any server specific instructions are performed:

Extract the distribution file into a directory of your choice. If you are installing PHP 4, extract to C:\, as the zip file expands to a foldername like php-4.3.7-Win32. If you are installing PHP 5, extract to C:\php as the zip file doesn't expand as in PHP 4. You may choose a different location but do not have spaces in the path (like C:\Program Files\PHP) as some web servers will crash if you do.

The directory structure extracted from the zip is different for PHP versions 4 and 5 and look like as follows:

Example #1 PHP 4 package structure


c:\php
   |
   +--cli
   |  |
   |  |-php.exe           -- CLI executable - ONLY for command line scripting
   |
   +--dlls                -- support DLLs required by some extensions
   |  |
   |  |-expat.dll
   |  |
   |  |-fdftk.dll
   |  |
   |  |-...
   |
   +--extensions          -- extension DLLs for PHP
   |  |
   |  |-php_bz2.dll
   |  |
   |  |-php_cpdf.dll
   |  |
   |  |-...
   |
   +--mibs                -- support files for SNMP
   |
   +--openssl             -- support files for Openssl
   |
   +--pdf-related         -- support files for PDF
   |
   +--sapi                -- SAPI (server module support) DLLs
   |  |
   |  |-php4apache.dll
   |  |
   |  |-php4apache2.dll
   |  |
   |  |-...
   |
   +--PEAR                -- initial copy of PEAR
   |
   |
   |-go-pear.bat          -- PEAR setup script
   |
   |-...
   |
   |-php.exe              -- CGI executable
   |
   |-...
   |
   |-php.ini-dist         -- default php.ini settings
   |
   |-php.ini-recommended  -- recommended php.ini settings
   | 
   |-php4ts.dll           -- core PHP DLL
   | 
   |-...

Or:

Example #2 PHP 5 package structure


c:\php
   |
   +--dev
   |  |
   |  |-php5ts.lib
   |
   +--ext                 -- extension DLLs for PHP
   |  |
   |  |-php_bz2.dll
   |  |
   |  |-php_cpdf.dll
   |  |
   |  |-...
   |
   +--extras
   |  |
   |  +--mibs             -- support files for SNMP
   |  |
   |  +--openssl          -- support files for Openssl
   |  |
   |  +--pdf-related      -- support files for PDF
   |  |
   |  |-mime.magic
   |
   +--pear                -- initial copy of PEAR
   |
   |
   |-go-pear.bat          -- PEAR setup script
   |
   |-fdftk.dll
   |
   |-...
   |
   |-php-cgi.exe          -- CGI executable
   |
   |-php-win.exe          -- executes scripts without an opened command prompt
   |
   |-php.exe              -- CLI executable - ONLY for command line scripting
   |
   |-...
   |
   |-php.ini-dist         -- default php.ini settings
   |
   |-php.ini-recommended  -- recommended php.ini settings
   | 
   |-php5activescript.dll
   |
   |-php5apache.dll
   |
   |-php5apache2.dll
   |
   |-...
   |
   |-php5ts.dll           -- core PHP DLL
   | 
   |-...

Notice the differences and similarities. Both PHP 4 and PHP 5 have a CGI executable, a CLI executable, and server modules, but they are located in different folders and/or have different names. While PHP 4 packages have the server modules in the sapi folder, PHP 5 distributions have no such directory and instead they're in the PHP folder root. The supporting DLLs for the PHP 5 extensions are also not in a seperate directory.

Note: In PHP 4, you should move all files located in the dll and sapi folders to the main folder (e.g. C:\php).

Here is a list of server modules shipped with PHP 4 and PHP 5:

  • sapi/php4activescript.dll (php5activescript.dll) - ActiveScript engine, allowing you to embed PHP in your Windows applications.

  • sapi/php4apache.dll (php5apache.dll) - Apache 1.3.x module.

  • sapi/php4apache2.dll (php5apache2.dll) - Apache 2.0.x module.

  • sapi/php5apache2_2.dll - Apache 2.2.x module.

  • sapi/php4isapi.dll (php5isapi.dll) - ISAPI Module for ISAPI compliant web servers like IIS 4.0/PWS 4.0 or newer.

  • sapi/php4nsapi.dll (php5nsapi.dll) - Sun/iPlanet/Netscape server module.

  • sapi/php4pi3web.dll (no equivalent in PHP 5) - Pi3Web server module.

Server modules provide significantly better performance and additional functionality compared to the CGI binary. The CLI version is designed to let you use PHP for command line scripting. More information about CLI is available in the chapter about using PHP from the command line.

Warning

The SAPI modules have been significantly improved as of the 4.1 release, however, in older systems you may encounter server errors or other server modules failing, such as ASP.

The CGI and CLI binaries, and the web server modules all require the php4ts.dll (php5ts.dll) file to be available to them. You have to make sure that this file can be found by your PHP installation. The search order for this DLL is as follows:

  • The same directory from where php.exe is called, or in case you use a SAPI module, the web server's directory (e.g. C:\Program Files\Apache Group\Apache2\bin).

  • Any directory in your Windows PATH environment variable.

To make php4ts.dll / php5ts.dll available you have three options: copy the file to the Windows system directory, copy the file to the web server's directory, or add your PHP directory, C:\php to the PATH. For better maintenance, we advise you to follow the last option, add C:\php to the PATH, because it will be simpler to upgrade PHP in the future. Read more about how to add your PHP directory to PATH in the corresponding FAQ entry (and then don't forget to restart the computer - logoff isn't enough).

The next step is to set up a valid configuration file for PHP, php.ini. There are two ini files distributed in the zip file, php.ini-dist and php.ini-recommended. We advise you to use php.ini-recommended, because we optimized the default settings in this file for performance, and security. Read this well documented file carefully because it has changes from php.ini-dist that will drastically affect your setup. Some examples are display_errors being off and magic_quotes_gpc being off. In addition to reading these, study the ini settings and set every element manually yourself. If you would like to achieve the best security, then this is the way for you, although PHP works fine with these default ini files. Copy your chosen ini-file to a directory that PHP is able to find and rename it to php.ini. PHP searches for php.ini in the locations described in 설정 파일 section.

If you are running Apache 2, the simpler option is to use the PHPIniDir directive (read the installation on Apache 2 page), otherwise your best option is to set the PHPRC environment variable. This process is explained in the following FAQ entry.

Note: If you're using NTFS on Windows NT, 2000, XP or 2003, make sure that the user running the web server has read permissions to your php.ini (e.g. make it readable by Everyone).

The following steps are optional:

  • Edit your new php.ini file. If you plan to use OmniHTTPd, do not follow the next step. Set the doc_root to point to your web servers document_root. For example:

    doc_root = c:\inetpub\wwwroot // for IIS/PWS
    
    doc_root = c:\apache\htdocs // for Apache

  • Choose the extensions you would like to load when PHP starts. See the section about Windows extensions, about how to set up one, and what is already built in. Note that on a new installation it is advisable to first get PHP working and tested without any extensions before enabling them in php.ini.
  • On PWS and IIS, you can set the browscap configuration setting to point to: c:\windows\system\inetsrv\browscap.ini on Windows 9x/Me, c:\winnt\system32\inetsrv\browscap.ini on NT/2000, and c:\windows\system32\inetsrv\browscap.ini on XP. For an up-to-date browscap.ini, read the following FAQ.

PHP is now setup on your system. The next step is to choose a web server, and enable it to run PHP. Choose a web server from the table of contents.



ActiveScript

This section contains notes specific to the ActiveScript installation.

ActiveScript is a Windows only SAPI that enables you to use PHP script in any ActiveScript compliant host, like Windows Script Host, ASP/ASP.NET, Windows Script Components or Microsoft Scriptlet control.

As of PHP 5.0.1, ActiveScript has been moved to the » PECL repository. 이 PECL 확장에 대한 DLL은 현재 사용할 수 없습니다. 윈도우에서 빌드하기 섹션을 참고하십시오.

Note: You should read the manual installation steps first!

After installing PHP, you should download the ActiveScript DLL (php5activescript.dll) and place it in the main PHP folder (e.g. C:\php).

After having all the files needed, you must register the DLL on your system. To achieve this, open a Command Prompt window (located in the Start Menu). Then go to your PHP directory by typing something like cd C:\php. To register the DLL just type regsvr32 php5activescript.dll.

To test if ActiveScript is working, create a new file, named test.wsf (the extension is very important) and type:

<job id="test">
 
 <script language="PHPScript">
  $WScript->Echo("Hello World!");
 </script>
 
</job>

Save and double-click on the file. If you receive a little window saying "Hello World!" you're done.

Note: In PHP 4, the engine was named 'ActivePHP', so if you are using PHP 4, you should replace 'PHPScript' with 'ActivePHP' in the above example.

Note: ActiveScript doesn't use the default php.ini file. Instead, it will look only in the same directory as the .exe that caused it to load. You should create php-activescript.ini and place it in that folder, if you wish to load extensions, etc.



Microsoft IIS / PWS

This section contains notes and hints specific to IIS (Microsoft Internet Information Server).

Warning

CGI 설정을 사용할 때, 서버가 여러 공격에 노출됩니다. 그러한 공격을 막기 위해 CGI 보안 섹션을 읽어보십시오.

General considerations for all installations of PHP with IIS or PWS

  • First, read the Manual Installation Instructions. Do not skip this step as it provides crucial information for installing PHP on Windows.
  • CGI users must set the cgi.force_redirect PHP directive to 0 inside php.ini. Read the faq on cgi.force_redirect for important details. Also, CGI users may want to set the cgi.redirect_status_env directive. When using directives, be sure these directives aren't commented out inside php.ini.
  • The PHP 4 CGI is named php.exe while in PHP 5 it's php-cgi.exe. In PHP 5, php.exe is the CLI, and not the CGI.
  • Modify the Windows PATH environment variable to include the PHP directory. This way the PHP DLL files and PHP executables can all remain in the PHP directory without cluttering up the Windows system directory. For more details, see the FAQ on Setting the PATH.
  • The IIS user (usually IUSR_MACHINENAME) needs permission to read various files and directories, such as php.ini, docroot, and the session tmp directory.
  • Be sure the extension_dir and doc_root PHP directives are appropriately set in php.ini. These directives depend on the system that PHP is being installed on. In PHP 4, the extension_dir is extensions while with PHP 5 it's ext. So, an example PHP 5 extensions_dir value is "c:\php\ext" and an example IIS doc_root value is "c:\Inetpub\wwwroot".
  • PHP extension DLL files, such as php_mysql.dll and php_curl.dll, are found in the zip package of the PHP download (not the PHP installer). In PHP 5, many extensions are part of PECL and can be downloaded in the "Collection of PECL modules" package. Files such as php_zip.dll and php_ssh2.dll. » Download PHP files here.
  • When defining the executable, the 'check that file exists' box may also be checked. For a small performance penalty, the IIS (or PWS) will check that the script file exists and sort out authentication before firing up PHP. This means that the web server will provide sensible 404 style error messages instead of CGI errors complaining that PHP did not output any data.
  • The PHP executable is distributed as a 32bit application. If you are running a 64bit version of Windows you will either need to rebuild the binary yourself, or make sure IIS is configured to also run 32bit extensions. You can usually turn this on by using the IIS Administration script as follows: Cscript.exe adsutil.vbs SET W3SVC/AppPools/Enable32bitAppOnWin64 1

Windows NT/200x/XP and IIS 4 or newer

PHP may be installed as a CGI binary, or with the ISAPI module. In either case, you need to start the Microsoft Management Console (may appear as 'Internet Services Manager', either in your Windows NT 4.0 Option Pack branch or the Control Panel=>Administrative Tools under Windows 2000/XP). Then right click on your Web server node (this will most probably appear as 'Default Web Server'), and select 'Properties'.

If you want to use the CGI binary, do the following:

  • Under 'Home Directory', 'Virtual Directory', or 'Directory', do the following:
  • Change the Execute Permissions to 'Scripts only'
  • Click on the 'Configuration' button, and choose the Application Mappings tab. Click Add and set the Executable path to the appropriate CGI file. An example PHP 5 value is: C:\php\php-cgi.exe Supply .php as the extension. Leave 'Method exclusions' blank, and check the 'Script engine' checkbox. Now, click OK a few times.
  • Set up the appropriate security. (This is done in Internet Service Manager), and if your NT Server uses NTFS file system, add execute rights for I_USR_ to the directory that contains php.exe / php-cgi.exe.

To use the ISAPI module, do the following:

  • If you don't want to perform HTTP Authentication using PHP, you can (and should) skip this step. Under ISAPI Filters, add a new ISAPI filter. Use PHP as the filter name, and supply a path to the php4isapi.dll / php5isapi.dll.
  • Under 'Home Directory', 'Virtual Directory', or 'Directory', do the following:
  • Change the Execute Permissions to 'Scripts only'
  • Click on the 'Configuration' button, and choose the Application Mappings tab. Click Add and set the Executable path to the appropriate ISAPI DLL. An example PHP 5 value is: C:\php\php5isapi.dll Supply .php as the extension. Leave 'Method exclusions' blank, and check the 'Script engine' checkbox. Now, click OK a few times.
  • Stop IIS completely (NET STOP iisadmin)
  • Start IIS again (NET START w3svc)

With IIS 6 (2003 Server), open up the IIS Manager, go to Web Service Extensions, choose "Add a new Web service extension", enter in a name such as PHP, choose the Add button and for the value browse to either the ISAPI file (php4isapi.dll or php5isapi.dll) or CGI (php.exe or php-cgi.exe) then check "Set extension status to Allowed" and click OK.

In order to use index.php as a default content page, do the following: From within the Documents tab, choose Add. Type in index.php and click OK. Adjust the order by choosing Move Up or Move Down. This is similar to setting DirectoryIndex with Apache.

The steps above must be repeated for each extension that is to be associated with PHP scripts. .php is the most common although .php3 may be required for legacy applications.

If you experience 100% CPU usage after some time, turn off the IIS setting Cache ISAPI Application.

Windows and PWS 4

PWS 4 does not support ISAPI, only PHP CGI should be used.

  • Edit the enclosed pws-php4cgi.reg / pws-php5cgi.reg file (look into the SAPI folder for PHP 4, or in the main folder for PHP 5) to reflect the location of your php.exe / php-cgi.exe. Backslashes should be escaped, for example: [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\w3svc\parameters\Script Map] ".php"="C:\\php\\php.exe" (change to C:\\php\\php-cgi.exe if you are using PHP 5) Now merge this registery file into your system; you may do this by double-clicking it.
  • In the PWS Manager, right click on a given directory you want to add PHP support to, and select Properties. Check the 'Execute' checkbox, and confirm.

Windows and PWS/IIS 3

The recommended method for configuring these servers is to use the REG file included with the distribution (pws-php4cgi.reg in the SAPI folder for PHP 4, or pws-php5cgi.reg in the main folder for PHP 5). You may want to edit this file and make sure the extensions and PHP install directories match your configuration. Or you can follow the steps below to do it manually.

Warning

These steps involve working directly with the Windows registry. One error here can leave your system in an unstable state. We highly recommend that you back up your registry first. The PHP Development team will not be held responsible if you damage your registry.

  • Run Regedit.
  • Navigate to: HKEY_LOCAL_MACHINE /System /CurrentControlSet /Services /W3Svc /Parameters /ScriptMap.
  • On the edit menu select: New->String Value.
  • Type in the extension you wish to use for your php scripts. For example .php
  • Double click on the new string value and enter the path to php.exe in the value data field. ex: C:\php\php.exe "%s" %s for PHP 4, or C:\php\php-cgi.exe "%s" %s for PHP 5.
  • Repeat these steps for each extension you wish to associate with PHP scripts.

The following steps do not affect the web server installation and only apply if you want your PHP scripts to be executed when they are run from the command line (ex. run C:\myscripts\test.php) or by double clicking on them in a directory viewer window. You may wish to skip these steps as you might prefer the PHP files to load into a text editor when you double click on them.

  • Navigate to: HKEY_CLASSES_ROOT
  • On the edit menu select: New->Key.
  • Name the key to the extension you setup in the previous section. ex: .php
  • Highlight the new key and in the right side pane, double click the "default value" and enter phpfile.
  • Repeat the last step for each extension you set up in the previous section.
  • Now create another New->Key under HKEY_CLASSES_ROOT and name it phpfile.
  • Highlight the new key phpfile and in the right side pane, double click the "default value" and enter PHP Script.
  • Right click on the phpfile key and select New->Key, name it Shell.
  • Right click on the Shell key and select New->Key, name it open.
  • Right click on the open key and select New->Key, name it command.
  • Highlight the new key command and in the right side pane, double click the "default value" and enter the path to php.exe. ex: c:\php\php.exe -q %1. (don't forget the %1).
  • Exit Regedit.
  • If using PWS on Windows, reboot to reload the registry.

PWS and IIS 3 users now have a fully operational system. IIS 3 users can use a nifty » tool from Steven Genusa to configure their script maps.



Apache 1.3.x on Microsoft Windows

This section contains notes and hints specific to Apache 1.3.x installs of PHP on Microsoft Windows systems. There are also instructions and notes for Apache 2 on a separate page.

Note: Please read the manual installation steps first!

There are two ways to set up PHP to work with Apache 1.3.x on Windows. One is to use the CGI binary (php.exe for PHP 4 and php-cgi.exe for PHP 5), the other is to use the Apache Module DLL. In either case you need to edit your httpd.conf to configure Apache to work with PHP, and then restart the server.

It is worth noting here that now the SAPI module has been made more stable under Windows, we recommend it's use above the CGI binary, since it is more transparent and secure.

Although there can be a few variations of configuring PHP under Apache, these are simple enough to be used by the newcomer. Please consult the Apache Documentation for further configuration directives.

After changing the configuration file, remember to restart the server, for example, NET STOP APACHE followed by NET START APACHE, if you run Apache as a Windows Service, or use your regular shortcuts.

Note: 윈도우 상에서 아파치 설정 파일에 경로값을 추가할 때는 다음과 같이 모든 백슬래시를 슬래시로 바꿔야 합니다: c:\directory\file.extc:/directory/file.ext로 바꿉니다. 디렉토리에는 마지막에 슬래시를 붙여줘야 합니다.

Installing as an Apache module

You should add the following lines to your Apache httpd.conf file:

Example #1 PHP as an Apache 1.3.x module

This assumes PHP is installed to c:\php. Adjust the path if this is not the case.

For PHP 4:

# Add to the end of the LoadModule section
# Don't forget to copy this file from the sapi directory!
LoadModule php4_module "C:/php/php4apache.dll"

# Add to the end of the AddModule section
AddModule mod_php4.c

For PHP 5:

# Add to the end of the LoadModule section
LoadModule php5_module "C:/php/php5apache.dll"

# Add to the end of the AddModule section
AddModule mod_php5.c

For both:

# Add this line inside the <IfModule mod_mime.c> conditional brace
AddType application/x-httpd-php .php

# For syntax highlighted .phps files, also add
AddType application/x-httpd-php-source .phps

Installing as a CGI binary

If you unzipped the PHP package to C:\php\ as described in the Manual Installation Steps section, you need to insert these lines to your Apache configuration file to set up the CGI binary:

Example #2 PHP and Apache 1.3.x as CGI

ScriptAlias /php/ "c:/php/"
AddType application/x-httpd-php .php

# For PHP 4
Action application/x-httpd-php "/php/php.exe"

# For PHP 5
Action application/x-httpd-php "/php/php-cgi.exe"

# specify the directory where php.ini is
SetEnv PHPRC C:/php

Note that the second line in the list above can be found in the actual versions of httpd.conf, but it is commented out. Remember also to substitute the c:/php/ for your actual path to PHP.

Warning

CGI 설정을 사용할 때, 서버가 여러 공격에 노출됩니다. 그러한 공격을 막기 위해 CGI 보안 섹션을 읽어보십시오.

If you would like to present PHP source files syntax highlighted, there is no such convenient option as with the module version of PHP. If you chose to configure Apache to use PHP as a CGI binary, you will need to use the highlight_file() function. To do this simply create a PHP script file and add this code: <?php highlight_file('some_php_script.php'); ?>.



마이크로소프트 윈도우에서 Apache 2.0.x

이 섹션은 마이크로소프트 윈도우 시스템에서 아파치 2.0.x에 PHP 설치에 관한 정보와 힌트를 가지고 있습니다. 아파치 1.3.x 사용자를 위한 지시와 정보는 별도 페이지에 존재합니다.

Note: 수동 설치 단계를 먼저 읽어야 합니다!

Note: 아파치 2.2.x 지원
아파치 2.2.x 사용자는 해당하는 DLL 파일이 php5apache2_2.dll이고, PHP 5.2.0부터 존재한다는 점을 생각하고 아래 문서를 사용해야 합니다. » http://snaps.php.net/를 참고하십시오.

Warning

제품 환경에서 아파치 2 쓰레드 MPM 사용을 권하지 않습니다. prefork MPM을 사용하거나, Apache 1을 사용하십시오. 이유는 관련 FAQ 아파치2 쓰레드 MPM 사용하기를 읽어보십시오.

아파치 2.0.x 서버에 대한 이해를 위하여 » 아파치 문서를 읽기를 권합니다. 또한, 아파치 2.0.x에 대한 » 윈도우 특정 노트도 읽어보십시오.

Note: PHP와 아파치 2.0.x 호환 노트
다음 버전의 PHP가 최신 버전의 아파치 2.0.x에서 작동합니다:

위 PHP 버전은 아파치 2.0.40 이후에 호환됩니다.
아파치 2.0 SAPI 지원은 PHP 4.2.0부터 시작했습니다. PHP 4.2.3은 아파치 2.0.39에서 작동하며, PHP 4.2.3과 다른 아파치 버전을 사용하지 마십시오. 그러나, 권장하는 설정은 최신 버전의 아파치2와 PHP 4.3.0 이후를 사용하는 것입니다.
언급한 모든 PHP 버전은 아파치 1.3.x에서 잘 동작합니다.

Warning

아파치 2.0.x는 윈도우 NT 4.0, 윈도우 2000, 윈도우 XP에서 실행하도록 설계되었습니다. 현 시점에서, 윈도우 9x 지원은 미완성입니다. 아파치 2.0.x는 아직 이러한 플랫폼에서 작동한다는 보장이 없습니다.

가장 최신 버전의 » 아파치 2.0.x와 적합한 PHP 버전을 받으십시오. 수동 설치 단계에 따르고 PHP와 아파치 통합을 진행하십시오.

윈도우에서 아파치 2.0.x에 PHP를 설치하는 방법은 두 가지가 있습니다. 하나는 CGI 바이너리이고, 다른 하나는 아파치 모듈 DLL입니다. 두 방법 모두 httpd.conf를 수정하여 아파치에서 PHP를 작동하도록 하고 서버를 재시작 해야 합니다.

Note: 윈도우 상에서 아파치 설정 파일에 경로값을 추가할 때는 다음과 같이 모든 백슬래시를 슬래시로 바꿔야 합니다: c:\directory\file.extc:/directory/file.ext로 바꿉니다. 디렉토리에는 마지막에 슬래시를 붙여줘야 합니다.

CGI 바이너리로 설치

CGI 바이너리로 설치하려면 아래 세 줄을 아파치 httpd.conf 설정 파일에 넣어야 합니다:

Example #1 CGI로 PHP와 아파치 2.0

ScriptAlias /php/ "c:/php/"
AddType application/x-httpd-php .php

# For PHP 4
Action application/x-httpd-php "/php/php.exe"

# For PHP 5
Action application/x-httpd-php "/php/php-cgi.exe"

Warning

CGI 설정을 사용할 때, 서버가 여러 공격에 노출됩니다. 그러한 공격을 막기 위해 CGI 보안 섹션을 읽어보십시오.

아파치 모듈로 설치

아파치 2.0에 PHP 모듈을 설치하려면 아래 두 줄을 아파치 httpd.conf 설정 파일에 넣어야 합니다:

Example #2 모듈로 PHP와 Apache 2.0

# For PHP 4 do something like this:
LoadModule php4_module "c:/php/php4apache2.dll"
# Don't forget to copy the php4apache2.dll file from the sapi directory!
AddType application/x-httpd-php .php

# For PHP 5 do something like this:
LoadModule php5_module "c:/php/php5apache2.dll"
AddType application/x-httpd-php .php

# configure the path to php.ini
PHPIniDir "C:/php"

Note: 위 예제에서 c:/php/을 실제 PHP 경로로 변경하십시오. LoadModule 지시어에 php4apache2.dll이나 php5apache2.dll을 사용하는 점에 주의하십시오. php4apache.dll이나 php5apache.dll아닙니다. 이들은 아파치 1.3.x에 사용하도록 설계되었습니다.

Note: 내용 협상을 사용하려면, 관련 FAQ를 읽어보십시오.

Warning

DLL 파일을 다른 PHP 버전과 섞지 마십시오. DLL 사용과 확장을 모두 내려받은 PHP 버전에서 사용해야 합니다.



Sun, iPlanet and Netscape servers on Microsoft Windows

This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Windows.

From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to generate custom directory listings and error pages. Additional functions for Apache compatibility are also available. For support in current web servers read the note about subrequests.

CGI setup on Sun, iPlanet and Netscape servers

To install PHP as a CGI handler, do the following:

  • Copy php4ts.dll to your systemroot (the directory where you installed Windows)
  • Make a file association from the command line. Type the following two lines:

    assoc .php=PHPScript
    ftype PHPScript=c:\php\php.exe %1 %*

  • In the Netscape Enterprise Administration Server create a dummy shellcgi directory and remove it just after (this step creates 5 important lines in obj.conf and allow the web server to handle shellcgi scripts).
  • In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/shellcgi, File Suffix:php).
  • Do it for each web server instance you want PHP to run

More details about setting up PHP as a CGI executable can be found here: » http://benoit.noss.free.fr/php/install-php.html

NSAPI setup on Sun, iPlanet and Netscape servers

To install PHP with NSAPI, do the following:

  • Copy php4ts.dll to your systemroot (the directory where you installed Windows)
  • Make a file association from the command line. Type the following two lines:

    assoc .php=PHPScript
    ftype PHPScript=c:\php\php.exe %1 %*

  • In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/x-httpd-php, File Suffix: php).
  • Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following: You should place the lines after mime types init.

    Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="c:/php/sapi/php4nsapi.dll"
    Init fn="php4_init" LateInit="yes" errorString="Failed to initialise PHP!" [php_ini="c:/path/to/php.ini"]
    

    (PHP >= 4.3.3) The php_ini parameter is optional but with it you can place your php.ini in your web server configuration directory.

  • Configure the default object in obj.conf (for virtual server classes [Sun Web Server 6.0+] in their vserver.obj.conf): In the <Object name="default"> section, place this line necessarily after all 'ObjectType' and before all 'AddLog' lines:

    Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...]
    

    (PHP >= 4.3.3) As additional parameters you can add some special php.ini-values, for example you can set a docroot="/path/to/docroot" specific to the context php4_execute is called. For boolean ini-keys please use 0/1 as value, not "On","Off",... (this will not work correctly), e.g. zlib.output_compression=1 instead of zlib.output_compression="On"

  • This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):

    <Object name="x-httpd-php">
    ObjectType fn="force-type" type="magnus-internal/x-httpd-php"
    Service fn=php4_execute [inikey=value inikey=value ...]
    </Object>
    

    After that you can configure a directory in the Administration server and assign it the style x-httpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming files to .html.

  • Restart your web service and apply changes
  • Do it for each web server instance you want PHP to run

Note: More details about setting up PHP as an NSAPI filter can be found here: » http://benoit.noss.free.fr/php/install-php4.html

Note: The stacksize that PHP uses depends on the configuration of the web server. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").

CGI environment and recommended modifications in php.ini

Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the web server itself) and this space has only one environment. If you want to get CGI variables like PATH_INFO, HTTP_HOST etc. it is not the correct way to try this in the old PHP way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running web server without any valid CGI variables!

Note: Why are there (invalid) CGI variables in the environment?
Answer: This is because you started the web server process from the admin server which runs the startup script of the web server, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started web server has some CGI environment variables in it. You can test this by starting the web server not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.

Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):

variables_order = "GPCS"
register_globals = On

Special use for error pages or self-made directory listings (PHP >= 4.3.3)

You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:

Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...]

where XXX is the HTTP error code. Please delete any other Error directives which could interfere with yours. If you want to place a page for all errors that could exist, leave the code parameter out. Your script can get the HTTP status code with $_SERVER['ERROR_TYPE'].

Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:

Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...]

For both error and directory listing pages the original URI and translated URI are in the variables $_SERVER['PATH_INFO'] and $_SERVER['PATH_TRANSLATED'].

Note about nsapi_virtual() and subrequests (PHP >= 4.3.3)

The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the web server and insert the result in the web page. The problem is, that this function uses some undocumented features from the NSAPI library.

Under Unix this is not a problem, because the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.

Under Windows limitations in the DLL handling need the use of a automatic detection of the most recent ns-httpdXX.dll file. This is tested for servers till version 6.1. If a newer version of the Sun server is used, the detection fails and nsapi_virtual() is disabled.

If this is the case, try the following: Add the following parameter to php4_init in magnus.conf/obj.conf:

Init fn=php4_init ... server_lib="ns-httpdXX.dll"

where XX is the correct DLL version number. To get it, look in the server-root for the correct DLL name. The DLL with the biggest filesize is the right one.

You can check the status by using the phpinfo() function.

Note: But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!



OmniHTTPd Server

This section contains notes and hints specific to » OmniHTTPd on Windows.

Note: You should read the manual installation steps first!

Warning

CGI 설정을 사용할 때, 서버가 여러 공격에 노출됩니다. 그러한 공격을 막기 위해 CGI 보안 섹션을 읽어보십시오.

You need to complete the following steps to make PHP work with OmniHTTPd. This is a CGI executable setup. SAPI is supported by OmniHTTPd, but some tests have shown that it is not so stable to use PHP as an ISAPI module.

Note: Important for CGI users
Read the faq on cgi.force_redirect for important details. This directive needs to be set to 0.

  1. Install OmniHTTPd server.

  2. Right click on the blue OmniHTTPd icon in the system tray and select Properties

  3. Click on Web Server Global Settings

  4. On the 'External' tab, enter: virtual = .php | actual = c:\php\php.exe (use php-cgi.exe if installing PHP 5), and use the Add button.

  5. On the Mime tab, enter: virtual = wwwserver/stdcgi | actual = .php, and use the Add button.

  6. Click OK

Repeat steps 2 - 6 for each extension you want to associate with PHP.

Note: Some OmniHTTPd packages come with built in PHP support. You can choose at setup time to do a custom setup, and uncheck the PHP component. We recommend you to use the latest PHP binaries. Some OmniHTTPd servers come with PHP 4 beta distributions, so you should choose not to set up the built in support, but install your own. If the server is already on your machine, use the Replace button in Step 4 and 5 to set the new, correct information.



Sambar Server on Microsoft Windows

This section contains notes and hints specific to the » Sambar Server for Windows.

Note: You should read the manual installation steps first!

This list describes how to set up the ISAPI module to work with the Sambar server on Windows.

  • Find the file called mappings.ini (in the config directory) in the Sambar install directory.

  • Open mappings.ini and add the following line under [ISAPI]:

    Example #1 ISAPI configuration of Sambar

    #for PHP 4
    *.php = c:\php\php4isapi.dll
    
    #for PHP 5
    *.php = c:\php\php5isapi.dll
    

    (This line assumes that PHP was installed in c:\php.)

  • Now restart the Sambar server for the changes to take effect.

Note: If you intend to use PHP to communicate with resources which are held on a different computer on your network, then you will need to alter the account used by the Sambar Server Service. The default account used for the Sambar Server Service is LocalSystem which will not have access to remote resources. The account can be amended by using the Services option from within the Windows Control Panel Administation Tools.



Xitami on Microsoft Windows

This section contains notes and hints specific to » Xitami on Windows.

Note: You should read the manual installation steps first!

This list describes how to set up the PHP CGI binary to work with Xitami on Windows.

Note: Important for CGI users
Read the faq on cgi.force_redirect for important details. This directive needs to be set to 0. If you want to use $_SERVER['PHP_SELF'] you have to enable the cgi.fix_pathinfo directive.

Warning

CGI 설정을 사용할 때, 서버가 여러 공격에 노출됩니다. 그러한 공격을 막기 위해 CGI 보안 섹션을 읽어보십시오.

  • Make sure the web server is running, and point your browser to xitamis admin console (usually http://127.0.0.1/admin), and click on Configuration.

  • Navigate to the Filters, and put the extension which PHP should parse (i.e. .php) into the field File extensions (.xxx).

  • In Filter command or script put the path and name of your PHP CGI executable i.e. C:\php\php.exe for PHP 4, or C:\php\php-cgi.exe for PHP 5.

  • Press the 'Save' icon.

  • Restart the server to reflect changes.



Building from source

This chapter teaches how to compile PHP from sources on windows, using Microsoft's tools. To compile PHP with cygwin, please refer to 유닉스 시스템에 설치.

This chapter is outdated therefore it's temporarily been removed from the manual. For now, consider the following:



Installation of extensions on Windows

After installing PHP and a web server on Windows, you will probably want to install some extensions for added functionality. You can choose which extensions you would like to load when PHP starts by modifying your php.ini. You can also load a module dynamically in your script using dl().

The DLLs for PHP extensions are prefixed with php_.

Many extensions are built into the Windows version of PHP. This means additional DLL files, and the extension directive, are not used to load these extensions. The Windows PHP Extensions table lists extensions that require, or used to require, additional PHP DLL files. Here's a list of built in extensions:

In PHP 4 (updated PHP 4.3.11): BCMath, Caledar, COM, Ctype, FTP, MySQL, ODBC, Overload, PCRE, Session, Tokenizer, WDDX, XML 그리고 Zlib

In PHP 5 (updated PHP 5.0.4), the following changes exist. Built in: DOM, LibXML, Iconv, SimpleXML, SPL 그리고 SQLite. And the following are no longer built in: MySQL and Overload.

The default location PHP searches for extensions is C:\php4\extensions in PHP 4 and C:\php5 in PHP 5. To change this setting to reflect your setup of PHP edit your php.ini file:

  • You will need to change the extension_dir setting to point to the directory where your extensions lives, or where you have placed your php_*.dll files. For example:

    extension_dir = C:\php\extensions

  • Enable the extension(s) in php.ini you want to use by uncommenting the extension=php_*.dll lines in php.ini. This is done by deleting the leading ; from the extension you want to load.

    Example #1 Enable Bzip2 extension for PHP-Windows

    // change the following line from ...
    ;extension=php_bz2.dll
    
    // ... to
    extension=php_bz2.dll

  • Some of the extensions need extra DLLs to work. Couple of them can be found in the distribution package, in the C:\php\dlls\ folder in PHP 4 or in the main folder in PHP 5, but some, for example Oracle (php_oci8.dll) require DLLs which are not bundled with the distribution package. If you are installing PHP 4, copy the bundled DLLs from C:\php\dlls folder to the main C:\php folder. Don't forget to include C:\php in the system PATH (this process is explained in a separate FAQ entry).

  • Some of these DLLs are not bundled with the PHP distribution. See each extensions documentation page for details. Also, read the manual section titled Installation of PECL extensions for details on PECL. An increasingly large number of PHP extensions are found in PECL, and these extensions require a separate download.

Note: If you are running a server module version of PHP remember to restart your web server to reflect your changes to php.ini.

The following table describes some of the extensions available and required additional dlls.

PHP Extensions
Extension Description Notes
php_bz2.dll bzip2 compression functions None
php_calendar.dll Calendar conversion functions Built in since PHP 4.0.3
php_crack.dll Crack functions None
php_ctype.dll ctype family functions Built in since PHP 4.3.0
php_curl.dll CURL, Client URL library functions Requires: libeay32.dll, ssleay32.dll (bundled)
php_dba.dll DBA: DataBase (dbm-style) Abstraction layer functions None
php_dbase.dll dBase functions None
php_dbx.dll dbx functions  
php_domxml.dll DOM XML functions PHP <= 4.2.0 requires: libxml2.dll (bundled) PHP >= 4.3.0 requires: iconv.dll (bundled)
php_dotnet.dll .NET functions PHP <= 4.1.1
php_exif.dll EXIF functions php_mbstring.dll. And, php_exif.dll must be loaded after php_mbstring.dll in php.ini.
php_fbsql.dll FrontBase functions PHP <= 4.2.0
php_fdf.dll FDF: Forms Data Format functions. Requires: fdftk.dll (bundled)
php_filepro.dll filePro functions Read-only access
php_ftp.dll FTP functions Built-in since PHP 4.0.3
php_gd.dll GD library image functions Removed in PHP 4.3.2. Also note that truecolor functions are not available in GD1, instead, use php_gd2.dll.
php_gd2.dll GD library image functions GD2
php_gettext.dll Gettext functions PHP <= 4.2.0 requires gnu_gettext.dll (bundled), PHP >= 4.2.3 requires libintl-1.dll, iconv.dll (bundled).
php_hyperwave.dll HyperWave functions None
php_iconv.dll ICONV characterset conversion Requires: iconv-1.3.dll (bundled), PHP >=4.2.1 iconv.dll
php_ifx.dll Informix functions Requires: Informix libraries
php_iisfunc.dll IIS management functions None
php_imap.dll IMAP POP3 and NNTP functions None
php_ingres.dll Ingres functions Requires: Ingres libraries
php_interbase.dll InterBase functions Requires: gds32.dll (bundled)
php_java.dll Java functions PHP <= 4.0.6 requires: jvm.dll (bundled)
php_ldap.dll LDAP functions PHP <= 4.2.0 requires libsasl.dll (bundled), PHP >= 4.3.0 requires libeay32.dll, ssleay32.dll (bundled)
php_mbstring.dll Multi-Byte String functions None
php_mcrypt.dll Mcrypt Encryption functions Requires: libmcrypt.dll
php_mhash.dll Mhash functions PHP >= 4.3.0 requires: libmhash.dll (bundled)
php_mime_magic.dll Mimetype functions Requires: magic.mime (bundled)
php_ming.dll Ming functions for Flash None
php_msql.dll mSQL functions Requires: msql.dll (bundled)
php_mssql.dll MSSQL functions Requires: ntwdblib.dll (bundled)
php_mysql.dll MySQL functions PHP >= 5.0.0, requires libmysql.dll (bundled)
php_mysqli.dll MySQLi functions PHP >= 5.0.0, requires libmysql.dll (libmysqli.dll in PHP <= 5.0.2) (bundled)
php_oci8.dll Oracle 8 functions Requires: Oracle 8.1+ client libraries
php_openssl.dll OpenSSL functions Requires: libeay32.dll (bundled)
php_overload.dll Object overloading functions Built in since PHP 4.3.0
php_pdf.dll PDF functions None
php_pgsql.dll PostgreSQL functions None
php_printer.dll Printer functions None
php_shmop.dll Shared Memory functions None
php_snmp.dll SNMP get and walk functions NT only!
php_soap.dll SOAP functions PHP >= 5.0.0
php_sockets.dll Socket functions None
php_sybase_ct.dll Sybase functions Requires: Sybase client libraries
php_tidy.dll Tidy functions PHP >= 5.0.0
php_tokenizer.dll Tokenizer functions Built in since PHP 4.3.0
php_w32api.dll W32api functions None
php_xmlrpc.dll XML-RPC functions PHP >= 4.2.1 requires: iconv.dll (bundled)
php_xslt.dll XSLT functions PHP <= 4.2.0 requires sablot.dll, expat.dll (bundled). PHP >= 4.2.1 requires sablot.dll, expat.dll, iconv.dll (bundled).
php_yaz.dll YAZ functions Requires: yaz.dll (bundled)
php_zip.dll Zip File functions Read only access
php_zlib.dll ZLib compression functions Built in since PHP 4.3.0




PECL 확장의 설치

Table of Contents


PECL 설치 소개

» PECL 은 PHP 확장의 저장소(repository)이며 » PEAR 패키징 시스템을 통하여 이용할 수가 있습니다. 본 섹션은 PECL을 구하여 설치하는것을 설명하기 위해 마련 되었습니다.

이 지침들은 /your/phpsrcdir/ 은 PHP 소스가 위치하는 경로이고, extname 은 PECL 확장의 이름인것으로 가정 합니다. 적절히 조절하시기 바랍니다. 또한 이 지침들은 » pear command 에 친숙한것을 가정합니다. pear 명령에 대한 PEAR 매뉴얼의 정보는 또한 pecl 명령에도 적용됩니다.

이 기능을 사용하기 위해서는, 확장모듈을 빌드하고, 설치하고, 로드해야 합니다. 확장모듈을 어떻게 빌드하고 설치할것인지에 대해 아래에서 다양한 지침과 함께 그 방법들이 설명되지만, 하지만 그것만으론 모듈을 자동으로 로드할 수는 없습니다. 확장모듈은 php.ini 파일에 extension 디렉티브를 추가하든지, dl() 함수를 사용하여 로드할 수 있습니다.

PHP 모듈을 빌드할때는, 적절한 버전의 필수 툴을 사용하는것이 중요합니다 (autoconf, automake, libtool, 등등.). 필수 툴과 그 버전에 대한 자세한 내용은 » Anonymous CVS 지침 을 보십시오.



PECL 확장모듈 다운로드

PECL 확장모듈을 다운로드 하는데에는 몇가지 방법이 있습니다. 다음과 같습니다:

  • pecl install extname 명령은 확장 코드를 자동으로 내려받으므로, 따로 다운로드 할 필요가 없습니다.
  • » http://pecl.php.net/ PECL 웹사이트는 PHP 개발팀이 제공하는 여러가지의 확장모듈에 대한 정보를 제공하고 있습니다. 다음과 같은 정보가 있습니다.: 변경내역(ChangeLog),릴리즈 노트(release notes), 요구사항(requirements) 과 같은 다른 비슷한 항목들이 있습니다.
  • pecl download extname 릴리즈된 PECL 확장모듈은 » pecl 명령 를 사용하여 다운로드나 설치를 할수 있도록 PECL 웹사이트에 게재됩니다. 또한 특정 리비전을 지정할수도 있습니다.
  • CVS 대부분의 PECL 확장모듈은 CVS 에도 존재합니다. 웹기반 보기는 » http://cvs.php.net/pecl/ 에서 볼수 있습니다. CVS 로부터 바로 다운로드 하기 위해서는, 다음과 같은 명령들을 사용해야 할것입니다. phpficvsread 사용자의 패스워드임을 상기하십시오.:


    $ cvs -d:pserver:cvsread@cvs.php.net:/repository login
    $ cvs -d:pserver:cvsread@cvs.php.net:/repository co pecl/extname

  • 윈도우용 다운로드 윈도우 사용자들은 컴파일된 PECL 바이너리를 » PHP 다운로드 페이지에 있는 PECL 확장모듈 모음 에서 다운로드 받을 수 있습니다. 또는 » PECL 스냅샷 을 가져오거나, » PECL4WIN 에서 확장모듈 DLL을 구할수 있습니다. 윈도우에서 PHP를 컴파일하기 위해서는 절충 장 을 읽어 보십시오.


PHP 확장 설치하기

윈도우에서, PHP 확장을 적재하는 두가지 방법이 있습니다: PHP 안에 컴파일하거나, DLL을 적재. 미리 컴파일된 확장을 적재하는 것이 쉽고 편한 방법입니다.

확장을 적재하려면, 시스템에 해당하는 ".dll" 파일이 있어야 합니다. 모든 확장은 자동으로 주기적으로 PHP 그룹에서 컴파일합니다. (내려받기는 다음 섹션을 참고하십시오)

확장을 PHP 안에 컴파일하려면, 소스에서 빌드하기 문서를 확인하십시오.

독립 확장(DLL 파일)을 컴파일하려면, 소스에서 빌드하기 문서를 확인하십시오. DLL 파일이 PHP 배포판이나 PECL에 존재하지 않는다면, 그 확장을 사용하기 전에 컴파일해야 합니다.



확장을 어디에서 찾나요?

PHP 확장은 일반적으로 "php_*.dll"(별은 확장 이름)로 불리고, "PHP\ext"(PHP 4에서는 "PHP\extensions") 폴더에 위치하고 있습니다.

PHP는 대다수의 개발자에게 가장 유용한 확장을 포함하고 있습니다. 이들은 "핵심" 확장이라고 불립니다.

그러나, 핵심 확장에서 지원하지 않는 기능이 필요하면, PECL에서 찾을 수 있습니다. PHP Extension Community Library (PECL)는 PHP 확장의 저장고로, 알려진 모든 알려진 확장의 디렉토리를 제공하고, PHP 확장 개발과 내려받기에 필요한 기능을 지원합니다.

스스로 사용할 확장을 개발했다면, PECL에 올려서 같은 요구를 가진 다른 사람들에게 혜택을 제공할 수 있습니다. 좋은 추가 효과로 다른 사람들의 피드백, 감사, 버그 보고와 심지어 픽스/패치를 받을 수 있습니다. PECL에 확장을 제공하기 전에, http://pecl.php.net/package-new.php를 읽어보십시오.

어떤 확장을 내려받나요?

많은 경우에, 각 DLL의 여러 버전을 찾을 수 있습니다:

  • 다른 버전 번호 (적어도 처음 두 숫자는 일치)
  • 쓰레드 안전 설정 차이
  • 프로세서 설정 차이 (x86, 64비트...)
  • 디버그 설정 차이
  • 기타

확장 설정이 사용하는 PHP 실행 설정과 일치해야만 합니다. 다음 PHP 스크립트가 모든 PHP 설정을 알려줍니다:

<?php
phpinfo();
?>

또는 명령줄에서, 실행:

drive:\\path\to\php\executable\php.exe -i

확장 적재하기

PHP 확장을 적재하는 가장 일반적인 방법은 php.ini 설정 파일에 포함하는 것입니다. 많은 확장이 이미 php.ini에 존재하고, 세미콜론을 제거하면 바로 활성화됩니다.

;extension=php_extname.dll
extension=php_extname.dll

그러나, 일부 웹서버는 PHP 실행에 놓여있는 php.ini를 사용하지 않아서 혼동을 가져옵니다. 정확한 php.ini의 위치를 확인하려면, phpinfo()에서 경로를 찾아보십시오:

Configuration File (php.ini) Path  C:\WINDOWS
Loaded Configuration File  C:\Program Files\PHP\5.2\php.ini

확장을 활성화한 후, php.ini을 저장, 웹서버를 재시작하고 phpinfo()를 다시 확인하십시오. 새 확장이 자신의 섹션을 가지고 있어야 합니다.

문제 해결

확장이 phpinfo()에 나타나지 않으면, 어디서 문제가 발생하였는지 로그를 확인해야 합니다.

PHP를 명령줄(CLI)에서 사용한다면, 확장 적재 오류를 화면에서 바로 읽을 수 있습니다.

PHP를 웹서버에서 사용하면, 로그의 위치와 형식은 웹서버 소프트웨어에 의존합니다. 웹서버 문서에서 로그 위치를 찾아서 읽어보십시오. PHP 자체로는 아무것도 하지 않습니다.

일반적인 문제는 DLL 위치입니다. php.ini 안의 "extension_dir" 값이 컴파일시 설정과 일치하지 않아서 발생합니다.

문제가 컴파일시 설정이 일치하지 않는 것이라면, 아마도 옮은 DLL을 내려받지 않았을 것입니다. 적합한 설정을 가진 확장을 다시 내려받아 보십시오. 다시 말하지만, phpinfo()가 큰 도움이 될 것입니다.



pecl 명령을 사용하여 공유 PECL 확장모듈을 컴파일 하기

PECL은 공유 PHP 확장모듈을 만들기 쉽게 합니다. » pecl command 을 사용하려면, 다음을 따라하십시오.:


$ pecl install extname

이 명령은 extname 소스를 다운받아 컴파일 하고, extname.soextension_dir 에 설치할 것입니다. extname.sophp.ini를 통해 로드될 것입니다.

기본적으로 peclalphabeta 상태로 마크되어 있는 패키지는 설치하지 않을 것입니다. 만약에 stable 패키지가 없다면, 다음 명령을 사용해 beta 패키지를 설치 할수 있습니다.:


$ pecl install extname-beta

다음과 같이 변형하면 특정버전을 설치할수 있을것입니다.


$ pecl install extname-0.1

Note: php.ini 에 확장모듈을 사용가능하도록 한 뒤에는, 그것이 반영되기 위해 웹서비스를 다시 시작해야 합니다.



phpize로 공유 PECL 확장모듈 컴파일하기

가끔은, pecl 인스톨러를 사용하는것이 선택사항이 아닐수 있습니다. 방화벽뒤에 있거나, CVS의 릴리즈되지 않은 확장 모듈처럼 설치할 PECL 호환패키지가 없는것이 이유가 될 것입니다. 이런 확장모듈을 빌드할 필요가 있을 경우, 좀더 하위 레벨의 빌드툴을 사용하여 직접 빌드할수가 있습니다.

phpize 명령은 PHP 확장모듈을 위한 빌드환경을 만들기 위해 사용합니다. 아래의 샘플코드에는 확장모듈의 소스가 extname 이름의 디렉터리 안에 있습니다.:

$ cd extname
$ phpize
$ ./configure
$ make
# make install

성공적으로 인스톨되었다면 extname.so 이 생성될것이고, 그것을 PHP의 확장모듈 디렉터리 안에 위치시킬 것입니다. 확장 모듈을 사용하기전에 php.iniextension=extname.so 라인의 추가가 필요할 것입니다.

만약에 시스템이 phpize 명령을 찾지 못하고, 미리컴파일된 패키지(RPM 같은)를 사용하고 있다면, 적절한 버전의 PHP devel 패키지를 설치하도록 합니다. 그것들은 대체로 phpize 명령 이외에 PHP와 확장모듈을 빌드할 적절한 헤더파일을 포함합니다.

phpize --help 를 실행하면 추가적인 사용법 정보를 볼수가 있습니다.



PECL 확장모듈을 PHP안에 정적으로 컴파일 하기

아마도 필요한 PECL 확장모듈을 PHP 바이너리 안에 정적으로 빌드하는 방법을 찾을 것입니다. 이것을 위해서는, 확장모듈 소스를 php-src/ext/ 디렉터리 아래에 위치시키고, PHP 빌드 시스템에 설정(configure) 스크립트를 다시 만들라고 말해줄 필요가 있습니다.

$ cd /your/phpsrcdir/ext
$ pecl download extname
$ gzip -d < extname.tgz | tar -xvf -
$ mv extname-x.x.x extname

이 스크립트는 아래의 디렉터리를 만들어 냅니다.:


/your/phpsrcdir/ext/extname

여기에서, 강제로 PHP 설정 스크립트를 리빌드 한다음, 통상적인 방법으로 PHP를 빌드하십시오:


$ cd /your/phpsrcdir
$ rm configure
$ ./buildconf --force
$ ./configure --help
$ ./configure --with-extname --enable-someotherext --with-foobar
$ make
$ make install

Note: 'buildconf' 스크립트를 실행하기 위해서는 autoconf 2.13 버전과 automake 1.4+ 의 버전이 필요합니다. (새로운 버전의 autoconf는 동작할지도 모르나 지원되지 않을수도 있습니다.)

--enable-extname 이든 --with-extname 이든 그것들은 확장모듈 의존성을 위해 사용됩니다. 일반적으로 외부 라이브러리를 필요로하지 않는 확장모듈은 --enable 을 사용합니다. 확인을 위해 다음의 buildconf를 실행하십시오.:


$ ./configure --help | grep extname




문제가 있습니까?

Table of Contents


FAQ를 읽어 보십시오.

어떤 문제들은 다른 문제들보다 더 일반적입니다. 가장 일반적인 것들이 PHP FAQ에 본 매뉴얼의 일부로서 기재되어 있습니다.



다른 문제들

아직도 문제에 봉착해 있다면, PHP 설치 메일링 리스트의 누군가는 도움을 줄수 있을 것입니다. 누군가 당신과 같은 문제를 가지고 있거나 답변이 없는지 제일 먼저 아카이브를 체크해야만 합니다. 아카이브는 » http://www.php.net/support.php의 서포트 페이지에서 제공 합니다. PHP 설치 메일링 리스트를 구독하기 위해서는, 빈(empty) 메일을 » php-install-subscribe@lists.php.net로 보내시기 바랍니다. 메일링 리스트 주소는 » php-install@lists.php.net 입니다.

메일링 리스트로부터 도움을 얻길 원한다면, 필요한 세부 환경( 어떤 운영체제 인지, PHP 버전이 무엇인지, 무슨 웹서버 인지, PHP를 돌리고 있다면 CGI방식인지 웹서버 모듈 방식인지, 안전 모드, 등등)과 함께, 되도록이면 다른 사람들이 문제를 재현하고 테스트 할수 있도록 충분한 코드를 명확하게 알려주시기 바랍니다.



버그 보고

PHP에서 버그를 찾은것 같다면, 그것을 보고해 주시기 바랍니다. PHP 개발자들은 그것에 관해 모를수도 있으며, 그것을 보고 하기 전에는, 충분히 그럴 가능성이 있습니다. » http://bugs.php.net/의 버그 트랙킹(bug-tracking) 시스템을 사용하여 버그를 보고 할 수 있습니다. 버그 보고를 메일링 리스트나 개인적인 편지로 보내지 마시기 바랍니다. 버그 시스템은 또한 기능요청을 제출 하기에 적합합니다.

어떤 버그를 보고하기 전에 » 버그를 보고하는 방법 을 읽어 보시기 바랍니다.




실행시 설정

Table of Contents


설정 파일

설정 파일(php.ini)은 PHP를 시작할 때 읽습니다. PHP 서버 모듈 버전은 웹 서버가 시작할 때 한번만 일어납니다. CGICLI 버전에서는 매번 일어납니다.

php.ini는 세 위치에서 찾아집니다 (순서대로):

  • SAPI 모듈 지정 위치 (아파치 2에서 PHPIniDir 지시어, CGI와 CLI에서 -c 명령줄 옵션, NSAPI에서 php_ini 인수, THTTPD에서 PHP_INI_PATH 환경 변수)

  • PHPRC 환경 변수. PHP 5.2.0 이전에는 아래 언급한 레지스트리 키 이후에 확인했습니다.

  • PHP 5.2.0부터, 다음 레지스트리 위치가 순서대로 찾아집니다: HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y.z\IniFilePath, HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y\IniFilePath, HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x\IniFilePath. x, y, z는 PHP 메이저, 마이너, 릴리즈 버전을 의미합니다.

  • HKEY_LOCAL_MACHINE\SOFTWARE\PHP\IniFilePath (윈도우 레지스트리 위치)

  • 현재 작업 디렉토리 (CLI 제외)

  • 웹 서버 디렉토리(SAPI 모듈의 경우)나 PHP 디렉토리(윈도우 제외)

  • 윈도우 디렉토리(C:\windowsC:\winnt)(윈도우)나 --with-config-file-path 컴파일 시 옵션

php-SAPI.ini이 존재하면(SAPI는 사용하는 SAPI, 그러므로 파일명은 php-cli.ini, php-apache.ini 등), php.ini 대신 사용합니다. SAPI 이름은 php_sapi_name()으로 확인할 수 있습니다.

Note: 아파치 웹 서버는 시작할 때 디렉토리를 루트로 변경하므로, PHP는 루트 파일시스템에 php.ini가 존재할 경우 이를 읽으려고 시도합니다.

확장에 의해 다뤄지는 php.ini 지시어는 각 확장 페이지에 문서가 있습니다. 핵심 지시어 목록은 부록에 있습니다. 모든 PHP 지시어가 매뉴얼에 나와있지 않을 수 있습니다. PHP 버전에 따른 완전한 지시어 목록은, php.ini 파일을 읽어보십시오. 또는, CVS에서 » 최신 php.ini를 찾아볼 수 있습니다.

Example #1 php.ini 예제

; any text on a line after an unquoted semicolon (;) is ignored
[php] ; section markers (text within square brackets) are also ignored
; Boolean values can be set to either:
;    true, on, yes
; or false, off, no, none
register_globals = off
track_errors = yes

; you can enclose strings in double-quotes
include_path = ".:/usr/local/lib/php"

; backslashes are treated the same as any other character
include_path = ".;c:\php\lib"

PHP 5.1.0부터, .ini 파일 안에서 이미 존재하는 .ini 변수를 참조할 수 있습니다. 예: open_basedir = ${open_basedir} ":/new/dir".



환경 설정을 바꿀 수 있는 곳

이 모드는 PHP 지시어를 언제, 어디서 설정할 수 있는지 결정하고, 매뉴얼의 각 지시어는 이 모드를 참조합니다. 예를 들어, 몇몇 설정은 PHP 스크립트 안에서 ini_set()으로 설정할 수 있지만, 어떤 설정은 php.inihttpd.conf를 요구합니다.

예를 들어, output_buffering 설정은 PHP_INI_PERDIR이므로 ini_set()으로 설정할 수 없습니다. 그러나, display_errors 지시어는 PHP_INI_ALL이므로 ini_set()을 포함하여 어디에서라도 설정할 수 있습니다.

PHP_INI_* 모드의 정의
모드 의미
PHP_INI_USER 사용자 스크립트(ini_set() 등)나 윈도우 레지스트리에서 설정할 수 있습니다
PHP_INI_PERDIR php.ini, .htaccess, httpd.conf에서 설정할 수 있습니다
PHP_INI_SYSTEM php.inihttpd.conf에서 설정할 수 있습니다
PHP_INI_ALL 어디에서라도 설정할 수 있습니다



설정을 바꾸는 방법

PHP를 아파치 모듈로 실행

PHP를 아파치 모듈로 사용할 때, 아파치 설정 파일(즉 httpd.conf)과 .htaccess 파일에서 설정을 변경할 수 있습니다. 이를 위해서는 "AllowOverride Options"나 "AllowOverride All" 권한이 필요합니다.

몇몇 아파치 지시어는 PHP 설정을 아파치 설정 파일에서 바꿀 수 있게 합니다. 어떤 지시어가 PHP_INI_ALL, PHP_INI_PERDIR, PHP_INI_SYSTEM인지는, php.ini 지시어 목록 부록을 참고하십시오.

php_value name value

지정한 지시어의 값을 설정합니다. PHP_INI_ALLPHP_INI_PERDIR 형식 지시어에만 사용할 수 있습니다. 이전 설정 값을 지우려면 값에 none을 사용합니다.

Note: php_value 로 논리 값을 설정하지 마십시오. 대신 php_flag (아래 참고)를 사용해야 합니다.

php_flag name on|off

논리값 지시어를 설정합니다. PHP_INI_ALLPHP_INI_PERDIR 형식 지시어에만 사용할 수 있습니다.

php_admin_value name value

지정한 지시어의 값을 설정합니다. .htaccess 파일에서 사용할 수 없습니다. php_admin_value 로 설정하는 지시어 형식은 .htaccessini_set()으로 덮어쓸 수 없습니다. 이전 설정 값을 지우려면 값에 none을 사용합니다.

php_admin_flag name on|off

논리값 지시어를 설정합니다. .htaccess 파일에서 사용할 수 없습니다. php_admin_flag 로 설정하는 지시어 형식은 .htaccess로 덮어쓸 수 없습니다.

Example #1 아파치 설정 예제

<IfModule mod_php5.c>
  php_value include_path ".:/usr/local/lib/php"
  php_admin_flag safe_mode on
</IfModule>
<IfModule mod_php4.c>
  php_value include_path ".:/usr/local/lib/php"
  php_admin_flag safe_mode on
</IfModule>

Caution

PHP 상수는 PHP 밖에 존재하지 않습니다. 예를 들어, httpd.conf에서 E_ALLE_NOTICE 등의 PHP 상수를 사용할 수 없습니다. error_reporting 지시어에 이런 설정을 하면, 아무런 의미를 가지지 않고 0으로 평가됩니다. 대신 할당된 비트마스크 값을 사용하십시오. 이런 상수는 php.ini에서는 사용할 수 있습니다.

윈도우 레지스트리에서 PHP 설정 바꾸기

PHP를 윈도우에서 실행할 때, 설정값은 윈도우 레지스트리를 사용하여 디렉토리 기반으로 변경할 수 있습니다. 설정값은 레지스트리 키 HKLM\SOFTWARE\PHP\Per Directory Values에 저장되며, 보조키는 경로명에 해당합니다. 예를 들어, c:\inetpub\wwwroot 디렉토리를 위한 설정값은 HKLM\SOFTWARE\PHP\Per Directory Values\c\inetpub\wwwroot 키에 저장됩니다. 디렉토리 설정은 이 디렉토리와 그 밑의 서브디렉토리에서 실행하는 모든 스크립트에 적용됩니다. 키 아래 값은 PHP 설정 지시어 이름을 가지고 문자열 값이여야 합니다. 값에 사용하는 PHP 상수는 해석되지 않습니다. 그러나, PHP_INI_USER로 바꿀 수 있는 설정값만 이 방법을 사용할 수 있습니다. PHP_INI_PERDIR 값은 사용할 수 없습니다.

PHP의 다른 인터페이스

PHP를 어떻게 실행하는가에 관계 없이, ini_set()으로 몇몇 값을 실행시에 변경할 수 있습니다. 자세한 정보는 ini_set() 페이지 문서를 참고하십시오.

시스템의 모든 설정 목록과 현재 값을 얻고 싶다면, phpinfo()를 실행하여 결과 페이지를 살펴보십시오. 각 설정 지시어의 값은 실행시에 ini_get()이나 get_cfg_var()를 사용하여 접근할 수 있습니다.





언어 레퍼런스


기본 문법

Table of Contents


HTML에서 벗어나기

PHP가 파일을 해석할 때, PHP가 사이에 있는 코드를 해석하라고 하는 시작과 끝 태그를 찾습니다. 이런 방법의 해석은, 시작과 끝 태그 밖에 있는 부분은 PHP 해석기가 무시하게 됨으로써, php가 어떠한 종료의 문서에도 포함될 수 있도록 합니다. 대부분의 경우 다음 예제와 같이 php가 포함된 HTML 문서를 보게 될 것입니다.

<p>이 부분은 무시합니다.</p>
<?php echo '이 부분은 해석합니다.'?>
<p>이 부분도 무시합니다.</p>

좀 더 복잡한 구조도 사용할 수 있습니다:

Example #1 복잡한 벗어나기

<?php
if ($expression) {
    
?>
    <strong>This is true.</strong>
    <?php
} else {
    
?>
    <strong>This is false.</strong>
    <?php
}
?>

예상한 대로 작동합니다. PHP가 ?> 닫기 태그를 만나면, 그것이 무엇이던간에 다른 시작 태그를 만나기 전까지 단순히 출력하기 때문입니다. (바로 따라오는 줄바꿈 제외 - 명령 구분 참고) 물론, 여기서 주어진 예제는 부자연스럽지만 큰 텍스트 블록을 출력할 경우에는 PHP 해석 모드를 벗어나는 것이 모든 텍스트를 echo()print()를 통하여 전송하는 것보다 효율적입니다.

php에서 사용할 수 있는 네가지 형태의 시작과 끝 태그가 있습니다. 그 중 두가지, <?php ?>와 <script language="php"> </script>는 항상 사용할 수 있습니다. 두가지 짧은 태그와 ASP 형식 태그는 php.ini 설정 파일에서 끄거나 켤 수 있습니다. 그러므로, 몇몇 사람들에겐 짧은 태그나 ASP 형식 태그가 편할지는 몰라도, 이식성이 부족하므로 일반적으로 권하지 않습니다.

Note: PHP를 XML이나 XHTML에 넣을 경우 <?php ?> 태그를 사용해야 표준과 호환을 유지할 수 있습니다.

Example #2 PHP 시작과 끝 태그

1.  <?php echo 'XHTML나 XML 문서와 호환시키려면, 이렇게 쓰세요'?>

2.  <script language="php">
        
echo '어떤 에디터 (프론트페이지같은)는 
              처리 명령을 좋아하지 않습니다'
;
    
</script>

3.  <? echo '이런 형태가 제일 간단한 SGML 처리명령입니다'?>
    <?= expression ?>은 "<? echo expression ?>"을 간단히 쓴 모양입니다

4.  <% echo ("ASP스타일 태그를 쓸 수도 있습니다"); %>
    <%= $variable; # 이것은 "<% echo . . ." %>을 간단히 쓴 모양입니다

예제에서 볼 수 있는 태그 중 첫번째와 두번째는 항상 사용할 수 있지만, 둘 중 첫번째 예제가 가장 보편적으로 사용되며, 권장됩니다.

짧은 태그(예제 3)은 php.ini 설정 파일 지시어 short_open_tag를 활성화하거나, php를 --enable-short-tags 옵션으로 설정하였을 경우에만 사용할 수 있습니다.

ASP 형식 태그(예제 4)는 php.ini 설정 파일 지시어 asp_tags를 활성화 했을 경우에만 사용할 수 있습니다.

Note: 프로그램이나 재사용을 위한 라이브러리를 개발할때, 또는 통제밖의 PHP서버에 배치시킬때는 짧은 형 태그를 쓰는것은 피해야 한다. 왜냐하면 짧은 형 태그는 목표하는 서버에서 지원되지 않을수도 있기 때문이다. 이식성을 위해서, 재사용 코드는 짧은 형 태그로 쓰지 않도록 한다.



명령 구분

C나 펄처럼, PHP는 각 명령 구문 끝을 세미콜론으로 종료해야 합니다. PHP 코드 블록을 종료하면 자동으로 세미콜론을 적용합니다; PHP 블록의 마지막 줄에는 세미콜론 종료를 하지 않아도 됩니다. 블록의 닫기 태그는 바로 뒤에 따라올 수 있는 줄바꿈도 포함합니다.

<?php
    
echo 'This is a test';
?>

<?php echo 'This is a test' ?>

<?php echo '마지막 닫기 태그를 생략합니다';

Note: 파일의 마지막에서 PHP 블록의 닫기 태그를 생략할 수 있으며, 때로는 유용합니다. include()require()를 사용할 경우, 원하지 않은 공백이 파일 마지막에 들어가지 않게 함으로써, 나중에 추가 응답 헤더를 추가할 수 있습니다. 또한 출력 버퍼링을 사용할 경우에도 포함한 파일들에 의해서 각 파트의 마지막에 원하지 않은 공백을 피할 수 있으므로 도움이 됩니다.



주석

PHP는 'C', 'C++', Unix 쉘 형식(펄 형식)의 주석(comment)형태를 지원한다. 예를 들면:

<?php
    
echo 'This is a test'// 한줄짜리 c++ 스타일 주석
    /* 여러줄의 주석
       이줄까지 주석처리 된다 */
    
echo 'This is yet another test';
    echo 
'One Final Test'# 쉘 형식의 한줄짜리 주석
?>

"한 줄" 주석 형식은 줄의 끝까지나 PHP 코드의 현재 블록까지 중, 먼저 오는 부분까지만 주석으로 처리합니다. 이는 // ... ?># ... ?> 뒤에 오는 HTML 코드가 출력됨을 의미합니다: ?>는 PHP 모드를 종료하고 HTML 모드로 돌아가게 하므로, //#은 영향을 주지 않습니다. asp_tags 설정 지시어가 켜져 있으면, // %># %>에도 동일하게 적용됩니다. 그러나, </script> 태그는 한 줄 주석에서 PHP 모드를 종료하지 않습니다.

<h1>This is an <?php # echo 'simple';?> example.</h1>
<p>The header above will say 'This is an example'.</p>

'C' 형식 주석은 첫 */에서 종료합니다. 그러므로 'C' 형식 주석을 중첩하지 않아야 합니다. 이는 큰 코드 블럭을 주석처리 하려고 할 경우에 자주 발생하는 실수입니다.

<?php
 
/* 
    echo 'This is a test'; /* 이 주석은 문제가 발생합니다 */
 
*/
?>




자료형

Table of Contents


소개

PHP는 여덟가지 기본 자료형을 지원합니다.

네가지 스칼라형:

두가지 복합형:

마지막으로 두가지 특별형:

이 매뉴얼에는 설명을 위해서 몇가지 모의형을 사용합니다:

그리고 모의 변수 $...

매뉴얼의 몇몇 레퍼런스에 "double" 형이 남아 있습니다. double은 float와 같다고 생각하십시오; 두 이름은 단지 역사적인 이유로 남아 있습니다.

변수의 자료형은 보통 프로그래머가 설정하지 않습니다; 대신, PHP가 변수가 사용되는 지점에 따라서 실행시에 자동으로 결정합니다.

Note: 표현에 따른 자료형과 값을 확인하려면, var_dump() 함수를 사용하십시오. 디버깅을 위해 자료형을 쉽게 읽을 수 있는 형태를 얻으려면, gettype() 함수를 사용하십시오. 특정한 자료형을 확인하려면 gettype()사용하지 말고 is_type 함수를 사용하십시오. 예를 들면:

<?php
$a_bool 
TRUE;   // 논리
$a_str  "foo";  // 문자열
$a_str  'foo';  // 문자열
$an_int 12;     // 정수

echo gettype($a_bool); // 출력:  boolean
echo gettype($a_str);  // 출력:  string

// 정수라면, 4 증가
if (is_int($an_int)) {
    
$an_int += 4;
}

// $bool이 문자열이라면, 출력
// (아무것도 출력하지 않음)
if (is_string($a_bool)) {
    echo 
"문자열: $a_bool";
}
?>

변수를 강제로 특정 자료형으로 변환하려면, 변수를 형변환하거나 settype() 함수를 사용하십시오.

변수는 어떤 상황이냐에 따라서, 그 시점에 어떠한 자료형을 요구하냐에 따라서 다른 자료형으로 평가될 수 있습니다. 자세한 정보는 자료형 조절 섹션을 참고하십시오. 자료형 비교표도 유용합니다. 다양한 자료형 관련 비교 예제를 볼 수 있습니다.



Booleans

This is the simplest type. A boolean expresses a truth value. It can be either TRUE or FALSE.

Note: The boolean type was introduced in PHP 4.

Syntax

To specify a boolean literal, use the keywords TRUE or FALSE. Both are case-insensitive.

<?php
$foo 
True// assign the value TRUE to $foo
?>

Typically, some kind of operator which returns a boolean value, and the value is passed on to a control structure.

<?php
// == is an operator which test
// equality and returns a boolean
if ($action == "show_version") {
    echo 
"The version is 1.23";
}

// this is not necessary...
if ($show_separators == TRUE) {
    echo 
"<hr>\n";
}

// ...because instead, this can be used:
if ($show_separators) {
    echo 
"<hr>\n";
}
?>

Converting to boolean

To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unncecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.

See also Type Juggling.

When converting to boolean, the following values are considered FALSE:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

Every other value is considered TRUE (including any resource).

Warning

-1 is considered TRUE, like any other non-zero (whether negative or positive) number!

<?php
var_dump
((bool) "");        // bool(false)
var_dump((bool) 1);         // bool(true)
var_dump((bool) -2);        // bool(true)
var_dump((bool) "foo");     // bool(true)
var_dump((bool) 2.3e5);     // bool(true)
var_dump((bool) array(12)); // bool(true)
var_dump((bool) array());   // bool(false)
var_dump((bool) "false");   // bool(true)
?>


Integers

An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}.

See also:

Syntax

Integers can be specified in decimal (base 10), hexadecimal (base 16), or octal (base 8) notation, optionally preceded by a sign (- or +).

To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x.

Example #1 Integer literals

<?php
$a 
1234// decimal number
$a = -123// a negative number
$a 0123// octal number (equivalent to 83 decimal)
$a 0x1A// hexadecimal number (equivalent to 26 decimal)
?>

Formally, the structure for integer literals is:

decimal     : [1-9][0-9]*
            | 0

hexadecimal : 0[xX][0-9a-fA-F]+

octal       : 0[0-7]+

integer     : [+-]?decimal
            | [+-]?hexadecimal
            | [+-]?octal

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

Warning

If an invalid digit is given in an octal integer (i.e. 8 or 9), the rest of the number is ignored.

Example #2 Octal weirdness

<?php
var_dump
(01090); // 010 octal = 8 decimal
?>

Integer overflow

If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.

<?php
$large_number 
=  2147483647;
var_dump($large_number);
// output: int(2147483647)

$large_number =  2147483648;
var_dump($large_number);
// output: float(2147483648)

// it's true also for hexadecimal specified integers between 2^31 and 2^32-1:
var_dump0xffffffff );
// output: float(4294967295)

// this doesn't go for hexadecimal specified integers above 2^32-1:
var_dump0x100000000 );
// output: int(2147483647)

$million 1000000;
$large_number =  50000 $million;
var_dump($large_number);
// output: float(50000000000)
?>
Warning

Unfortunately, there was a bug in PHP which caused this to not always work correctly when negative numbers were involved. For example, the result of -50000 * $million is -429496728. However, when both operands were positive, there was no problem.

This was fixed in PHP 4.1.0.

There is no integer division operator in PHP. 1/2 yields the float 0.5. The value can be casted to an integer to round it downwards, or the round() function provides finer control over rounding.

<?php
var_dump
(25/7);         // float(3.5714285714286) 
var_dump((int) (25/7)); // int(3)
var_dump(round(25/7));  // float(4) 
?>

Converting to integer

To explicitly convert a value to integer, use either the (int) or (integer) casts. However, in most cases the cast is not needed, since a value will be automatically converted if an operator, function or control structure requires an integer argument. A value can also be converted to integer with the intval() function.

See also: type-juggling.

From booleans

FALSE will yield 0 (zero), and TRUE will yield 1 (one).

From floating point numbers

When converting from float to integer, the number will be rounded towards zero.

If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31), the result is undefined, since the float doesn't have enough precision to give an exact integer result. No warning, not even a notice will be issued when this happens!

Warning

Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results.

<?php
echo (int) ( (0.1+0.7) * 10 ); // echoes 7!
?>

See also the warning about float precision.

From strings

See String conversion to numbers

From other types

Caution

The behaviour of converting to integer is undefined for other types. Do not rely on any observed behaviour, as it can change without notice.



Floating point numbers

Floating point numbers (also known as "floats", "doubles", or "real numbers") can be specified using any of the following syntaxes:

<?php
$a 
1.234
$b 1.2e3
$c 7E-10;
?>

Formally:

LNUM          [0-9]+
DNUM          ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM})

The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64 bit IEEE format).

Warning

Floating point precision

It is typical that simple decimal fractions like 0.1 or 0.7 cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9.

This is due to the fact that it is impossible to express some fractions in decimal notation with a finite number of digits. For instance, 1/3 in decimal form becomes 0.3.

So never trust floating number results to the last digit, and never compare floating point numbers for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

Converting to float

For information on converting strings to float, see String conversion to numbers. For values of other types, the conversion is performed by converting the value to integer first and then to float. See Converting to integer for more information. As of PHP 5, a notice is thrown if an object is converted to float.



Strings

A string is series of characters. Before PHP 6, a character is the same as a byte. That is, there are exactly 256 different characters possible. This also implies that PHP has no native support of Unicode. See utf8_encode() and utf8_decode() for some basic Unicode functionality.

Note: It is no problem for a string to become very large. PHP imposes no boundary on the size of a string; the only limit is the available memory of the computer on which PHP is running.

Syntax

A string literal can be specified in four different ways:

Single quoted

The simplest way to specify a string is to enclose it in single quotes (the character ').

To specify a literal single quote, escape it with a backslash (\). To specify a literal backslash before a single quote, or at the end of the string, double it (\\). Note that attempting to escape any other character will print the backslash too.

Note: Unlike the two other syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

<?php
echo 'this is a simple string';

echo 
'You can also have embedded newlines in 
strings this way as it is
okay to do'
;

// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';

// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';

// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';

// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';

// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>

Double quoted

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

Escaped characters
Sequence Meaning
\n linefeed (LF or 0x0A (10) in ASCII)
\r carriage return (CR or 0x0D (13) in ASCII)
\t horizontal tab (HT or 0x09 (9) in ASCII)
\v vertical tab (VT or 0x0B (11) in ASCII) (since PHP 5.2.5)
\f form feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
\\ backslash
\$ dollar sign
\" double-quote
\[0-7]{1,3} the sequence of characters matching the regular expression is a character in octal notation
\x[0-9A-Fa-f]{1,2} the sequence of characters matching the regular expression is a character in hexadecimal notation

As in single quoted strings, escaping any other character will result in the backslash being printed too. Before PHP 5.1.1, the backslash in \{$var} had not been printed.

The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.

Heredoc

A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.

The closing identifier must begin in the first column of the line. Also, the identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.

Warning

It is very important to note that the line with the closing identifier must contain no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter (possibly followed by a semicolon) must also be followed by a newline.

If this rule is broken and the closing identifier is not "clean", it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line.

Heredocs can not be used for initializing class members. Since PHP 5.3, this limitation is valid only for heredocs containing variables.

Example #1 Invalid example

<?php
class foo {
    public 
$bar = <<<EOT
bar
EOT;
}
?>

Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.

Example #2 Heredoc string quoting example

<?php
$str 
= <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

/* More complex example, with variables. */
class foo
{
    var 
$foo;
    var 
$bar;

    function 
foo()
    {
        
$this->foo 'Foo';
        
$this->bar = array('Bar1''Bar2''Bar3');
    }
}

$foo = new foo();
$name 'MyName';

echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some 
{$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>

위 예제의 출력:

My name is "MyName". I am printing some Foo.
Now, I am printing some Bar2.
This should print a capital 'A': A

It is also possible to use the Heredoc syntax to pass data to function arguments:

Example #3 Heredoc in arguments example

<?php
var_dump
(array(<<<EOD
foobar!
EOD
));
?>

As of PHP 5.3.0, its possible to initialize static variables and class members/constants using the Heredoc syntax:

Example #4 Using Heredoc to initialize static values

<?php
// Static variables
function foo()
{
    static 
$bar = <<<LABEL
Nothing in here...
LABEL;
}

// Class members/constants
class foo
{
    const 
BAR = <<<FOOBAR
Constant example
FOOBAR;

    public 
$baz = <<<FOOBAR
Property example
FOOBAR;
}
?>

PHP 5.3.0 also introduces the possibility for Heredoc's to use double quotes in declarings:

Example #5 Using double quotes in Heredoc

<?php
echo <<<"FOOBAR"
Hello World!
FOOBAR;
?>

Note: Heredoc support was added in PHP 4.

Nowdoc

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML <![CDATA[ ]]> construct, in that it declares a block of text which is not for parsing.

A nowdoc is identified with the same <<< seqeuence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.

Example #6 Nowdoc string quoting example

<?php
$str 
= <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;

/* More complex example, with variables. */
class foo
{
    public 
$foo;
    public 
$bar;

    function 
foo()
    {
        
$this->foo 'Foo';
        
$this->bar = array('Bar1''Bar2''Bar3');
    }
}

$foo = new foo();
$name 'MyName';

echo <<<'EOT'
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41
EOT;
?>

위 예제의 출력:

My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41

Note: Unlike heredocs, nowdocs can be used in any static data context. The typical example is initializing class members or constants:

Example #7 Static data example

<?php
class foo {
    public 
$bar = <<<'EOT'
bar
EOT;
}
?>

Note: Nowdoc support was added in PHP 5.3.0.

Variable parsing

When a string is specified in double quotes or with heredoc, variables are parsed within it.

There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort.

The complex syntax was introduced in PHP 4, and can be recognised by the curly braces surrounding the expression.

Simple syntax

If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name.

<?php
$beer 
'Heineken';
echo 
"$beer's taste is great"// works; "'" is an invalid character for variable names
echo "He drank some $beers";   // won't work; 's' is a valid character for variable names but the variable is "$beer"
echo "He drank some ${beer}s"// works
echo "He drank some {$beer}s"// works
?>

Similarly, an array index or an object property can be parsed. With array indices, the closing square bracket (]) marks the end of the index. The same rules apply to object properties as to simple variables.

<?php
// These examples are specific to using arrays inside of strings.
// When outside of a string, always quote array string keys and do not use
// {braces}.

// Show all errors
error_reporting(E_ALL);

$fruits = array('strawberry' => 'red''banana' => 'yellow');

// Works, but note that this works differently outside a string
echo "A banana is $fruits[banana].";

// Works
echo "A banana is {$fruits['banana']}.";

// Works, but PHP looks for a constant named banana first, as described below.
echo "A banana is {$fruits[banana]}.";

// Won't work, use braces.  This results in a parse error.
echo "A banana is $fruits['banana'].";

// Works
echo "A banana is " $fruits['banana'] . ".";

// Works
echo "This square is $square->width meters broad.";

// Won't work. For a solution, see the complex syntax.
echo "This square is $square->width00 centimeters broad.";
?>

For anything more complex, you should use the complex syntax.

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

In fact, any value in the namespace can be included in a string with this syntax. Simply write the expression the same way as it would have appeared outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

<?php
// Show all errors
error_reporting(E_ALL);

$great 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";
echo 
"This is ${great}";

// Works
echo "This square is {$square->width}00 centimeters broad."

// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong  outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}"

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " $arr['foo'][3];

echo 
"This works too: {$obj->values[3]->name}";

echo 
"This is the value of the var named $name{${$name}}";

echo 
"This is the value of the var named by the return value of getName(): {${getName()}}";

echo 
"This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";
?>

Note: Functions and method calls inside {$} work since PHP 5.

String access and modification by character

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose.

Note: Strings may also be accessed using braces, as in $str{42}, for the same purpose. However, this syntax is deprecated as of PHP 6. Use square brackets instead.

Warning

Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer. Illegal offset type emits E_NOTICE. Negative offset emits E_NOTICE in write but reads empty string. Only the first character of an assigned string is used. Assigning empty string assigns NUL byte.

Example #8 Some string examples

<?php
// Get the first character of a string
$str 'This is a test.';
$first $str[0];

// Get the third character of a string
$third $str[2];

// Get the last character of a string.
$str 'This is still a test.';
$last $str[strlen($str)-1]; 

// Modify the last character of a string
$str 'Look at the sea';
$str[strlen($str)-1] = 'e';

?>

Note: Accessing variables of other types using [] or {} silently returns NULL.

Useful functions and operators

Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. See String operators for more information.

There are a number of useful functions for string manipulation.

See the string functions section for general functions, and the regular expression functions or the Perl-compatible regular expression functions for advanced find & replace functionality.

There are also functions for URL strings, and functions to encrypt/decrypt strings (mcrypt and mhash).

Finally, see also the character type functions.

Converting to string

A value can be converted to a string using the (string) cast or the strval() function. String conversion is automatically done in the scope of an expression where a string is needed. This happens when using the echo() or print() functions, or when a variable is compared to a string. The sections on Types and Type Juggling will make the following clearer. See also the settype() function.

A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

An integer or float is converted to a string representing the number textually (including the exponent part for floats). Floating point numbers can be converted using exponential notation (4.1E+6).

Note: The decimal point character is defined in the script's locale (category LC_NUMERIC). See the setlocale() function.

Arrays are always converted to the string "Array"; because of this, echo() and print() can not by themselves show the contents of an array. To view a single element, use a construction such as echo $arr['foo']. See below for tips on viewing the entire contents.

Objects in PHP 4 are always converted to the string "Object". To print the values of object members for debugging reasons, read the paragraphs below. To get an object's class name, use the get_class() function. As of PHP 5, the __toString method is used when applicable.

Resources are always converted to strings with the structure "Resource id #1", where 1 is the unique number assigned to the resource by PHP at runtime. Do not rely upon this structure; it is subject to change. To get a resource's type, use the get_resource_type() function.

NULL is always converted to an empty string.

As stated above, directly converting an array, object, or resource to a string does not provide any useful information about the value beyond its type. See the functions print_r() and var_dump() for more effective means of inspecting the contents of these types.

Most PHP values can also be converted to strings for permanent storage. This method is called serialization, and is performed by the serialize() function. If the PHP engine was built with WDDX support, PHP values can also be serialized as well-formed XML text.

String conversion to numbers

When a string is evaluated in a numeric context, the resulting value and type are determined as follows.

If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

<?php
$foo 
"10.5";                // $foo is float (11.5)
$foo "-1.3e3";              // $foo is float (-1299)
$foo "bob-1.3e3";           // $foo is integer (1)
$foo "bob3";                // $foo is integer (1)
$foo "10 Small Pigs";       // $foo is integer (11)
$foo "10.2 Little Piggies"// $foo is float (14.2)
$foo "10.0 pigs " 1;          // $foo is float (11)
$foo "10.0 pigs " 1.0;        // $foo is float (11)     
?>

For more information on this conversion, see the Unix manual page for strtod(3).

To test any of the examples in this section, cut and paste the examples and insert the following line to see what's going on:

<?php
echo "\$foo==$foo; type is " gettype ($foo) . "<br />\n";
?>

Do not expect to get the code of one character by converting it to integer, as is done in C. Use the ord() and chr() functions to convert between ASCII codes and characters.



Arrays

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

Explanation of those data structures is beyond the scope of this manual, but at least one example is provided for each of them. For more information, look towards the considerable literature that exists about this broad topic.

Syntax

Specifying with array()

An array can be created by the array() language construct. It takes as parameters any number of comma-separated key => value pairs.

array(  key =>  value
     , ...
     )
// key may only be an integer or string
// value may be any value of any type
<?php
$arr 
= array("foo" => "bar"12 => true);

echo 
$arr["foo"]; // bar
echo $arr[12];    // 1
?>

A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.

A value can be any PHP type.

<?php
$arr 
= array("somearray" => array(=> 513 => 9"a" => 42));

echo 
$arr["somearray"][6];    // 5
echo $arr["somearray"][13];   // 9
echo $arr["somearray"]["a"];  // 42
?>

If a key is not specified for a value, the maximum of the integer indices is taken and the new key will be that value plus 1. If a key that already has an assigned value is specified, that value will be overwritten.

<?php
// This array is the same as ...
array(=> 433256"b" => 12);

// ...this array
array(=> 43=> 32=> 56"b" => 12);
?>
Warning

Before PHP 4.3.0, appending to an array in which the current maximum key was negative would create a new key as described above. Since PHP 4.3.0, the new key will be 0.

Using TRUE as key will evaluate to integer 1 as a key. Using FALSE as key will evaluate to integer 0 as a key. Using NULL as a key will evaluate to the empty string. Using the empty string as a key will create (or overwrite) a key with the empty string and its value; it is not the same as using empty brackets.

Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.

Creating/modifying with square bracket syntax

An existing array can be modified by explicitly setting values in it.

This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]).

$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type

If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the unset() function on it.

<?php
$arr 
= array(=> 112 => 2);

$arr[] = 56;    // This is the same as $arr[13] = 56;
                // at this point of the script

$arr["x"] = 42// This adds a new element to
                // the array with key "x"
                
unset($arr[5]); // This removes the element from the array

unset($arr);    // This deletes the whole array
?>

Note: As mentioned above, if no key is specified, the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1. If no integer indices exist yet, the key will be 0 (zero).
Note that the maximum integer key used for this need not currently exist in the array. It need only have existed in the array at some time since the last time the array was re-indexed. The following example illustrates:

<?php
// Create a simple array.
$array = array(12345);
print_r($array);

// Now delete every item, but leave the array itself intact:
foreach ($array as $i => $value) {
    unset(
$array[$i]);
}
print_r($array);

// Append an item (note that the new key is 5, instead of 0).
$array[] = 6;
print_r($array);

// Re-index:
$array array_values($array);
$array[] = 7;
print_r($array);
?>

위 예제의 출력:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Array
(
)
Array
(
    [5] => 6
)
Array
(
    [0] => 6
    [1] => 7
)

Useful functions

There are quite a few useful functions for working with arrays. See the array functions section.

Note: The unset() function allows removing keys from an array. Be aware that the array will not be reindexed. If a true "remove and shift" behavior is desired, the array can be reindexed using the array_values() function.

<?php
$a 
= array(=> 'one'=> 'two'=> 'three');
unset(
$a[2]);
/* will produce an array that would have been defined as
   $a = array(1 => 'one', 3 => 'three');
   and NOT
   $a = array(1 => 'one', 2 =>'three');
*/

$b array_values($a);
// Now $b is array(0 => 'one', 1 =>'three')
?>

The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array.

Array do's and don'ts

Why is $foo[bar] wrong?

Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while $foo[bar] is not. But why? It is common to encounter this kind of syntax in old scripts:

<?php
$foo
[bar] = 'enemy';
echo 
$foo[bar];
// etc
?>

This is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in future define constants which, unfortunately for such code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.

Note: This does not mean to always quote the key. Do not quote keys which are constants or variables, as this will prevent PHP from interpreting them.

<?php
error_reporting
(E_ALL);
ini_set('display_errors'true);
ini_set('html_errors'false);
// Simple array:
$array = array(12);
$count count($array);
for (
$i 0$i $count$i++) {
    echo 
"\nChecking $i: \n";
    echo 
"Bad: " $array['$i'] . "\n";
    echo 
"Good: " $array[$i] . "\n";
    echo 
"Bad: {$array['$i']}\n";
    echo 
"Good: {$array[$i]}\n";
}
?>

위 예제의 출력:

Checking 0: 
Notice: Undefined index:  $i in /path/to/script.html on line 9
Bad: 
Good: 1
Notice: Undefined index:  $i in /path/to/script.html on line 11
Bad: 
Good: 1

Checking 1: 
Notice: Undefined index:  $i in /path/to/script.html on line 9
Bad: 
Good: 2
Notice: Undefined index:  $i in /path/to/script.html on line 11
Bad: 
Good: 2

More examples to demonstrate this behaviour:

<?php
// Show all errors
error_reporting(E_ALL);

$arr = array('fruit' => 'apple''veggie' => 'carrot');

// Correct
print $arr['fruit'];  // apple
print $arr['veggie']; // carrot

// Incorrect.  This works but also throws a PHP error of level E_NOTICE because
// of an undefined constant named fruit
// 
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit];    // apple

// This defines a constant to demonstrate what's going on.  The value 'veggie'
// is assigned to a constant named fruit.
define('fruit''veggie');

// Notice the difference now
print $arr['fruit'];  // apple
print $arr[fruit];    // carrot

// The following is okay, as it's inside a string. Constants are not looked for
// within strings, so no E_NOTICE occurs here
print "Hello $arr[fruit]";      // Hello apple

// With one exception: braces surrounding arrays within strings allows constants
// to be interpreted
print "Hello {$arr[fruit]}";    // Hello carrot
print "Hello {$arr['fruit']}";  // Hello apple

// This will not work, and will result in a parse error, such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using superglobals in strings as well
print "Hello $arr['fruit']";
print 
"Hello $_GET['foo']";

// Concatenation is another option
print "Hello " $arr['fruit']; // Hello apple
?>

When error_reporting is set to show E_NOTICE level errors (by setting it to E_ALL, for example), such uses will become immediately visible. By default, error_reporting is set not to show notices.

As stated in the syntax section, what's inside the square brackets ('[' and ']') must be an expression. This means that code like this works:

<?php
echo $arr[somefunc($bar)];
?>

This is an example of using a function return value as the array index. PHP also knows about constants:

<?php
$error_descriptions
[E_ERROR]   = "A fatal error has occured";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE]  = "This is just an informal notice";
?>

Note that E_ERROR is also a valid identifier, just like bar in the first example. But the last example is in fact the same as writing:

<?php
$error_descriptions
[1] = "A fatal error has occured";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";
?>

because E_ERROR equals 1, etc.

So why is it bad then?

At some point in the future, the PHP team might want to add another constant or keyword, or a constant in other code may interfere. For example, it is already wrong to use the words empty and default this way, since they are reserved keywords.

Note: To reiterate, inside a double-quoted string, it's valid to not surround array indexes with quotes so "$foo[bar]" is valid. See the above examples for details on why as well as the section on variable parsing in strings.

Converting to array

For any of the types: integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue).

If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behaviour:

<?php

class {
    private 
$A// This will become '\0A\0A'
}

class 
extends {
    private 
$A// This will become '\0B\0A'
    
public $AA// This will become 'AA'
}

var_dump((array) new B());
?>

The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'.

Converting NULL to an array results in an empty array.

Comparing

It is possible to compare arrays with the array_diff() function and with array operators.

Examples

The array type in PHP is very versatile. Here are some examples:

<?php
// This:
$a = array( 'color' => 'red',
            
'taste' => 'sweet',
            
'shape' => 'round',
            
'name'  => 'apple',
            
4        // key will be 0
          
);

$b = array('a''b''c');

// . . .is completely equivalent with this:
$a = array();
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name']  = 'apple';
$a[]        = 4;        // key will be 0

$b = array();
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';

// After the above code is executed, $a will be the array
// array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round', 
// 'name' => 'apple', 0 => 4), and $b will be the array 
// array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c').
?>

Example #1 Using array()

<?php
// Array as (property-)map
$map = array( 'version'    => 4,
              
'OS'         => 'Linux',
              
'lang'       => 'english',
              
'short_tags' => true
            
);
            
// strictly numerical keys
$array = array( 7,
                
8,
                
0,
                
156,
                -
10
              
);
// this is the same as array(0 => 7, 1 => 8, ...)

$switching = array(         10// key = 0
                    
5    =>  6,
                    
3    =>  7
                    
'a'  =>  4,
                            
11// key = 6 (maximum of integer-indices was 5)
                    
'8'  =>  2// key = 8 (integer!)
                    
'02' => 77// key = '02'
                    
0    => 12  // the value 10 will be overwritten by 12
                  
);
                  
// empty array
$empty = array();         
?>

Example #2 Collection

<?php
$colors 
= array('red''blue''green''yellow');

foreach (
$colors as $color) {
    echo 
"Do you like $color?\n";
}

?>

위 예제의 출력:

Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?

Changing the values of the array directly is possible since PHP 5 by passing them by reference. Before that, a workaround is necessary:

Example #3 Collection

<?php
// PHP 5
foreach ($colors as &$color) {
    
$color strtoupper($color);
}
unset(
$color); /* ensure that following writes to
$color will not modify the last array element */

// Workaround for older versions
foreach ($colors as $key => $color) {
    
$colors[$key] = strtoupper($color);
}

print_r($colors);
?>

위 예제의 출력:

Array
(
    [0] => RED
    [1] => BLUE
    [2] => GREEN
    [3] => YELLOW
)

This example creates a one-based array.

Example #4 One-based index

<?php
$firstquarter  
= array(=> 'January''February''March');
print_r($firstquarter);
?>

위 예제의 출력:

Array 
(
    [1] => 'January'
    [2] => 'February'
    [3] => 'March'
)

Example #5 Filling an array

<?php
// fill an array with all items from a directory
$handle opendir('.');
while (
false !== ($file readdir($handle))) {
    
$files[] = $file;
}
closedir($handle); 
?>

Arrays are ordered. The order can be changed using various sorting functions. See the array functions section for more information. The count() function can be used to count the number of items in an array.

Example #6 Sorting an array

<?php
sort
($files);
print_r($files);
?>

Because the value of an array can be anything, it can also be another array. This enables the creation of recursive and multi-dimensional arrays.

Example #7 Recursive and multi-dimensional arrays

<?php
$fruits 
= array ( "fruits"  => array ( "a" => "orange",
                                       
"b" => "banana",
                                       
"c" => "apple"
                                     
),
                  
"numbers" => array ( 1,
                                       
2,
                                       
3,
                                       
4,
                                       
5,
                                       
6
                                     
),
                  
"holes"   => array (      "first",
                                       
=> "second",
                                            
"third"
                                     
)
                );

// Some examples to address values in the array above 
echo $fruits["holes"][5];    // prints "second"
echo $fruits["fruits"]["a"]; // prints "orange"
unset($fruits["holes"][0]);  // remove "first"

// Create a new multi-dimensional array
$juices["apple"]["green"] = "good"
?>

Array assignment always involves value copying. Use the reference operator to copy an array by reference.

<?php
$arr1 
= array(23);
$arr2 $arr1;
$arr2[] = 4// $arr2 is changed,
             // $arr1 is still array(2, 3)
             
$arr3 = &$arr1;
$arr3[] = 4// now $arr1 and $arr3 are the same
?>


Objects

Object Initialization

To create a new object, use the new statement to instantiate a class:

<?php
class foo
{
    function 
do_foo()
    {
        echo 
"Doing foo."
    }
}

$bar = new foo;
$bar->do_foo();
?>

For a full discussion, see the Classes and Objects chapter.

Converting to object

If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. If the value was NULL, the new instance will be empty. Arrays convert to an object with properties named by keys, and corresponding values. For any other value, a member variable named scalar will contain the value.

<?php
$obj 
= (object) 'ciao';
echo 
$obj->scalar;  // outputs 'ciao'
?>


Resources

A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. See the appendix for a listing of all these functions and the corresponding resource types.

Note: The resource type was introduced in PHP 4

See also the get_resource_type() function.

Converting to resource

As resource variables hold special handlers to opened files, database connections, image canvas areas and the like, converting to a resource makes no sense.

Freeing resources

Thanks to the reference-counting system introduced with PHP 4's Zend Engine, a resource with no more references to it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the memory manually.

Note: Persistent database links are an exception to this rule. They are not destroyed by the garbage collector. See the persistent connections section for more information.



NULL

The special NULL value represents a variable with no value. NULL is the only possible value of type NULL.

Note: The null type was introduced in PHP 4.

A variable is considered to be null if:

  • it has been assigned the constant NULL.

  • it has not been set to any value yet.

  • it has been unset().

Syntax

There is only one value of type null, and that is the case-insensitive keyword NULL.

<?php
$var 
NULL;       
?>

See also the functions is_null() and unset().

Casting to NULL

Casting a variable to null will remove the variable and unset its value.



Pseudo-types and variables used in this documentation

mixed

mixed indicates that a parameter may accept multiple (but not necessarily all) types.

gettype() for example will accept all PHP types, while str_replace() will accept strings and arrays.

number

number indicates that a parameter can be either integer or float.

callback

Some functions like call_user_func() or usort() accept user-defined callback functions as a parameter. Callback functions can not only be simple functions, but also object methods, including static class methods.

A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs such as: array(), echo(), empty(), eval(), exit(), isset(), list(), print() or unset().

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.

Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object at index 0.

Apart from common user-defined function, create_function() can also be used to create an anonymous callback function. As of PHP 5.3.0 its possible to also pass a closure to a callback parameter.

Example #1 Callback function examples

<?php 

// An example callback function
function my_callback_function() {
    echo 
'hello world!';
}

// An example callback method
class MyClass {
    static function 
myCallbackMethod() {
        echo 
'Hello World!';
    }
}

// Type 1: Simple callback
call_user_func('my_callback_function'); 

// Type 2: Static class method call
call_user_func(array('MyClass''myCallbackMethod')); 

// Type 3: Object method call
$obj = new MyClass();
call_user_func(array($obj'myCallbackMethod'));

// Type 4: Static class method call (As of PHP 5.2.3)
call_user_func('MyClass::myCallbackMethod');

// Type 5: Relative static class method call (As of PHP 5.3.0)
class {
    public static function 
who() {
        echo 
"A\n";
    }
}

class 
extends {
    public static function 
who() {
        echo 
"B\n";
    }
}

call_user_func(array('B''parent::who')); // A
?>

Example #2 Callback example using a Closure

<?php
// Our closure
$double = function($a) {
    return 
$a 2;
};

// This is our range of numbers
$numbers range(15);

// Use the closure as a callback here to 
// double the size of each element in our 
// range
$new_numbers array_map($double$numbers);

print 
implode(' '$new_numbers);
?>

위 예제의 출력:

2 4 6 8 10

Note: In PHP4, it was necessary to use a reference to create a callback that points to the actual object, and not a copy of it. For more details, see References Explained.

void

void as a return type means that the return value is useless. void in a parameter list means that the function doesn't accept any parameters.

...

$... in function prototypes means and so on. This variable name is used when a function can take an endless number of arguments.



Type Juggling

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.

An example of PHP's automatic type conversion is the addition operator '+'. If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does not change the types of the operands themselves; the only change is in how the operands are evaluated and what the type of the expression itself is.

<?php
$foo 
"0";  // $foo is string (ASCII 48)
$foo += 2;   // $foo is now an integer (2)
$foo $foo 1.3;  // $foo is now a float (3.3)
$foo "10 Little Piggies"// $foo is integer (15)
$foo "10 Small Pigs";     // $foo is integer (15)
?>

If the last two examples above seem odd, see String conversion to numbers.

To force a variable to be evaluated as a certain type, see the section on Type casting. To change the type of a variable, see the settype() function.

To test any of the examples in this section, use the var_dump() function.

Note: The behaviour of an automatic conversion to array is currently undefined.
Also, because PHP supports indexing into strings via offsets using the same syntax as array indexing, the following example holds true for all PHP versions:

<?php
$a    
'car'// $a is a string
$a[0] = 'b';   // $a is still a string
echo $a;       // bar
?>

See the section titled String access by character for more information.

Type Casting

Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.

<?php
$foo 
10;   // $foo is an integer
$bar = (boolean) $foo;   // $bar is a boolean
?>

The casts allowed are:

  • (int), (integer) - cast to integer
  • (bool), (boolean) - cast to boolean
  • (float), (double), (real) - cast to float
  • (string) - cast to string
  • (binary) - cast to binary string (PHP 6)
  • (array) - cast to array
  • (object) - cast to object
  • (unset) - cast to NULL (PHP 5)

(binary) casting and b prefix forward support was added in PHP 5.2.1

Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent:

<?php
$foo 
= (int) $bar;
$foo = ( int ) $bar;
?>

Casting literal strings and variables to binary strings:

<?php
$binary 
= (binary) $string;
$binary b"binary string";
?>

Note: Instead of casting a variable to a string, it is also possible to enclose the variable in double quotes.

<?php
$foo 
10;            // $foo is an integer
$str "$foo";        // $str is a string
$fst = (string) $foo// $fst is also a string

// This prints out that "they are the same"
if ($fst === $str) {
    echo 
"they are the same";
}
?>

It may not be obvious exactly what will happen when casting between certain types. For more information, see these sections:




변수

Table of Contents


기본문법

PHP에서 변수는 변수명 앞에 달러사인을 덧붙여 표현된다. 변수명은 대소문자를 구별한다.

PHP에서 변수명은 다음 규칙을 따른다. 유효한 변수명은 문자나 밑줄로 시작하고, 그 뒤에 문자, 숫자, 밑줄이 붙을수 있다. 정규표현식으로 표현하면 다음과 같다: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

Note: 여기서 문자는 a-z, A-Z, 그리고 127부터 255까지(0x7f-0xff) 바이트를 의미합니다.

Note: $this은 특수 변수로, 할당할 수 없습니다.

변수 관련 함수는, 변수 관련 함수 레퍼런스를 참고하십시오.

<?php
$var 
'Bob';
$Var 'Joe';
echo 
"$var$Var";      // outputs "Bob, Joe"

$4site 'not yet';     // invalid; starts with a number
$_4site 'not yet';    // valid; starts with an underscore
$täyte 'mansikka';    // valid; 'ä' is ASCII 228.
?>

기본값으로, 변수는 항상 값에 의해 할당되어야 합니다. 변수를 표현식으로 지정할때에 원래 표현식의 모든 값이 목표 변수로 복사된다. 이 말의 의미는 예를 들면, 어떤 변수값을 다른 변수로 지정한 후에, 그 변수중 어떤 하나를 변경하는것이 다른 변수에 영향을 미치지 않는다는 의미를 갖는다. 이런 종류의 지정에 대해서 표현식을 참고.

또한, PHP에서는 이와 다른 방법으로 변수에 값이 지정된다: 참조에 의한 지정. 이 용어의 의미는 새로운 변수가 원래 변수를 참조한다는 것이다.(즉, "원래 변수의 별명이 되는것" 이나 "가리키는 것") 새 변수의 변경은 원래 변수에 영향을 미치고, 그 반대도 가능하다.

참조에 의한 지정을 위해서는, 단순히 지정되는(소스 변수) 변수의 시작부분에 엠퍼센트(&)를 덧붙이면 된다. 예를 들면 다음 코드 예는 'My name is Bob'이 두번 출력된다.

<?php
$foo 
'Bob';              // Assign the value 'Bob' to $foo
$bar = &$foo;              // Reference $foo via $bar.
$bar "My name is $bar";  // Alter $bar...
echo $bar;
echo 
$foo;                 // $foo is altered too.
?>

주의할 것은 오직 이름이 부여된 변수만이 참조에 의해 지정된다는 것이다.

<?php
$foo 
25;
$bar = &$foo;      // This is a valid assignment.
$bar = &(24 7);  // Invalid; references an unnamed expression.

function test()
{
   return 
25;
}

$bar = &test();    // Invalid.
?>

PHP에서 변수를 초기화 할 필요는 없지만, 초기화는 매우 좋은 습관입니다. 초기화되지 않은 변수는 자료형과 사용되는 위치에 따라서 기본값을 가집니다 - 논리 기본값은 FALSE, 정수형과 소수형은 0, 문자열(echo()등에서 사용)은 빈 문자열로 설정되고, 배열은 빈 배열로 설정됩니다.

Example #1 초기화되지 않은 변수의 기본값

<?php
// 설정되지 않고 참조되지 않은 (사용되지 않은) 변수; NULL 출력
var_dump($unset_var);

// 논리 사용; 'false' 출력 (이 구문에 대한 설명은 3항 연산자를 참고하십시오)
echo($unset_bool "true\n" "false\n");

// 문자열 사용; 'string(3) "abc"' 출력
$unset_str .= 'abc';
var_dump($unset_str);

// 정수 사용; 'int(25)' 출력
$unset_int += 25// 0 + 25 => 25
var_dump($unset_int);

// 소수 사용; 'float(1.25)' 출력
$unset_float += 1.25;
var_dump($unset_float);

// 배열 사용; array(1) {  [3]=>  string(3) "def" } 출력
$unset_arr[3] = "def" // array() + array(3 => "def") => array(3 => "def")
var_dump($unset_arr);

// 객체 사용; 새 stdClass 객체 생성 (http://www.php.net/manual/kr/reserved.classes.php 참고)
// 출력: object(stdClass)#1 (1) {  ["foo"]=>  string(3) "bar" }
$unset_obj->foo 'bar';
var_dump($unset_obj);
?>

초기화되지 않은 변수의 기본값에 의존하는 것은, 같은 변수명을 사용하는 파일을 포함하는 등에서 문제가 될 수 있습니다. 또한, register_globals를 켜놓은 상태에서 주요한 보안 위험입니다. 초기화되지 않은 변수를 사용할 때 E_NOTICE 등급의 오류가 발생하지만, 초기화되지 않은 배열에 원소를 추가할 때는 발생하지 않습니다. isset() 언어 구조로 변수가 초기화되었는지 확인 할 수 있습니다.



미리 선언된 변수

PHP는 실행되는 스크립트에 적용이되는 상당량의 미리 선언된 변수를 제공한다. 하지만, 이 변수의 대부분은 운영되는 서버, 서버의 버전, 서버의 설정, 다른 팩터와 관련되어 있어서 완벽하게 문서화되지 않았다. 이 중 몇개의 변수는 커맨드 라인에서 실행되는 PHP에서는 유효하지 않다. 예약된 미리 선언된 변수의 섹션을 참고.

Warning

PHP 4.2.0 이후 버전부터, PHP 디렉티브 register_globals의 기본값은 off가 되었다. register_globals를 off로 놓으면, 전역 유효영역안의 미리 선언된 변수 집합들에 영향을 미친다. 예를 들면, DOCUMENT_ROOT값을 얻기 위해서는 $DOCUMENT_ROOT 대신에 $_SERVER['DOCUMENT_ROOT']를, http://www.example.com/test.php?id=3에서 $id 대신에 $_GET['id']를, $HOME 대신에 $_ENV['HOME']을 사용해야 한다.

이와 관련된 변경사항은 register_globals의 설정 엔트리를 읽거나, 전역 등록 사용하기에 관한 보안 챕터는 물론, » 4.1.0» 4.2.0 Release Announcements도 참고하기 바란다.

superglobal arrays와 같은 가용한 PHP의 예약된 미리 선언된 변수를 사용하는 것을 추천한다.

4.1.0 버전 이후에, PHP는 웹서버, 환경, 유저 입력과 관련된 미리 선언된 배열 변수 집합을 추가적으로 제공한다. 이 새로운 배열은 자동적으로 전역화되기 때문에 더 특별해진다. 즉, 자동적으로 모든 유효영역안에서 적용이 가능하다. 이런 이유로, 이런 변수를 '자동전역변수'라고 한다. (PHP에서는 사용자-선언 슈퍼전역변수가 허용되지 않는다.) 슈퍼전역변수는 아래에 열거한다. 하지만, 이 변수 목록과 논의는 예약된 미리선언된 변수섹션을 참고한다. 또한 구버전의 미리선언된 변수($HTTP_*_VARS)가 아직도 존재한다는 것에 주의한다. PHP 5.0.0부터, 긴 형태의 PHP 예약 변수 배열을 register_long_arrays 지시어로 제거할 수 있습니다.

Note: 가변 변수
슈퍼전역변수는 함수나 클래스 메쏘드 안에서 가변 변수로는 쓰일수 없다.

Note: 자동 전역과 HTTP_*_VARS가 동시에 존재할 수 있습니다; 하지만 동일하지 않으며, 하나를 변경해도 다른 하나는 바뀌지 않습니다.

variables_order내의 특정 변수들이 설정되어있지 않으면, 적합한 PHP의 미리선언된 배열도 비워있게 된다.



변수 유효영역

변수의 유효영역은 변수가 정의된 환경을 말한다. 대부분의 경우 모든 PHP 변수는 한군데의 유효영역만을 갖는다. 이 한군데의 유효영역은 include되거나 require된 파일로도 확장된다. 예를 들면:

<?php
$a 
1;
include 
'b.inc';
?>

위 예제코드에서는 include된 b.inc 스크립트안에서도 $a 변수가 사용가능하다. 하지만, 사용자-선언 함수에서는 로컬 함수 유효영역이 적용된다. 함수내에서 사용되는 모든 변수는 기본값으로 로컬 변수 유효영역 안으로 제한된다. 예를 들면:

<?php
$a 
1/* global scope */ 

function test()

    echo 
$a/* reference to local scope variable */ 


test();
?>

위 스크립트에서 echo문이 $a의 로컬 버전을 참조하고, 이 영역 안에서 값을 지정되지 않았기 때문에 아무것도 출력되지 않는다. C에서 전역변수는 특별히 로컬 선언으로 덮어쓰지 않는이상은 자동적으로 함수안에서 사용가능하다는 점에서 C 언어와 약간 차이가 있다는 것에 주의해야 할것이다. 이런 생각으로 부주의하게 전역변수를 변경하려한다면 문제가 될것이다. PHP에서 전역변수가 함수내에서 계속적으로 사용이 된다면 함수안에서 global로 선언해야 합니다.

global 키워드

우선, global의 사용 예제입니다:

Example #1 global 사용하기

<?php
$a 
1;
$b 2;

function 
Sum()
{
    global 
$a$b;

    
$b $a $b;


Sum();
echo 
$b;
?>

위 스크립느는 "3"를 출력할것이다. $a$b를 함수내에서 global로 선언함으로써, 각 변수에 대한 모든 참조는 전역 버전으로 참조될것이다. 함순에서 조작되는 전역변수의 수는 제한이 없다.

전역 유효영역의 변수에 접근할수 있는 두번째 방법이 특별 PHP-선언 $GLOBALS 배열을 사용하는 것이다. 이전 예제코드는 다음과 같이 다시 작성할 수 있습니다:

Example #2 global 대신 $GLOBALS 사용하기

<?php
$a 
1;
$b 2;

function 
Sum()
{
    
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];


Sum();
echo 
$b;
?>

$GLOBALS 배열은 전역변수명이 key가 되는 연관배열이고 배열의 원소 값이 그 변수의 내용이 된다. $GLOBALS이 어떻게 모든 유효영역에서 존재하는지 주의하라. 이유는 $GLOBALS이 슈퍼전역변수이기 때문이다. 아래에 슈퍼전역변수의 파워를 설명하는 예제코드를 보였다:

Example #3 자동 전역과 영역을 보여주는 예제

<?php
function test_global()
{
    
// 대부분의 예약 변수는 "자동 전역"이 아니기에,
    // 함수 내부 영역에서 사용하려면 'global'이 필요합니다.
    
global $HTTP_POST_VARS;

    echo 
$HTTP_POST_VARS['name'];
    
    
// 자동 전역은 어떠한 영역에서도 사용할 수 있고,
    // 'global'이 필요하지 않습니다. 자동 전역은
    // PHP 4.1.0부터 사용할 수 있고, HTTP_POST_VARS는
    // 배제되었습니다.
    
echo $_POST['name'];
}
?>

정적 변수 사용하기

변수 유효영역의 또 다른 중요한 기능이 static 변수이다. 정적(static) 변수는 로컬 함수 영역에서만 존재한다. 그러나 프로그램이 그 영역을 떠나지 않으면 그 값을 잃지 않는다. 다음 예제를 생각해 봅시다:

Example #4 정적 변수의 필요성을 보여주는 예제

<?php
function test()
{
    
$a 0;
    echo 
$a;
    
$a++;
}
?>

이 함수는 매번 호출될때마다 $a0으로 설정하고 "0"를 출력한다. $a++ 는 변수를 증가시키지만 함수에서 빠져나가면 $a 변수는 사라지게되므로 아무 가치가 없다. 현재 카운트 값을 잃지 않는 유용한 카운트 함수를 만들려면, $a 변수를 static으로 선언한다.

Example #5 정적 변수의 사용 예제

<?php
function test()
{
    static 
$a 0;
    echo 
$a;
    
$a++;
}
?>

처음 함수를 호출할 때만 $a가 초기화 되고, test() 함수가 호출될때마다 $a 값을 출력하고 그 값이 증가합니다.

정적 변수는 또한 재귀함수를 다루는 한 방법을 제공한다. 재귀함수는 자기 자신을 호출하는 함수를 말한다. 재귀함수는 무한히 실행될수 있기 때문에 재귀함수를 작성할때는 주의가 필요하다. 재귀를 벗어나는 방법을 반드시 갖고 있어야 한다. 다음과 같은 단순 재귀함수는 10까지 카운트한다. 정적 변수 $count는 멈춰야 할 때는 안다.

Example #6 재귀 함수에서 정적 변수

<?php
function test()
{
    static 
$count 0;

    
$count++;
    echo 
$count;
    if (
$count 10) {
        
test();
    }
    
$count--;
}
?>

Note: 정적 변수는 위 예제처럼 선언해야 합니다. 이 변수에 표현식의 결과를 할당하려 할 경우는 해석 오류를 발생합니다.

Example #7 정적 변수 선언하기

<?php
function foo() {
    static 
$int 0;          // 적합
    
static $int 1+2;        // 오류 (표현식이기에)
    
static $int sqrt(121);  // 오류 (역시 표현식이기에)

    
$int++;
    echo 
$int;
}
?>


전역 변수와 정적 변수의 참조

PHP 4를 작동하는 Zend Engine 1은 staticglobal참조를 통한 변수 변경자로 구현합니다. 예를 들어, 실제 전역 변수를 global 키워드를 사용하여 함수 영역 내부로 가져올 경우, 그 전역 변수의 참조를 생성합니다. 이로 인해 다음 예제에서 처럼 원하지 않은 동작을 할 수 있습니다:

<?php
function test_global_ref() {
    global 
$obj;
    
$obj = &new stdclass;
}

function 
test_global_noref() {
    global 
$obj;
    
$obj = new stdclass;
}

test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>

위 예제코드를 실행하면 다음과 같은 결과가 유도된다.


NULL
object(stdClass)(0) {
}

이와 비슷한 동작이 static 절에서도 발생한다. 참조가 정적으로 저장되지 않는것이다:

<?php
function &get_instance_ref() {
    static 
$obj;

    echo 
'Static object: ';
    
var_dump($obj);
    if (!isset(
$obj)) {
        
// Assign a reference to the static variable
        
$obj = &new stdclass;
    }
    
$obj->property++;
    return 
$obj;
}

function &
get_instance_noref() {
    static 
$obj;

    echo 
'Static object: ';
    
var_dump($obj);
    if (!isset(
$obj)) {
        
// Assign the object to the static variable
        
$obj = new stdclass;
    }
    
$obj->property++;
    return 
$obj;
}

$obj1 get_instance_ref();
$still_obj1 get_instance_ref();
echo 
"\n";
$obj2 get_instance_noref();
$still_obj2 get_instance_noref();
?>

위 예제코드를 실행하면 다음과 같은 결과가 유도된다.


Static object: NULL
Static object: NULL

Static object: NULL
Static object: object(stdClass)(1) {
["property"]=>
int(1)
}

위 예제 코드는 정적 변수에 대한 참조를 지정할때, &get_instance_ref()함수가 두번째로 호출되는 때에 기억되지 않는다는 것을 보여준다.



가변 변수

때때로 가변 변수명을 갖을수 있는것다는 것은 편리함을 준다. 즉, 변수명이 유동적으로 설정되거나 사용될수 있다. 일반적인 변수는 다음과 같은 구문에 의해 설정된다:

<?php
$a 
'hello';
?>

가변변수는 변수값을 취해서 변수명으로 취급한다. 위 예제코드는, hello를 두개의 달러사인을 사용하여 변수명으로 사용할수 있다.

<?php
$$a 'world';
?>

이 지점에서 두 변수가 선언되었고 PHP 심볼 트리에 저장된다: $a는 "hello" 값을 갖고 $hello는 "world" 값을 갖게 된다. 따라서, 이 구문:

<?php
echo "$a ${$a}";
?>

다음과 완전히 똑같이 출력된다:

<?php
echo "$a $hello";
?>

즉, 둘다 hello world를 출력한다.

배열을 갖는 가변변수를 사용하기 위해서는 애매한 문제를 해결해야 한다. 즉 $$a[1]를 쓴다면 해석기는 $a[1]가 변수를 의미하는지 알수 있어야 한다. 또는 $$a가 변수이기를 바라고, [1]가 그 변수의 인덱스인지 알수 있어야 한다. 이런 애매한 문제를 해결하기 위한 문법: 첫번째 목적을 위해 ${$a[1]}과 두번째 목적을 위해 ${$a}[1]을 들수 있다.

Warning

가변 변수로 함수나 클래스 메쏘드 안에서 PHP 자동 전역 배열을 사용할 수 없음에 주의하십시오. $this 변수도 특수 변수로써, 동적으로 참조할 수 없습니다.



외부에서 오는 변수들

HTML 폼 (GET과 POST)

폼이 PHP 스크립트로 전달될때, 그 폼안의 정보가 스크립트내에서 자동적으로 유효해진다. 이 정보에 접근할 수 있는 많은 방법이 제공된다. 예를 들면:

Example #1 단순한 HTML 폼

<form action="foo.php" method="post">
    이름:  <input type="text" name="username" /><br />
    메일: <input type="text" name="email" /><br />
    <input type="submit" name="submit" value="전송합니다!" />
</form>

특별한 설정과 개인적인 선호에 의해, HTML 폼으로부터 데이터를 접근할수 있는 많은 방법이 존재한다. 몇가지르 예를 들면:

Example #2 단순한 POST HTML 폼으로 부터 데이터에 접근하기

<?php 
// PHP 4.1.0부터 사용 가능

   echo $_POST['username'];
   echo $_REQUEST['username'];

   import_request_variables('p', 'p_');
   echo $p_username;

// PHP 6부터 사용 불가. PHP 5.0.0부터, 이러한 긴 예약 변수는
// register_long_arrays 지시어로 비활성화 할 수 있습니다.

   echo $HTTP_POST_VARS['username'];

// PHP 지시어 register_globals = on 일 경우에 사용할 수 있습니다.
// PHP 4.2.0부터 기본값은 register_globals = off 입니다.
// 이 방법을 사용하는 것은 권장되지 않습니다.

   echo $username;
?>

GET 폼을 사용하는 것은 적절한 GET 기선언 변수를 대신 사용할때를 제외하면 동일하다. GET은 QUERY_STRING (URL에서 '?'이후의 값)에도 적용이 된다. 따라서, 예를 들면 http://www.example.com/test.php?id=3$_GET['id']으로 접근할수 있는 GET 데이터를 포함한다. 또한 $_REQUESTimport_request_variables()를 참고.

Note: $_POST$_GET 같은 슈퍼전역 배열은 PHP 4.1.0 이후버전부터 사용되기 시작했다.

전에 설명한대로, PHP 4.2.0 이전에는 register_globals의 기본값이 on이였다. PHP 커뮤니티는 그 디렉티브 값이 off가 되어있다고 가정하고 적절하게 코딩하는 것을 추천하기 때문에 이 디렉티브값에 연연할 필요가 없다.

Note: magic_quotes_gpc 설정 디렉티브는 Get, Post, Cookie 값에 영향을 준다. 이 값이 켜져있으면, 그 값(It's "PHP!")은 자동적으로 (It\'s \"PHP!\")이 될것이다. 이 회피는 DB 입력을 위해 필요하다. 또한 addslashes(), stripslashes()magic_quotes_sybase를 참고한다.

PHP는 폼 변수가 쓰이는 환경안의 배열도 이해한다. (관련 faq를 참고) 예를 들면, 관련 변수를 함께 그룹화하거나, 다중 select 입력으로부터 값을 끄집어내기위해 이 기능을 사용할수 있다. 예로써, 자신에게 폼을 post하고 그 데이터를 출력해보자:

Example #3 좀더 복잡해진 폼 변수들

<?php
if ($_POST) {
    echo 
'<pre>';
    echo 
htmlspecialchars(print_r($_POSTtrue));
    echo 
'</pre>';
}
?>
<form action="" method="post">
    이름: <input type="text" name="personal[name]" /><br />
    메일: <input type="text" name="personal[email]" /><br />
    맥주: <br />
    <select multiple name="beer[]">
        <option value="warthog">Warthog</option>
        <option value="guinness">Guinness</option>
        <option value="stuttgarter">Stuttgarter Schwabenbräu</option>
    </select><br />
    <input type="hidden" name="action" value="submitted" />
    <input type="submit" value="전송합니다!" />
</form>

변수명으로 IMAGE SUBMIT

form을 전달할때, 표준적인 submit 버튼 태그 대신 다음과 같이 image 태그를 사용할수 있다.

<input type="image" src="image.gif" name="sub" />

유저가 image의 어느곳에서 클릭하더라도 수행 폼은 두가지 추가적인 변수를 서버로 전송할것이다. sub_x와 sub_y. 이 변수는 image안에서 유저가 클릭하는 좌표를 갖는다. 실제로 브라우저에 의해 보내지는 변수명은 밑줄(_)이 아니라 마침표(.)를 포함한다. 그러나 PHP는 자동으로 마침표를 밑줄로 변환한다.

HTTP 쿠키

PHP는 » Netscape's Spec에 의해 정의된 HTTP 쿠키를 투명하게 지원한다. 쿠키는 원격 브라우저안에 데이터를 저장하는 메카니즘이고 따라서 복귀하는 유저를 추적하거나 식별하게 해준다. setcookie() 함수를 사용하여 쿠키를 설정할수 있다. 쿠키는 HTTP 헤더의 일부분이고, 그래서 SetCookie함수는 브라우저에 출력이 생기기전에 호출되어야 한다. 이 제약은 header() 함수에도 같이 적용된다. 쿠키 데이터는 적절한 쿠키 데이터 배열에 존재하게 된다. $_COOKIE, $HTTP_COOKIE_VARS는 물론 $_REQUEST 배열에 존재한다. 더 자세한 정보와 예제를 보기 위해 setcookie() 매뉴얼 페이지를 참고.

단일 쿠키 변수에 여러값을 지정하려한다면, 배열로 그 값을 지정할수 있다. 예를 들면:

<?php
  setcookie
("MyCookie[foo]"'Testing 1'time()+3600);
  
setcookie("MyCookie[bar]"'Testing 2'time()+3600);
?>

위 예제코드는 MyCookie가 스크립트내에서 단일 배열이 될지라도 두개의 분리된 쿠키를 생성할수 있다. 여러값을 갖는 단일 쿠키를 설정하려면, 첫번째로 그 값에 serialize()explode()를 사용할것을 고려하도록 한다.

쿠키는 경로나 도메인이 다르지 않으면 브라우저안에서 같은 이름을 갖는 이전 쿠키를 교체한다는 것에 주의해야 한다. 따라서, 쇼핑 카트 애플리케이션을 위해서는 카운터를 유지하고 이 카운터를 전달하기를 원할것이다.

Example #4 setcookie()예제 코드

<?php
if (isset($_COOKIE['count'])) {
    
$count $_COOKIE['count'] + 1;
} else {
    
$count++;
}
setcookie('count'$counttime()+3600);
setcookie("Cart[$count]"$itemtime()+3600);
?>

유입되는 변수명에 존재하는 점(dot)

표준적으로, PHP는 스크립트내로 변수를 전달할때 변수명을 변경하지 않는다. 하지만, 점(마침표, full stop)은 PHP 변수명안에서 유효한 문자가 될수 없다는것에 주의해야 할것이다. 이에 유의하여 다음 코드를 보자:

<?php
$varname
.ext;  /* invalid variable name */
?>

현재, 해석기가 보게되는 것은 $varname이라는 변수와 그 뒤에 문자열 결합 연산자, 그 뒤에 벌거벗은 문자열(barestring) 'ext'이다. (즉, 따옴표로 둘러싸지 않은 문자열은 key나 예약된 단어와 일치하지 않음) 확실하게 이 결과는 원치 않은것이다.

이러한 이유로, PHP는 유입되는 변수명안의 점(.)을 밑줄(_)로 변경한다는것을 명심해야 한다.

변수 타입 결정하기

PHP는 변수 타입을 결정하고 변수를(보통) 필요한 타입으로 변환하기 때문에, 어느 시간에 변수가 무슨 타입인지 알수가 없다. PHP는 변수가 무슨 타입인지 확인할수 있는 몇가지 함수를 제공한다. 그 함수들은 다음과 같다: gettype(), is_array(), is_float(), is_int(), is_object(), is_string(). 타입 챕터를 참고.




상수

Table of Contents

상수는 단순한 값을 위한 식별자(이름)이다. 이름이 제시하는것과 같이, 이 값은 스크립트 실행중에는 변경될수 없다. (실질적으로 상수가 아닌 마법 상수 을 제외하고) 상수는 기본적으로 대소문자를 구별한다. 관례상, 상수 식별자는 항상 대문자이다.

PHP에서 상수명은 같은 규칙을 따른다. 유효한 상수명은 문자나 밑줄로 시작하고 다른 문자나 숫자, 밑줄이 뒤를 따른다. 정규식으로는 다음처럼 표현할수 있다: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Example #1 상수명으로 적합하거나 부적합한 이름들

<?php

// 유효한 상수명
define("FOO",     "something");
define("FOO2",    "something else");
define("FOO_BAR""something more");

// 무효한 상수명
define("2FOO",    "something");

// 유효하지만, 피해야할 상수명:
// 어느날 PHP에서 마법 상수를 제공할 수 있으며,
// 이 경우 스크립트를 사용할 수 없습니다
define("__FOO__""something");

?>

Note: 여기서 문자는 a-z, A-Z와 아스키 문자 127에서 255까지이다 (0x7f-0xff).

superglobals처럼 상수의 유효범위(scope)는 전역적이다. 유효범위에 상관없이 스크립트의 어느곳에서도 상수를 참조할수 있다. 상수에 관한 더 자세한 정보를 위해 변수 범위 매뉴얼 섹션을 참고합니다.


문법

define() 함수를 사용해서 상수를 정의할 수 있습니다. PHP 5.3.0부터 클래스 정의 밖에서 const 키워드를 사용할 수도 있습니다. 상수가 한번 정의되면, 변경하거나 해제(undefine)할 수 없습니다.

상수는 스칼라 데이터(boolean, integer, float, string)만 가질 수 있습니다. resource를 상수로 등록할 수 있지만, 피하십시오. 예상할 수 없는 결과를 낳을 수 있습니다.

단순히 상수명을 써서 상수값을 얻을 수 있다. 변수와는 달리 $가 상수명 앞으로 오면 안된다 동적으로 상수명을 취하려한다면 constant()함수로 상수값을 가져올수 있다. 정의된 모든 상수 목록을 구하려면 get_defined_constants() 함수를 쓴다.

Note: 상수와 (전역)변수는 서로 다른 네임스페이스(namespace)상에 있다. 이말의 의미는 예를 들면 TRUE$TRUE은 일반적으로 다르다는것이다.

해제된 상수를 사용한다면, PHP는 상수명 자체를 쓴것이라고 가정할것이다 즉,string으로 인식할것이다. (CONSTANT vs "CONSTANT") E_NOTICE로 이런 일이 발생했는지 알수 있다. 왜 $foo[bar]가 잘못됐는지 (bar를 상수로 define() 하지않았다면) 매뉴얼을 참고한다. 단순히 상수가 설정되었는지만 확인하려 한다면 defined()함수를 쓰면 됩니다.

다음은 상수와 변수의 차이점이다:

  • 상수는 이름 앞에 달러표시($)가 없다.
  • 상수는 단순 지정(assingment)이 아니라 define() 함수로만 정의될수 있다.
  • 상수는 변수의 유효범위 규칙과는 상관없이 어느곳에서든 정의되거나 값을 취할수 있다.
  • 상수는 한번 설정되면 재정의하거나 해제할수 없을것이다; 그리고
  • 상수는 스칼라 값만 쓸수 있다.

Example #1 상수 정의하기

<?php
define
("CONSTANT""Hello world.");
echo 
CONSTANT// "Hello world."을 출력한다
echo Constant// "Constant"를 출력하고 경고가 뜬다.
?>

Example #2 const 키워드를 사용해서 상수 정의하기

<?php
// PHP 5.3.0부터 작동
const CONSTANT 'Hello World';

echo 
CONSTANT;
?>

참고: 클래스 상수.



마법 상수

PHP는 어떤스크립트에서도 유효한 많은 수의 미리 정의된 상수를 제공한다. 하지만 이 상수의 대부분은 다양한 확장(extension)에 의해 생성된다. 그래서 그 확장이 같이 컴파일되어 유효하거나 동적인 로딩이 되어있어야 이런 상수가 존재하게 된다.

일곱 가지 마법 상수가 존재한다. 이 상수들은 어디에서 쓰느냐에 따라 용도가 변경된다. 예를 들면, __LINE__상수의 값은 스크립트의 해당 줄과 관련이 있다. 이 특별한 상수들은 대소문자 구별이 없고 다음과 같다:

약간의 "마법" PHP 상수
이름 설명
__LINE__ 파일의 현재 줄 번호
__FILE__ 파일의 전체경로와 파일명. 포함한 파일 안에서 사용하면, 포함된 파일명을 반환합니다.. PHP 4.0.2부터, __FILE__은 언제나 절대 경로를 가지고 있습니다. 이전에는 특정한 경우에서 상대 경로를 가지고 있었습니다.
__DIR__ 파일의 디렉토리. 포함한 파일 안에서는, 포함된 파일의 디렉토리를 반환합니다. 이는 dirname(__FILE__)과 동일합니다. 디렉토리명은 루트 디렉토리가 아닌 이상, 마지막에 슬래시가 없습니다. (PHP 5.3.0에서 추가)
__FUNCTION__ 함수명. (PHP 4.3.0에서 추가) PHP 5부터 이 상수는 정의된 그대로의 함수명을 반환합니다. (대소문자 구분) PHP 4에서는 항상 소문자였습니다.
__CLASS__ 클래스명. (PHP 4.3.0에서 추가) PHP 5부터 이 상수는 정의된 그대로의 클래스명을 반환합니다. (대소문자 구분) PHP 4에서는 항상 소문자였습니다.
__METHOD__ 클래스 메쏘드명 (PHP 5.0.0에서 추가) 메쏘드 명은 정의한 대로 반환됩니다. (대소문자 구분)
__NAMESPACE__ 현재 이름공간 이름 (대소문자 구분). 이 상수는 컴파일 시에 정의됩니다. (PHP 5.3.0에서 추가)

참고: get_class(), get_object_vars(), file_exists(), function_exists().




표현식

표현식은 PHP에서 가장 중요한 구성요소다. PHP에서 쓰는 거의 대부분이 표현식이다. 표현식을 정의한 가장 단순하고 가장 정확한 말은 "모든것이 값을 갖는다"는 것이다.

표현식의 가장 기본적인 형태가 상수와 변수이다. "$a = 5"라고 쓰면, $a에 '5'를 지정하는것이다.'5'는 확실히 5란 값을 갖는다. 다르게 표현하면 '5'는 5란 값을 갖는 표현식이 된다 (이경우에, '5'는 정수형 상수이다)

이렇게 지정하고 나면 $a의 값은 5가 될것이란 것도 기대할수 있을것이다. 그래서 $b = $a라고 쓴다면, $b = 5를 쓴것과 같이 동작할것이라고 기대할수 있을것이다. 다른말로, $a는 또한 5란 값을 갖는 표현식이다. 모든것이 제대로 작동한다면, 기대하던대로 될것이다.

표현식의 약간 더 복잡한 예가 함수이다. 다음 함수를 예로 들어보자.

<?php
function foo ()
{
    return 
5;
}
?>

함수의 개념에 익숙하다면 (그렇지 않으면, 함수에 관한 장을 참고) $c = foo()로 쓰는것이 $c = 5와 같을것이라고 생각할것이다. 옳은 생각이다. 함수는 반환된 값을 갖는 표현식이다. foo()가 5를 반환하기때문에 'foo()'표현식의 값은 5가 된다. 함수는 대체로 정적인 값보다는 계산값을 반환한다.

물론, PHP에서 값은 정수가 되어야 하는것은 아니다.. PHP에서는 4가지 스칼라 값 자료형을 지원한다: integer 값, 부동소수점 값(float), string 값, boolean 값. (스칼라 값은 배열과 다르게, 더 작게 쪼갤수 없는 값을 말한다) PHP는 두가지 조합형(스칼라값이 아닌)을 지원한다: 배열과 객체. 이 두가지 값형은 변수나 함수에서 넘기는 값으로 지정될수 있다.

PHP는 여기에 더하여, 많은 다른 언어들이 하는 방식의 표현식을 받아들입니다. PHP는 거의 모든것이 표현식이라는 관점에 입각한 표현식-지향 언어이다. 전술했던 예제 '$a = 5'를 보자. 이 식과 연관된 값은 '5'라는 정수상수 두개라는것과 $a는 5로 수정이 된다는 것을 알수 있다. 그러나 진실은 여기에 연관되어있는 것이 하나의 추가값이라는것이고, 이 추가된 값이 지정되어지는 값 자체라는 것이다. 지정 자체는 지정값 5만 적용된다. 실제로, '$a = 5'라는 식은 그것이 무엇을 하든 5라는 값을 갖는 표현식이라는 것이다. 따라서, '$b = ($a = 5)'라는 식은 '$a = 5; $b = 5'를 쓰는것과 같다 (세미콜른은 구문의 끝을 표시한다). 지정연산은 오른쪽에서 왼쪽방향으로 해석되므로 '$b = $a = 5'라고 쓸수 있다.

표현식-지향의 또다른 좋은 예는 전처리(pre)/후처리(post)되는 증가와 감소 연산이다. PHP 사용자와 다른 언어 사용자는 변수++과 변수--의 부호표시에 익숙할것이다. 이런 부호표시는 증가와 감소 연산자이다. PHP/FI 2에서 '$a++'문은 값을 갖지않는다 (즉, 표현식이 아니다), 그래서 어떤수단으로도 특정값을 지정하거나 사용할수 없다. PHP는 C처럼 이런 표현식을 사용할수 있어서 증가/감소 연산 능력을 확장시켰다. PHP는 C처럼 두가지 연산형이 존재한다 - 전처리-증가 와 후처리-증가. 전처리 증가와 후처리 증가 모두 변수를 증가시키고 변수에 적용하므로, 변수에 미치는 영향은 동일합니다. 차이점은 증가 표현식의 값에 달려있다. 전처리-증가, 즉 '++$변수' 는 값을 증가시켜 평가합니다. (PHP는 처음 값을 읽기 전에 값을 증가시킨다, 따라서 이름이 '전처리-증가'가 되는것이다) 후처리-연산, '$변수++'는 값을 증가시키기 전의 $변수의 처음값을 평가합니다. (PHP는 그 값을 읽은 후에 그 값을 증가시킨다, 그래서 '후처리-증가'가 되는것이다)

가장 흔한 표현식 형태는 비교 표현식입니다. 이 표현식은 FALSETRUE로 평가합니다. PHP는 >(초과), >=(이상), ==(같음), !=(같지 않음), <(미만), <=(이하)를 지원합니다. 또한 엄격한 등가 연산자를 지원합니다: ===(같고 같은 자료형)과 !==(같지 않거나 다른 자료형). 이 표현식은 보통 if 구문과 같은 조건부 실행문에 사용됩니다.

이 장에서 취급할 제일 마지막 표현식의 예는 조합된 연산자-지정 표현식이다. $a를 1만큼 증가시키고자 한다면 단순히 '$a++'이나 '++$a'로 쓸수 있다는것을 이미 알고 있을것이다. 그러나 하나 이상의 값을 증가시키고자 한다면, 예를 들어 3을 증가시키고자 한다면 어떻게 해야 할까? '$a++'을 여러번 쓸수도 있다. 그러나 이런 식으로 쓰는것은 효과적이거나 편한 방법이 아니라는것을 쉽게 알수 있다. 좀더 평범하게 표현하면 '$a = $a + 3'이다. '$a + 3'은 $a에 3을 더한 값이 계산 되고 $a로 그 값이 지정된다. 그래서 $a에 3을 증가시킨 결과가 된다. PHP에서는 C와 같은 다른 언어처럼 더 짧은 형태로 쓸수있다. 그래서, 좀더 이해하기 쉽고 좀더 빨리 이해할수있다. $a의 현재 값에 3을 더하는 것은 '$a += 3'으로 쓸수 있다. 이 표현식의 의미는 정확히 '$a값을 취해 그 값에 3을 더하고 다시 $a에 계산된값을 지정하라'이다. 좀더 짧고 명확할 뿐만 아니라, 좀더 빠른 수행이 이루어진다. 일반적인 표현식의 값처럼 '$a += 3'의 값은 지정값이다. 3이 아니라, $a에 3을 더한 값이라는 것에 주의하라 (이값은 $a에 지정되는 값이다) 어떠한 두개연속의 연산자도 이런 연산자-지정 방식으로 사용될수 있다. 예를 들면, '$a -= 5' ($a의 값에서 5를 뺀것), '$b *= 7' ($b의 값에 7을 곱한것) 등등이 쓰일수 있다.

다른 언어에서 본적이 없다면 이상하게 보이는 표현식이 있다. 3중 조건적 연산자이다:

<?php
$first 
$second $third
?>

first 에 속하는 표현식의 값이 TRUE (non-zero)이면 second 에 속하는 표현식이 적용되고, 이것이 조건적 표현식의 결과가 된다. 이 경우가 아니면, third 에 속하는 표현식이 적용되고, 그 값이 된다.

다음 예제 코드는 좀더 일반적으로 사용된 전처리/후처리-증가와 표현식을 이해하는데 도움이 될것이다.

<?php
function double($i)
{
    return 
$i*2;
}
$b $a 5;        /* $a와 $b에 5라는 값을 지정함 */
$c $a++;          /* 후처리-증가, $a 의 원래값을 적용함
                       $c는 (5)가 됨 */
$e $d = ++$b;     /* 전처리-증가, $b가 증가된 값이 적용됨
                       $d와 $e는 (6)이 됨 */

/* 여기서, $d와 $e는 6과 같다 */

$f double($d++);  /* 증가되기 전의 $d값의 두배가 적용됨
                       $f는  2*6 = 12가 됨 */
$g double(++$e);  /* 증가된 후의 $e값의 두배가 적용됨
                       $g는  2*7 = 14가 됨 */
$h $g += 10;      /* 우선, $g는 10만큼 증가되어 24가 됨.
                       지정된 값 (24)가 $h로 지정된다.
                       $h도 24값으로 지정된다 */
?>

몇몇 표현식은 구문으로 간주할 수 있습니다. 이런 경우는 구문이 'expr' ';'의 형태를 갖는다. 즉, 세미콜른이 표현식 뒤에 온다. '$b=$a=5;'에서 $a=5는 유효한 표현식이다. 그러나 그자체가 구문이 되지는 않는다. 하지만, '$b=$a=5;'는 유효한 구문이다

마지막으로 언급할 만큼 가치있는것이 표현식의 진리값이다. 많은 사건중, 주로 조건적 수행과 루프에서, 표현식의 특정 값에 흥미있지는 않을것이다. 그러나 그 값이 TRUE인지 FALSE인지는 중요하다. 상수 TRUEFALSE (대소문자를 구별하지 않음)는 두가지 논리값이다. 필요하면, 표현식은 자동적으로 논리값으로 변환된다. 더 자세한 정보는 자료형 변환을 참고할것.

PHP는 표현식의 완벽하고도 강력한 구현방법을 제공한다. 그런 방법을 완전히 문서화하는 것은 이 매뉴얼의 범위를 넘는다. 위 예제 코드들은 표현식이 무엇인지에 대한것과 유용한 표현식을 구축할수 있는 방법에 대한 아이디어를 줄것이다. 이후 매뉴얼에서는 유효한 PHP 표현식을 expr라고 쓰겠다.



연산자

Table of Contents

연산자는 하나 이상의 값(또는, 프로그래밍 은어로 표현)을 받아서 다른 값을 산출합니다. (그러므로 구조 자체는 표현이 됩니다) 그러므로 (print처럼) 값을 반환하는 함수나 구조를 연산자로 생각할 수 있고, (echo처럼) 아무것도 반환하지 않는 것을 다른 것으로 생각할 수 있습니다.

세 종류의 연산자가 있습니다. 첫번째는 하나의 값에만 작용하는 일항 연산자입니다. 예를 들면, !(부정 연산자)나 ++(증가 연산자)가 있습니다. 두번째는 이항 연산자로 불립니다; 이 종류는 PHP가 지원하는 대부분의 연산자에 해당합니다. 목록은 아래의 연산자 우선권 섹션에 있습니다.

세번째는 삼항 연산자입니다: ?:. 이것은 세번째에 의존해서 두 표현 중 하나를 선택하는 데 사용합니다. 삼항 연산자를 괄호로 감싸는 건 매우 좋은 생각입니다.


연산자 우선권

연산자 우선권은 두 표현이 얼마나 "단단하게" 묶여 있는지 정의합니다. 예를 들어, 1 + 5 * 3 표현의 답은 18이 아닌 16입니다. 곱셈("*") 연산자가 덧셈(+) 연산자보다 높은 우선권을 가지기 때문입니다. 필요하다면, 우선권을 강제하기 위해 괄호를 사용할 수 있습니다. 예를 들면: (1 + 5) * 318로 평가됩니다. 연산자 우선권이 같으면, 왼쪽에서 오른쪽 결합을 사용합니다.

다음 표는 높은 우선권을 가지는 연산자가 위쪽에 나오는 연산자 우선권 목록입니다. 같은 줄에 있는 연산자는 같은 우선권을 가지며, 이 경우 결합이 평가하는 순서를 결정합니다.

연산자 우선권
결합 연산자 추가 정보
무결합 clone new clonenew
왼쪽 [ array()
무결합 ++ -- 증가/감소
무결합 ~ - (int) (float) (string) (array) (object) (bool) @ 자료형
무결합 instanceof 자료형
오른쪽 ! 논리
왼쪽 * / % 계산
왼쪽 + - . 계산 그리고 문자열
왼쪽 << >> 비트
무결합 < <= > >= <> 비교
무결합 == != === !== 비교
왼쪽 & 비트 그리고 참조
왼쪽 ^ 비트
왼쪽 | 비트
왼쪽 && 논리
왼쪽 || 논리
왼쪽 ? : 삼항
오른쪽 = += -= *= /= .= %= &= |= ^= <<= >>= 할당
왼쪽 and 논리
왼쪽 xor 논리
왼쪽 or 논리
왼쪽 , 다양한 사용

왼쪽 결합은 표현이 왼쪽에서 오른쪽으로 평가됨을 의미하며, 오른쪽 결합은 반대입니다.

Example #1 결합성

<?php
$a 
5// (3 * 3) % 5 = 4
$a true true 2// (true ? 0 : true) ? 1 : 2 = 2

$a 1;
$b 2;
$a $b += 3// $a = ($b += 3) -> $a = 5, $b = 5
?>

괄호를 사용하는 것은 표현의 가독성을 증가시킵니다.

Note: =이 대부분의 연산자보다 낮은 우선권을 가지지만, PHP는 다음과 같은 표현을 허용합니다: if (!$a = foo()), 이 경우 foo()의 반환값은 $a에 들어갑니다.



계산 연산자

학교에서 배운 기본 계산을 떠올렸습니까? 그와 같이 작동합니다.

계산 연산자
예제 이름 결과
-$a 부정 $a의 반대.
$a + $b 덧셈 $a와 $b의 합.
$a - $b 뺄셈 $a와 $b의 차.
$a * $b 곱셈 $a와 $b의 곱.
$a / $b 나눗셈 $a와 $b의 몫.
$a % $b 나머지 $a를 $b로 나눈 나머지.

나눗셈 연산자("/")는 두 연산수가 정수(또는 정수로 변환되는 문자열)가 아니고 수가 정확히 나눠질 수 있으면 정수 값을 반환합니다. 그렇지 않으면 소수 값을 반환합니다.

나머지 연산자는 계산하기 전에 정수로 변환(소수점 부분을 제거)합니다.

Note: 음수 $a에 대한 $a % $b의 나머지는 음수입니다.

매뉴얼 수학 함수 페이지를 참고하십시오.



할당 연산자

기본 할당 연산자는 "="입니다. 처음에는 이것을 "같다"로 생각할 수 있습니다. 아닙니다. 실제로는 왼쪽 연산수가 오른쪽 표현의 값으로 설정됨을 의미합니다. ("를 설정"입니다)

할당 연산자의 값은 할당된 값입니다. 그러므로, "$a = 3"의 값은 3입니다. 이는 트릭 같은 일을 허용합니다:

<?php

$a 
= ($b 4) + 5// $a는 이제 9와 같고, $b는 4로 설정됩니다.

?>

기본 연산자에 추가로, 모든 이항 계산, 배열 합집합과 문자열 연산자에 대하여 "결합 연산자"가 존재합니다. 이를 사용해서 값을 표현으로 사용하고 그 표현의 결과를 값에 설정할 수 있도록 합니다. 예를 들면:

<?php

$a 
3;
$a += 5// $a를 8로 설정, 다음과 같습니다: $a = $a + 5;
$b "Hello ";
$b .= "There!"// $b = $b . "There!";와 마찬가지로, $b를 "Hello There!"로 설정

?>

할당은 원래 값을 새로운 것으로 복사하기 때문에(값으로 할당), 하나의 변경은 다른 것에 영향을 주지 않습니다. 또한 빠듯한 루프 안에서 커다란 배열을 복사해야할 필요성이 존재하게 됩니다. $var = &$othervar; 구문을 사용해서, 참조로 할당도 지원합니다. '참조로 할당'은 두 변수가 같은 데이터를 가리키는 것을 의미하며, 아무것도 복사하지 않습니다. 참조에 대해서 알아보려면, 참조 설명을 읽어보십시오. PHP 5부터, 객체는 명시적으로 새로운 것을 만드는 clone 키워드를 사용하지 않는 한 참조로 할당됩니다.



비트 연산자

비트 연산자는 정수에 있는 특정 비트를 끄거나 켤 수 있도록 합니다. 왼쪽과 오른쪽 인수가 모두 문자열이면, 비트 연산자는 문자의 아스키 값으로 연산합니다.

<?php
echo 12 9// Outputs '5'

echo "12" "9"// Outputs the Backspace character (ascii 8)
                 // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8

echo "hallo" "hello"// Outputs the ascii values #0 #4 #0 #0 #0
                        // 'a' ^ 'e' = #4

echo "3"// Outputs 1
              // 2 ^ ((int)"3") == 1

echo "2" 3// Outputs 1
              // ((int)"2") ^ 3 == 1
?>

비트 연산자
예제 이름 결과
$a & $b And $a와 $b 모두에 설정된 비트가 설정됩니다.
$a | $b Or $a나 $b에 설정된 비트가 설정됩니다.
$a ^ $b Xor $a나 $b에 설정되었지만, 양쪽에 설정되지 않은 비트.
~ $a Not $a에 설정되지 않은 비트가 설정되는, 역입니다.
$a << $b Shift left $a의 비트를 $b 단계만큼 왼쪽으로 시프트 (각 단계는 "2로 곱하기"를 의미합니다)
$a >> $b Shift right $a의 비트를 $b 단계만큼 오른쪽으로 시프트 (각 단계는 "2로 나누기"를 의미합니다)
Warning

32비트 시스템에서 32비트 초과하는 오른쪽 시프트를 하지 마십시오. 결과가 32비트를 수 넘어가는 왼쪽 시프트를 하지 마십시오.



비교 연산자

비교 연산자는 이름 그대로 두 값을 비교하도록 합니다. 자료형 비교표에서 다양한 자료형 관련 비교의 예제를 확인해 볼 수 있습니다.

비교 연산자
예제 이름 결과
$a == $b Equal $a와 $b가 같으면 TRUE.
$a === $b Identical $a와 $b가 같고, 같은 자료형이면 TRUE. (PHP 4에서 추가)
$a != $b Not equal $a가 $b와 같지 않으면 TRUE.
$a <> $b Not equal $a가 $b와 같지 않으면 TRUE.
$a !== $b Not identical $a가 $b와 같지 않거나, 같은 자료형이 아니면 TRUE. (PHP 4에서 추가)
$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.

정수를 문자열과 비교하면, 문자열이 수로 변환됩니다. 두개의 수 문자열을 비교하면, 정수로 비교됩니다. 이 규칙은 switch 구문에도 적용됩니다.

<?php
var_dump
(== "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("1" == "1e0"); // 1 == 1 -> true

switch ("a") {
case 
0:
    echo 
"0";
    break;
case 
"a"// never reached because "a" is already matched with 0
    
echo "a";
    break;
}
?>

다양한 자료형에 대해서, 비교는 다음 표에 따라 이루어집니다. (순서대로)

다양한 자료형 비교
연산수 1의 자료형 연산수 2의 자료형 결과
null이나 string string NULL을 ""로 변환, 수치나 어휘 비교
bool이나 null anything bool로 변환, FALSE < TRUE
object object 내장 클래스는 자신의 비교 함수를 정의할 수 있습니다. 다른 클래스는 비교할 수 없고, 같은 클래스는 배열과 같은 방식으로 프로퍼티를 비교합니다(PHP 4). PHP 5는 자체의 해석법을 가지고 있습니다.
string, resource, number string, resource, number 문자열과 자원을 수로 변환하여, 일반적인 수학
array array 적은 멤버를 가진 배열이 작고, 연산수 1의 키가 연산수 2에서 발견되지 않으면 배열을 비교할 수 없고, 그렇지 않으면 - 값대 값으로 비교(아래 예제를 참고)
array 모두 array가 항상 큽니다
object 모두 object가 항상 큽니다

Example #1 표준 배열 비교의 모사

<?php
// 표준 비교 연산자로 배열은 이렇게 비교합니다
function standard_array_compare($op1$op2)
{
    if (
count($op1) < count($op2)) {
        return -
1// $op1 < $op2
    
} elseif (count($op1) > count($op2)) {
        return 
1// $op1 > $op2
    
}
    foreach (
$op1 as $key => $val) {
        if (!
array_key_exists($key$op2)) {
            return 
null// uncomparable
        
} elseif ($val $op2[$key]) {
            return -
1;
        } elseif (
$val $op2[$key]) {
            return 
1;
        }
    }
    return 
0// $op1 == $op2
}
?>

참고: strcasecmp(), strcmp(), 배열 연산자, 매뉴얼 자료형 섹션.

삼항 연산자

또다른 조건부 연산자는 "?:"(삼항) 연산자입니다.

Example #2 기본값 할당하기

<?php
// 사용 예제: 삼항 연산자
$action = (empty($_POST['action'])) ? 'default' $_POST['action'];

// 위 예제는 다음의 if/else 구문과 동일합니다
if (empty($_POST['action'])) {
    
$action 'default';
} else {
    
$action $_POST['action'];
}

?>

(expr1) ? (expr2) : (expr3) 표현은 expr1TRUE이면 expr2로 평가되고, expr1FALSE이면 expr3로 평가됩니다.

PHP 5.3부터, 삼항 연산자의 중간 부분을 비울 수 있습니다. 표현식 expr1 ?: expr3expr1TRUE이면 expr1, 아니면 expr3를 반환합니다.

Note: 삼항 연산자는 구문이므로, 변수로 평가되지 않고 구문의 결과로 평가되는 점에 주의하십시오. 이 점은 참조로 변수를 반환할 때 중요합니다. 그러므로 참조로 반환하는 함수에서 return $var == 42 ? $a : $b; 구문은 작동하지 않고, 경고가 발생합니다.

Note: 삼항 연사자를 "쌓는" 일을 피하길 권합니다. 하나의 구문에서 하나를 초과하는 삼항 연산자를 사용할 때, PHP 작동은 명확하지 않습니다:

Example #3 명확하지 않은 삼항 작동

<?php
// 얼핏 보기에, 'true'를 출력할 것 같습니다
echo (true?'true':false?'t':'f');

// 그러나 위의 실제 출력은 't'입니다
// 이는 삼항 표현이 왼쪽에서 오른쪽으로 평가되기 때문입니다

// 다음이 위 코드와 동일한 더 명확한 버전입니다
echo ((true 'true' 'false') ? 't' 'f');

// 여기서, 첫 표현이 'true'로 평가되고, 이것이
// (bool)true로 전환되어 평가된 후, 두번째
// 삼항 표현의 true쪽을 반환합니다.
?>




오류 제어 연산자

PHP는 하나의 오류 제어 연산자를 지원합니다: at 부호(@). PHP 표현의 앞에 덧붙이면, 그 표현에서 생성되는 모든 오류 메세지를 무시합니다.

track_errors 기능을 켜면, 표현이 생성한 모든 오류 메세지는 $php_errormsg 변수에 저장됩니다. 이 변수는 각 오류마다 덮어씌워지므로, 사용하려면 일찍 확인하십시오.

<?php
/* Intentional file error */
$my_file = @file ('non_existent_file') or
    die (
"Failed opening file: error was '$php_errormsg'");

// this works for any expression, not just functions:
$value = @$cache[$key]; 
// will not issue a notice if the index $key doesn't exist.

?>

Note: @ 연산자는 표현에만 작용합니다. 간단한 규칙으로: 어떠한 값을 얻을 수 있으면, @를 붙일 수 있습니다. 즉, 변수, 함수, include() 호출, 상수 등에 붙일 수 있습니다. 함수 정의, 클래스 정의, ifforeach 같은 조건부 구문 등에는 붙일 수 없습니다.

error_reporting()과 매뉴얼 오류 다루기와 기록 함수 섹션을 참고하십시오.

Warning

현재 "@" 오류 제어 연산자는 스크립트 실행을 종료하는 치명적인 오류에 대한 오류 보고도 꺼버립니다. 즉, "@"를 어떠한 함수에서 오류를 제거하려고 사용하였을 때, 그 함수가 존재하지 않거나, 오타를 내면 그 위치에서 아무런 이유를 알려주는 지시도 없이 스크립트가 종료됩니다.



실행 연산자

PHP는 하나의 실행 연산자를 지원합니다: 역따옴표(``). 홑따옴표가 아닌 점에 주의하십시오! PHP는 역따옴표 안의 내용을 쉘 명령으로 실행하려 할 것입니다; 출력을 반환합니다. (즉, 단순히 출력하는 것이 아닙니다; 변수에 할당할 수 있습니다) 역따옴표 연산자를 사용하는 것은 shell_exec()와 동일합니다.

<?php
$output 
= `ls -al`;
echo 
"<pre>$output</pre>";
?>

Note: 역따옴표 연산자는 안전 모드가 켜져있거나 shell_exec()가 비활성화 되면 사용할 수 없습니다.

매뉴얼 프로그램 실행 함수 섹션, popen(), proc_open(), PHP를 명령줄에서 사용하기를 참고하십시오.



증가/감소 연산자

PHP는 C 형식의 사전, 사후 증가 및 감소 연산자를 지원합니다.

Note: 증가/감소 연산자는 논리 값에 영향을 주지 않습니다. NULL 값을 감소하는 것도 영향이 없지만, 증가시키면 1이 됩니다.

증가/감소 연산자
예제 이름 효과
++$a Pre-increment $a를 1 증가하고, $a를 반환.
$a++ Post-increment $a를 반환하고, $a를 1 증가.
--$a Pre-decrement $a를 1 감소하고, $a를 반환.
$a-- Post-decrement $a를 반환하고, $a를 1 감소.

간단한 예제 스크립트입니다:

<?php
echo "<h3>Postincrement</h3>";
$a 5;
echo 
"Should be 5: " $a++ . "<br />\n";
echo 
"Should be 6: " $a "<br />\n";

echo 
"<h3>Preincrement</h3>";
$a 5;
echo 
"Should be 6: " . ++$a "<br />\n";
echo 
"Should be 6: " $a "<br />\n";

echo 
"<h3>Postdecrement</h3>";
$a 5;
echo 
"Should be 5: " $a-- . "<br />\n";
echo 
"Should be 4: " $a "<br />\n";

echo 
"<h3>Predecrement</h3>";
$a 5;
echo 
"Should be 4: " . --$a "<br />\n";
echo 
"Should be 4: " $a "<br />\n";
?>

PHP는 문자 변수에 계산 연산을 할 경우, C가 아닌 펄의 규정을 따릅니다. 예를 들면, 펄에서 'Z'+1은 'AA'가 되지만, C에서 'Z'+1은 '['( ord('Z') == 90, ord('[') == 91)입니다. 문자 변수는 증가만 할 수 있고, 감소는 할 수 없으며, 아스키 알파벳 문자(a-z와 A-Z)만 지원합니다.

Example #1 문자 변수에 계산 연산

<?php
$i 
'W';
for (
$n=0$n<6$n++) {
    echo ++
$i "\n";
}
?>

위 예제의 출력:

X
Y
Z
AA
AB
AC

논리값에 대한 증가나 감소는 영향이 없습니다.



논리 연산자

논리 연산자
예제 이름 결과
$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" 연산자가 두 종류가 있는 것은, 다른 우선권을 가지기 때문입니다. (연산자 우선권 참고)

Example #1 논리 연산자 설명

<?php

// foo() will never get called as those operators are short-circuit
$a = (false && foo());
$b = (true  || foo());
$c = (false and foo());
$d = (true  or  foo());

// "||" has a greater precedence than "or"
$e false || true// $e will be assigned to (false || true) which is true
$f false or true// $f will be assigned to false
var_dump($e$f);

// "&&" has a greater precedence than "and"
$g true && false// $g will be assigned to (true && false) which is false
$h true and false// $h will be assigned to true
var_dump($g$h);
?>

위 예제의 출력 예시:

bool(true)
bool(false)
bool(false)
bool(true)


문자열 연산자

두 개의 string 연산자가 있습니다. 첫번째는 연결 연산자('.')로, 오른쪽과 왼쪽 인수의 연결을 반환합니다. 두번째는 연결 할당 연산자('.=')로, 오른쪽 인수를 왼쪽 인수에 덧붙입니다. 자세한 정보는 할당 연산자를 참고하십시오.

<?php
$a 
"Hello ";
$b $a "World!"// now $b contains "Hello World!"

$a "Hello ";
$a .= "World!";     // now $a contains "Hello World!"
?>

매뉴얼 문자열형문자열 함수 섹션을 참고하십시오.



배열 연산자

배열 연산자
예제 이름 결과
$a + $b Union $a와 $b의 합집합.
$a == $b Equality $a와 $b가 동일한 키/값 쌍을 가지면 TRUE.
$a === $b Identity $a와 $b가 동일한 키/값 쌍을 동일한 순서와 동일한 자료형으로 가지면 TRUE.
$a != $b Inequality $a가 $b와 같지 않으면 TRUE.
$a <> $b Inequality $a가 $b와 같지 않으면 TRUE.
$a !== $b Non-identity $a가 $b와 동일하지 않으면 TRUE.

+ 연산자는 오른쪽 배열에서 왼쪽 배열로 키를 유지하며 원소를 덧붙입니다. 중복되는 키를 덮어쓰지 않습니다.

<?php
$a 
= array("a" => "apple""b" => "banana");
$b = array("a" => "pear""b" => "strawberry""c" => "cherry");

$c $a $b// Union of $a and $b
echo "Union of \$a and \$b: \n";
var_dump($c);

$c $b $a// Union of $b and $a
echo "Union of \$b and \$a: \n";
var_dump($c);
?>

실행하면, 위 스크립트는 다음을 출력합니다:

Union of $a and $b:
array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(6) "cherry"
}
Union of $b and $a:
array(3) {
  ["a"]=>
  string(4) "pear"
  ["b"]=>
  string(10) "strawberry"
  ["c"]=>
  string(6) "cherry"
}

동일한 키와 값을 가지고 있으면, 비교할 때 같은 배열 원소입니다.

Example #1 비열 비교하기

<?php
$a 
= array("apple""banana");
$b = array(=> "banana""0" => "apple");

var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>

매뉴얼 배열형배열 함수 섹션을 참고하십시오.



자료형 연산자

instanceof는 PHP 변수가 어떤 클래스에서 생성된 객체인지 확인할 때 사용합니다:

Example #1 클래스에 instanceof 사용하기

<?php
class MyClass
{
}

class 
NotMyClass
{
}
$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof NotMyClass);
?>

위 예제의 출력:

bool(true)
bool(false)

instanceof는 변수가 부모 클래스에서 상속받은 클래스인지 확인할 때도 사용할 수 있습니다:

Example #2 상속 클래스에 instanceof 사용하기

<?php
class ParentClass
{
}

class 
MyClass extends ParentClass
{
}

$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof ParentClass);
?>

위 예제의 출력:

bool(true)
bool(true)

객체가 클래스의 인스턴스가 아닌지 확인하려면, 논리 not 연산자를 사용할 수 있습니다.

Example #3 객체가 클래스의 인스턴스가 아닌지 확인하기 위해 instanceof 사용하기

<?php
class MyClass
{
}

$a = new MyClass;
var_dump(!($a instanceof stdClass));
?>

위 예제의 출력:

bool(true)

마지막으로, instanceof는 변수가 인터페이스를 구현한 클래스의 객체 인스턴스인지 확인하기 위해 사용할 수 있습니다:

Example #4 클래스에 instanceof 사용하기

<?php
interface MyInterface
{
}

class 
MyClass implements MyInterface
{
}

$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof MyInterface);
?>

위 예제의 출력:

bool(true)
bool(true)

보통 instanceof를 문자 클래스명에 사용하지만, 다른 객체나 문자열 변수와도 사용할 수 있습니다:

Example #5 다른 변수와 instanceof 사용하기

<?php
interface MyInterface
{
}

class 
MyClass implements MyInterface
{
}

$a = new MyClass;
$b = new MyClass;
$c 'MyClass';
$d 'NotMyClass';

var_dump($a instanceof $b); // $b is an object of class MyClass
var_dump($a instanceof $c); // $c is a string 'MyClass'
var_dump($a instanceof $d); // $d is a string 'NotMyClass'
?>

위 예제의 출력:

bool(true)
bool(true)
bool(false)

주의해야할 함정이 있습니다. PHP 5.1.0 이전에, instanceof는 클래스명이 존재하지 않으면 __autoload()를 호출했습니다. 추가로, 클래스가 적재되지 않으면 치명적인 오류가 발생했습니다. 이는 동적 클래스 참조를 사용하거나, 클래스명을 가지는 문자열 변수로 해결할 수 있습니다:

Example #6 PHP 5.0 intanceof에서 클래스명 찾기와 치명적인 오류 피하기

<?php
$d 
'NotMyClass';
var_dump($a instanceof $d); // no fatal error here
?>

위 예제의 출력:

bool(false)

instanceof 연산자는 PHP 5에서 추가되었습니다. 이전에는 is_a()가 사용되었지만, is_a()instanceof의 기능으로 인해 배제되었습니다. PHP 5.3.0부터 is_a()는 배제되지 않게 되었습니다.

참고: get_class(), is_a().




제어 구조

Table of Contents


소개

모든 PHP 스크립트는 연속적인 구문으로 이루어진다. 하나의 구문은 지정문 이 될수도 있고, 함수 호출, 반복문, 조건문이 될수 있으며 심지어는 아무 내용이 없는 빈 문장일수도 있다. 한 구문은 보통 세미콜론(;)으로 끝난다. 또한 여러개의 구문을 중괄호({,})를 사용하여 하나의 그룹으로 만들어 사용할 수도 있다. 이 구문 그룹은 그 그룹의 모든 구문들이 하나의 구문인 것처럼 인식된다. 이 장에서는 여러 가지 구문형태에 대해 알아본다.



if

if문은 PHP를 포함해서 모든 언어에 있어서 가장 중요한 기능 중 하나이다. 이 제어문으로 각각 다른 코드에 대해 조건적인 수행을 가능케한다. if문의 기능은 C와 비슷하다:

if (expr)
    statement

표현식에 관한 섹션에서 설명된것처럼 expr은 논리(Boolean)값으로 취급된다. exprTRUE와 같다면 PHP는 statement를 수행할것이고, FALSE라면 무시될것이다. 무슨값이 FALSE인지 알려면 '논리값으로 변환하기' 섹션을 참고한다.

다음 예는 $a$b보다 크다면 a는 b보다 크다를 출력할 것이다.

<?php
if ($a $b)
    echo 
"a는 b보다 크다";
?>

종종 하나 이상의 구문을 조건적으로 수행시켜야 하는 때가 있다. 물론 if절로 각 구문을 감싸줄 필요는 없다. 대신, 구문 그룹안에 몇개의 구문을 그룹화할 수 있다. 예를 들면, 이코드는 $a$b보다 크다면 a는 b보다 크다라고 출력할것이고, $a의 값을 $b로 지정하게 될것이다.

<?php
if ($a $b) {
    echo 
"a는 b보다 크다";
    
$b $a;
}
?>

If문은 다른 if문안에 무한정으로 내포될수 있다. 이와 같은 기능은 프로그램의 여러부분을 조건적으로 수행하기 위한 유연성을 제공한다.



else

가끔은 특정 조건에 맞을때 구문을 수행하지 않고, 조건과 맞지 않을 때 다른 구문을 수행하게 하고 싶은 때가 있다. else 문은 이 목적을 위한 것이다. if문 다음의 else문은 if구문안의 표현식이 FALSE일때 수행된다. 예를 들면, 다음 코드는 $a$b보다 크다면 a는 b보다 크다 를 출력할것이고, 그렇지않다면 a는 b보다 크지 않다를 출력할것이다:

<?php
if ($a $b) {
    echo 
"a는 b보다 크다";
} else {
    echo 
"a는 b보다 크지 않다";
}
?>

else문은 if문이 FALSE일때만 수행이 된다. 그리고 그들 모두 FALSE값이 될수있다면 elseif문 을 쓸수 있다. (elseif를 참고)



elseif/else if

elseif, 이 이름에서 알수 있듯이, ifelse의 조합이다. else처럼 이 구문은 if절 다음에 와서 원래 if표현식이 FALSE와 같은 경우에 다른 구문을 수행한다. 그러나, else와는 달리 elseif조건 표현식이 TRUE일 때만 대체 표현식을 수행할것이다. 예를 들면 다음 코드는 a는 b보다 크다, a는 b와 같다a는 b보다 작다을 출력할것이다.

<?php
if ($a $b) {
    echo 
"a는 b보다 크다";
} elseif (
$a == $b) {
    echo 
"a는 b와 같다";
} else {
    echo 
"a는 b보다 작다";
}
?>

같은 if절 안에 몇개의 elseif절이 존재할수 있다. 가장 먼저 TRUE가 되는 elseif표현식이 수행될것이다. PHP에서는 'else if' (두 단어)로 쓸수 있고 'elseif' (한 단어) 와 방식은 같다. 문장적(syntactic)으로는 다르다 (C에 익숙하다면, 이것은 같은 방식이다) 그러나 그 둘 모두 완전히 같은 결과를 보여줄것이다.

elseif절은 선행 if 표현식과 다른 elseif표현식이 FALSE이고, 이 elseif표현식이 TRUE일때만 수행된다.

Note: elseifelse if은 위 예제처럼 대괄호를 사용할 때 정확히 같은 구문으로 간주됩니다. if/elseif 조건을 콜론을 사용해서 정의할 때, else if 처럼 두 단어로 나눠서는 안됩니다. PHP는 처리 오류로 실패합니다.

<?php

/* 부적합한 방법: */
if($a $b):
    echo 
$a." is greater than ".$b;
else if(
$a == $b): // 컴파일 되지 않습니다.
    
echo "위 줄은 처리 오류를 일으킵니다.";
endif;


/* 적합한 방법: */
if($a $b):
    echo 
$a." is greater than ".$b;
elseif(
$a == $b): // 단어가 붙어 있는 점에 주의.
    
echo $a." equals ".$b;
else:
    echo 
$a." is neither greater than or equal to ".$b;
endif;

?>



제어 구조의 대체 문법

PHP는 제어 구조를 위해 대체 문법을 제공한다; 즉 if, while, for, foreach, 그리고 switch. 각 경우에 대체 문법의 기본형태는 괄호열기를 콜른 (:)으로 대체하고 괄호닫기는 각각 endif;, endwhile;, endfor;, endforeach;, 또는 endswitch;으로 대체한다.

<?php if ($a == 5): ?>
A는 5와 같다
<?php endif; ?>

위 예에서는 대체 문법으로 쓰여진 if구문안에 "A는 5와 같다" HTML 블록이 포함되어있다. 이 HTML 블록은 $a가 5와 같을때만 출력될것이다.

대체 문법은 elseelseif문에도 적용이 된다. 다음은 elseifelse문 과 같이 있는 if문 절의 대체 형태이다:

<?php
if ($a == 5):
    echo 
"a는 5와 같다";
    echo 
"...";
elseif (
$a == 6):
    echo 
"a는 6과 같다";
    echo 
"!!!";
else:
    echo 
"a는 5도 아니고 6도 아니다";
endif;
?>

더 많은 예는while, forif섹션에 있다.



while

while는 PHP에서 제일 간단한 루프형이다. C와 똑같은 방식으로 동작한다. while문의 기본적인 형태는 다음과 같다:

while (expr)
    statement

while문의 의미는 단순하다. while 표현식이 계속 TRUE이면, PHP에게 내포되어있는 구문(들)을 반복 수행하도 록 하라는것이다. 표현식의 값은 루프의 시작에서 매번 체크가 된다. 그래서 이 표현식 값이 내포된 구문(들)의 수행동안에 바뀔지라도 반복(iteration) 의 끝이 아니면 수행은 끝나지 않게 된다.(루프에서 PHP가 구문을 한번수행 할때 한번 반복(iteration)이다) 시작된지 얼마안되어 while표현식이 FALSE로 판명되면, 내포된 구문(들)은 즉시 수행을 멈출것이다.

if문과 마찬가지로 중괄호나 대체문법을 사용하여 구문의 그룹을 둘러쌈으로써 while루프 안에 여러 구문을 그룹화할 수 있다.

while (expr):
    statement
    ...
endwhile;

다음 예는 모두 동일하다. 둘다 1부터 10까지의 숫자를 출력한다:

<?php
/* example 1 */

$i 1;
while (
$i <= 10) {
    echo 
$i++;  /* 출력하는 값은 증가하기
                   전의 $i입니다.
                   (post-increment) */
}

/* example 2 */

$i 1;
while (
$i <= 10):
    echo 
$i;
    
$i++;
endwhile;
?>



do-while

do-while 루프는 시작부분이 아니라 각 반복(iteration)의 끝부분에서 표현식이 참인지 체크한다는것을 제외하고 while루프와 매우 비슷하다. 일반적인 while문과의 주요한 차이점은 do-while문의 첫번째 반복이 반드시 수행된다는것이다 (반복의 끝부분에서 표현식이 참인지 체크한다), 이와 같은 경우는 일반 while루프로 수행시킬수 없을것이다. (while루프에서는 각 반복의 시작부분에서 표현식이 참인지 체크되고, 시작부터 바로 그 값이 FALSE이면 그 루프는 즉시 수행을 멈추게 된다)

다음에 do-while루프의 한가지 문법을 보인다:

<?php
$i 
0;
do {
   echo 
$i;
} while (
$i 0);
?>

위 루프는 정확히 한번 수행된다. 첫번째 반복(iteration) 이후에 표현식이 참인지 체크할때, FALSE가 되므로 ($i는 0보다 크지 않다) 루프 수행이 멈춘다.

고급 C 유저는 do-while루프의 다른 사용법에 익숙할것이다. 즉, do-while (0)으로 감싸고, break절을 사용하여 코드 블록의 중간에서 수행을 멈출수 있습니다. 다음 코드 예는 이런 경우를 보여준다:

<?php
do {
    if (
$i 5) {
        echo 
"i는 충분히 크지 않다";
        break;
    }
    
$i *= $factor;
    if (
$i $minimum_limit) {
        break;
    }
    echo 
"i is ok";

    
/* process i */

} while (0);
?>

이 코드를 바로 또는 전혀 이해할수 없다고 걱정하지 마라. 이런 '기능'을 사용하지 않고도 일반 스크립트나 심지어 훌륭한 스크립트를 작성할 수 있다.



for

for루프는 PHP에서 제일 복잡한 루프이다. C와 똑같은 방식으로 동작한다. for루프의 문법은 다음과 같다:

for (expr1; expr2; expr3)
    statement

첫번째 표현식(expr1)은 루프의 시작에서 바로 조건없이 평가된다 (수행된다).

각 반복(iteration)의 시작부분에서 expr2이 평 가된다. 이 표현식이 TRUE이면 루프는 계속되고 내포된 구문(들)이 수행된다. FALSE이면, 루프 수행을 멈춘다.

expr3표현식은 각 반복의 끝부분에서 평가된다 (수행된다).

각 표현은 비어있거나 콤마로 구분한 여러 표현을 가질 수 있습니다. expr2에서, 콤마로 구분한 표현은 모두 평가되지만 결과는 마지막 부분에서만 가져옵니다. expr2이 비어있다는 것은 루프가 무제한 수행되어야 한다는 것을 의미한다 (PHP는 C처럼 TRUE로 인식) 이런 기법은 생각처럼 필요없지는 않다. 왜냐 하면 종종 for문의 표현식 대신에 break문으로 루프를 끝낼 필요가 있기 때문이다.

다음 예제 코드들을 보세요. 이 코드 모두 1부터 10까지의 숫자를 출력한다:

<?php
/* 예제 1 */

for ($i 1$i <= 10$i++) {
    echo 
$i;
}

/* 예제 2 */

for ($i 1; ; $i++) {
    if (
$i 10) {
        break;
    }
    echo 
$i;
}

/* 예제 3 */

$i 1;
for (; ; ) {
    if (
$i 10) {
        break;
    }
    echo 
$i;
    
$i++;
}

/* 예제 4 */

for ($i 1$j 0$i <= 10$j += 1, print $i$i++);
?>

물론, 첫번째 예제(혹은 네번째) 코드가 가장 좋은 방법이다. 그러나 for루프에서 빈 표현식을 사용해야 하는 경우도 부딪히게 될것이다.

PHP는 for루프에 대한 대체 "콜른 문법"을 지원한다.

for (expr1; expr2; expr3):
    statement
    ...
endfor;

많은 사용자가 아래 예제처럼 배열을 탐색합니다.

<?php
/*
 * 이 배열은 루프를 도는 동안
 * 변경할 데이터를 가지고 있습니다.
 */
$people = Array(
        Array(
'name' => 'Kalle''salt' => 856412),
        Array(
'name' => 'Pierre''salt' => 215863),
        );

for(
$i 0$i sizeof($people); ++$i)
{
    
$people[$i]['salt'] = rand(000000999999);
}
?>

문제는 두번째 표현식입니다. 이 코드는 매 실행마다 배열의 크기를 계산하기 때문에 느려집니다. 크기는 변하지 않기 때문에, 크기를 저장하는 중간 변수를 사용하여 루프를 돌리도록 최적화 할 수 있습니다. 아래 예제가 보여줍니다:

<?php
$people 
= Array(
        Array(
'name' => 'Kalle''salt' => 856412),
        Array(
'name' => 'Pierre''salt' => 215863),
        );
 
for(
$i 0$size sizeof($people); $i $size; ++$i)
{
    
$people[$i]['salt'] = rand(000000999999);
}
?>



foreach

PHP 4는 펄이나 다른 언어처럼 foreach구문을 지원합니다. 이런 구문은 간단하게 배열에 대한 작업을 수행하는 가장 쉬운 기법입니다. foreach는 배열에서만 작동하고 다른 데이터형을 갖는 변수나 초기화되지 않은 변수에 대해서 이 구문을 사용하려한다면 에러 메시지를 만날것입니다. 이 구문은 두가지 문법이 있습니다; 두번째보다는 첫번째문법이 더 유용한 사용법입니다:

foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement

첫번째 형태는 array_expression에서 주어진 배열에 대해 루프를 돈다. 각 루프에서 현재 배열 원소의 값은 $value 로 지정되고 내부적인 배열 포인터는 하나씩 이동하게 된다 (그래서 다음 루프에서 다음 배열 원소를 보게 될것이다)

두번째 루프도 같은 일을 한다. 단 현재 배열 원소의 키(key)값은 각 루프의 $key변수로 지정된다.

PHP 5부터 객체 순환도 할 수 있습니다.

Note: foreach문이 처음 실행할때, 내부적인 배열 포인터는 자동적으로 배열의 첫번째 원소로 리셋된다. 따라서 foreach절 이전에 reset()함수를 호출할 필요는 없다.

Note: 배열이 참조되지 않는 이상, foreach는 지정한 배열 자체가 아닌 복사한 배열을 대상으로 작동합니다. foreach는 배열 포인터에 영향이 있습니다. foreach 도중이나 이후에는 리셋하지 않은 배열 포인터에 의존하지 마십시오.

PHP 5부터, $value 앞에 &를 붙여서 배열 원소를 쉽게 변경할 있습니다. 값을 복사하지 않고 참조합니다.

<?php
$arr 
= array(1234);
foreach (
$arr as &$value) {
    
$value $value 2;
}
// $arr은 이제 array(2, 4, 6, 8)입니다.
unset($value); // 마지막 원소로 참조를 제거합니다.

이는 반복할 배열을 참조할 수 있을 때(즉, 변수)만 가능합니다.

Warning

$value 참조와 마지막 배열 원소는 foreach 루프 뒤에도 남아 있습니다. unset()으로 제거하는 것을 권합니다.

Note: foreach는 '@'를 사용해서 에러메시지를 출력하지 못하도록 할 수 없습니다.

다음 예는 기능적으로 동일하다는것을 알 필요가 있다:

<?php
$arr 
= array("하나""둘""셋");
reset($arr);
while (list(, 
$value) = each($arr)) {
    echo 
"값: $value<br />\n";
}

foreach (
$arr as $value) {
    echo 
"값: $value<br />\n";
}
?>

다음 예도 기능적으로 동일하다:

<?php
$arr 
= array("하나""둘""셋");
reset($arr);
while (list(
$key$value) = each($arr)) {
    echo 
"키: $key; 값: $value<br />\n";
}

foreach (
$arr as $key => $value) {
    echo 
"키: $key; 값: $value<br />\n";
}
?>

더 많은 예제 코드들이 사용법에 대해서 설명해준다:

<?php
/* foreach 예제 1: 값만 */

$a = array(12317);

foreach (
$a as $v) {
   echo 
"\$a의 현재 값: $v.\n";
}

/* foreach 예제 2: 값 (표시를 위해 수동으로 접근 순서를 출력) */

$a = array(12317);

$i 0/* 가상 목적으로만 사용 */

foreach ($a as $v) {
    echo 
"\$a[$i] => $v.\n";
    
$i++;
}

/* foreach 예제 3: 키와 값 */

$a = array(
    
"one" => 1,
    
"two" => 2,
    
"three" => 3,
    
"seventeen" => 17
);

foreach (
$a as $k => $v) {
    echo 
"\$a[$k] => $v.\n";
}

/* foreach 예제 4: 다차원 배열 */

$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach (
$a as $v1) {
    foreach (
$v1 as $v2) {
        echo 
"$v2\n";
    }
}

/* foreach 예제 5: 동적 배열 */

foreach (array(12345) as $v) {
    echo 
"$v\n";
}
?>



break

break는 현재 for, foreach, while, do-while 또는 switch절의 수행을 멈춘다.

break는 숫자 인수 옵션을 허용함으로써 내포된 구문구조의 깊이를 표시하고 거기서 빠져나올수 있게 해준다.

<?php
$arr 
= array('one''two''three''four''stop''five');
while (list (, 
$val) = each ($arr)) {
    if (
$val == 'stop') {
        break;    
/* 여기서는 'break 1;'으로 슬 수 있습니다. */
    
}
    echo 
"$val<br />\n";
}

/* 옵션 인수 사용하기. */

$i 0;
while (++
$i) {
    switch (
$i) {
    case 
5:
        echo 
"At 5<br />\n";
        break 
1;  /* switch만 빠져나갑니다. */
    
case 10:
        echo 
"At 10; quitting<br />\n";
        break 
2;  /* switch와 while을 빠져나갑니다. */
    
default:
        break;
    }
}
?>



continue

continue는 루프 구조 내부에서 현재 루프 반복의 나머지 부분을 생략하고 조건 평가를 한 후 다음 반복 시작에서 실행을 지속하게 합니다.

Note: PHP에서 switch구문은 continue에 의해 루프 구조로 사용할수 있다는것을 참고할것.

continue는 숫자 인수 옵션을 사용하여 루프의 깊이를 표시할수 있고, 루프의 끝까지 건너뛸수 있다.

<?php
while (list($key$value) = each($arr)) {
    if (!(
$key 2)) { // skip odd members
        
continue;
    }
    
do_something_odd($value);
}

$i 0;
while (
$i++ < 5) {
    echo 
"Outer<br />\n";
    while (
1) {
        echo 
"&nbsp;&nbsp;Middle<br />\n";
        while (
1) {
            echo 
"&nbsp;&nbsp;Inner<br/ >\n";
            continue 
3;
        }
        echo 
"This never gets output.<br />\n";
    }
    echo 
"Neither does this.<br />\n";
}
?>

continue 뒤의 세미콜론을 빼먹으면 혼란스러울 것입니다. 여기에 해서는 안되는 일의 예제입니다:

<?php
  
for ($i 0$i 5; ++$i) {
      if (
$i == 2)
          continue
      print 
"$i\n";
  }
?>

기대했던 결과는:

0
1
3
4

하지만 스크립트의 출력은:

2

print() 호출의 반환값은 int(1)이기 때문에, 위에서 언급한 선택적인 수 인수로 간주합니다.



switch

switch구문은 연속적인 같은 표현식을 갖는 연속적인 IF구문과 비슷하다. 많은 경우, 하나의 변수(또는 표현식)으로 다른 많은 값과 비교할 필요가 있으며, 그 값이 동일한 코드의 파편들을 수행할 필요가 생기게 된다. 정확히 이런 목적을 위해 switch구문이 사용된다.

Note: 다른 언어와는 달리 continue문은 switch문에서 사용할수 있고, break문과 비슷하게 동작한다. 루프 내에 switch문을 포함하고 있고 바깥 루프의 다음 반복문으로 진행하고 싶다면 continue 2를 사용한다.

Note: switch/case는 느슨한 비교를 하는 점에 주의하십시오.

다음 예제 코드들은 같은 일을 서로 다르게 표현한 것입니다. 하나는 ifelseif문을 사용한 것이고, 다른 하나는 switch문을 사용했습니다:

Example #1 switch 구조

<?php
if ($i == 0) {
    echo 
"i는 0";
} elseif (
$i == 1) {
    echo 
"i는 1";
} elseif (
$i == 2) {
    echo 
"i는 2";
}

switch (
$i) {
case 
0:
    echo 
"i는 0";
    break;
case 
1:
    echo 
"i는 1";
    break;
case 
2:
    echo 
"i는 2";
    break;
}
?>

Example #2 문자열을 사용하는 switch 구조

<?php
switch ($i) {
case 
"apple":
    echo 
"i는 apple";
    break;
case 
"bar"
    
echo "i는 bar";
    break;
case 
"cake":
    echo 
"i는 cake";
    break;
}
?>

실수하지 않기 위해 switch문이 어떻게 동작하는지 이해할 필요가 있다. switch문은 한줄씩 수행된다 (실제는, 한구문씩). 처음에는 아무 코드도 수행되지 않는다. switch 표현의 값과 일치하는 값을 가진 case 구문을 발견했을 때, PHP는 그 구분을 실행합니다. PHP는 switch블록의 끝부분이 될때까지, 또는 break문와 첫번째 조우를 할때까지 구문을 계속 수행해 간다. 만약 각 case 구문 목록의 끝부분에 break문을 쓰지않는다면 PHP는 다음 case문으로 계속 진행하게 된다. 예를 들면 다음과 같다:

<?php
switch ($i) {
case 
0:
    echo 
"i는 0과 같다";
case 
1:
    echo 
"i는 1과 같다";
case 
2:
    echo 
"i는 2와 같다";
}
?>

여기에서, $i가 0이라면, PHP는 모든 echo문을 실행합니다! $i가 1이라면, PHP는 마지막 두 echo문을 실행합니다. $i가 2일 때만, 원하는 동작('i는 2와 같다' 표시)을 합니다. 따라서, break을 잊어서는 안됩니다. (어떤 경우에는 일부러 빠트릴 수 있어도, 잊지 마십시오)

switch구문에서, 조건문은 오직 한번만 평가되고 각 case문에서 결과가 비교되어진다. elseif문에서는 조건문은 다시 평가된다. 조건문이 한번 이상의 비교가 필요한 복잡한 것이거나 거친(tight) 루프안에 있다면 switch문 좀 더 빠를것이다.

case에 대한 구문 목록은 비어있을수 있다. 이것은 단순히 다음 case문으로 제어권을 넘겨줄 뿐이다.

<?php
switch ($i) {
case 
0:
case 
1:
case 
2:
    echo 
"i는 3보다 작지만 음수는 아닙니다.";
    break;
case 
3:
    echo 
"i는 3";
}
?>

특별한 case가 바로 default case문이다. 이것은 다른 case문과 모두 조건이 맞지 않을때의 경우를 위한 것입니다. 예를 들면:

<?php
switch ($i) {
case 
0:
    echo 
"i는 0과 같다";
    break;
case 
1:
    echo 
"i는 1과 같다";
    break;
case 
2:
    echo 
"i는 2와 같다";
    break;
default:
    echo 
"i는 0, 1, 2 어느것도 아니다";
}
?>

case의 표현식은 정수나 부동소수점 수와 문자열같은 단순형으로 평가되는 어던 표현식도 될수 있다. 여기에 단순형으로 재참조(dereference)되지 않는 배열이나 객체를 사용할수는 없다.

switch문을 위한 제어 구조의 대체 문법이 지원된다. 더 자세한 정보는 제어 구조의 대체 문법을 참고.

<?php
switch ($i):
case 
0:
    echo 
"i equals 0";
    break;
case 
1:
    echo 
"i equals 1";
    break;
case 
2:
    echo 
"i equals 2";
    break;
default:
    echo 
"i is not equal to 0, 1 or 2";
endswitch;
?>

case 뒤에 세미콜론 대신 콜론을 쓸 수 있습니다:

<?php
switch($beer)
{
    case 
'tuborg';
    case 
'carlsberg';
    case 
'heineken';
        echo 
'Good choice';
    break;
    default;
        echo 
'Please make a new selection...';
    break;
}
?>



declare

declare구문은 코드 블록의 수행 지시어를 활성화하기 위해 사용된다. declare문법은 다른 흐름 제어 구조의 문법과 비슷하다:

declare (directive) statement

directive 부분은 declare 블록의 동작을 활성화합니다. 현재는 두 지시어만 인식합니다: ticks 지시어(자세한 정보는 아래 ticks 지시어 참고)와 encoding 지시어(자세한 정보는 아래 encoding 지시어 참고).

Note: encoding 지시어는 PHP 5.3.0에서 추가되었습니다.

declare블록의 statement부분이 수행될것이다 - 어떻게 수행이 되고 수행중에 어떤 사이드 이펙트가 발생할지는 directive블록의 디렉티브에 달려있다.

declare 구문은 전역 유효영역 안에서 사용할수 있다. 그래서 모든 코드가 그 디렉티브에 영향을 받는다. (그러나 declare가 있는 파일을 포함하였을 때에는 원 파일에는 영향을 주지 않습니다)

<?php
// 이들은 동일합니다:

// 이를 사용할 수 있습니다:
declare(ticks=1) {
    
// 여기에 전체 스크립트
}

// 또는 이렇게 사용할 수 있습니다:
declare(ticks=1);
// 여기에 전체 스크립트
?>

틱(Ticks)

Caution

PHP 5.3.0부터 틱은 배제되었고, PHP 6.0.0에서 제거될 예정입니다.

틱은 declare블록에서 파서에 의해 수행되는 N 저레벨(low-level) 구문마다 발생하는 이벤트이다. N 값은 declare블록의 directive부분에서 ticks=N 으로 지정할수 있다.

각 틱에서 발생하는 이벤트(들)은 register_tick_function()함수 를 써서 지정한다. 자세한 것은 아래 예제를 볼것. 각 틱에서는 하나 이상의 이벤트가 발생할수 있음에 주의해야 한다.

Example #1 PHP 각 코드 섹션의 분석표만들기(Profile)

<?php
// 호출될대의 시간을 기록하는 함수
function profile($dump FALSE)
{
    static 
$profile;

    
// Profile에 저장된 모든 시간 리턴하고, 삭제함
    
if ($dump) {
        
$temp $profile;
        unset(
$profile);
        return 
$temp;
    }

    
$profile[] = microtime();
}

// 틱 핸들러 설정
register_tick_function("profile");

// declare 블록 전에 함수를 초기화
profile();

// 코드 블록의 실행하고, 두번째 구문에 틱을 부여함
declare(ticks=2) {
    for (
$x 1$x 50; ++$x) {
        echo 
similar_text(md5($x), md5($x*$x)), "<br />;";
    }
}

// 분석표에 저장된 데이터를 출력
print_r(profile(TRUE));
?>

위 예제 코드는 실행 블록안의 두번째 저레벨(low-level) 구문의 시간에 따라 'declare'블록 안의 PHP코드를 분석한다. 이런 정보로 어느 코드 부분에서 느려지는지 알아볼 수 있다. 이런 처리방법은 다른 기법으로 수행할수있다: 틱을 이용하는 것은 좀더 편하고 좀더 구현하기 쉽다.

틱은 디버깅, 단순한 멀티태스킹 구현, 백그라운드 I/O와 다른 많은 작업 에 적합하게 이용할수 있다.

register_tick_function()함수와 unregister_tick_function()함수를 참고하세요.

인코딩

encoding 지시어를 사용하여 스크립트 별로 지정할 수 있는 인코딩입니다.

Example #2 스크립트의 인코딩 선언하기

<?php
declare(encoding='ISO-8859-1');
// code here

Caution

이름공간과 결합할 때, declare의 적합한 문법은 declare(encoding='...'); 뿐입니다. (...은 인코딩 값) 이름공간과 결합했을 때, declare(encoding='...') {}은 해석 오류를 발생합니다.

PHP 5.3에서는 PHP가 --enable-zend-multibyte로 컴파일 되지 않았을 경우, encoding 선언 값이 무시됩니다. PHP 6.0에서는, encoding 지시어가 파일이 생성된 인코딩을 스캐너에게 알려줍니다. 적절한 값은 UTF-8 등의 인코딩 이름입니다.



return

return()문이 함수안에서 호출된다면, 현재 함수의 수행을 즉시 끝내고, 함수 호출 결과값으로 return의 인수값을 넘겨준다. return()문은 eval()함수나 스크립트 파일의 수행을 종료시킨다.

전역 유효범위에서 호출된다면, 현재 스크립트 파일의 수행을 끝마친다. 현재 스크립트가 include()require()되었다면, 호출하고 있는 파일로 제어를 넘긴다. 더욱이, 현재 스크립트 파일이 include()되어있는것이면, return()에 주어지는 값은 include()호출에 대한 값으로 넘겨줄것이다. return()이 주 스크립트 파일에서 호출되면, 스크립트의 수행이 종료된다. 현재 스크립트 파일이 php.iniauto_prepend_file이나 auto_append_file 옵션에 의해 명명되었다면, 스크립트 파일의 수행은 중단된다.

좀더 자세한 정보는 Returning values 을 참고하세요.

Note: return()은 함수가 아닌 언어 구조이기 때문에, 인수를 괄호로 쌀 필요가 없습니다. 괄호가 없는 것이 일반적으로, PHP가 더 적은 일을 하게 합니다.

Note: 반환값이 참조로 반환될 때는 절대로 괄호를 사용하면 안되며, 동작하지 않습니다. 참조는 변수만 반환할 수 있으며, 구문 결과는 반환할 수 없습니다. return ($a);를 사용한다면, 변수를 반환하지 않고 ($a) 표현의 반환값을 반환합니다. (물론, $a의 값입니다)



require()

require()는 실패시에 치명적인 E_ERROR 등급 오류가 발생한다는 점을 제외하면, include()와 동일합니다. 즉, include()가 경고(E_WARNING)만 발생하고 스크립트는 계속 진행되는 것과 달리, 스크립트가 중단됩니다.

작동에 관해서는 include() 문서를 참고하십시오.



include()

include()문은 특정 파일을 인클루드 하고, 적용시킨다.

아래 내용은 require()에도 적용됩니다. 두 구조는 수행 실패를 다루는 방법을 제외하고 완전히 동일합니다. 둘 모두 Warning을 발생시키지만, require()Fatal Error가 나타납니다. 즉, 파일이 없을 때 페이지 처리를 멈추고 싶으면 require()를 사용하면 됩니다. include()는 멈추지 않고 스크립트가 계속 실행됩니다. 또한, 적합한 include_path 설정인지 확인해야 합니다. PHP 4.3.5 이전에는 포함한 파일 안에서 해석 오류가 발생해도 수행을 멈추지 않는 점에 주의하십시오. 이 버전부터는 멈춥니다.

파일을 포함할 때는 각 include_path에 대해서 먼저 현재 작업 디렉토리에서 상대 경로를 찾고, 실행중인 스크립트가 있는 디렉토리를 찾습니다. 즉, include_path가 libraries이고, 현재 작업 디렉토리가 /www/이며, 포함한 파일 include/a.phpinclude "b.php"가 있으면, b.php는 먼저 /www/libraries/에서 찾고, 그 후에 /www/include/을 찾습니다. 파일 이름이 ./이나 ../로 시작하면, 현재 작업 디렉토리 안에서만 찾습니다.

파일이 인클루드 되면, 그 코드를 포함하는 코드는 인클루드가 발생한 줄의 변수 유효 범위를 물려받는다. 호출하는 파일의 그 줄에서 사용되는 어떤 변수도 그 줄부터는 호출된 파일안에서 사용이 가능하다. 그러나, 포함한 파일에서 선언한 모든 함수와 클래스는 전역 영역에 들어갑니다.

Example #1 기본적인 include() 사용예

vars.php
<?php

$color 
'green';
$fruit 'apple';

?>

test.php
<?php

echo "A $color $fruit"// A

include 'vars.php';

echo 
"A $color $fruit"// A green apple

?>

인클루드가 호출하는 파일안의 함수내에서 발생한다면, 호출된 파일안의 모든 코드가 그 함수에서 정의된것처럼 동작한다. 그래서, 그 함수의 변수 유효범위를 따를것이다. 이 규칙의 에외는 포함이 일어나기 전에 평가되는 마법 상수입니다.

Example #2 함수 내에서 인클루드하기

<?php

function foo()
{
    global 
$color;

    include 
'vars.php';

    echo 
"A $color $fruit";
}

/* vars.php is in the scope of foo() so     *
 * $fruit is NOT available outside of this  *
 * scope.  $color is because we declared it *
 * as global.                               */

foo();                    // A green apple
echo "A $color $fruit";   // A green

?>

파일이 인클루드되면, 파싱은 PHP모드의 밖으로 나가서 목적 파일의 시작부분은 HTML모드로 들어가게 되고, 끝부분에서 원래대로 회복된다. 이때문에, 목적 파일에서 PHP코드로서 수행되어야 하는 코드는 유효한 PHP 시작과 마침 태그 로 막아줘야 한다.

PHP에서 "URL fopen wrappers"가 활성화되어 있으면 (디폴트 설정임), URL(HTTP나 다른 지원 래퍼(wrapper) - 프로토콜 목록은 지원 프로토콜/래퍼 목록을 참고)을 사용하여 파일을 인클루드 할수 있다. 목적 서버가 목적 파일을 PHP코드로 해석한다면, HTTP GET으로 사용된 URL 리퀘스트 문자열은 변수로서 넘겨지게 될것이다. 이와같은 일은 파일을 인크루드 하고 부모 파일의 변수 유효범위를 상속하는 것과 같은 경우가 되지는 않는다. 스크립트는 실질적으로 원격 서버에서 실행이 되고 나서 로컬 스크립트에 포함된다.

Warning

PHP 4.3.0 이전의 윈도우 버전 PHP에서는 이 함수를 이용하여 원격 파일에 접근할 수 없습니다. allow_url_fopen을 활성화하여도 마찬가지입니다.

Example #3 HTTP로 include()하기

<?php

/* This example assumes that www.example.com is configured to parse .php
 * files and not .txt files. Also, 'Works' here means that the variables
 * $foo and $bar are available within the included file. */

// Won't work; file.txt wasn't handled by www.example.com as PHP
include 'http://www.example.com/file.txt?foo=1&bar=2';

// Won't work; looks for a file named 'file.php?foo=1&bar=2' on the
// local filesystem.
include 'file.php?foo=1&bar=2';

// Works.
include 'http://www.example.com/file.php?foo=1&bar=2';

$foo 1;
$bar 2;
include 
'file.txt';  // Works.
include 'file.php';  // Works.

?>

Warning

보안 경고

원격 파일은 원격 서버에서 실행(파일 확장자와 원격 서버가 PHP를 실행하는가에 따라 다릅니다)되지만, 로컬 서버에서 실행할 수 있는 유효한 PHP 스크립트를 만들 수도 있습니다. 원격 서버에서만 실행한 결과를 그대로 출력해야 한다면, readfile() 함수가 더 적합합니다. 아니라면, 원격 스크립트가 유효하고 적합한 코드를 생성하도록 특별한 주의를 기울이십시오.

참고: 원격 파일, fopen(), file()에 관련 정보가 있습니다.

반환 다루기: include한 파일 안에서 그 파일의 수행을 종료하고, 호출한 스크립트로 돌아가기 위해서 return()문을 실행할 수 있습니다. 또한, 값을 반환하는 일도 가능합니다. include 호출을 일반 함수를 사용한 것처럼 값을 받을 수 있습니다. 그러나, 원격 파일을 포함하였을 때, 그 파일의 출력이 (다른 로컬 파일처럼) 유효한 PHP 시작과 끝 태그를 가지지 않는다면 이 값을 받을 수 없습니다. 이 태그들 안에 필요한 값을 정의하면, include한 파일의 어떤 위치에서라도 사용할 수 있습니다.

include()은 특별한 언어 구조이기 때문에, 인수를 괄호로 쌀 필요가 없습니다. 반환값을 비교할 때는 조심하십시오.

Example #4 include의 반환값 비교하기

<?php
// include(('vars.php') == 'OK'), 즉 include('')로 인식하여 작동하지 않습니다.
if (include('vars.php') == 'OK') {
    echo 
'OK';
}

// 작동합니다.
if ((include 'vars.php') == 'OK') {
    echo 
'OK';
}
?>

Example #5 include()return()

return.php
<?php

$var 
'PHP';

return 
$var;

?>

noreturn.php
<?php

$var 
'PHP';

?>

testreturns.php
<?php

$foo 
= include 'return.php';

echo 
$foo// prints 'PHP'

$bar = include 'noreturn.php';

echo 
$bar// prints 1

?>

include가 성공했기 때문에 $bar의 값은 1입니다. 위 예제 사이의 차이에 주목하십시오. 처음 것은 포함한 파일 안에서 return()을 사용하였지만, 다른 것은 하지 않았습니다. 파일을 포함할 수 없으면 FALSE를 반환하고 E_WARNING을 발생합니다.

포함한 파일에서 함수를 정의하면, 어디서 return()을 했는지에 관계 없이 메인 파일에서 사용할 수 있습니다. 파일이 두번 포함되면, PHP 5는 함수가 이미 정의되어 있기 때문에 치명적인 오류를 발생하지만, PHP 4는 return() 뒤에 정의했다면 불평하지 않습니다. 이미 포함한 파일을 확인하기 위해서는 포함한 파일 안에서 조건적으로 return하기 보다는 include_once()를 사용하는 것을 권합니다.

PHP 파일을 변수로 "포함"하는 또 다른 방법은 출력 제어 함수include()와 함께 사용하여 출력을 캡쳐하는 것입니다. 예를 들면:

Example #6 PHP 파일을 포함하여 문자열로 변환하기 위해 출력 버퍼링 사용하기

<?php
$string 
get_include_contents('somefile.php');

function 
get_include_constents($filename) {
    if (
is_file($filename)) {
        
ob_start();
        include 
$filename;
        
$contents ob_get_contents();
        
ob_end_clean();
        return 
$contents;
    }
    return 
false;
}

?>

스크립트 안에 자동으로 파일을 포함하기 위해서는, php.iniauto_prepend_fileauto_append_file 설정 옵션을 참고하십시오.

Note: 이것은 함수가 아닌 언어 구조이기 때문에, 가변 함수 방식으로 호출할 수 없습니다.

참고: require(), require_once(), include_once(), get_included_files(), readfile(), virtual(), virtual(), include_path.



require_once()

require_once() 구문은 PHP가 파일을 이미 포함하였는지 확인하여 다시 include(require)하지 않는 점을 제외하면, require()와 동일합니다.

_once 동작에 대한 정보와, _once 없는 것과 어떻게 다른가에 대해서는 include_once() 문서를 참고하십시오.



include_once()

include_once()문은 스크립트 수행기간동안 특정파일을 인클루드하고 적용시킨다. 이것은 include()문과 비슷하게 동작한다. 단지 파일의 특정 코드가 이미 인클루되었다면 그 코드는 다시는 인클루드 될수 없다는 차이점만 있다. 이 이름이 제시하듯이 한번만 인클루드할것이다.

include_once()는 특정 스크립트 수행기간동안 동일한 파일이 한번 이상 인클루드되고 적용될지도 모르는 상황에서 사용해야 할것이다. 그리고 함수 중복정의, 변수값 중복 지정 등의 문제를 회피하려면 정확히 한번만 인클루드할 때가 있을것이다.

require_once()include_once()의 더 많은 사용예는, 최신 PHP 소스 내의 » PEAR코드를 참고할것.

반환값은 include()와 동일합니다. 파일이 이미 포함되었으면, TRUE를 반환합니다.

Note: include_once()는 PHP 4.0.1에서 추가됨

Note: include_once()require_once()는 대소문자를 구별하지 않는 운영체제(윈도우 등)에서 기대하지 않은 동작을 할 수 있습니다.

Example #1 include_once()는 윈도우에서 대소문자를 구분하지 못합니다.

<?php
include_once "a.php"// a.php를 포함합니다.
include_once "A.php"// 윈도우에서 또다시 a.php를 포함합니다. (PHP 4만)
?>

이 동작은 PHP 5에서 바뀌었습니다 - 경로를 표준화를 먼저 하기 때문에, C:\PROGRA~1\A.phpC:\Program Files\a.php로 인식하고, 파일을 한 번만 포함합니다.

Warning

PHP 4.3.0 이전의 윈도우 버전 PHP에서는 이 함수를 이용하여 원격 파일에 접근할 수 없습니다. allow_url_fopen을 활성화하여도 마찬가지입니다.

참고: include(), require(), require_once(), get_required_files(), get_included_files(), readfile(), virtual().



goto

The goto operator can be used to jump to another section in the program. The target point is specified by a label followed by a colon, and the instruction is given as goto followed by the desired target label. This is not a full unrestricted goto. The target label must be within the same file and context, meaning that you cannot jump out of a function or method, nor can you jump into one. You also cannot jump into any sort of loop or switch structure. You may jump out of these, and a common use is to use a goto in place of a multi-level break.

Example #1 goto example

<?php
goto a;
echo 
'Foo';
 
a:
echo 
'Bar';
?>

위 예제의 출력:

Bar

Example #2 goto loop example

<?php
for($i=0,$j=50$i<100$i++) {
  while(
$j--) {
    if(
$j==17) goto end
  }  
}
echo 
"i = $i";
end:
echo 
'j hit 17';
?>

위 예제의 출력:

j hit 17

Example #3 This will not work

<?php
goto loop;
for(
$i=0,$j=50$i<100$i++) {
  while(
$j--) {
    
loop:
  }
}
echo 
"$i = $i";
?>

위 예제의 출력:

Fatal error: 'goto' into loop or switch statement is disallowed in
script on line 2

Note: The goto operator is available as of PHP 5.3.

Image courtesy of » xkcd




함수

Table of Contents


사용자 선언 함수

다음과 같은 문법을 사용하여 함수를 선언한다:

Example #1 함수 사용을 설명하기 위한 가상 코드

<?php
function foo($arg_1$arg_2/* ..., */ $arg_n)
{
    echo 
"예제 함수.\n";
    return 
$retval;
}
?>

모든 유효 PHP코드는 특정 함수 내에서 뿐만 아니라, 여러 다른 함수나 class정의 안에서도 나타날수있다.

함수 이름은 PHP의 다른 라벨과 같은 규칙을 따릅니다. 유효한 함수 이름은 문자나 _로 시작하고, 여러 개의 문자, 숫자, _가 붙습니다. 정규 표현식으로는 다음과 같이 표현됩니다: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.

함수는 아래 두 예제처럼 조건적으로 정의할 경우를 제외하고, 참조하기 전에 정의할 필요는 없습니다.

아래 예제 코드와 같이 함수가 조건적으로 선언되면 그 함수가 호출되기 전에 함수를 선언해야 한다.

Example #2 조건적인 함수

<?php

$makefoo 
true;

/* We can't call foo() from here 
   since it doesn't exist yet,
   but we can call bar() */

bar();

if (
$makefoo) {
  function 
foo()
  {
    echo 
"I don't exist until program execution reaches me.\n";
  }
}

/* Now we can safely call foo()
   since $makefoo evaluated to true */

if ($makefoofoo();

function 
bar() 
{
  echo 
"I exist immediately upon program start.\n";
}

?>

Example #3 함수 안의 함수

<?php
function foo() 
{
  function 
bar() 
  {
    echo 
"foo()를 호출하기 전까지는 존재하지 않습니다.\n";
  }
}

/* bar()를 호출할 수 없습니다.
   아직 존재하지 않습니다. */

foo();

/* 이제 bar()를  호출할 수
   있습니다. foo()를 실행하여
   접근할 수 있게 되었습니다. */

bar();

?>

PHP의 모든 함수와 클래스는 전역입니다 - 함수가 내부에서 정의되었더라도 외부에서 호출할 수 있으며, 반대도 성립합니다.

PHP는 함수 오버로딩(overloading)을 지원하지 않으며, 함수 정의를 해제하거나 이미 선언된 함수를 다시 선언할수 없다.

Note: 함수명은 선언시에 그 함수를 호출하기 편하게 만들겠지만, 대소문자 구별을 하지 않는다.

함수에서 가변 길이 인수 목록인수 기본값을 지원합니다. 자세한 정보는 func_num_args(), func_get_arg(), func_get_args() 함수 레퍼런스를 참고하십시오.

PHP에서 재귀 함수 호출을 할 수 있습니다. 그러나 100-200 재귀 레벨을 넘어서는 함수/메쏘드 호출을 피하십시오. 스택 한계에 도달하여 현재 스크립트가 중단됩니다.

Example #4 재귀 함수

<?php
function recursion($a)
{
    if (
$a 20) {
        echo 
"$a\n";
        
recursion($a 1);
    }
}
?>



함수 인수

함수 인수를 통해서 함수에 정보를 넘겨줄수 있다. 이런 함수 인수는 콤마(,)로 구별되는 표현 목록이다.

PHP는 값에 의한 인수 전달(passing by value) (기본값), 참조에 의한 전달, 인수 기본값 기능을 지원합니다. 가변 길이 인수 목록도 지원하며, 자세한 정보는 func_num_args(), func_get_arg(), func_get_args() 함수 레퍼런스를 참고하십시오.

Example #1 함수에 배열 넘겨주기

<?php
function takes_array($input)
{
    echo 
"$input[0] + $input[1] = "$input[0]+$input[1];
}
?>

참조에 의한 인수 전달하기

기본적으로, 함수 인수는 값에 의해 전달됩니다. (그래서 함수내의 인수 변수값을 변경해도 함수 밖에서는 바뀌지 않습니다) 함수가 그 인수를 바꾸게 하려면, 참조로 넘겨줘야 합니다.

항상 함수의 인수를 참조로 넘기게 하려면, 함수 정의에서 엠퍼샌드(&)를 인수 이름 앞에 붙이면 됩니다:

Example #2 참조에 의해 함수 인수 전달하기

<?php
function add_some_extra(&$string)
{
    
$string .= 'and something extra.';
}
$str 'This is a string, ';
add_some_extra($str);
echo 
$str;    // outputs 'This is a string, and something extra.'
?>

기본 인수 값

함수는 다음과 같이 스칼라 인수에 대해 C++스타일 기본값으로 지정할수있다:

Example #3 함수에 기본 인수 사용하기

<?php
function makecoffee($type "cappuccino")
{
    return 
"Making a cup of $type.\n";
}
echo 
makecoffee();
echo 
makecoffee(null);
echo 
makecoffee("espresso");
?>

위 예제 코드의 출력은 다음과 같다:


Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.

PHP는 array와 특별형 NULL을 기본값으로 사용할 수 있습니다. 예를 들면:

Example #4 스칼라 형이 아닌 기본값 사용하기

<?php
function makecoffee($types = array("카푸치노"), $coffeeMaker NULL)
{
    
$device is_null($coffeeMaker) ? "손" $coffeeMaker;
    return 
"$device(으)로 ".join(", "$types)."를 만듭니다.\n";
}
echo 
makecoffee();
echo 
makecoffee(array("카푸치노""라바짜"), "찻주전자");
?>

기본값은 상수 표현식이 될수 있으나 (예를 들면) 변수나 클래스 멤버가 될수는 없다.

기본 인수를 사용할때에는 모든 기본값은 기본값을 쓰지 않는 인수의 오른쪽으로 가야 한다; 그렇지 않으면, 기대하던대로 작동하지 않을것이다. 다음 예제 코드를 참고:

Example #5 기본 함수 인수가 잘못 사용된 예

<?php
function makeyogurt($type "acidophilus"$flavour)
{
    return 
"Making a bowl of $type $flavour.\n";
}
 
echo 
makeyogurt("raspberry");   // won't work as expected
?>

위 예제 코드의 출력은 다음과 같다:


Warning: Missing argument 2 in call to makeyogurt() in
/usr/local/etc/httpd/htdocs/phptest/functest.html on line 41
Making a bowl of raspberry .

위 코드를 아래 코드와 비교하라:

Example #6 기본 함수 인수의 정확한 사용예

<?php
function makeyogurt($flavour$type "acidophilus")
{
    return 
"Making a bowl of $type $flavour.\n";
}
 
echo 
makeyogurt("raspberry");   // works as expected
?>

이 예제코드의 출력은 다음과 같다:


Making a bowl of acidophilus raspberry.

Note: PHP 5부터, 기본값을 참조로 넘길 수 있습니다.

가변 길이 인수 목록

PHP 4 이상에서는 사용자 선언 함수에서 가변 길이 변수 목록 기능을 지원합니다. 이 기능은 func_num_args(), func_get_arg(), func_get_args()함수를 사용하여 손쉽게 사용가능하다.

특별한 문법이 필요하지 않다. 인수 목록은 함수선언부에서 밝혀야하고 일반 인수와 동일하게 작동할것이다.



반환값

선택적인 return문을 사용하여 값을 돌려준다. 배열이나 객체를 포함하여 모든 타입을 돌려줄수있다. 이 구문에서 함수의 수행이 즉시 중단되고 현재 함수를 호출한 코드줄로 제어를 되돌린다. 자세한 정보는 return()섹션을 참고할것.

Example #1 return()의 사용예

<?php
function square($num)
{
    return 
$num $num;
}
echo 
square(4);   // outputs '16'.
?>

함수는 여러 값을 반환할 수 없습니다. 그러나 배열을 반환하게 해서 비슷한 결과를 얻을 수 있습니다.

Example #2 여러 값을 취하기 위해 배열을 돌려줌

<?php
function small_numbers()
{
    return array (
012);
}
list (
$zero$one$two) = small_numbers();
?>

함수에서 참조를 돌려주기위해서는, 함수 선언부와 돌려주는 변수값을 지정하는 곳에서 참조 연산자 & 를 사용해야 한다.

Example #3 함수에서 참조 돌려주기

<?php
function &returns_reference()
{
    return 
$someref;
}

$newref =& returns_reference();
?>

참조에 관한 자세한 정보는, 참조 표현섹션을 참고.



가변 함수

PHP는 가변 함수에 대한 개념을 지원한다. 이 용어의 의미는 어떤 변수 뒤에 괄호가 따라온다면, PHP는 그 변수의 값을 갖는 함수를 찾아서 실행하려 할것이란 것이다. 이런 개념은 이기능 외에도 콜백과 함수 테이블 등등을 구현할수 있게 해준다.

가변 함수는 echo(), print(), unset(), isset(), empty(), include(), require()와 같은 언어 구조와 함께 작동하지 않을것이다. 래퍼 함수를 사용해서 이러한 구조를 가변 함수로 이용할 수 있습니다.

Example #1 가변 변수 사용예

<?php
function foo() {
    echo 
"foo() 안입니다.<br />\n";
}

function 
bar($arg '')
{
    echo 
"bar() 안입니다; 인수는 '$arg'입니다.<br />\n";
}

// echo를 감싸는 래퍼 함수입니다.
function echoit($string)
{
    echo 
$string;
}

$func 'foo';
$func();        // foo()를 호출합니다.

$func 'bar';
$func('test');  // bar()를 호출합니다.

$func 'echoit';
$func('test');  // echoit()을 호출합니다.
?>

객체 메쏘드도 가변 함수 구문으로 호출할 수 있습니다.

Example #2 가변 메쏘드 사용예

<?php
class Foo
{
    function 
Variable()
    {
        
$name 'Bar';
        
$this->$name(); // Bar() 메쏘드를 호출합니다.
    
}
    
    function 
Bar()
    {
        echo 
"This is Bar";
    }
}

$foo = new Foo();
$funcname "Variable";
$foo->$funcname();  // $foo->Var()를 호출합니다.

?>

call_user_func(), variable variables, function_exists()섹션을 참고



내부 (내장) 함수

PHP는 많은 함수와 상수로 표준화되었다. 그리고 특정 PHP확장 컴파일이 요구하는 함수도 제공한다. 이런 함수는 확장을 컴파일하지 않으면 "undefined function"같은 치명적 오류 메시지를 출력합니다. 예를 들면, 이미지 함수를 사용하기 위해서는 GD 지원이 가능하게 컴파일해야 합니다. mysql_connect() 함수를 사용하려면 MySQL을 지원하도록 컴파일해야 한다. 문자열변수 관련 함수와 같이 PHP의 모든 버전에 포함되어있는 많은 핵심 함수가 존재한다. phpinfo()get_loaded_extensions()를 호출하면 현재 PHP에 올라간 확장에 어떤것인지 확인할수 있다. 많은 확장이 기본값으로 활성화되어있고, PHP 매뉴얼은 여러 확장에 의해 분할되어있다는 것에 주의해야 한다. PHP를 셋업하는 방법을 알고 싶다면, 설정, 설치, 각 확장에 대한 챕터를 보라.

함수의 원형(prototype) 읽기와 이해는 함수 선언 읽는 법이라는 매뉴얼 섹션에서 설명한다. 함수가 돌려주는 것이나 함수가 값으로 직접 전달하는지 이해하는것이 중요하다. 예를 들면, str_replace()함수는 변경된 문자열을 돌려주는 반면에 usort()함수는 실질적으로 변수 자체에 전달하도록 동작한다. 각 매뉴얼 페이지는 각함수에 대해서 함수 인수와 동작 변경,성공과 실패시 돌려주는 값과 유용한 정보에 대해서 나와있다. 이런 중요한 차이점(아직은 희박) 을 아는 것은 PHP 코드를 정확하게 쓰는데 있어서 매우 결정적인 역할을 한다.

Note: string을 기대한 곳에 array를 넘기는 등, 함수에 주어진 인수가 기대한 것이 아닐 경우, 함수의 반환값은 정의되지 않았습니다. 이런 경우 NULL을 반환할 수 있지만, 이는 단순한 경우이며, 이에 의존하지 마십시오.

더불어 function_exists(), the function reference, get_extension_funcs(), dl()섹션을 참고할것.



익명 함수

익명 함수는 이름을 지정하지 않은 함수를 생성할 수 있게 합니다. 콜백 인수에 매우 유용하나, 다른 용도로 사용할 수도 있습니다.

Example #1 익명 함수 예제

<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
    return 
strtoupper($match[1]);
}, 
'hello-world');
// 출력: helloWorld
?>

익명 함수는 내부적으로 Closure 클래스로 구현됩니다.

Note: 익명 함수는 PHP 5.3.0부터 사용할 수 있습니다.




클래스와 객체 (PHP 4)

Table of Contents


class

클래스는 변수들과 이 변수들과 같이 동작하는 함수의 집합체이다. 변수는 var로 정의하고 함수는 function으로 정의합니다. 클래스는 다음 구문을 사용하여 정의합니다:

<?php
class Cart {
    var 
$items;  // Items in our shopping cart

    // Add $num articles of $artnr to the cart
 
    
function add_item ($artnr$num) {
        
$this->items[$artnr] += $num;
    }

    
// Take $num articles of $artnr out of the cart
 
    
function remove_item ($artnr$num) {
        if (
$this->items[$artnr] > $num) {
            
$this->items[$artnr] -= $num;
            return 
true;
        } elseif (
$this->items[$artnr] == $num) {
            unset(
$this->items[$artnr]);
            return 
true;
        } else {
            return 
false;
        }
    }
}
?>

위 코드에서 Cart라는 이름을 갖는 클래스는 카트(cart)를 위한 품목의 연관 배열, 그리고 카트에 아이템을 추가하거나 제거하는 두 개의 함수로 구성되어있다.

Warning

클래스 정의를 여러 파일로 나눌 수 없습니다. 또한, 메쏘드 선언 안에서 나누지 않는 한, 클래스 정의를 여러 PHP 블록으로 나눌 수 없습니다. 다음 코드는 작동하지 않습니다:

<?php
class test {
?>
<?php
    
function test() {
        print 
'OK';
    }
}
?>

하지만, 다음 코드는 허용됩니다:

<?php
class test {
    function 
test() {
        
?>
        <?php
        
print 'OK';
    }
}
?>

PHP 4에서는 다음 사항에 주의해야 한다.

Caution

Zend에서는 stdClass같은 명칭을 내부적으로 사용하며 이 명칭은 예약되어있다. 따라서 PHP에서 stdClass라는 클래스명을 만들수 없다.

Caution

__sleep__wakeup함수는 PHP 클래스에서 중요한 역할을 수행한다. 이들과 결합된 매직 기능을 원 하지 않는다면 이런 이름을 클래스내에서 사용할수 없다. 다음 글에서 자세하게 설명할것이다.

Caution

PHP에서 __으로 시작하는 함수명은 매직 기능을 수행하도록 예약되어있다. 문서화된 매직 기능을 원하지 않는다면 PHP에서 __를 갖는 함수명을 사용하지 않도록 한다.

PHP 4에서 var로 변수를 선언할때는 상수로만 초기화될수 있다. 상수가 아닌 값으로 초기화하려면, 클래스로부터 객체를 생성할때 자동적 으로 호출되는 함수에서 초기화할 필요가 있다. 이런 함수를 생성자(constructor) 라고 부른다. (다음글을 보세요)

<?php
class Cart {
    
/* PHP 4에서 이 코드는 작동하지 않을것이다 */
    
var $todays_date date("Y-m-d");
    var 
$name $firstname;
    var 
$owner 'Fred ' 'Jones';
    
/* 그러나, 배열은 고정값을 가질 수 있습니다 */
    
var $items = array("VCR""TV");
}

/* 이와 같이 해야 한다 */
class Cart {
    var 
$todays_date;
    var 
$name;
    var 
$owner;
    var 
$items = array("VCR""TV");

    function 
Cart() {
        
$this->todays_date date("Y-m-d");
        
$this->name $GLOBALS['firstname'];
        
/* etc. . . */
    
}
}
?>

class는 타입이다. 즉, 실제 변수를 위한 청사진이다. new 연산자를 사용하여 원하는 이런 타입의 변수를 생성할 수 있다.

<?php
$cart 
= new Cart;
$cart->add_item("10"1);

$another_cart = new Cart;
$another_cart->add_item("0815"3);
?>

위 예제 코드는 Cart클래스의 $cart, $another_cart 객체를 생성한다. $cart의 add_item() 함수는 $cart 에 품목 번호가 10인 아이템 1개를 추가하고, $another_cart에 품목 번호가 0815인 아이템 3개를 추가한다.

$cart$another_cart 둘다 add_item(), remove_item() 함수와 items변수를 갖는다. 이들 모두 서로 다른 함수와 변수들이다. 이런 객체는 파일시스템의 디렉토리에 비유될수 있다. 파일 시스템에서는 서로 다른 디렉토리에 존재하는 두 개의 다른 README.TXT를 가질 수 있습니다. 디렉토리에서 최상위 디렉토리에서 이들 파일까지의 경로를 지정하는 것과 마찬가지로 , 호출하려는 함수의 완전한 이름을 지정해야 합니다: PHP에서, 최상위 디렉토리는 전역 이름공간이고, 경로 구분자는 ->입니다. 따라서, $cart->items$another_cart->items 은 서로 다른 변수를 지칭하는 것이다. 변수는 $cart->$items이 아니라, $cart->items 로 지정해야 한다는 것에 주의해야 한다. 즉, PHP에서 변수명은 오직 한개의 달러사인($) 기호만 허용된다.

<?php
// correct, single $
$cart->items = array("10" => 1); 

// invalid, because $cart->$items becomes $cart->""
$cart->$items = array("10" => 1);

// correct, but may or may not be what was intended:
// $cart->$myvar becomes $cart->items
$myvar 'items';
$cart->$myvar = array("10" => 1);  
?>

클래스의 선언부에서는 프로그램이 객체에 접근할때 어느 객체명 밑에 속해있을지 알수 없다: Cart 클래스가 선언된 후에 그 객체가 $cart, $another_cart, 또다른 객체명을 갖을지 알 수 없는것이다. 따라서, Cart 클래스 선언부 안에서 $cart->items라고 쓸수 없다. 대신에, 클래스내의 함수나 변수에 접근할 수 있게 하려면 '내 소유'나 '현재 객체'라고 해석할수 있는 $this라는 의사-변수를 사용할수 있다. 따라서, '$this->items[$artnr] += $num' 이라는 코드는 '내 소유의 items 배열의 $artnr카운터를 $num만큼 더하라' 또는 '현재 객체의 items 배열의 $artnr 카운터를 $num만큼 더하라'고 해석할 수 있다.

Note: $this 모의 변수는 메쏘드가 정적으로 호출되었을 때는 일반적으로 정의되지 않습니다. 그러나, 정적 규칙: 메쏘드가 다른 객체 안에서 정적으로 호출되었을 때는 $this가 정의됩니다. 이런 경우, $this은 호출한 객체의 것입니다. 다음 예제가 이를 보여줍니다:

<?php
class A
{
    function 
foo()
    {
        if (isset(
$this)) {
            echo 
'$this is defined (';
            echo 
get_class($this);
            echo 
")\n";
        } else {
            echo 
"\$this is not defined.\n";
        }
    }
}

class 
B
{
    function 
bar()
    {
        
A::foo();
    }
}

$a = new A();
$a->foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>

위 예제의 출력:

$this is defined (a)
$this is not defined.
$this is defined (b)
$this is not defined.


Note: 클래스와 객체를 제어할 수 있는 몇가지의 유용한 함수가 제공된다. 클래스/객체 함수에서 확인할수 있다.



extends

때때로 기존의 클래스와 비슷한 변수와 함수를 갖는 클래스가 필요할때 가 있다. 실제로, 모든 프로젝트에서 사용할수 있는 범용의 클래스를 선언하고, 특정 프로젝트에서 이런 클래스를 필요에 의해 변경하는 것은 좋은 습관이다. 이런 일을 수월하게 하기 위해서 클래스는 다른 클래스에서 확장(extension) 될수 있다. 이렇게 확장되거나 파생된 클래스는 원래 클래스의 모든 변수와 함수를 소유하고 (이런 경우를 아무도 죽지 않았음 에도 불구하고 '상속'이라고 부른다) 필요로 하는 확장된 선언을 추가할수 있다. 기존 클래스에서 기존 함수나 변수의 선언을 해제하여 뺄수는 없다. 확장 클래스는 항상 하나의 기존 클래스에만 연관되어있다. 즉 다중 상속은 지원되지 않는다. 클래스는 'extends'라는 키워드를 사용하여 확장된다.

<?php
class Named_Cart extends Cart {
    var 
$owner;

    function 
set_owner ($name) {
        
$this->owner $name;
    }
}
?>

위 코드는 Cart의 모든 변수와 함수는 물론 추가된 변수 $owner 와 추가된 함수 set_owner()를 갖는 클래스를 선언한다. 이로써 이름이 있는 카트를 만들고 카트의 소유자를 설정하고 얻어올수 있다. 이름이 있는 카트에서는 물론 기존의 일반 카트 함수 도 쓸수 있다:

<?php
$ncart 
= new Named_Cart;    // 이름이 있는 카트 만들기
$ncart->set_owner("kris");  // 그 카트에 소유자를 설정
print $ncart->owner;        // 소유자 이름을 출력
$ncart->add_item("10"1);  // (기존 cart에서 상속한 함수 사용)
?>

이런 경우를 "부모-자식" 관계라고 부르기도 한다. 부모 클래스를 만들고, 부모 클래스에 기반한 새 클래스를 만들려면 extends를 사용한다: 자식 클래스. 심지어 이런 새로운 자식 클래스를 사용하거나 이 자식 클래스에 기반한 다른 클래스도 만들수 있다.

Note: 클래스는 그것이 사용되기 전에 이미 선언되어 있어야 한다! Cart클래스를 상속하는 Named_Cart클래스가 필요하면 우선 Cart클래스를 먼저 선언해야 할것이다. Named_Cart클래스에 기반한 다른 클래스 Yellow_named_cart 를 생성하고자 한다면 Named_Cart클래스를 먼저 선언해야 한다. 짧게 말해서: 클래스가 선언되는 순서는 중요하다.



생성자

생성자는 new를 사용하여 클래스의 새 인스턴스를 생성할때 자동으로 호출되는 클래스 내의 함수를 말한다. 클래스명과 동일한 이름을 가지는 함수가 생성자가 됩니다. 클래스에 생성자가 없으면, 부모 클래스의 생성자가 호출됩니다. (존재할 경우)

<?php
class Auto_Cart extends Cart {
    function 
Auto_Cart() {
        
$this->add_item("10"1);
    }
}
?>

위 코드는 Cart와 같은 Auto_Cart 클래스를 선언하고 "new"로 새로운 Auto_Cart가 생성될때마다 상품번호 "10"인 아이템 하나를 갖는 카트로 초기화하는 생성자를 만든다. 생성자는 인수를 취할수 있고 이런 인수로 인해 생성자를 더 유용하게 만들어주지만 없을수도 있다. 인수가 없는 클래스를 사용하려면 생성자의 모든 인수는 기본값을 제공해 줄수 있다.

<?php
class Constructor_Cart extends Cart {
    function 
Constructor_Cart($item "10"$num 1) {
        
$this->add_item ($item$num);
    }
}
 
// Shop the same old boring stuff.
$default_cart = new Constructor_Cart;
 
// Shop for real...
$different_cart = new Constructor_Cart("20"17);
?>

생성자에서 발생할수 있는 에러 메시지를 보이지 않게 하려면 @연산자를 사용할수 있다.즉, @new를 쓸수 있다.

<?php
class A
{
    function 
A()
    {
        echo 
"I am the constructor of A.<br />\n";
    }

    function 
B()
    {
        echo 
"I am a regular function named B in class A.<br />\n";
        echo 
"I am not a constructor in A.<br />\n";
    }
}

class 
extends A
{
}

// B()를 생성자로 호출합니다
$b = new B;
?>

클래스 A의 함수 B()는 의도하지 않았을지라도 즉시 클래스 B의 생성자가 될것이다. PHP 4에서는 그 함수가 클래스 B에서 선언되었는지 또는 거기서 상속되었는지는 상관하지 않는다.

Caution

PHP 4는 파생 클래스의 생성자에서 자동으로 부모 클래스의 생성자를 호출하지 않는다. 적절하게 상단에 생성자 호출을 전달할 책임은 당신에게 달려있다.

소멸자는 객체가 파괴될때, unset()함수나, 단순히 현재 영역을 벗어남으로써 자동으로 호출되는 함수이다. PHP에서는 소멸자가 없다. 대신 register_shutdown_function()을 사용하여 소멸자의 효과를 낼 수는 있습니다.



영역 해결 연산자 (::)

Caution

다음은 PHP 4 이후에서만 적용되는 글이다.

때때로 원래 클래스의 함수와 변수를 참조하거나 아직 어떤 인스턴스도 갖지 않는 클래스의 함수를 참조할 필요가 있다. 이런 목적으로 :: 연산자를 사용한다.

<?php
class {
    function 
example() {
        echo 
"I am the original function A::example().<br />\n";
    }
}

class 
extends {
    function 
example() {
        echo 
"I am the redefined function B::example().<br />\n";
        
A::example();
    }
}

// 여기서는 클래스 A의 객체가 존재하지 않는다.
// 이 코드는
//   I am the original function A::example().<br />를 출력한다.
A::example();

// B 클래스의 객체를 생성한다.
$b = new B;

// 여기서는 다음과 같이 출력할것이다.
//   I am the redefined function B::example().<br />
//   I am the original function A::example().<br />
$b->example();
?>

위 예제 코드는 클래스 A의 함수 example()이 호출된다. 그러나 클래스 A의 객체가 존재하지 않는다. 그래서 $a->example()와 비슷한 코드를 쓸수 없다. 대신에 '클래스 함수'인 example()을 호출한다. 즉, 그 클래스의 객체가 아니라 클래스 자체의 함수를 호출하는 것이다.

클래스 함수는 존재하지만, 클래스 변수는 존재하지 않는다. 실제로, 호출의 모든 시간동안 전혀 객체가 없었고 따라서, 클래스 함수는 어떤 객체 변수도 사용할수 없다 (그러나 로컬 변수와 전역 변수는 사용할수 있다) 그래서 $this를 전혀 사용하지 않는다.

위 예제 코드에서 클래스 B는 함수 example()을 재선언한다. ::을 사용하여 클래스 A의 example 구현에 대해 특별히 참조하지 않으면, 클래스 A의 원래 선언은 가려지게 되고 더이상 가용하지 않다. 이와 같이 하려면 A::example()라고 써야 한다 (다음섹션에서 설명한대로 parent::example() 라고 써야 한다).

이런 환경에서는 현재 객체가 있고 그 객체는 객체 변수를 갖을수도 있다. 따라서 객체 함수 안에서 사용할때에는 $this와 객체 변수를 사용해야 할것이다.



parent

원래 클래스의 변수와 함수를 참조하는 코드를 짜야할 필요가 생길수 있다. 파생 클래스가 세분화되어 고안되었거나 원래 클래스의 코드에서 특수화되어 있는경우에는 더욱 그럴 필요성이 생긴다.

코드에서 원래 클래스명을 사용하는 대신에, 특별한 이름 parent 을 사용해야 한다. 이 용어는 현재 클래스의 extends선언 안에 주어진 원래 클래스를 참조한다는 의미를 갖는다. 이렇게 씀으로써 여러 곳에서 원래 클래스명을 쓰는것을 피할수 있다. 구현중에 상속이 세번 바뀌게 되면, 단순히 현재 클래스의 extends선언을 바꾸기만 하면 된다.

<?php
class {
    function 
example() {
        echo 
"I am A::example() and provide basic functionality.<br />\n";
    }
}

class 
extends {
    function 
example() {
        echo 
"I am B::example() and provide additional functionality.<br />\n";
        
parent::example();
    }
}

$b = new B;

// This will call B::example(), which will in turn call A::example().
$b->example();
?>


객체 일렬화 - 세션 내의 객체

serialize()함수는 PHP에 저장할수 있는 값은 뭐든지 바이트-스트림(byte-stream) 대표성을 내포하는 문자열로 돌려준다. unserialize()함수는 이런 문자열을 원래 변수값으로 되돌려준다. serialize를 사용하여 객체를 저장하면 객체 내의 모든 변수 를 저장할 수 있다. 객체 내의 함수들을 저장할 수는 없고, 오직 클래스의 이름만 저장될것이다.

객체를 unserialize()하기 위해서는, 그 객체의 클래스가 선언되어 있어야 한다. 즉, page1.php에서 클래스 A의 객체 $a 가 있고 이것을 일렬화하면, 클래스 A를 참조하는 문자열을 얻게 되고, 이 문자열은 $a에 속해있는 모든 변수값을 포함하게 될것이다. Page2.php에서 이 문자열을 비일렬화하려면, 클래스 A의 $a를 재생성하고, 클래스 A의 선언이 page2.php에 존재해야 한다. 예를 들면 인클루드 파일 안에 클래스 A의 클래스 선언부를 저장하고 page1.php와 page2.php 에서 이 파일을 인클루드 하면 된다.

<?php
// classa.inc:
  
  
class {
      var 
$one 1;
    
      function 
show_one() {
          echo 
$this->one;
      }
  }
  
// page1.php:

  
include("classa.inc");
  
  
$a = new A;
  
$s serialize($a);
  
// store $s somewhere where page2.php can find it.
  
$fp fopen("store""w");
  
fwrite($fp$s);
  
fclose($fp);

// page2.php:
  
  // this is needed for the unserialize to work properly.
  
include("classa.inc");

  
$s implode("", @file("store"));
  
$a unserialize($s);

  
// now use the function show_one() of the $a object.  
  
$a->show_one();
?>

세션을 사용해서 객체를 등록하기 위해 session_register()함수를 사용한다면, 이 객체들은 각 PHP 페이지의 끝에서 자동으로 일렬화되고, 다음 페이지들 각각에서 자동으로 비일렬화된다. 이 객체들이 일단 세션의 일부분이 되면 페이지의 어느 부분에서도 이런 객체가 나타날 수 있다는것을 의미한다.

모든 페이지에서 실제로 이런 클래스를 사용하지 않더라도, 모든 페이지에 등록된 모든 객체의 클래스 선언을 인클루드하도록 한다. 이렇게 하지 않고, 존재하는 클래스 선언부없이 객체가 일렬화되면, 그 객체는 클래스 구성원을 잃게 될것이고 어떤 함수도 갖지 않는 __PHP_Incomplete_Class_Name 클래스의 객체가 될것이다. 즉, 그 객체는 쓸모없게 될것이다.

그래서 위 예제코드에서 $asession_register("a") 수행하여 세션의 일부분이 되면, page1.php와 page2.php뿐만 아니라 사용중인 모든 페이지에 classa.inc파일을 인클루드해야 한다.



매직함수 __sleep__wakeup

serialize()는 클래스가 __sleep라는 매직 이름을 갖는 함수를 갖는지 체크한다. 이 함수를 갖고있다면, 일렬화되기 전에 이 함수가 수행된다. 이 함수는 객체를 깨끗하게 비울수 있고, 일렬화되어야 하는 그 객체의 모든 변수명을 갖는 배열을 돌려준다. 이 메쏘드가 아무것도 반환하지 않는다면, NULL이 일렬화되고 E_NOTICE가 발생합니다.

__sleep의 의도된 사용은 지연된 데이터를 커밋하거나 비슷한 정리 작업을 수행하는 것입니다. 또한, 완전히 저장할 필요가 없는 매우 거대한 객체를 갖고 있다면 이 함수를 유용하게 쓸수 있다.

반대로, unserialize()__wakeup라는 매직 이름을 갖는 함수의 존재를 체크한다. 이 함수가 존재하면, 객체가 갖고 있을지도 모르는 모든 자원을 해제할수 있다.

__wakeup의 의도된 사용은 일렬화동안에 소실될수 있는 모든 데이터베이스 접속을 재구축하고 다른 재초기화 작업을 수행 한다.



생성자 안에서 참조

생성자 내로 참조를 만드는 것은 혼란스런 결과를 유도할수 있다. 이런 튜토리얼같은 섹션이 문제를 회피하도록 도와준다.

<?php
class Foo {
    function 
Foo($name) {
        
// 전역 배열 $globalref 안에 참조를 만든다
        
global $globalref;
        
$globalref[] = &$this;
        
// 값을 전달하기 위해 이름을 부여한다
        
$this->setName($name);
        
// 그리고 그것을 출력한다
        
$this->echoName();
    }

    function 
echoName() {
        echo 
"<br />"$this->name;
    }
 
    function 
setName($name) {
        
$this->name $name;
    }
}
?>

= 복사 연산자를 사용하여 만들어지는 $bar1=& 참조 연산자를 사용하여 만들어지는 $bar2 사이에 차이점이 있는지 확인해보자...

<?php
$bar1 
= new Foo('set in constructor');
$bar1->echoName();
$globalref[0]->echoName();

/* output:
set in constructor
set in constructor
set in constructor */

$bar2 =& new Foo('set in constructor');
$bar2->echoName();
$globalref[1]->echoName();

/* output:
set in constructor
set in constructor
set in constructor */
?>

외관상으로 둘 사이에는 아무 차이점도 없다. 그러나 실제로 매우 중요한 사실이 하나 있다: $bar1$globalref[0]은 참조되지 않는다. 그들은 같은 변수가 아니다. 이것은 "new"가 기본적으로 참조를 돌려주지 않기 때문이다. 대신 그것은 복사본을 돌려준다.

Note: 참조 대신 복사본을 돌려주는것 (PHP 4이상의 버전은 참조 카운팅을 사용한다) 때문에 퍼포먼스가 나빠지지는 않는다. 반대로 참조 대신에 복사본을 사용하는 것이 대부분 더 낫다. 왜냐하면 참조를 생성하는 것은 가상적으로 복사본을 만드는 데 약간의 시간이 걸리기 때문이다 (그것들이 거대한 배열이나 객체이고 그들 중 하나만 바뀌고 다른것들이 연속적으로 존재한다면, 그리고 동시에 그들 모두를 변경하려한다면 참조를 쓰는것이 더 현명할것이다)

위에서 서술한 것을 검증하기 위해 아래 예제 코드를 보자.

<?php
// now we will change the name. what do you expect?
// you could expect that both $bar1 and $globalref[0] change their names...
$bar1->setName('set from outside');

// as mentioned before this is not the case.
$bar1->echoName();
$globalref[0]->echoName();

/* output:
set from outside
set in constructor */

// let us see what is different with $bar2 and $globalref[1]
$bar2->setName('set from outside');

// luckily they are not only equal, they are the same variable
// thus $bar2->name and $globalref[1]->name are the same too
$bar2->echoName();
$globalref[1]->echoName();

/* output:
set from outside
set from outside */
?>

마지막으로 다음 예제를 보고 이해하도록 하자.

<?php
class {
    function 
A($i) {
        
$this->value $i;
        
// try to figure out why we do not need a reference here
        
$this->= new B($this);
    }

    function 
createRef() {
        
$this->= new B($this);
    }

    function 
echoValue() {
        echo 
"<br />","class ",get_class($this),': ',$this->value;
    }
}


class 
{
    function 
B(&$a) {
        
$this->= &$a;
    }

    function 
echoValue() {
        echo 
"<br />","class ",get_class($this),': ',$this->a->value;
    }
}

// try to understand why using a simple copy here would yield
// in an undesired result in the *-marked line
$a =& new A(10);
$a->createRef();

$a->echoValue();
$a->b->echoValue();
$a->c->echoValue();

$a->value 11;

$a->echoValue();
$a->b->echoValue(); // *
$a->c->echoValue();

?>

위 예제의 출력:

class A: 10
class B: 10
class B: 10
class A: 11
class B: 11
class B: 11



객체 비교

PHP 4에서 객체는 매우 단순한 방식으로 비교된다. 즉: 두 객체 인스턴스 가 같은 속성과 값을 갖고, 같은 클래스의 인스턴스라면 두 객체는 동일하다. 식별 연산자 (===)를 사용하여 두 객체를 비교할때에도 비슷한 규칙이 적용된다.

아래 예제 코드를 실행해보면:

Example #1 PHP 4에서 객체 비교를 위한 예제코드

<?php
function bool2str($bool) {
    if (
$bool === false) {
            return 
'FALSE';
    } else {
            return 
'TRUE';
    }
}

function 
compareObjects(&$o1, &$o2) {
    echo 
'o1 == o2 : '.bool2str($o1 == $o2)."\n";
    echo 
'o1 != o2 : '.bool2str($o1 != $o2)."\n";
    echo 
'o1 === o2 : '.bool2str($o1 === $o2)."\n";
    echo 
'o1 !== o2 : '.bool2str($o1 !== $o2)."\n";
}

class 
Flag {
    var 
$flag;

    function 
Flag($flag=true) {
            
$this->flag $flag;
    }
}

class 
SwitchableFlag extends Flag {

    function 
turnOn() {
        
$this->flag true;
    }

    function 
turnOff() {
        
$this->flag false;
    }
}

$o = new Flag();
$p = new Flag(false);
$q = new Flag();

$r = new SwitchableFlag();

echo 
"Compare instances created with the same parameters\n";
compareObjects($o$q);

echo 
"\nCompare instances created with different parameters\n";
compareObjects($o$p);

echo 
"\nCompare an instance of a parent class with one from a subclass\n";
compareObjects($o$r);
?>

위 예제의 출력:

Compare instances created with the same parameters
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

Compare instances created with different parameters
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Compare an instance of a parent class with one from a subclass
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE

위 출력중 어떤것은 위에서 설명한 비교 규칙이 적용된다는 것을 알수 있다. 같은 속성에 대해 같은 값을 갖고, 같은 클래스에서 파생된 인스턴스만 동일 하고 동치로 판단한다.

복합 객체를 갖는 경우에도 같은 비교 규칙이 적용된다. 아래 예제 코드에서는 컨테이너 클래스를 만들어서 Flag 객체의 결합 배열을 저장한다.

Example #2 PHP 4에서 복합 객체 비교

<?php
class FlagSet {
    var 
$set;

    function 
FlagSet($flagArr = array()) {
        
$this->set $flagArr;
    }

    function 
addFlag($name$flag) {
        
$this->set[$name] = $flag;
    }

    function 
removeFlag($name) {
        if (
array_key_exists($name$this->set)) {
            unset(
$this->set[$name]);
        }
    }
}


$u = new FlagSet();
$u->addFlag('flag1'$o);
$u->addFlag('flag2'$p);
$v = new FlagSet(array('flag1'=>$q'flag2'=>$p));
$w = new FlagSet(array('flag1'=>$q));

echo 
"\nComposite objects u(o,p) and v(q,p)\n";
compareObjects($u$v);

echo 
"\nu(o,p) and w(q)\n";
compareObjects($u$w);
?>

위 예제의 출력:

Composite objects u(o,p) and v(q,p)
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

u(o,p) and w(q)
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE




클래스와 객체 (PHP 5)

Table of Contents


소개

PHP 5는 새로운 객체 모델을 가집니다. PHP의 객체 조작은 완전히 새로 쓰여졌고, 더욱 나은 성능과 많은 기능을 허용합니다.



The Basics

class

Every class definition begins with the keyword class, followed by a class name, which can be any name that isn't a reserved word in PHP. Followed by a pair of curly braces, which contains the definition of the classes members and methods. A pseudo-variable, $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but can be another object, if the method is called statically from the context of a secondary object). This is illustrated in the following examples:

Example #1 $this variable in object-oriented language

<?php
class A
{
    function 
foo()
    {
        if (isset(
$this)) {
            echo 
'$this is defined (';
            echo 
get_class($this);
            echo 
")\n";
        } else {
            echo 
"\$this is not defined.\n";
        }
    }
}

class 
B
{
    function 
bar()
    {
        
A::foo();
    }
}

$a = new A();
$a->foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>

위 예제의 출력:

$this is defined (a)
$this is not defined.
$this is defined (b)
$this is not defined.

Example #2 Simple Class definition

<?php
class SimpleClass
{
    
// member declaration
    
public $var 'a default value';

    
// method declaration
    
public function displayVar() {
        echo 
$this->var;
    }
}
?>

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

Example #3 Class members' default value

<?php
class SimpleClass
{
    
// invalid member declarations:
    
public $var1 'hello '.'world';
    public 
$var2 = <<<EOD
hello world
EOD;
    public 
$var3 1+2;
    public 
$var4 self::myStaticMethod();
    public 
$var5 $myVar;

    
// valid member declarations:
    
public $var6 myConstant;
    public 
$var7 self::classConstant;
    public 
$var8 = array(truefalse);
    
    
}
?>

Note: There are some nice functions to handle classes and objects. You might want to take a look at the Class/Object Functions.

Unlike heredocs, nowdocs can be used in any static data context.

Example #4 Static data example

<?php
class foo {
    
// As of PHP 5.3.0
    
public $bar = <<<'EOT'
bar
EOT;
}
?>

Note: Nowdoc support was added in PHP 5.3.0.

new

To create an instance of a class, a new object must be created and assigned to a variable. An object will always be assigned when creating a new object unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).

Example #5 Creating an instance

<?php
$instance 
= new SimpleClass();

// This can also be done with a variable:
$className 'Foo';
$instance = new $className(); // Foo()
?>

In the class context, it is possible to create a new object by new self and new parent.

When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A copy of an already created object can be made by cloning it.

Example #6 Object Assignment

<?php
$assigned   
=  $instance;
$reference  =& $instance;

$instance->var '$assigned will have this value';

$instance null// $instance and $reference become null

var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>

위 예제의 출력:

NULL
NULL
object(SimpleClass)#1 (1) {
   ["var"]=>
     string(30) "$assigned will have this value"
}

extends

A class can inherit methods and members of another class by using the extends keyword in the declaration. It is not possible to extend multiple classes, a class can only inherit one base class.

The inherited methods and members can be overridden, unless the parent class has defined a method as final, by redeclaring them with the same name defined in the parent class. It is possible to access the overridden methods or static members by referencing them with parent::

Example #7 Simple Class Inheritance

<?php
class ExtendClass extends SimpleClass
{
    
// Redefine the parent method
    
function displayVar()
    {
        echo 
"Extending class\n";
        
parent::displayVar();
    }
}

$extended = new ExtendClass();
$extended->displayVar();
?>

위 예제의 출력:

Extending class
a default value


Autoloading Objects

Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).

In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class/interface which hasn't been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.

Note: Exceptions thrown in __autoload function cannot be caught in the catch block and results in a fatal error.

Note: Autoloading is not available if using PHP in CLI interactive mode.

Note: If the class name is used e.g. in call_user_func() then it can contain some dangerous characters such as ../. It is recommended to not use the user-input in such functions or at least verify the input in __autoload().

Example #1 Autoload example

This example attempts to load the classes MyClass1 and MyClass2 from the files MyClass1.php and MyClass2.php respectively.

<?php
function __autoload($class_name) {
    require_once 
$class_name '.php';
}

$obj  = new MyClass1();
$obj2 = new MyClass2(); 
?>

Example #2 Autoload other example

This example attempts to load the interface ITest.

<?php

function __autoload($name) {
    
var_dump($name);
}

class 
Foo implements ITest {
}

/*
string(5) "ITest"

Fatal error: Interface 'ITest' not found in ...
*/
?>



Constructors and Destructors

Constructor

void __construct ([ mixed $args [, $... ]] )

PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.

Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.

Example #1 using new unified constructors

<?php
class BaseClass {
   function 
__construct() {
       print 
"In BaseClass constructor\n";
   }
}

class 
SubClass extends BaseClass {
   function 
__construct() {
       
parent::__construct();
       print 
"In SubClass constructor\n";
   }
}

$obj = new BaseClass();
$obj = new SubClass();
?>

For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.

Destructor

void __destruct ( void )

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence.

Example #2 Destructor Example

<?php
class MyDestructableClass {
   function 
__construct() {
       print 
"In constructor\n";
       
$this->name "MyDestructableClass";
   }

   function 
__destruct() {
       print 
"Destroying " $this->name "\n";
   }
}

$obj = new MyDestructableClass();
?>

Like constructors, parent destructors will not be called implicitly by the engine. In order to run a parent destructor, one would have to explicitly call parent::__destruct() in the destructor body.

Note: Destructors called during the script shutdown have HTTP headers already sent. The working directory in the script shutdown phase can be different with some SAPIs (e.g. Apache).

Note: Attempting to throw an exception from a destructor (called in the time of script termination) causes a fatal error.



Visibility

The visibility of a property or method can be defined by prefixing the declaration with the keywords: public, protected or private. Public declared items can be accessed everywhere. Protected limits access to inherited and parent classes (and to the class that defines the item). Private limits visibility only to the class that defines the item.

Members Visibility

Class members must be defined with public, private, or protected.

Example #1 Member declaration

<?php
/**
 * Define MyClass
 */
class MyClass
{
    public 
$public 'Public';
    protected 
$protected 'Protected';
    private 
$private 'Private';

    function 
printHello()
    {
        echo 
$this->public;
        echo 
$this->protected;
        echo 
$this->private;
    }
}

$obj = new MyClass();
echo 
$obj->public// Works
echo $obj->protected// Fatal Error
echo $obj->private// Fatal Error
$obj->printHello(); // Shows Public, Protected and Private


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    
// We can redeclare the public and protected method, but not private
    
protected $protected 'Protected2';

    function 
printHello()
    {
        echo 
$this->public;
        echo 
$this->protected;
        echo 
$this->private;
    }
}

$obj2 = new MyClass2();
echo 
$obj2->public// Works
echo $obj2->private// Undefined
echo $obj2->protected// Fatal Error
$obj2->printHello(); // Shows Public, Protected2, Undefined

?>

Note: The PHP 4 method of declaring a variable with the var keyword is still supported for compatibility reasons (as a synonym for the public keyword). In PHP 5 before 5.1.3, its usage would generate an E_STRICT warning.

Method Visibility

Class methods must be defined with public, private, or protected. Methods without any declaration are defined as public.

Example #2 Method Declaration

<?php
/**
 * Define MyClass
 */
class MyClass
{
    
// Declare a public constructor
    
public function __construct() { }

    
// Declare a public method
    
public function MyPublic() { }

    
// Declare a protected method
    
protected function MyProtected() { }

    
// Declare a private method
    
private function MyPrivate() { }

    
// This is public
    
function Foo()
    {
        
$this->MyPublic();
        
$this->MyProtected();
        
$this->MyPrivate();
    }
}

$myclass = new MyClass;
$myclass->MyPublic(); // Works
$myclass->MyProtected(); // Fatal Error
$myclass->MyPrivate(); // Fatal Error
$myclass->Foo(); // Public, Protected and Private work


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    
// This is public
    
function Foo2()
    {
        
$this->MyPublic();
        
$this->MyProtected();
        
$this->MyPrivate(); // Fatal Error
    
}
}

$myclass2 = new MyClass2;
$myclass2->MyPublic(); // Works
$myclass2->Foo2(); // Public and Protected work, not Private

class Bar 
{
    public function 
test() {
        
$this->testPrivate();
        
$this->testPublic();
    }

    public function 
testPublic() {
        echo 
"Bar::testPublic\n";
    }
    
    private function 
testPrivate() {
        echo 
"Bar::testPrivate\n";
    }
}

class 
Foo extends Bar 
{
    public function 
testPublic() {
        echo 
"Foo::testPublic\n";
    }
    
    private function 
testPrivate() {
        echo 
"Foo::testPrivate\n";
    }
}

$myFoo = new foo();
$myFoo->test(); // Bar::testPrivate 
                // Foo::testPublic
?>



Scope Resolution Operator (::)

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden members or methods of a class.

When referencing these items from outside the class definition, use the name of the class.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

Paamayim Nekudotayim would, at first, seem like a strange choice for naming a double-colon. However, while writing the Zend Engine 0.5 (which powers PHP 3), that's what the Zend team decided to call it. It actually does mean double-colon - in Hebrew!

Example #1 :: from outside the class definition

<?php
class MyClass {
    const 
CONST_VALUE 'A constant value';
}

$classname 'MyClass';
echo 
$classname::CONST_VALUE// As of PHP 5.3.0

echo MyClass::CONST_VALUE;
?>

Two special keywords self and parent are used to access members or methods from inside the class definition.

Example #2 :: from inside the class definition

<?php
class OtherClass extends MyClass
{
    public static 
$my_static 'static var';

    public static function 
doubleColon() {
        echo 
parent::CONST_VALUE "\n";
        echo 
self::$my_static "\n";
    }
}

$classname 'OtherClass';
echo 
$classname::doubleColon(); // As of PHP 5.3.0

OtherClass::doubleColon();
?>

When an extending class overrides the parents definition of a method, PHP will not call the parent's method. It's up to the extended class on whether or not the parent's method is called. This also applies to Constructors and Destructors, Overloading, and Magic method definitions.

Example #3 Calling a parent's method

<?php
class MyClass
{
    protected function 
myFunc() {
        echo 
"MyClass::myFunc()\n";
    }
}

class 
OtherClass extends MyClass
{
    
// Override parent's definition
    
public function myFunc()
    {
        
// But still call the parent function
        
parent::myFunc();
        echo 
"OtherClass::myFunc()\n";
    }
}

$class = new OtherClass();
$class->myFunc();
?>


Static Keyword

Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can).

For compatibility with PHP 4, if no visibility declaration is used, then the member or method will be treated as if it was declared as public.

Because static methods are callable without an instance of the object created, the pseudo variable $this is not available inside the method declared as static.

Static properties cannot be accessed through the object using the arrow operator ->.

Calling non-static methods statically generates an E_STRICT level warning.

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

Example #1 Static member example

<?php
class Foo
{
    public static 
$my_static 'foo';

    public function 
staticValue() {
        return 
self::$my_static;
    }
}

class 
Bar extends Foo
{
    public function 
fooStatic() {
        return 
parent::$my_static;
    }
}


print 
Foo::$my_static "\n";

$foo = new Foo();
print 
$foo->staticValue() . "\n";
print 
$foo->my_static "\n";      // Undefined "Property" my_static 

print $foo::$my_static "\n";
$classname 'Foo';
print 
$classname::$my_static "\n"// As of PHP 5.3.0

print Bar::$my_static "\n";
$bar = new Bar();
print 
$bar->fooStatic() . "\n";
?>

Example #2 Static method example

<?php
class Foo {
    public static function 
aStaticMethod() {
        
// ...
    
}
}

Foo::aStaticMethod();
$classname 'Foo';
$classname::aStaticMethod(); // As of PHP 5.3.0
?>


Class Constants

It is possible to define constant values on a per-class basis remaining the same and unchangeable. Constants differ from normal variables in that you don't use the $ symbol to declare or use them.

The value must be a constant expression, not (for example) a variable, a class member, result of a mathematical operation or a function call.

Its also possible for interfaces to have constants. Look at the interface documentation for examples.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

Example #1 Defining and using a constant

<?php
class MyClass
{
    const 
constant 'constant value';

    function 
showConstant() {
        echo  
self::constant "\n";
    }
}

echo 
MyClass::constant "\n";

$classname "MyClass";
echo 
$classname::constant "\n"// As of PHP 5.3.0

$class = new MyClass();
$class->showConstant();

echo 
$class::constant."\n"// As of PHP 5.3.0
?>

Example #2 Static data example

<?php
class foo {
    
// As of PHP 5.3.0
    
const bar = <<<'EOT'
bar
EOT;
}
?>

Unlike heredocs, nowdocs can be used in any static data context.

Note: Nowdoc support was added in PHP 5.3.0.



Class Abstraction

PHP 5 introduces abstract classes and methods. It is not allowed to create an instance of a class that has been defined as abstract. Any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature they cannot define the implementation.

When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.

Example #1 Abstract class example

<?php
abstract class AbstractClass
{
    
// Force Extending class to define this method
    
abstract protected function getValue();
    abstract protected function 
prefixValue($prefix);

    
// Common method
    
public function printOut() {
        print 
$this->getValue() . "\n";
    }
}

class 
ConcreteClass1 extends AbstractClass
{
    protected function 
getValue() {
        return 
"ConcreteClass1";
    }

    public function 
prefixValue($prefix) {
        return 
"{$prefix}ConcreteClass1";
    }
}

class 
ConcreteClass2 extends AbstractClass
{
    public function 
getValue() {
        return 
"ConcreteClass2";
    }

    public function 
prefixValue($prefix) {
        return 
"{$prefix}ConcreteClass2";
    }
}

$class1 = new ConcreteClass1;
$class1->printOut();
echo 
$class1->prefixValue('FOO_') ."\n";

$class2 = new ConcreteClass2;
$class2->printOut();
echo 
$class2->prefixValue('FOO_') ."\n";
?>

위 예제의 출력:

ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2

Old code that has no user-defined classes or functions named 'abstract' should run without modifications.



Object Interfaces

Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.

Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.

All methods declared in an interface must be public, this is the nature of an interface.

implements

To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.

Note: A class cannot implement two interfaces that share function names, since it would cause ambiguity.

Note: Interfaces can be extended like classes using the extend operator.

Constants

Its possible for interfaces to have constants. Interface constants works exactly like class constants. They cannot be overridden by a class/interface that inherits it.

예제

Example #1 Interface example

<?php

// Declare the interface 'iTemplate'
interface iTemplate
{
    public function 
setVariable($name$var);
    public function 
getHtml($template);
}

// Implement the interface
// This will work
class Template implements iTemplate
{
    private 
$vars = array();
  
    public function 
setVariable($name$var)
    {
        
$this->vars[$name] = $var;
    }
  
    public function 
getHtml($template)
    {
        foreach(
$this->vars as $name => $value) {
            
$template str_replace('{' $name '}'$value$template);
        }
 
        return 
$template;
    }
}

// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
    private 
$vars = array();
  
    public function 
setVariable($name$var)
    {
        
$this->vars[$name] = $var;
    }
}
?>

Example #2 Extendable Interfaces

<?php
interface a
{
    public function 
foo();
}

interface 
extends a
{
    public function 
baz(Baz $baz);
}

// This will work
class implements b
{
    public function 
foo()
    {
    }

    public function 
baz(Baz $baz)
    {
    }
}

// This will not work and result in a fatal error
class implements b
{
    public function 
foo()
    {
    }

    public function 
baz(Foo $foo)
    {
    }
}
?>

Example #3 Multiple interface inheritance

<?php
interface a
{
    public function 
foo();
}

interface 
b
{
    public function 
bar();
}

interface 
extends ab
{
    public function 
baz();
}

class 
implements c
{
    public function 
foo()
    {
    }

    public function 
bar()
    {
    }

    public function 
baz()
    {
    }
}
?>

Example #4 Interfaces with constants

<?php
interface a
{
    const 
'Interface constant';
}

// Prints: Interface constant
echo a::b;


// This will however not work because its not allowed to 
// override constants. This is the same concept as with 
// class constants
class implements a
{
    const 
'Class constant';
}
?>

See also the instanceof operator.



Overloading

Overloading in PHP provides means to dynamically "create" members and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types.

The overloading methods are invoked when interacting with members or methods that have not been declared or are not visible in the current scope. The rest of this section will use the terms "inaccessible members" and "inaccessible methods" to refer to this combination of declaration and visibility.

All overloading methods must be defined as public.

Note: None of the arguments of these magic methods can be passed by reference.

Note: PHP's interpretation of "overloading" is different than most object oriented languages. Overloading traditionally provides the ability to have multiple methods with the same name but different quantities and types of arguments.

변경점

버전 설명
5.3.0 Added __callStatic(). Added warning to enforce public visibility and non-static declaration.
5.1.0 Added __isset() and __unset().

Member overloading

void __set ( string $name , mixed $value )
mixed __get ( string $name )
bool __isset ( string $name )
void __unset ( string $name )

__set() is run when writing data to inaccessible members.

__get() is utilized for reading data from inaccessible members.

__isset() is triggered by calling isset() or empty() on inaccessible members.

__unset() is invoked when unset() is used on inaccessible members.

The $name argument is the name of the member being interacted with. The __set() method's $value argument specifies the value the $name'ed member should be set to.

Member overloading only works in object context. These magic methods will not be triggered in static context. Therefore these methods can not be declared static.

Example #1 overloading with __get, __set, __isset and __unset example

<?php
class MemberTest {
    
/**  Location for overloaded data.  */
    
private $data = array();

    
/**  Overloading not used on declared members.  */
    
public $declared 1;

    
/**  Overloading only used on this when accessed outside the class.  */
    
private $hidden 2;

    public function 
__set($name$value) {
        echo 
"Setting '$name' to '$value'\n";
        
$this->data[$name] = $value;
    }

    public function 
__get($name) {
        echo 
"Getting '$name'\n";
        if (
array_key_exists($name$this->data)) {
            return 
$this->data[$name];
        }

        
$trace debug_backtrace();
        
trigger_error(
            
'Undefined property via __get(): ' $name .
            
' in ' $trace[0]['file'] .
            
' on line ' $trace[0]['line'],
            
E_USER_NOTICE);
        return 
null;
    }

    
/**  As of PHP 5.1.0  */
    
public function __isset($name) {
        echo 
"Is '$name' set?\n";
        return isset(
$this->data[$name]);
    }

    
/**  As of PHP 5.1.0  */
    
public function __unset($name) {
        echo 
"Unsetting '$name'\n";
        unset(
$this->data[$name]);
    }

    
/**  Not a magic method, just here for example.  */
    
public function getHidden() {
        return 
$this->hidden;
    }
}


echo 
"<pre>\n";

$obj = new MemberTest;

$obj->1;
echo 
$obj->"\n\n";

var_dump(isset($obj->a));
unset(
$obj->a);
var_dump(isset($obj->a));
echo 
"\n";

echo 
$obj->declared "\n\n";

echo 
"Let's experiment with the private property named 'hidden':\n";
echo 
"Privates are visible inside the class, so __get() not used...\n";
echo 
$obj->getHidden() . "\n";
echo 
"Privates not visible outside of class, so __get() is used...\n";
echo 
$obj->hidden "\n";
?>

위 예제의 출력:

Setting 'a' to '1'
Getting 'a'
1

Is 'a' set?
bool(true)
Unsetting 'a'
Is 'a' set?
bool(false)

1

Let's experiment with the private property named 'hidden':
Privates are visible inside the class, so __get() not used...
2
Privates not visible outside of class, so __get() is used...
Getting 'hidden'


Notice:  Undefined property via __get(): hidden in <file> on line 70 in <file> on line 29

Method overloading

mixed __call ( string $name , array $arguments )
mixed __callStatic ( string $name , array $arguments )

__call() is triggered when invoking inaccessible methods in an object context.

__callStatic() is triggered when invoking inaccessible methods in a static context.

The $name argument is the name of the method being called. The $arguments argument is an enumerated array containing the parameters passed to the $name'ed method.

Example #2 overloading instantiated methods with __call and __callStatic

<?php
class MethodTest {
    public function 
__call($name$arguments) {
        
// Note: value of $name is case sensitive.
        
echo "Calling object method '$name' "
             
implode(', '$arguments). "\n";
    }

    
/**  As of PHP 5.3.0  */
    
public static function __callStatic($name$arguments) {
        
// Note: value of $name is case sensitive.
        
echo "Calling static method '$name' "
             
implode(', '$arguments). "\n";
    }
}

$obj = new MethodTest;
$obj->runTest('in object context');

MethodTest::runTest('in static context');  // As of PHP 5.3.0
?>

위 예제의 출력:

Calling object method 'runTest' in object context
Calling static method 'runTest' in static context


Object Iteration

PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example a foreach statement. By default, all visible properties will be used for the iteration.

Example #1 Simple Object Iteration

<?php
class MyClass
{
    public 
$var1 'value 1';
    public 
$var2 'value 2';
    public 
$var3 'value 3';

    protected 
$protected 'protected var';
    private   
$private   'private var';

    function 
iterateVisible() {
       echo 
"MyClass::iterateVisible:\n";
       foreach(
$this as $key => $value) {
           print 
"$key => $value\n";
       }
    }
}

$class = new MyClass();

foreach(
$class as $key => $value) {
    print 
"$key => $value\n";
}
echo 
"\n";


$class->iterateVisible();

?>

위 예제의 출력:

var1 => value 1
var2 => value 2
var3 => value 3

MyClass::iterateVisible:
var1 => value 1
var2 => value 2
var3 => value 3
protected => protected var
private => private var

As the output shows, the foreach iterated through all visible variables that can be accessed. To take it a step further you can implement one of PHP 5's internal interface named Iterator. This allows the object to decide what and how the object will be iterated.

Example #2 Object Iteration implementing Iterator

<?php
class MyIterator implements Iterator
{
    private 
$var = array();

    public function 
__construct($array)
    {
        if (
is_array($array)) {
            
$this->var $array;
        }
    }

    public function 
rewind() {
        echo 
"rewinding\n";
        
reset($this->var);
    }

    public function 
current() {
        
$var current($this->var);
        echo 
"current: $var\n";
        return 
$var;
    }

    public function 
key() {
        
$var key($this->var);
        echo 
"key: $var\n";
        return 
$var;
    }

    public function 
next() {
        
$var next($this->var);
        echo 
"next: $var\n";
        return 
$var;
    }

    public function 
valid() {
        
$var $this->current() !== false;
        echo 
"valid: {$var}\n";
        return 
$var;
    }
}

$values = array(1,2,3);
$it = new MyIterator($values);

foreach (
$it as $a => $b) {
    print 
"$a$b\n";
}
?>

위 예제의 출력:

rewinding
current: 1
valid: 1
current: 1
key: 0
0: 1
next: 2
current: 2
valid: 1
current: 2
key: 1
1: 2
next: 3
current: 3
valid: 1
current: 3
key: 2
2: 3
next:
current:
valid:

You can also define your class so that it doesn't have to define all the Iterator functions by simply implementing the PHP 5 IteratorAggregate interface.

Example #3 Object Iteration implementing IteratorAggregate

<?php
class MyCollection implements IteratorAggregate
{
    private 
$items = array();
    private 
$count 0;

    
// Required definition of interface IteratorAggregate
    
public function getIterator() {
        return new 
MyIterator($this->items);
    }

    public function 
add($value) {
        
$this->items[$this->count++] = $value;
    }
}

$coll = new MyCollection();
$coll->add('value 1');
$coll->add('value 2');
$coll->add('value 3');

foreach (
$coll as $key => $val) {
    echo 
"key/value: [$key -> $val]\n\n";
}
?>

위 예제의 출력:

rewinding
current: value 1
valid: 1
current: value 1
key: 0
key/value: [0 -> value 1]

next: value 2
current: value 2
valid: 1
current: value 2
key: 1
key/value: [1 -> value 2]

next: value 3
current: value 3
valid: 1
current: value 3
key: 2
key/value: [2 -> value 3]

next:
current:
valid:

Note: For more examples of iterators, see the SPL Extension.



Patterns

Patterns are ways to describe best practices and good designs. They show a flexible solution to common programming problems.

Factory

The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for "manufacturing" an object. A Parameterized Factory receives the name of the class to instantiate as argument.

Example #1 Parameterized Factory Method

<?php
class Example
{
    
// The parameterized factory method
    
public static function factory($type)
    {
        if (include_once 
'Drivers/' $type '.php') {
            
$classname 'Driver_' $type;
            return new 
$classname;
        } else {
            throw new 
Exception ('Driver not found');
        }
    }
}
?>

Defining this method in a class allows drivers to be loaded on the fly. If the Example class was a database abstraction class, loading a MySQL and SQLite driver could be done as follows:

<?php
// Load a MySQL Driver
$mysql Example::factory('MySQL');

// Load a SQLite Driver
$sqlite Example::factory('SQLite');
?>

Singleton

The Singleton pattern applies to situations in which there needs to be a single instance of a class. The most common example of this is a database connection. Implementing this pattern allows a programmer to make this single instance easily accessible by many other objects.

Example #2 Singleton Function

<?php
class Example
{
    
// Hold an instance of the class
    
private static $instance;
    
    
// A private constructor; prevents direct creation of object
    
private function __construct() 
    {
        echo 
'I am constructed';
    }

    
// The singleton method
    
public static function singleton() 
    {
        if (!isset(
self::$instance)) {
            
$c __CLASS__;
            
self::$instance = new $c;
        }

        return 
self::$instance;
    }
    
    
// Example method
    
public function bark()
    {
        echo 
'Woof!';
    }

    
// Prevent users to clone the instance
    
public function __clone()
    {
        
trigger_error('Clone is not allowed.'E_USER_ERROR);
    }

}

?>

This allows a single instance of the Example class to be retrieved.

<?php
// This would fail because the constructor is private
$test = new Example;

// This will always retrieve a single instance of the class
$test Example::singleton();
$test->bark();

// This will issue an E_USER_ERROR.
$test_clone = clone $test;

?>


Magic Methods

The function names __construct, __destruct, __call, __callStatic, __get, __set, __isset, __unset, __sleep, __wakeup, __toString, __invoke, __set_state and __clone are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.

Caution

PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality.

__sleep and __wakeup

serialize() checks if your class has a function with the magic name __sleep. If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.

The intended use of __sleep is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which do not need to be saved completely.

Conversely, unserialize() checks for the presence of a function with the magic name __wakeup. If present, this function can reconstruct any resources that the object may have.

The intended use of __wakeup is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.

Example #1 Sleep and wakeup

<?php
class Connection {
    protected 
$link;
    private 
$server$username$password$db;
    
    public function 
__construct($server$username$password$db)
    {
        
$this->server $server;
        
$this->username $username;
        
$this->password $password;
        
$this->db $db;
        
$this->connect();
    }
    
    private function 
connect()
    {
        
$this->link mysql_connect($this->server$this->username$this->password);
        
mysql_select_db($this->db$this->link);
    }
    
    public function 
__sleep()
    {
        return array(
'server''username''password''db');
    }
    
    public function 
__wakeup()
    {
        
$this->connect();
    }
}
?>

__toString

The __toString method allows a class to decide how it will react when it is converted to a string.

Example #2 Simple example

<?php
// Declare a simple class
class TestClass
{
    public 
$foo;

    public function 
__construct($foo) {
        
$this->foo $foo;
    }

    public function 
__toString() {
        return 
$this->foo;
    }
}

$class = new TestClass('Hello');
echo 
$class;
?>

위 예제의 출력:

Hello

It is worth noting that before PHP 5.2.0 the __toString method was only called when it was directly combined with echo() or print(). Since PHP 5.2.0, it is called in any string context (e.g. in printf() with %s modifier) but not in other types contexts (e.g. with %d modifier). Since PHP 5.2.0, converting objects without __toString method to string would cause E_RECOVERABLE_ERROR.

__invoke

The __invoke method is called when a script tries to call an object as a function.

Note: This feature is available since PHP 5.3.0.

Example #3 Using __invoke

<?php
class CallableClass {
    function 
__invoke($x) {
        
var_dump($x);
    }
}
$obj = new CallableClass;
$obj(5);
var_dump(is_callable($obj));
?>

위 예제의 출력:

int(5)
bool(true)

__set_state

This static method is called for classes exported by var_export() since PHP 5.1.0.

The only parameter of this method is an array containing exported properties in the form array('property' => value, ...).

Example #4 Using __set_state (since PHP 5.1.0)

<?php

class A
{
    public 
$var1;
    public 
$var2;

    public static function 
__set_state($an_array// As of PHP 5.1.0
    
{
        
$obj = new A;
        
$obj->var1 $an_array['var1'];
        
$obj->var2 $an_array['var2'];
        return 
$obj;
    }
}

$a = new A;
$a->var1 5;
$a->var2 'foo';

eval(
'$b = ' var_export($atrue) . ';'); // $b = A::__set_state(array(
                                            //    'var1' => 5,
                                            //    'var2' => 'foo',
                                            // ));
var_dump($b);

?>

위 예제의 출력:

object(A)#2 (2) {
  ["var1"]=>
  int(5)
  ["var2"]=>
  string(3) "foo"
}


Final 키워드

PHP 5는 자식 클래스가 메쏘드를 덮어 쓰는 것을 막도록, final 키워드를 지원합니다. 정의시에 final을 앞에 붙이면 됩니다. 클래스 자체를 final로 정의하면 상속할 수 없습니다.

Example #1 Final 메쏘드 예제

<?php
class BaseClass {
   public function 
test() {
       echo 
"BaseClass::test() 호출\n";
   }
   
   final public function 
moreTesting() {
       echo 
"BaseClass::moreTesting() 호출\n";
   }
}

class 
ChildClass extends BaseClass {
   public function 
moreTesting() {
       echo 
"ChildClass::moreTesting() 호출\n";
   }
}
// 결과는 Fatal error: Cannot override final method BaseClass::moreTesting()
?>

Example #2 Final 클래스 예제

<?php
final class BaseClass {
   public function 
test() {
       echo 
"BaseClass::test() 호출\n";
   }

   
// 여기서는 함수의 final 지정 여부는 관계 없습니다.
   
final public function moreTesting() {
       echo 
"BaseClass::moreTesting() 호출\n";
   }
}

class 
ChildClass extends BaseClass {
}
// 결과는 Fatal error: Class ChildClass may not inherit from final class (BaseClass)
?>


Object cloning

Creating a copy of an object with fully replicated properties is not always the wanted behavior. A good example of the need for copy constructors, is if you have an object which represents a GTK window and the object holds the resource of this GTK window, when you create a duplicate you might want to create a new window with the same properties and have the new object hold the resource of the new window. Another example is if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy.

An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly.

$copy_of_object = clone $object;

When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references.

Once the cloning is complete, if a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed.

Example #1 Cloning an object

<?php
class SubObject
{
    static 
$instances 0;
    public 
$instance;

    public function 
__construct() {
        
$this->instance = ++self::$instances;
    }

    public function 
__clone() {
        
$this->instance = ++self::$instances;
    }
}

class 
MyCloneable
{
    public 
$object1;
    public 
$object2;

    function 
__clone()
    {
        
// Force a copy of this->object, otherwise
        // it will point to same object.
        
$this->object1 = clone $this->object1;
    }
}

$obj = new MyCloneable();

$obj->object1 = new SubObject();
$obj->object2 = new SubObject();

$obj2 = clone $obj;


print(
"Original Object:\n");
print_r($obj);

print(
"Cloned Object:\n");
print_r($obj2);

?>

위 예제의 출력:

Original Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 1
        )

    [object2] => SubObject Object
        (
            [instance] => 2
        )

)
Cloned Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 3
        )

    [object2] => SubObject Object
        (
            [instance] => 2
        )

)


Comparing objects

In PHP 5, object comparison is more complicated than in PHP 4 and more in accordance to what one will expect from an Object Oriented Language (not that PHP 5 is such a language).

When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.

On the other hand, when using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.

An example will clarify these rules.

Example #1 Example of object comparison in PHP 5

<?php
function bool2str($bool)
{
    if (
$bool === false) {
        return 
'FALSE';
    } else {
        return 
'TRUE';
    }
}

function 
compareObjects(&$o1, &$o2)
{
    echo 
'o1 == o2 : ' bool2str($o1 == $o2) . "\n";
    echo 
'o1 != o2 : ' bool2str($o1 != $o2) . "\n";
    echo 
'o1 === o2 : ' bool2str($o1 === $o2) . "\n";
    echo 
'o1 !== o2 : ' bool2str($o1 !== $o2) . "\n";
}

class 
Flag
{
    public 
$flag;

    function 
Flag($flag true) {
        
$this->flag $flag;
    }
}

class 
OtherFlag
{
    public 
$flag;

    function 
OtherFlag($flag true) {
        
$this->flag $flag;
    }
}

$o = new Flag();
$p = new Flag();
$q $o;
$r = new OtherFlag();

echo 
"Two instances of the same class\n";
compareObjects($o$p);

echo 
"\nTwo references to the same instance\n";
compareObjects($o$q);

echo 
"\nInstances of two different classes\n";
compareObjects($o$r);
?>

위 예제의 출력:

Two instances of the same class
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Two references to the same instance
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

Instances of two different classes
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Note: Extensions can define own rules for their objects comparison.



Reflection

소개

PHP 5 comes with a complete reflection API that adds the ability to reverse-engineer classes, interfaces, functions and methods as well as extensions. Additionally, the reflection API also offers ways of retrieving doc comments for functions, classes and methods.

The reflection API is an object-oriented extension to the Zend Engine, consisting of the following classes:

<?php
class Reflection { }
interface 
Reflector { }
class 
ReflectionException extends Exception { }
class 
ReflectionFunction extends ReflectionFunctionAbstract implements Reflector { }
class 
ReflectionParameter implements Reflector { }
class 
ReflectionMethod extends ReflectionFunctionAbstract implements Reflector { }
class 
ReflectionClass implements Reflector { }
class 
ReflectionObject extends ReflectionClass { }
class 
ReflectionProperty implements Reflector { }
class 
ReflectionExtension implements Reflector { }
?>

Note: For details on these classes, have a look at the next chapters.

If we were to execute the code in the example below:

Example #1 Basic usage of the reflection API

<?php
Reflection
::export(new ReflectionClass('Exception'));
?>

위 예제의 출력:

Class [ <internal> class Exception ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [6] {
    Property [ <default> protected $message ]
    Property [ <default> private $string ]
    Property [ <default> protected $code ]
    Property [ <default> protected $file ]
    Property [ <default> protected $line ]
    Property [ <default> private $trace ]
  }

  - Methods [9] {
    Method [ <internal> final private method __clone ] {
    }

    Method [ <internal, ctor> public method __construct ] {

      - Parameters [2] {
        Parameter #0 [ <optional> $message ]
        Parameter #1 [ <optional> $code ]
      }
    }

    Method [ <internal> final public method getMessage ] {
    }

    Method [ <internal> final public method getCode ] {
    }

    Method [ <internal> final public method getFile ] {
    }

    Method [ <internal> final public method getLine ] {
    }

    Method [ <internal> final public method getTrace ] {
    }

    Method [ <internal> final public method getTraceAsString ] {
    }

    Method [ <internal> public method __toString ] {
    }
  }
}

Reflector

Reflector is an interface implemented by all exportable Reflection classes.

<?php
interface Reflector
{
    public 
string __toString()
    public static 
string export()
}
?>

ReflectionException

ReflectionException extends the standard Exception and is thrown by Reflection API. No specific methods or properties are introduced.

ReflectionFunction

The ReflectionFunction class lets you reverse-engineer functions.

<?php
class ReflectionFunction extends ReflectionFunctionAbstract implements Reflector
{
    final private 
__clone()
    public 
void __construct(string name)
    public 
string __toString()
    public static 
string export(string namebool return)
    public 
string getName()
    public 
bool isInternal()
    public 
bool isDisabled()
    public 
bool isUserDefined()
    public 
string getFileName()
    public 
int getStartLine()
    public 
int getEndLine()
    public 
string getDocComment()
    public array 
getStaticVariables()
    public 
mixed invoke([mixed args [, ...]])
    public 
mixed invokeArgs(array args)
    public 
bool returnsReference()
    public 
ReflectionParameter[] getParameters()
    public 
int getNumberOfParameters()
    public 
int getNumberOfRequiredParameters()
}
?>

Parent class ReflectionFunctionAbstract has the same methods except invoke(), invokeArgs(), export() and isDisabled().

Note: getNumberOfParameters() and getNumberOfRequiredParameters() were added in PHP 5.0.3, while invokeArgs() was added in PHP 5.1.0.

To introspect a function, you will first have to create an instance of the ReflectionFunction class. You can then call any of the above methods on this instance.

Example #2 Using the ReflectionFunction class

<?php
/**
 * A simple counter
 *
 * @return    int
 */
function counter()
{
    static 
$c 0;
    return 
$c++;
}

// Create an instance of the ReflectionFunction class
$func = new ReflectionFunction('counter');

// Print out basic information
printf(
    
"===> The %s function '%s'\n".
    
"     declared in %s\n".
    
"     lines %d to %d\n",
    
$func->isInternal() ? 'internal' 'user-defined',
    
$func->getName(),
    
$func->getFileName(),
    
$func->getStartLine(),
    
$func->getEndline()
);

// Print documentation comment
printf("---> Documentation:\n %s\n"var_export($func->getDocComment(), 1));

// Print static variables if existant
if ($statics $func->getStaticVariables())
{
    
printf("---> Static variables: %s\n"var_export($statics1));
}

// Invoke the function
printf("---> Invokation results in: ");
var_dump($func->invoke());


// you may prefer to use the export() method
echo "\nReflectionFunction::export() results:\n";
echo 
ReflectionFunction::export('counter');
?>

Note: The method invoke() accepts a variable number of arguments which are passed to the function just as in call_user_func().

ReflectionParameter

The ReflectionParameter class retrieves information about a function's or method's parameters.

<?php
class ReflectionParameter implements Reflector
{
    final private 
__clone()
    public 
void __construct(string function, string parameter)
    public 
string __toString()
    public static 
string export(mixed function, mixed parameterbool return)
    public 
string getName()
    public 
bool isPassedByReference()
    public 
ReflectionClass getDeclaringClass()
    public 
ReflectionClass getClass()
    public 
bool isArray()
    public 
bool allowsNull()
    public 
bool isPassedByReference()
    public 
bool isOptional()
    public 
bool isDefaultValueAvailable()
    public 
mixed getDefaultValue()
    public 
int getPosition()
}
?>

Note: getDefaultValue(), isDefaultValueAvailable() and isOptional() were added in PHP 5.0.3, while isArray() was added in PHP 5.1.0. getDeclaringFunction() and getPosition() were added in PHP 5.2.3.

To introspect function parameters, you will first have to create an instance of the ReflectionFunction or ReflectionMethod classes and then use their getParameters() method to retrieve an array of parameters.

Example #3 Using the ReflectionParameter class

<?php
function foo($a$b$c) { }
function 
bar(Exception $a, &$b$c) { }
function 
baz(ReflectionFunction $a$b 1$c null) { }
function 
abc() { }

// Create an instance of ReflectionFunction with the
// parameter given from the command line.
$reflect = new ReflectionFunction($argv[1]);

echo 
$reflect;

foreach (
$reflect->getParameters() as $i => $param) {
    
printf(
        
"-- Parameter #%d: %s {\n".
        
"   Class: %s\n".
        
"   Allows NULL: %s\n".
        
"   Passed to by reference: %s\n".
        
"   Is optional?: %s\n".
        
"}\n",
        
$i// $param->getPosition() can be used from PHP 5.2.3
        
$param->getName(),
        
var_export($param->getClass(), 1),
        
var_export($param->allowsNull(), 1),
        
var_export($param->isPassedByReference(), 1),
        
$param->isOptional() ? 'yes' 'no'
    
);
}
?>

ReflectionClass

The ReflectionClass class lets you reverse-engineer classes and interfaces.

<?php
class ReflectionClass implements Reflector
{
    final private 
__clone()
    public 
void __construct(string name)
    public 
string __toString()
    public static 
string export(mixed class, bool return)
    public 
string getName()
    public 
bool isInternal()
    public 
bool isUserDefined()
    public 
bool isInstantiable()
    public 
bool hasConstant(string name)
    public 
bool hasMethod(string name)
    public 
bool hasProperty(string name)
    public 
string getFileName()
    public 
int getStartLine()
    public 
int getEndLine()
    public 
string getDocComment()
    public 
ReflectionMethod getConstructor()
    public 
ReflectionMethod getMethod(string name)
    public 
ReflectionMethod[] getMethods()
    public 
ReflectionProperty getProperty(string name)
    public 
ReflectionProperty[] getProperties()
    public array 
getConstants()
    public 
mixed getConstant(string name)
    public 
ReflectionClass[] getInterfaces()
    public 
bool isInterface()
    public 
bool isAbstract()
    public 
bool isFinal()
    public 
int getModifiers()
    public 
bool isInstance(stdclass object)
    public 
stdclass newInstance(mixed args)
    public 
stdclass newInstanceArgs(array args)
    public 
ReflectionClass getParentClass()
    public 
bool isSubclassOf(ReflectionClass class)
    public array 
getStaticProperties()
    public 
mixed getStaticPropertyValue(string name [, mixed default])
    public 
void setStaticPropertyValue(string namemixed value)
    public array 
getDefaultProperties()
    public 
bool isIterateable()
    public 
bool implementsInterface(string name)
    public 
ReflectionExtension getExtension()
    public 
string getExtensionName()
}
?>

Note: hasConstant(), hasMethod(), hasProperty(), getStaticPropertyValue() and setStaticPropertyValue() were added in PHP 5.1.0, while newInstanceArgs() was added in PHP 5.1.3.

To introspect a class, you will first have to create an instance of the ReflectionClass class. You can then call any of the above methods on this instance.

Example #4 Using the ReflectionClass class

<?php
interface Serializable
{
    
// ...
}

class 
Object
{
    
// ...
}

/**
 * A counter class
 */
class Counter extends Object implements Serializable
{
    const 
START 0;
    private static 
$c Counter::START;

    
/**
     * Invoke counter
     *
     * @access  public
     * @return  int
     */
    
public function count() {
        return 
self::$c++;
    }
}

// Create an instance of the ReflectionClass class
$class = new ReflectionClass('Counter');

// Print out basic information
printf(
    
"===> The %s%s%s %s '%s' [extends %s]\n" .
    
"     declared in %s\n" .
    
"     lines %d to %d\n" .
    
"     having the modifiers %d [%s]\n",
        
$class->isInternal() ? 'internal' 'user-defined',
        
$class->isAbstract() ? ' abstract' '',
        
$class->isFinal() ? ' final' '',
        
$class->isInterface() ? 'interface' 'class',
        
$class->getName(),
        
var_export($class->getParentClass(), 1),
        
$class->getFileName(),
        
$class->getStartLine(),
        
$class->getEndline(),
        
$class->getModifiers(),
        
implode(' 'Reflection::getModifierNames($class->getModifiers()))
);

// Print documentation comment
printf("---> Documentation:\n %s\n"var_export($class->getDocComment(), 1));

// Print which interfaces are implemented by this class
printf("---> Implements:\n %s\n"var_export($class->getInterfaces(), 1));

// Print class constants
printf("---> Constants: %s\n"var_export($class->getConstants(), 1));

// Print class properties
printf("---> Properties: %s\n"var_export($class->getProperties(), 1));

// Print class methods
printf("---> Methods: %s\n"var_export($class->getMethods(), 1));

// If this class is instantiable, create an instance
if ($class->isInstantiable()) {
    
$counter $class->newInstance();

    echo 
'---> $counter is instance? ';
    echo 
$class->isInstance($counter) ? 'yes' 'no';

    echo 
"\n---> new Object() is instance? ";
    echo 
$class->isInstance(new Object()) ? 'yes' 'no';
}
?>

Note: The method newInstance() accepts a variable number of arguments which are passed to the function just as in call_user_func().

Note: $class = new ReflectionClass('Foo'); $class->isInstance($arg) is equivalent to $arg instanceof Foo or is_a($arg, 'Foo').

ReflectionObject

The ReflectionObject class lets you reverse-engineer objects.

<?php
class ReflectionObject extends ReflectionClass
{
    final private 
__clone()
    public 
void __construct(mixed object)
    public 
string __toString()
    public static 
string export(mixed objectbool return)
}
?>

ReflectionMethod

The ReflectionMethod class lets you reverse-engineer class methods.

<?php
class ReflectionMethod extends ReflectionFunctionAbstract implements Reflector
{
    public 
void __construct(mixed class, string name)
    public 
string __toString()
    public static 
string export(mixed class, string namebool return)
    public 
mixed invoke(stdclass object [, mixed args [, ...]])
    public 
mixed invokeArgs(stdclass object, array args)
    public 
bool isFinal()
    public 
bool isAbstract()
    public 
bool isPublic()
    public 
bool isPrivate()
    public 
bool isProtected()
    public 
bool isStatic()
    public 
bool isConstructor()
    public 
bool isDestructor()
    public 
int getModifiers()
    public 
ReflectionClass getDeclaringClass()

    
// Inherited from ReflectionFunctionAbstract
    
final private __clone()
    public 
string getName()
    public 
bool isInternal()
    public 
bool isUserDefined()
    public 
string getFileName()
    public 
int getStartLine()
    public 
int getEndLine()
    public 
string getDocComment()
    public array 
getStaticVariables()
    public 
bool returnsReference()
    public 
ReflectionParameter[] getParameters()
    public 
int getNumberOfParameters()
    public 
int getNumberOfRequiredParameters()
}
?>

To introspect a method, you will first have to create an instance of the ReflectionMethod class. You can then call any of the above methods on this instance.

Example #5 Using the ReflectionMethod class

<?php
class Counter
{
    private static 
$c 0;

    
/**
     * Increment counter
     *
     * @final
     * @static
     * @access  public
     * @return  int
     */
    
final public static function increment()
    {
        return ++
self::$c;
    }
}

// Create an instance of the ReflectionMethod class
$method = new ReflectionMethod('Counter''increment');

// Print out basic information
printf(
    
"===> The %s%s%s%s%s%s%s method '%s' (which is %s)\n" .
    
"     declared in %s\n" .
    
"     lines %d to %d\n" .
    
"     having the modifiers %d[%s]\n",
        
$method->isInternal() ? 'internal' 'user-defined',
        
$method->isAbstract() ? ' abstract' '',
        
$method->isFinal() ? ' final' '',
        
$method->isPublic() ? ' public' '',
        
$method->isPrivate() ? ' private' '',
        
$method->isProtected() ? ' protected' '',
        
$method->isStatic() ? ' static' '',
        
$method->getName(),
        
$method->isConstructor() ? 'the constructor' 'a regular method',
        
$method->getFileName(),
        
$method->getStartLine(),
        
$method->getEndline(),
        
$method->getModifiers(),
        
implode(' 'Reflection::getModifierNames($method->getModifiers()))
);

// Print documentation comment
printf("---> Documentation:\n %s\n"var_export($method->getDocComment(), 1));

// Print static variables if existant
if ($statics$method->getStaticVariables()) {
    
printf("---> Static variables: %s\n"var_export($statics1));
}

// Invoke the method
printf("---> Invokation results in: ");
var_dump($method->invoke(NULL));
?>

ReflectionProperty

The ReflectionProperty class lets you reverse-engineer class properties.

<?php
class ReflectionProperty implements Reflector
{
    final private 
__clone()
    public 
void __construct(mixed class, string name)
    public 
string __toString()
    public static 
string export(mixed class, string namebool return)
    public 
string getName()
    public 
bool isPublic()
    public 
bool isPrivate()
    public 
bool isProtected()
    public 
bool isStatic()
    public 
bool isDefault()
    public 
void setAccessible() /* As of PHP 5.3.0 */
    
public int getModifiers()
    public 
mixed getValue(stdclass object)
    public 
void setValue(stdclass objectmixed value)
    public 
ReflectionClass getDeclaringClass()
    public 
string getDocComment()
}
?>

Note: getDocComment() was added in PHP 5.1.0. setAccessible() was added in PHP 5.3.0.

To introspect a property, you will first have to create an instance of the ReflectionProperty class. You can then call any of the above methods on this instance.

Example #6 Using the ReflectionProperty class

<?php
class String
{
    public 
$length  5;
}

// Create an instance of the ReflectionProperty class
$prop = new ReflectionProperty('String''length');

// Print out basic information
printf(
    
"===> The%s%s%s%s property '%s' (which was %s)\n" .
    
"     having the modifiers %s\n",
        
$prop->isPublic() ? ' public' '',
        
$prop->isPrivate() ? ' private' '',
        
$prop->isProtected() ? ' protected' '',
        
$prop->isStatic() ? ' static' '',
        
$prop->getName(),
        
$prop->isDefault() ? 'declared at compile-time' 'created at run-time',
        
var_export(Reflection::getModifierNames($prop->getModifiers()), 1)
);

// Create an instance of String
$obj= new String();

// Get current value
printf("---> Value is: ");
var_dump($prop->getValue($obj));

// Change value
$prop->setValue($obj10);
printf("---> Setting value to 10, new value is: ");
var_dump($prop->getValue($obj));

// Dump object
var_dump($obj);
?>

Example #7 Getting value from private and protected properties using ReflectionProperty class

<?php

class Foo {
    public 
$x 1;
    protected 
$y 2;
    private 
$z 3;
}

$obj = new Foo;

$prop = new ReflectionProperty('Foo''y');
$prop->setAccessible(true); /* As of PHP 5.3.0 */
var_dump($prop->getValue($obj)); // int(2)

$prop = new ReflectionProperty('Foo''z');
$prop->setAccessible(true); /* As of PHP 5.3.0 */
var_dump($prop->getValue($obj)); // int(2)

?>

Note: Trying to get or set private or protected class property's values will result in an exception being thrown.

ReflectionExtension

The ReflectionExtension class lets you reverse-engineer extensions. You can retrieve all loaded extensions at runtime using the get_loaded_extensions().

<?php
class ReflectionExtension implements Reflector {
    final private 
__clone()
    public 
void __construct(string name)
    public 
string __toString()
    public static 
string export(string namebool return)
    public 
string getName()
    public 
string getVersion()
    public 
ReflectionFunction[] getFunctions()
    public array 
getConstants()
    public array 
getINIEntries()
    public 
ReflectionClass[] getClasses()
    public array 
getClassNames()
    public 
string info()
}
?>

To introspect an extension, you will first have to create an instance of the ReflectionExtension class. You can then call any of the above methods on this instance.

Example #8 Using the ReflectionExtension class

<?php
// Create an instance of the ReflectionExtension class
$ext = new ReflectionExtension('standard');

// Print out basic information
printf(
    
"Name        : %s\n" .
    
"Version     : %s\n" .
    
"Functions   : [%d] %s\n" .
    
"Constants   : [%d] %s\n" .
    
"INI entries : [%d] %s\n" .
    
"Classes     : [%d] %s\n",
        
$ext->getName(),
        
$ext->getVersion() ? $ext->getVersion() : 'NO_VERSION',
        
sizeof($ext->getFunctions()),
        
var_export($ext->getFunctions(), 1),

        
sizeof($ext->getConstants()),
        
var_export($ext->getConstants(), 1),

        
sizeof($ext->getINIEntries()),
        
var_export($ext->getINIEntries(), 1),

        
sizeof($ext->getClassNames()),
        
var_export($ext->getClassNames(), 1)
);
?>

Extending the reflection classes

In case you want to create specialized versions of the built-in classes (say, for creating colorized HTML when being exported, having easy-access member variables instead of methods or having utility methods), you may go ahead and extend them.

Example #9 Extending the built-in classes

<?php
/**
 * My Reflection_Method class
 */
class My_Reflection_Method extends ReflectionMethod
{
    public 
$visibility = array();

    public function 
__construct($o$m)
    {
        
parent::__construct($o$m);
        
$this->visibility Reflection::getModifierNames($this->getModifiers());
    }
}

/**
 * Demo class #1
 *
 */
class {
    protected function 
x() {}
}

/**
 * Demo class #2
 *
 */
class extends {
    function 
x() {}
}

// Print out information
var_dump(new My_Reflection_Method('U''x'));
?>

Note: Caution: If you're overwriting the constructor, remember to call the parent's constructor before any code you insert. Failing to do so will result in the following: Fatal error: Internal error: Failed to retrieve the reflection object



Type Hinting

PHP 5 introduces Type Hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype) or arrays (since PHP 5.1). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call.

Example #1 Type Hinting examples

<?php
// An example class
class MyClass
{
    
/**
     * A test function
     *
     * First parameter must be an object of type OtherClass
     */
    
public function test(OtherClass $otherclass) {
        echo 
$otherclass->var;
    }


    
/**
     * Another test function
     *
     * First parameter must be an array
     */
    
public function test_array(array $input_array) {
        
print_r($input_array);
    }
}

// Another example class
class OtherClass {
    public 
$var 'Hello World';
}
?>

Failing to satisfy the type hint results in a catchable fatal error.

<?php
// An instance of each class
$myclass = new MyClass;
$otherclass = new OtherClass;

// Fatal Error: Argument 1 must be an object of class OtherClass
$myclass->test('hello');

// Fatal Error: Argument 1 must be an instance of OtherClass
$foo = new stdClass;
$myclass->test($foo);

// Fatal Error: Argument 1 must not be null
$myclass->test(null);

// Works: Prints Hello World
$myclass->test($otherclass);

// Fatal Error: Argument 1 must be an array
$myclass->test_array('a string');

// Works: Prints the array
$myclass->test_array(array('a''b''c'));
?>

Type hinting also works with functions:

<?php
// An example class
class MyClass {
    public 
$var 'Hello World';
}

/**
 * A test function
 *
 * First parameter must be an object of type MyClass
 */
function MyFunction (MyClass $foo) {
    echo 
$foo->var;
}

// Works
$myclass = new MyClass;
MyFunction($myclass);
?>

Type hinting allowing NULL value:

<?php

/* Accepting NULL value */
function test(stdClass $obj NULL) {

}

test(NULL);
test(new stdClass);

?>

Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.



Late Static Bindings

As of PHP 5.3.0, PHP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance.

This feature was named "late static bindings" with an internal perspective in mind. "Late binding" comes from the fact that static:: will no longer be resolved using the class where the method is defined but it will rather be computed using runtime information. It was also called a "static binding" as it can be used for (but is not limited to) static method calls.

Limitations of self::

Static references to the current class like self:: or __CLASS__ are resolved using the class in which the function belongs, as in where it was defined:

Example #1 self:: usage

<?php
class {
    public static function 
who() {
        echo 
__CLASS__;
    }
    public static function 
test() {
        
self::who();
    }
}

class 
extends {
    public static function 
who() {
         echo 
__CLASS__;
    }
}

B::test();
?>

위 예제의 출력:

A

Late Static Bindings' usage

Late static bindings tries to solve that limitation by introducing a keyword that references the class that was initially called at runtime. Basically, a keyword that would allow you to reference B from test() in the previous example. It was decided not to introduce a new keyword but rather use static that was already reserved.

Example #2 static:: simple usage

<?php
class {
    public static function 
who() {
        echo 
__CLASS__;
    }
    public static function 
test() {
        static::
who(); // Here comes Late Static Bindings
    
}
}

class 
extends {
    public static function 
who() {
         echo 
__CLASS__;
    }
}

B::test();
?>

위 예제의 출력:

B

Note: static:: does not work like $this for static methods! $this-> follows the rules of inheritance while static:: doesn't. This difference is detailed later on this manual page.

Example #3 static:: usage in a non-static context

<?php
class TestChild extends TestParent {
    public function 
__construct() {
        static::
who();
    }

    public function 
test() {
        
$o = new TestParent();
    }

    public static function 
who() {
        echo 
__CLASS__."\n";
    }
}

class 
TestParent {
    public function 
__construct() {
        static::
who();
    }

    public static function 
who() {
        echo 
__CLASS__."\n";
    }
}
$o = new TestChild;
$o->test();

?>

위 예제의 출력:

TestChild
TestParent

Note: Late static bindings' resolution will stop at a fully resolved static call with no fallback. On the other hand, static calls using keywords like parent:: or self:: will forward the calling information.

Example #4 Forwarding and non-forwarding calls

<?php
class {
    public static function 
foo() {
        static::
who();
    }

    public static function 
who() {
        echo 
__CLASS__."\n";
    }
}

class 
extends {
    public static function 
test() {
        
A::foo();
        
parent::foo();
        
self::foo();
    }

    public static function 
who() {
        echo 
__CLASS__."\n";
    }
}
class 
extends {
    public static function 
who() {
        echo 
__CLASS__."\n";
    }
}

C::test();
?>

위 예제의 출력:

A
C
C

Edge cases

There are lots of different ways to trigger a method call in PHP, like callbacks or magic methods. As late static bindings base their resolution on runtime information, it might give unexpected results in so-called edge cases.

Example #5 Late static bindings inside magic methods

<?php
class {

   protected static function 
who() {
        echo 
__CLASS__."\n";
   }

   public function 
__get($var) {
       return static::
who();
   }
}

class 
extends {

   protected static function 
who() {
        echo 
__CLASS__."\n";
   }
}

$b = new B;
$b->foo;
?>

위 예제의 출력:

B


Objects and references

One of the key-points of PHP5 OOP that is often mentioned is that "objects are passed by references by default". This is not completely true. This section rectifies that general thought using some examples.

A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.

Example #1 References and Objects

<?php
class {
    public 
$foo 1;
}  

$a = new A;
$b $a;     // $a and $b are copies of the same identifier
             // ($a) = ($b) = <id>
$b->foo 2;
echo 
$a->foo."\n";


$c = new A;
$d = &$c;    // $c and $d are references
             // ($c,$d) = <id>

$d->foo 2;
echo 
$c->foo."\n";


$e = new A;

function 
foo($obj) {
    
// ($obj) = ($e) = <id>
    
$obj->foo 2;
}

foo($e);
echo 
$e->foo."\n";

?>

위 예제의 출력:

2
2
2



Namespaces

Table of Contents


Namespaces overview

What are namespaces? In the broadest definition namespaces are a way of encapsulating items. This can be seen as an abstract concept in many places. For example, in any operating system directories serve to group related files, and act as a namespace for the files within them. As a concrete example, the file foo.txt can exist in both directory /home/greg and in /home/other, but two copies of foo.txt cannot co-exist in the same directory. In addition, to access the foo.txt file outside of the /home/greg directory, we must prepend the directory name to the file name using the directory separator to get /home/greg/foo.txt. This same principle extends to namespaces in the programming world.

In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions:

  1. Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
  2. Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.

PHP Namespaces provide a way in which to group related classes, functions and constants. Here is an example of namespace syntax in PHP:

Example #1 Namespace syntax example

<?php
namespace my\name// see "Defining Namespaces" section

class MyClass {}
function 
myfunction() {}
const 
MYCONST 1;

$a = new MyClass;
$c = new \my\name\MyClass// see "Global Space" section

$a strlen('hi'); // see "Using namespaces: fallback to global
                   // function/constant" section

$d = namespace\MYCONST// see "namespace operator and __NAMESPACE__
                        // constant" section
$d __NAMESPACE__ '\MYCONST';
echo 
constant($d); // see "Namespaces and dynamic language features" section
?>

Namespaces are available in PHP as of PHP 5.3.0.



Defining namespaces

Although any valid PHP code can be contained within a namespace, only three type of code are affected by namespaces: classes, functions and constants.

Namespaces are declared using the namespace keyword. A file containing a namespace must declare the namespace at the top of the file before any other code - with one exception: the declare keyword.

Example #1 Declaring a single namespace

<?php
namespace MyProject;

const 
CONNECT_OK 1;
class 
Connection /* ... */ }
function 
connect() { /* ... */  }

?>

The only code construct allowed before a namespace declaration is the declare statement, for defining encoding of a source file. In addition, no non-PHP code may precede a namespace declaration, including extra whitespace:

Example #2 Declaring a single namespace

<html>
<?php
namespace MyProject// fatal error - namespace must be the first statement in the script
?>

In addition, unlike any other PHP construct, the same namespace may be defined in multiple files, allowing splitting up of a namespace's contents across the filesystem.



Declaring sub-namespaces

Much like directories and files, PHP namespaces also contain the ability to specify a hierarchy of namespace names. Thus, a namespace name can be defined with sub-levels:

Example #1 Declaring a single namespace with hierarchy

<?php
namespace MyProject\Sub\Level;

const 
CONNECT_OK 1;
class 
Connection /* ... */ }
function 
connect() { /* ... */  }

?>

The above example creates constant MyProject\Sub\Level\CONNECT_OK, class MyProject\Sub\Level\Connection and function MyProject\Sub\Level\connect.



Defining multiple namespaces in the same file

Multiple namespaces may also be declared in the same file. There are two allowed syntaxes.

Example #1 Declaring multiple namespaces, simple combination syntax

<?php
namespace MyProject;

const 
CONNECT_OK 1;
class 
Connection /* ... */ }
function 
connect() { /* ... */  }

namespace 
AnotherProject;

const 
CONNECT_OK 1;
class 
Connection /* ... */ }
function 
connect() { /* ... */  }
?>

This syntax is not recommended for combining namespaces into a single file. Instead it is recommended to use the alternate bracketed syntax.

Example #2 Declaring multiple namespaces, bracketed syntax

<?php
namespace MyProject {

const 
CONNECT_OK 1;
class 
Connection /* ... */ }
function 
connect() { /* ... */  }
}

namespace 
AnotherProject {

const 
CONNECT_OK 1;
class 
Connection /* ... */ }
function 
connect() { /* ... */  }
}
?>

It is strongly discouraged as a coding practice to combine multiple namespaces into the same file. The primary use case is to combine multiple PHP scripts into the same file.

To combine global non-namespaced code with namespaced code, only bracketed syntax is supported. Global code should be encased in a namespace statement with no namespace name as in:

Example #3 Declaring multiple namespaces and unnamespaced code

<?php
namespace MyProject {

const 
CONNECT_OK 1;
class 
Connection /* ... */ }
function 
connect() { /* ... */  }
}

namespace { 
// global code
session_start();
$a MyProject\connect();
echo 
MyProject\Connection::start();
}
?>

No PHP code may exist outside of the namespace brackets except for an opening declare statement.

Example #4 Declaring multiple namespaces and unnamespaced code

<?php
declare(encoding='UTF-8');
namespace 
MyProject {

const 
CONNECT_OK 1;
class 
Connection /* ... */ }
function 
connect() { /* ... */  }
}

namespace { 
// global code
session_start();
$a MyProject\connect();
echo 
MyProject\Connection::start();
}
?>



Using namespaces: Basics

Before discussing the use of namespaces, it is important to understand how PHP knows which namespaced element your code is requesting. A simple analogy can be made between PHP namespaces and a filesystem. There are three ways to access a file in a file system:

  1. Relative file name like foo.txt. This resolves to currentdirectory/foo.txt where currentdirectory is the directory currently occupied. So if the current directory is /home/foo, the name resolves to /home/foo/foo.txt.
  2. Relative path name like subdirectory/foo.txt. This resolves to currentdirectory/subdirectory/foo.txt.
  3. Absolute path name like /main/foo.txt. This resolves to /main/foo.txt.

The same principle can be applied to namespaced elements in PHP. For example, a class name can be referred to in three ways:

  1. Unqualified name, or an unprefixed class name like $a = new foo(); or foo::staticmethod();. If the current namespace is currentnamespace, this resolves to currentnamespace\foo. If the code is global, non-namespaced code, this resolves to foo. One caveat: unqualified names for functions and constants will resolve to global functions and constants if the namespaced function or constant is not defined. See Using namespaces: fallback to global function/constant for details.
  2. Qualified name, or a prefixed class name like $a = new subnamespace\foo(); or subnamespace\foo::staticmethod();. If the current namespace is currentnamespace, this resolves to currentnamespace\subnamespace\foo. If the code is global, non-namespaced code, this resolves to subnamespace\foo.
  3. Fully qualified name, or a prefixed name with global prefix operator like $a = new \currentnamespace\foo(); or \currentnamespace\foo::staticmethod();. This always resolves to the literal name specified in the code, currentnamespace\foo.

Here is an example of the three kinds of syntax in actual code:

file1.php

<?php
namespace Foo\Bar\subnamespace;

const 
FOO 1;
function 
foo() {}
class 
foo
{
    static function 
staticmethod() {}
}
?>

file2.php

<?php
namespace Foo\Bar;
include 
'file1.php';

const 
FOO 2;
function 
foo() {}
class 
foo
{
    static function 
staticmethod() {}
}

/* Unqualified name */
foo(); // resolves to function Foo\Bar\foo
foo::staticmethod(); // resolves to class Foo\Bar\foo, method staticmethod
echo FOO// resolves to constant Foo\Bar\FOO

/* Qualified name */
subnamespace\foo(); // resolves to function Foo\Bar\subnamespace\foo
subnamespace\foo::staticmethod(); // resolves to class Foo\Bar\subnamespace\foo,
                                  // method staticmethod
echo subnamespace\FOO// resolves to constant Foo\Bar\subnamespace\FOO
                                  
/* Fully qualified name */
\Foo\Bar\foo(); // resolves to function Foo\Bar\foo
\Foo\Bar\foo::staticmethod(); // resolves to class Foo\Bar\foo, method staticmethod
echo \Foo\Bar\FOO// resolves to constant Foo\Bar\FOO
?>

Note that to access any global class, function or constant, a fully qualified name can be used, such as \strlen() or \Exception or \INI_ALL.

Example #1 Accessing global classes, functions and constants from within a namespace

<?php
namespace Foo;

function 
strlen() {}
const 
INI_ALL 3;
class 
Exception {}

$a = \strlen('hi'); // calls global function strlen
$b = \INI_ALL// accesses global constant INI_ALL
$c = new \Exception('error'); // instantiates global class Exception
?>



Namespaces and dynamic language features

PHP's implementation of namespaces is influenced by its dynamic nature as a programming language. Thus, to convert code like the following example into namespaced code:

Example #1 Dynamically accessing elements

example1.php:

<?php
class classname
{
    function 
__construct()
    {
        echo 
__METHOD__,"\n";
    }
}
function 
funcname()
{
    echo 
__FUNCTION__,"\n";
}
const 
constname "global";

$a 'classname';
$obj = new $a// prints classname::__construct
$b 'funcname';
$b(); // prints funcname
echo constant('constname'), "\n"// prints global
?>

One must use the fully qualified name (class name with namespace prefix). Note that because there is no difference between a qualified and a fully qualified Name inside a dynamic class name, function name, or constant name, the leading backslash is not necessary.

Example #2 Dynamically accessing namespaced elements

<?php
namespace namespacename;
class 
classname
{
    function 
__construct()
    {
        echo 
__METHOD__,"\n";
    }
}
function 
funcname()
{
    echo 
__FUNCTION__,"\n";
}
const 
constname "namespaced";

include 
'example1.php';

$a 'classname';
$obj = new $a// prints classname::__construct
$b 'funcname';
$b(); // prints funcname
echo constant('constname'), "\n"// prints global

/* note that if using double quotes, "\\namespacename\\classname" must be used */
$a '\namespacename\classname';
$obj = new $a// prints namespacename\classname::__construct
$a 'namespacename\classname';
$obj = new $a// also prints namespacename\classname::__construct
$b 'namespacename\funcname';
$b(); // prints namespacename\funcname
$b '\namespacename\funcname';
$b(); // also prints namespacename\funcname
echo constant('\namespacename\constname'), "\n"// prints namespaced
echo constant('namespacename\constname'), "\n"// also prints namespaced
?>

Be sure to read the note about escaping namespace names in strings.



namespace keyword and __NAMESPACE__ constant

PHP supports two ways of abstractly accessing elements within the current namespace, the __NAMESPACE__ magic constant, and the namespace keyword.

The value of __NAMESPACE__ is a string that contains the current namespace name. In global, un-namespaced code, it contains an empty string.

Example #1 __NAMESPACE__ example, namespaced code

<?php
namespace MyProject;

echo 
'"'__NAMESPACE__'"'// outputs "MyProject"
?>

Example #2 __NAMESPACE__ example, global code

<?php

echo '"'__NAMESPACE__'"'// outputs ""
?>

The __NAMESPACE__ constant is useful for dynamically constructing names, for instance:

Example #3 using __NAMESPACE__ for dynamic name construction

<?php
namespace MyProject;

function 
get($classname)
{
    
$a __NAMESPACE__ '\\' $classname;
    return new 
$a;
}
?>

The namespace keyword can be used to explicitly request an element from the current namespace or a sub-namespace. It is the namespace equivalent of the self operator for classes.

Example #4 the namespace operator, inside a namespace

<?php
namespace MyProject;

use 
blah\blah as mine// see "Using namespaces: importing/aliasing"

blah\mine(); // calls function MyProject\blah\mine()
namespace\blah\mine(); // calls function MyProject\blah\mine()

namespace\func(); // calls function MyProject\func()
namespace\sub\func(); // calls function MyProject\sub\func()
namespace\cname::method(); // calls static method "method" of class MyProject\cname
$a = new namespace\sub\cname(); // instantiates object of class MyProject\sub\cname
$b = namespace\CONSTANT// assigns value of constant MyProject\CONSTANT to $b
?>

Example #5 the namespace operator, in global code

<?php

namespace\func(); // calls function func()
namespace\sub\func(); // calls function sub\func()
namespace\cname::method(); // calls static method "method" of class cname
$a = new namespace\sub\cname(); // instantiates object of class sub\cname
$b = namespace\CONSTANT// assigns value of constant CONSTANT to $b
?>



Using namespaces: Aliasing/Importing

The ability to refer to an external fully qualified name with an alias, or importing, is an important feature of namespaces. This is similar to the ability of unix-based filesystems to create symbolic links to a file or to a directory.

PHP namespaces support two kinds of aliasing or importing: aliasing a class name, and aliasing a namespace name. Note that importing a function or constant is not supported.

In PHP, aliasing is accomplished with the use operator. Here is an example showing all 3 kinds of importing:

Example #1 importing/aliasing with the use operator

<?php
namespace foo;
use 
My\Full\Classname as Another;

// this is the same as use My\Full\NSname as NSname
use My\Full\NSname;

// importing a global class
use \ArrayObject;

$obj = new namespace\Another// instantiates object of class foo\Another
$obj = new Another// instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
$a = new ArrayObject(array(1)); // instantiates object of class ArrayObject
// without the "use \ArrayObject" we would instantiate an object of class foo\ArrayObject
?>

Note that for namespaced names (fully qualified namespace names containing namespace separator, such as Foo\Bar as opposed to global names that do not, such as FooBar), the leading backslash is unnecessary and not allowed, as import names must be fully qualified, and are not processed relative to the current namespace.

PHP additionally supports a convenience shortcut to place multiple use statements on the same line

Example #2 importing/aliasing with the use operator, multiple use statements combined

<?php
use My\Full\Classname as AnotherMy\Full\NSname;

$obj = new Another// instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
?>

Importing is performed at compile-time, and so does not affect dynamic class, function or constant names.

Example #3 Importing and dynamic names

<?php
use My\Full\Classname as AnotherMy\Full\NSname;

$obj = new Another// instantiates object of class My\Full\Classname
$a 'Another';
$obj = new $a;      // instantiates object of class Another
?>

In addition, importing only affects unqualified and qualified names. Fully qualified names are absolute, and unaffected by imports.

Example #4 Importing and fully qualified names

<?php
use My\Full\Classname as AnotherMy\Full\NSname;

$obj = new Another// instantiates object of class My\Full\Classname
$obj = new \Another// instantiates object of class Another
$obj = new Another\thing// instantiates object of class My\Full\Classname\thing
$obj = new \Another\thing// instantiates object of class Another\thing
?>



Global space

Without any namespace definition, all class and function definitions are placed into the global space - as it was in PHP before namespaces were supported. Prefixing a name with \ will specify that the name is required from the global space even in the context of the namespace.

Example #1 Using global space specification

<?php
namespace A\B\C;

/* This function is A\B\C\fopen */
function fopen() { 
     
/* ... */
     
$f = \fopen(...); // call global fopen
     
return $f;

?>



Using namespaces: fallback to global function/constant

Inside a namespace, when PHP encounters a unqualified Name in a class name, function or constant context, it resolves these with different priorities. Class names always resolve to the current namespace name. Thus to access internal or non-namespaced user classes, One must refer to them with their fully qualified Name as in:

Example #1 Accessing global classes inside a namespace

<?php
namespace A\B\C;
class 
Exception extends \Exception {}

$a = new Exception('hi'); // $a is an object of class A\B\C\Exception
$b = new \Exception('hi'); // $b is an object of class Exception

$c = new ArrayObject// fatal error, class A\B\C\ArrayObject not found
?>

For functions and constants, PHP will fall back to global functions or constants if a namespaced function or constant does not exist.

Example #2 global functions/constants fallback inside a namespace

<?php
namespace A\B\C;

const 
E_ERROR 45;
function 
strlen($str)
{
    return \
strlen($str) - 1;
}

echo 
E_ERROR"\n"// prints "45"
echo INI_ALL"\n"// prints "7" - falls back to global INI_ALL

echo strlen('hi'), "\n"// prints "1"
if (is_array('hi')) { // prints "is not array"
    
echo "is array\n";
} else {
    echo 
"is not array\n";
}
?>



Name resolution rules

For the purposes of these resolution rules, here are some important definitions:

Namespace name definitions
Unqualified name

This is an identifier without a namespace separator, such as Foo

Qualified name

This is an identifier with a namespace separator, such as Foo\Bar

Fully qualified name

This is an identifier with a namespace separator that begins with a namespace separator, such as \Foo\Bar. namespace\Foo is also a fully qualified name.

Names are resolved following these resolution rules:

  1. Calls to fully qualified functions, classes or constants are resolved at compile-time. For instance new \A\B resolves to class A\B.
  2. All unqualified and qualified names (not fully qualified names) are translated during compilation according to current import rules. For example, if the namespace A\B\C is imported as C, a call to C\D\e() is translated to A\B\C\D\e().
  3. Inside a namespace, all qualified names not translated according to import rules have the current namespace prepended. For example, if a call to C\D\e() is performed within namespace A\B, it is translated to A\B\C\D\e().
  4. Unqualified class names are translated during compilation according to current import rules (full name substituted for short imported name). In example, if the namespace A\B\C is imported as C, new C() is translated to new A\B\C().
  5. Inside namespace (say A\B), calls to unqualified functions are resolved at run-time. Here is how a call to function foo() is resolved:
    1. It looks for a function from the current namespace: A\B\foo().
    2. It tries to find and call the global function foo().
  6. Inside namespace (say A\B), calls to unqualified or qualified class names (not fully qualified class names) are resolved at run-time. Here is how a call to new C() or new D\E() is resolved. For new C():
    1. It looks for a class from the current namespace: A\B\C.
    2. It attemts to autoload A\B\C.
    For new D\E():
    1. It looks for a class by prepending the current namespace: A\B\D\E.
    2. It attemts to autoload A\B\D\E.
    To reference any global class in the global namespace, its fully qualified name new \C() must be used.

Example #1 Name resolutions illustrated

<?php
namespace A;
use 
B\DC\as F;

// function calls

foo();      // first tries to call "foo" defined in namespace "A"
            // then calls global function "foo"

\foo();     // calls function "foo" defined in global scope

my\foo();   // calls function "foo" defined in namespace "A\my"

F();        // first tries to call "F" defined in namespace "A"
            // then calls global function "F"

// class references

new B();    // creates object of class "B" defined in namespace "A"
            // if not found, it tries to autoload class "A\B"

new D();    // using import rules, creates object of class "D" defined in namespace "B"
            // if not found, it tries to autoload class "B\D"

new F();    // using import rules, creates object of class "E" defined in namespace "C"
            // if not found, it tries to autoload class "C\E"

new \B();   // creates object of class "B" defined in global scope
            // if not found, it tries to autoload class "B"

new \D();   // creates object of class "D" defined in global scope
            // if not found, it tries to autoload class "D"

new \F();   // creates object of class "F" defined in global scope
            // if not found, it tries to autoload class "F"

// static methods/namespace functions from another namespace

B\foo();    // calls function "foo" from namespace "A\B"

B::foo();   // calls method "foo" of class "B" defined in namespace "A"
            // if class "A\B" not found, it tries to autoload class "A\B"

D::foo();   // using import rules, calls method "foo" of class "D" defined in namespace "B"
            // if class "B\D" not found, it tries to autoload class "B\D"

\B\foo();   // calls function "foo" from namespace "B"

\B::foo();  // calls method "foo" of class "B" from global scope
            // if class "B" not found, it tries to autoload class "B"

// static methods/namespace functions of current namespace

A\B::foo();   // calls method "foo" of class "B" from namespace "A\A"
              // if class "A\A\B" not found, it tries to autoload class "A\A\B"

\A\B::foo();  // calls method "foo" of class "B" from namespace "A\B"
              // if class "A\B" not found, it tries to autoload class "A\B"
?>


FAQ: things you need to know about namespaces

This FAQ is split into two sections: common questions, and some specifics of implementation that are helpful to understand fully.

First, the common questions.

  1. If I don't use namespaces, should I care about any of this?
  2. How do I use internal or global classes in a namespace?
  3. How do I use namespaces classes functions, or constants in their own namespace?
  4. How does a name like \my\name or \name resolve?
  5. How does a name like my\name resolve?
  6. How does an unqualified class name like name resolve?
  7. How does an unqualified function name or unqualified constant name like name resolve?

There are a few implementation details of the namespace implementations that are helpful to understand.

  1. Import names cannot conflict with classes defined in the same file.
  2. Nested namespaces are not allowed.
  3. Neither functions nor constants can be imported via the use statement.
  4. Dynamic namespace names (quoted identifiers) should escape backslash.
  5. Undefined Constants referenced using any backslash die with fatal error
  6. Cannot override special constants NULL, TRUE, FALSE, ZEND_THREAD_SAFE or ZEND_DEBUG_BUILD

If I don't use namespaces, should I care about any of this?

No. Namespaces do not affect any existing code in any way, or any as-yet-to-be-written code that does not contain namespaces. You can write this code if you wish:

Example #1 Accessing global classes outside a namespace

<?php
$a 
= new \stdClass;

This is functionally equivalent to:

Example #2 Accessing global classes outside a namespace

<?php
$a 
= new stdClass;

How do I use internal or global classes in a namespace?

Example #3 Accessing internal classes in namespaces

<?php
namespace foo;
$a = new \stdClass;

function 
test(\ArrayObject $typehintexample null) {}

$a = \DirectoryIterator::CURRENT_AS_FILEINFO;

// extending an internal or global class
class MyException extends \Exception {}
?>

How do I use namespaces classes, functions, or constants in their own namespace?

Example #4 Accessing internal classes, functions or constants in namespaces

<?php
namespace foo;

class 
MyClass {}

// using a class from the current namespace as a type hint
function test(MyClass $typehintexample null) {}
// another way to use a class from the current namespace as a type hint
function test(\foo\MyClass $typehintexample null) {}

// extending a class from the current namespace
class Extended extends MyClass {}

// accessing a global function
$a = \globalfunc();

// accessing a global constant
$b = \INI_ALL;
?>

How does a name like \my\name or \name resolve?

Names that begin with a \ always resolve to what they look like, so \my\name is in fact my\name, and \Exception is Exception.

Example #5 Fully Qualified names

<?php
namespace foo;
$a = new \my\name(); // instantiates "my\name" class
echo \strlen('hi'); // calls function "strlen"
$a = \INI_ALL// $a is set to the value of constant "INI_ALL"
?>

How does a name like my\name resolve?

Names that contain a backslash but do not begin with a backslash like my\name can be resolved in 2 different ways.

If there is an import statement that aliases another name to my, then the import alias is applied to the my in my\name.

Otherwise, the current namespace name is prepended to my\name.

Example #6 Qualified names

<?php
namespace foo;
use 
blah\blah as foo;

$a = new my\name(); // instantiates "foo\my\name" class
foo\bar::name(); // calls static method "name" in class "blah\blah\bar"
my\bar(); // calls function "foo\my\bar"
$a my\BAR// sets $a to the value of constant "foo\my\BAR"
?>

How does an unqualified class name like name resolve?

Class names that do not contain a backslash like name can be resolved in 2 different ways.

If there is an import statement that aliases another name to name, then the import alias is applied.

Otherwise, the current namespace name is prepended to name.

Example #7 Unqualified class names

<?php
namespace foo;
use 
blah\blah as foo;

$a = new name(); // instantiates "foo\name" class
foo::name(); // calls static method "name" in class "blah\blah"
?>

How does an unqualified function name or unqualified constant name like name resolve?

Function or constant names that do not contain a backslash like name can be resolved in 2 different ways.

First, the current namespace name is prepended to name.

Finally, if the constant or function name does not exist in the current namespace, a global constant or function name is used if it exists.

Example #8 Unqualified function or constant names

<?php
namespace foo;
use 
blah\blah as foo;

const 
FOO 1;

function 
my() {}
function 
foo() {}
function 
sort(&$a)
{
    
sort($a);
    
$a array_flip($a);
    return 
$a;
}

my(); // calls "foo\my"
$a strlen('hi'); // calls global function "strlen" because "foo\strlen" does not exist
$arr = array(1,3,2);
$b sort($arr); // calls function "foo\sort"
$c foo(); // calls function "foo\foo" - import is not applied

$a FOO// sets $a to value of constant "foo\FOO" - import is not applied
$b INI_ALL// sets $b to value of global constant "INI_ALL"
?>

Import names cannot conflict with classes defined in the same file.

The following script combinations are legal:

file1.php

<?php
namespace my\stuff;
class 
MyClass {}
?>

another.php

<?php
namespace another;
class 
thing {}
?>

file2.php

<?php
namespace my\stuff;
include 
'file1.php';
include 
'another.php';

use 
another\thing as MyClass;
$a = new MyClass// instantiates class "thing" from namespace another
?>

There is no name conflict, even though the class MyClass exists within the my\stuff namespace, because the MyClass definition is in a separate file. However, the next example causes a fatal error on name conflict because MyClass is defined in the same file as the use statement.

<?php
namespace my\stuff;
use 
another\thing as MyClass;
class 
MyClass {} // fatal error: MyClass conflicts with import statement
$a = new MyClass;
?>

Nested namespaces are not allowed.

PHP does not allow nesting namespaces

<?php
namespace my\stuff {
    namespace 
nested {
        class 
foo {}
    }
}
?>

However, it is easy to simulate nested namespaces like so:

<?php
namespace my\stuff\nested {
    class 
foo {}
}
?>

Neither functions nor constants can be imported via the use statement.

The only elements that are affected by use statements are namespaces and class names. In order to shorten a long constant or function, import its containing namespace

<?php
namespace mine;
use 
ultra\long\ns\name;

$a name\CONSTANT;
name\func();
?>

Dynamic namespace names (quoted identifiers) should escape backslash

It is very important to realize that because the backslash is used as an escape character within strings, it should always be doubled when used inside a string. Otherwise there is a risk of unintended consequences:

Example #9 Dangers of using namespaced names inside a double-quoted string

<?php
$a 
= new "dangerous\name"// \n is a newline inside double quoted strings!
$obj = new $a;

$a = new 'not\at\all\dangerous'// no problems here.
$obj = new $a;
?>

Inside a single-quoted string, the backslash escape sequence is much safer to use, but it is still recommended practice to escape backslashes in all strings as a best practice.

Undefined Constants referenced using any backslash die with fatal error

Any undefined constant that is unqualified like FOO will produce a notice explaining that PHP assumed FOO was the value of the constant. Any constant, qualified or fully qualified, that contains a backslash will produce a fatal error if not found.

Example #10 Undefined constants

<?php
namespace bar;
$a FOO// produces notice - undefined constants "FOO" assumed "FOO";
$a = \FOO// fatal error, undefined namespace constant FOO
$a Bar\FOO// fatal error, undefined namespace constant bar\Bar\FOO
$a = \Bar\FOO// fatal error, undefined namespace constant Bar\FOO
?>

Cannot override special constants NULL, TRUE, FALSE, ZEND_THREAD_SAFE or ZEND_DEBUG_BUILD

Any attempt to define a namespaced constant that is a special, built-in constant results in a fatal error

Example #11 Undefined constants

<?php
namespace bar;
const 
NULL 0// fatal error;
const true 'stupid'// also fatal error;
// etc.
?>




예외

Table of Contents

PHP 5는 다른 프로그래밍 언어와 유사한 예외 모델을 가지고 있습니다. 예외는 throw해서, PHP 안에서 잡을("catch") 수 있습니다. 잠재적인 예외를 쉽게 잡기 위해서 코드를 try 블럭으로 감쌀 수 있습니다. 각 try는 최소한 하나의 해당하는 catch 블럭을 가져야 합니다. 여러 catch 블럭은 각각 다른 예외 클래스를 잡을 수 있습니다. 일반적인 실행(try 블럭에서 예외를 던지지 않거나, 던져진 예외 클래스에 해당하는 catch가 없을 경우)은 마지막 catch 블럭 정의 이후로 진행합니다. 예외는 catch 블럭 안에서 throw할(또는 다시 던질) 수 있습니다.

예외가 던져지면, 따라오는 구문은 실행되지 않고, PHP는 첫번째 해당하는 catch 블럭을 찾습니다. 예외를 잡지 않으면, set_exception_handler()로 핸들러를 정의하지 않는 한, "Uncaught Exception ..." 메세지로 PHP Fatal Error가 발생합니다.

Note: 내부 PHP 함수는 주로 오류 보고를 사용합니다. 최근의 객체 지향 확장만 예외를 사용합니다. 그러나, 오류는 간단히 ErrorException으로 변환할 수 있습니다.

Tip

표준 PHP 라이브러리(SPL)는 좋은 내장 예외를 제공합니다.

Example #1 예외 던지기

<?php
function inverse($x) {
    if (!
$x) {
        throw new 
Exception('Division by zero.');
    }
    else return 
1/$x;
}

try {
    echo 
inverse(5) . "\n";
    echo 
inverse(0) . "\n";
} catch (
Exception $e) {
    echo 
'Caught exception: ',  $e->getMessage(), "\n";
}

// 계속 실행
echo 'Hello World';
?>

위 예제의 출력:

0.2
Caught exception: Division by zero.
Hello World

Example #2 중첩 에외

<?php

class MyException extends Exception { }

class 
Test {
    public function 
testing() {
        try {
            try {
                throw new 
MyException('foo!');
            } catch (
MyException $e) {
                
/* rethrow it */
                
throw $e;
            }
        } catch (
Exception $e) {
            
var_dump($e->getMessage());
        }
    }
}

$foo = new Test;
$foo->testing();

?>

위 예제의 출력:

string(4) "foo!"

예외 확장하기

내장 Exception 클래스를 확장하여 사용자 정의 예외 클래스를 정의할 수 있습니다. 멤버와 프로퍼티는 아래에 있습니다. 내장 Exception 클래스에서 상속받은 자식 클래스에서 어떤 것에 접근할 수 있는지 확인하십시오.

Example #1 내장 Exception 클래스

<?php
class Exception
{
    protected 
$message 'Unknown exception';   // 예외 메세지
    
protected $code 0;                        // 사용자 정의 예외 코드
    
protected $file;                            // 예외 소스 파일명
    
protected $line;                            // 예외 소스 줄

    
function __construct($message null$code 0);

    final function 
getMessage();                // 예외 메세지
    
final function getCode();                   // 예외 코드
    
final function getFile();                   // 소스 파일명
    
final function getLine();                   // 소스 줄
    
final function getTrace();                  // backtrace() 배열
    
final function getTraceAsString();          // 추적의 형식화된 문자열

    /* Overrideable */
    
function __toString();                       // 출력용 형식화된 문자열
}
?>

내장 Exception 클래스를 확장해서 생성자를 재정의할 경우에는, parent::__construct()를 호출하여 모든 사용가능한 데이터가 적합하게 할당될 수 있도록 하길 권합니다. __toString() 메쏘드를 덮어써서, 객체가 문자열로 표현될 때 사용자 출력을 제공할 수 있습니다.

Example #2 Exception 클래스 확장하기

<?php
/**
 * 사용자 예외 클래스 정의
 */
class MyException extends Exception
{
    
// 예외를 재정의해서 메세지가 필수가 됩니다
    
public function __construct($message$code 0) {
        
// some code
    
        // 모든 것이 제대로 할당되도록 합니다
        
parent::__construct($message$code);
    }

    
// 객체의 사용자 문자열 표현
    
public function __toString() {
        return 
__CLASS__ ": [{$this->code}]: {$this->message}\n";
    }

    public function 
customFunction() {
        echo 
"A Custom function for this type of exception\n";
    }
}


/**
 * 예외를 시험하는 클래스 생성
 */
class TestException
{
    public 
$var;

    const 
THROW_NONE    0;
    const 
THROW_CUSTOM  1;
    const 
THROW_DEFAULT 2;

    function 
__construct($avalue self::THROW_NONE) {

        switch (
$avalue) {
            case 
self::THROW_CUSTOM:
                
// 사용자 예외 던지기
                
throw new MyException('1 is an invalid parameter'5);
                break;

            case 
self::THROW_DEFAULT:
                
// 기본 예외 던지기
                
throw new Exception('2 is not allowed as a parameter'6);
                break;

            default: 
                
// 예외 없음, 객체 생성.
                
$this->var $avalue;
                break;
        }
    }
}


// 예제 1
try {
    
$o = new TestException(TestException::THROW_CUSTOM);
} catch (
MyException $e) {      // 잡아집니다
    
echo "Caught my exception\n"$e;
    
$e->customFunction();
} catch (
Exception $e) {        // 무시
    
echo "Caught Default Exception\n"$e;
}

// 계속 실행
var_dump($o);
echo 
"\n\n";


// 예제 2
try {
    
$o = new TestException(TestException::THROW_DEFAULT);
} catch (
MyException $e) {      // 형식에 맞지 않음
    
echo "Caught my exception\n"$e;
    
$e->customFunction();
} catch (
Exception $e) {        // 잡아집니다
    
echo "Caught Default Exception\n"$e;
}

// 계속 실행
var_dump($o);
echo 
"\n\n";


// 예제 3
try {
    
$o = new TestException(TestException::THROW_CUSTOM);
} catch (
Exception $e) {        // 잡아집니다
    
echo "Default Exception caught\n"$e;
}

// 계속 실행
var_dump($o);
echo 
"\n\n";


// 예제 4
try {
    
$o = new TestException();
} catch (
Exception $e) {        // 무시, 예외 없음
    
echo "Default Exception caught\n"$e;
}

// 계속 실행
var_dump($o);
echo 
"\n\n";
?>



참조 표현

Table of Contents


참조란 무엇인가

PHP에서 참조란 다른 이름으로 같은 변수의 내용에 접근한다는 것을 의미한다. C 포인터와 비슷한 개념은 아닙니다; 심볼 테이블이라고 볼 수 있다. PHP에서 변수명과 변수의 내용은 다르다. 그래서 같은 내용이 다른 이름을 가질 수 있다. 가장 가까운 개념은 유닉스 파일명과 파일입니다 - 변수명은 디렉토리 엔트리이고, 변수 내용은 파일 자체입니다. 참조는 유닉스 파일시스템의 하드 링크와 유사하게 볼 수 있습니다.



참조는 무엇을 하는가

PHP 참조는 두 변수가 같은 내용을 참조할수 있게 한다. 다음과 같은 일을 한다:

<?php
$a 
=& $b;
?>

$a$b가 같은 내용을 가리키는 것을 의미합니다.

Note: 여기에서 $a$b는 완전히 동일합니다. $a$b를 가리키고, 그 반대일 수도 있습니다. $a$b는 같은 위치를 가리킵니다.

Note: 참조를 가진 배열이 복사되면, 그 값들은 참조인 상태로 남습니다. 이는 배열이 함수에 값으로 넘겨졌을 때에도 유효합니다.

Note: 정의되지 않은 변수를 참조를 통해 할당하거나, 넘기거나, 반환하면 변수가 생성됩니다.

Example #1 정의되지 않은 변수에 참조 사용하기

<?php
function foo(&$var) { }

foo($a); // $a가 "생성되고" null로 할당됩니다

$b = array();
foo($b['b']);
var_dump(array_key_exists('b'$b)); // bool(true)

$c = new StdClass;
foo($c->d);
var_dump(property_exists($c'd')); // boold(true)
?>


같은 문법을 참조를 반환하는 함수나, new 연산자(PHP 4.0.4부터)에도 사용합니다.

<?php
$bar 
=& new fooclass();
$foo =& find_var($bar);
?>

PHP 5부터, new는 자동으로 참조를 반환하므로, 여기에서처럼 =&를 사용하는 것은 배제되었고 E_STRICT 등급 메세지를 발생합니다.

Note: & 연산자를 사용하지않으면 생성된 객체의 복사본을 돌려받는다. 그 클래스에서 $this를 사용한다면 그것은 클래스의 현재 인스턴스에만 영향을 미친다. &가 없는 지정은 인스턴스(즉, 객체)를 복사할것이고 $this는 복사본에만 영향을 미칠것이다. 이와 같은 것은 퍼포먼스와 메모리의 효율적인 사용을 위해 오직 하나의 인스턴스만 취급하기를 원할 경우에 사용된다.
@new처럼 생성자에서 발생하는 모든 에러 메시지를 보이지 않게 하기 위해서 @연산자를 사용할수 있지만, &new구문을 사용할때는 이 연산자는 작동하지 않는다. 이것은 젠드 엔진의 한계로 이런 표현을 쓰면 해석 오류가 발생한다.

Warning

함수 안에서 global로 선언한 변수에 참조를 할당하면, 그 참조는 그 함수 안에서만 보여집니다. 이를 피하려면 $GLOBALS 배열을 사용하십시오.

Example #2 함수 안에서 전역 변수 참조하기

<?php
$var1 
"Example variable";
$var2 "";

function 
global_references($use_globals)
{
    global 
$var1$var2;
    if (
$use_globals) {
        
$var2 =& $var1// 함수 안에서만 보여집니다
    
} else {
        
$GLOBALS["var2"] =& $var1// 전역 문맥에서도 보여집니다
    
}
}

global_references(false);
echo 
"var2 is set to '$var2'\n"// var2 is set to ''
global_references(true);
echo 
"var2 is set to '$var2'\n"// var2 is set to 'Example variable'
?>

global $var;$var =& $GLOBALS['var'];의 단축형임을 생각하십시오. 그러므로 다른 참조를 $var에 할당하는 것은 지역 변수의 참조를 변경할 뿐입니다.

Note: foreach 구문 안에서 참조 변수에 값을 할당하면, 참조도 변경됩니다.

Example #3 참조와 foreach 구문

<?php
$ref 
0;
$row =& $ref;
foreach (array(
123) as $row) {
    
// do something
}
echo 
$ref// 3 - 반복한 배열의 마지막 원소
?>


참조가 하는 두번째 일은 참조에 의해 변수를 전달하는 것이다. 이는 함수에서 지역 변수를 만들거나 같은 내용을 참조하는 호출을 사용하는 변수를 생성함으로써 가능해진다. 예를 들면:

<?php
function foo(&$var)
{
    
$var++;
}

$a=5;
foo($a);
?>

위 코드는 $a를 6으로 만들것이다. 이렇게 되는 이유는 foo함수 안의 변수 $var$a와 같은 내용을 가리키기 때문이다. 이에 대한 정보는 참조에 의한 전달 섹션을 읽어보십시오.

참조가 하는 세번째 일은 참조에 의해 돌려받기이다.



참조가 아닌 것

전에 설명했듯이, 참조는 포인터가 아니다. 이말의 의미는 다음 구문이 기대하던대로 작업을 수행하지 않을것이란 의미이다:

<?php
function foo(&$var)
{
    
$var =& $GLOBALS["baz"];
}
foo($bar); 
?>

위 예제에서 foo안의 $var변수는 호출자 안의 $bar와 연결될 것이다. 그리고 이 변수는 $GLOBALS["baz"]과 다시 연결될것이다. 참조 메카니즘을 사용하여 다른 호출 영역안의 $bar를 연결할수 있는 방법이 존재하지는 않는다. 왜냐하면 $bar는 함수 foo에서 유효하지 않기 때문이다 (그것은 $var에 의해 표현되는 것이 아니고, $var는 오직 변수 내용만을 소유하고 호출 심볼 테이블 내에서 이름이 값으로 변환되어 연결되지는 않는다). 함수에 의해 선택된 참조 변수를 참조 반환에 사용할 수 있습니다.



참조에 의한 전달

함수에 참조에 의한 전달을 할 수 있습니다. 이로써 함수가 변수를 변경할 수 있습니다. 문법은 다음과 같습니다:

<?php
function foo(&$var)
{
    
$var++;
}

$a=5;
foo($a);
// $a is 6 here
?>

함수 호출에 대해 참조 표시를 할수 없다는 것에 주의해야 한다. - 함수 선언에서만 참조 표시를 할수 있다 함수 선언만으로도 충분히 참조에 의해 인수를 정확하게 전달할수 있다. 최근 버전의 PHP에서 foo(&$a);처럼 &를 사용하면, "call-time pass-by-reference"가 배제되었다는 경고를 받습니다.

다음과 같은 것들은 참조에 의해 전달될수 있다:

  • 변수, 예, foo($a)
  • New 구문, 예. foo(new foobar())
  • 함수에서 반환한 참조, 예:

    <?php
    function &bar()
    {
        
    $a 5;
        return 
    $a;
    }
    foo(bar());
    ?>

    참조로 반환하기에 대해서도 참고하십시오.

결과가 정의되어 있지 않기 때문에, 다른 표현식을 참조에 의해 전달해서는 안됩니다. 예를 들어, 다음과 같은 참조에 의한 전달 예제는 유효하지 않다.

<?php
function bar() // Note the missing &
{
    
$a 5;
    return 
$a;
}
foo(bar()); // PHP 5.0.5부터 치명적인 오류가 발생합니다

foo($a 5); // 변수가 아닌, 표현식입니다
foo(5); // 치명적인 오류가 발생합니다
?>

이런 조건은 PHP 4.0.4 이후 버전에서만 요구된다.



참조 반환하기

참조에 의한 반환하기는 참조에 연결되어 있는 변수를 찾는 함수를 사용할 때 유용합니다. 참조에 의한 반환을 성능을 증가시키기 위해 사용하지 마십시오. 엔진이 스스로 최적화해 줍니다. 참조를 반환하는건 기술적으로 할 필요가 있을 경우에만 하십시오. 참조를 반환하려면, 다음 문법을 사용합니다:

<?php
class foo {
    public 
$value 42;

    public function &
getValue() {
        
retrun $this->value;
    }
}

$obj = new foo;
$myValue = &$obj->getValue(); // $myValue는 $obj->value의 참조로, 42입니다.
$obj->value 2;
echo 
$myValue;                // $obj->value의 새 값, 즉 2를 출력합니다.
?>

위 예제 코드는 함수 getvalue에 의해 반환하는 객체의 속성을 설정하지만, 참조 문법을 사용하지 않을 때와 같은 복사가 아니다.

Note: 인수 전달과 달리, 여기서는 두 군데에서 &을 사용해야 한다 - 보통의 복사가 아니라, 참조에 의해 반환하는 것을 가리킬 때, 그리고 일반적인 지정이 아닌 참조 연결이라는 것을 가리킬때, $myValue에 대해 사용해야 한다.

Note: 다음 문법으로 함수에서 참조를 반환하려 할 수 있습니다: return ($this->value); 이는 작동하지 않습니다. 변수가 아닌 표현식을 참조로 반환하려고 하는 일이기 때문입니다. 함수에서는 변수만을 참조로 반환할 수 있습니다 - 다른 것은 안됩니다. PHP4의 PHP 4.4.0부터, PHP5의 PHP 5.1.0부터 코드가 동적 표현식이나 new 연산자의 결과를 반환하려 하면, E_NOTICE 오류가 발생합니다.



참조 해제

참조 unset하면 변수 명과 변수 내용 사이의 연결만을 끊는다. 이 말의 의미는 변수 내용이 사라질것이라는 것을 의미하지 않는다. 예를 들면:

<?php
$a 
1;
$b =& $a;
unset(
$a); 
?>

위 예제 코드는 $a만 해제되고 $b를 해제(unset)하지는 않을것이다.

다시 말하면, 유닉스의 unlink 호출에 비유할수 있을것이다.



참조로 볼수 있는것

PHP내의 많은 문법 구조가 참조 메카니즘에 의해 구현된다. 그래서 위에서 설명한 모든 참조 연결이 이런 구조에 적용된다. 위에서 참조에 의한 전달과 참조에 의한 돌려주기 같은 몇몇 구조문을 설명했다. 다음과 같은 구조는 참조를 사용한다:

global 참조

global $var처럼 변수를 선언하면 전역 변수에 대한 참조를 생성하게 된다. 즉, 다음과 같은 의미를 갖는다:

<?php
$var 
=& $GLOBALS["var"];
?>

이는 $var를 해제해도 전역 변수가 해제되지는 않는다는 의미입니다.

$this

객체 메소드에서,$this는 항상 호출 객체로의 참조를 하게 된다.




Predefined Variables

PHP provides a large number of predefined variables to all scripts. The variables represent everything from external variables to built-in environment variables, last error messages to last retrieved headers.

See also the FAQ titled "How does register_globals affect me?"


Superglobals

SuperglobalsSuperglobals are built-in variables that are always available in all scopes

설명

Several predefined variables in PHP are "superglobals", which means they are available in all scopes throughout a script. There is no need to do global $variable; to access them within functions or methods.

These superglobal variables are:

변경점

버전 설명
4.1.0 Superglobals were introduced to PHP.

주의

Note: Variable availability
By default, all of the superglobals are available but there are directives that affect this availability. For further information, refer to the documentation for variables_order.

Note: Dealing with register_globals
If the deprecated register_globals directive is set to on then the variables within will also be made available in the global scope of the script. For example, $_POST['foo'] would also exist as $foo.
For related information, see the FAQ titled "How does register_globals affect me?"

Note: Variable variables
Superglobals cannot be used as variable variables inside functions or class methods.



$GLOBALS

$GLOBALSReferences all variables available in global scope

설명

An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

예제

Example #1 $GLOBALS example

<?php
function test() {
    
$foo "local variable";

    echo 
'$foo in global scope: ' $GLOBALS["foo"] . "\n";
    echo 
'$foo in current scope: ' $foo "\n";
}

$foo "Example content";
test();
?>

위 예제의 출력 예시:

$foo in global scope: Example content
$foo in current scope: local variable

주의

Note: 이는 '자동전역' 변수입니다. 스크립트의 모든 영역에서 사용할 수 있습니다. 함수나 메쏘드 안에서 접근하기 위해서 global $variable;를 할 필요가 없습니다.

Note: Variable availability
Unlike all of the other superglobals, $GLOBALS has essentially always been available in PHP.



$_SERVER

$HTTP_SERVER_VARS [deprecated]

$_SERVER -- $HTTP_SERVER_VARS [deprecated]Server and execution environment information

설명

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. That said, a large number of these variables are accounted for in the » CGI 1.1 specification, so you should be able to expect those.

$HTTP_SERVER_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_SERVER_VARS and $_SERVER are different variables and that PHP handles them as such)

인덱스

You may or may not find any of the following elements in $_SERVER. Note that few, if any, of these will be available (or indeed have any meaning) if running PHP on the command line.

'PHP_SELF'
The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar would be /test.php/foo.bar. The __FILE__ constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. Previously it was not available.
'argv'
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.
'argc'
Contains the number of command line parameters passed to the script (if run on the command line).
'GATEWAY_INTERFACE'
What revision of the CGI specification the server is using; i.e. 'CGI/1.1'.
'SERVER_ADDR'
The IP address of the server under which the current script is executing.
'SERVER_NAME'
The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.
'SERVER_SOFTWARE'
Server identification string, given in the headers when responding to requests.
'SERVER_PROTOCOL'
Name and revision of the information protocol via which the page was requested; i.e. 'HTTP/1.0';
'REQUEST_METHOD'
Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.

Note: PHP script is terminated after sending headers (it means after producing any output without output buffering) if the request method was HEAD.

'REQUEST_TIME'
The timestamp of the start of the request. Available since PHP 5.1.0.
'QUERY_STRING'
The query string, if any, via which the page was accessed.
'DOCUMENT_ROOT'
The document root directory under which the current script is executing, as defined in the server's configuration file.
'HTTP_ACCEPT'
Contents of the Accept: header from the current request, if there is one.
'HTTP_ACCEPT_CHARSET'
Contents of the Accept-Charset: header from the current request, if there is one. Example: 'iso-8859-1,*,utf-8'.
'HTTP_ACCEPT_ENCODING'
Contents of the Accept-Encoding: header from the current request, if there is one. Example: 'gzip'.
'HTTP_ACCEPT_LANGUAGE'
Contents of the Accept-Language: header from the current request, if there is one. Example: 'en'.
'HTTP_CONNECTION'
Contents of the Connection: header from the current request, if there is one. Example: 'Keep-Alive'.
'HTTP_HOST'
Contents of the Host: header from the current request, if there is one.
'HTTP_REFERER'
The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
'HTTP_USER_AGENT'
Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: 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 output to the capabilities of the user agent.
'HTTPS'
Set to a non-empty value if the script was queried through the HTTPS protocol.

Note: Note that when using ISAPI with IIS, the value will be off if the request was not made through the HTTPS protocol.

'REMOTE_ADDR'
The IP address from which the user is viewing the current page.
'REMOTE_HOST'
The Host name from which the user is viewing the current page. The reverse dns lookup is based off the REMOTE_ADDR of the user.

Note: Your web server must be configured to create this variable. For example in Apache you'll need HostnameLookups On inside httpd.conf for it to exist. See also gethostbyaddr().

'REMOTE_PORT'
The port being used on the user's machine to communicate with the web server.
'SCRIPT_FILENAME'

The absolute pathname of the currently executing script.

Note: If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user.

'SERVER_ADMIN'
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.
'SERVER_PORT'
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.
'SERVER_SIGNATURE'
String containing the server version and virtual host name which are added to server-generated pages, if enabled.
'PATH_TRANSLATED'
Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping.

Note: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly under the Apache 2 SAPI in contrast to the situation in Apache 1, where it's set to the same value as the SCRIPT_FILENAME server variable when it's not populated by Apache. This change was made to comply with the CGI specification that PATH_TRANSLATED should only exist if PATH_INFO is defined. Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO.

'SCRIPT_NAME'
Contains the current script's path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.
'REQUEST_URI'
The URI which was given in order to access this page; for instance, '/index.html'.
'PHP_AUTH_DIGEST'
When running under Apache as module doing Digest HTTP authentication this variable is set to the 'Authorization' header sent by the client (which you should then use to make the appropriate validation).
'PHP_AUTH_USER'
When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP authentication this variable is set to the username provided by the user.
'PHP_AUTH_PW'
When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP authentication this variable is set to the password provided by the user.
'AUTH_TYPE'
When running under Apache as module doing HTTP authenticated this variable is set to the authentication type.

변경점

버전 설명
4.1.0 Introduced $_SERVER that deprecated $HTTP_SERVER_VARS.

예제

Example #1 $_SERVER example

<?php
echo $_SERVER['SERVER_NAME'];
?>

위 예제의 출력 예시:

www.example.com

주의

Note: 이는 '자동전역' 변수입니다. 스크립트의 모든 영역에서 사용할 수 있습니다. 함수나 메쏘드 안에서 접근하기 위해서 global $variable;를 할 필요가 없습니다.



$_GET

$HTTP_GET_VARS [deprecated]

$_GET -- $HTTP_GET_VARS [deprecated]HTTP GET variables

설명

An associative array of variables passed to the current script via the URL parameters.

$HTTP_GET_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_GET_VARS and $_GET are different variables and that PHP handles them as such)

변경점

버전 설명
4.1.0 Introduced $_GET that deprecated $HTTP_GET_VARS.

예제

Example #1 $_GET example

<?php
echo 'Hello ' htmlspecialchars($_GET["name"]) . '!';
?>

Assuming the user entered http://example.com/?name=Hannes

위 예제의 출력 예시:

Hello Hannes!

주의

Note: 이는 '자동전역' 변수입니다. 스크립트의 모든 영역에서 사용할 수 있습니다. 함수나 메쏘드 안에서 접근하기 위해서 global $variable;를 할 필요가 없습니다.



$_POST

$HTTP_POST_VARS [deprecated]

$_POST -- $HTTP_POST_VARS [deprecated]HTTP POST variables

설명

An associative array of variables passed to the current script via the HTTP POST method.

$HTTP_POST_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_POST_VARS and $_POST are different variables and that PHP handles them as such)

변경점

버전 설명
4.1.0 Introduced $_POST that deprecated $HTTP_POST_VARS.

예제

Example #1 $_POST example

<?php
echo 'Hello ' htmlspecialchars($_POST["name"]) . '!';
?>

Assuming the user POSTed name=Hannes

위 예제의 출력 예시:

Hello Hannes!

주의

Note: 이는 '자동전역' 변수입니다. 스크립트의 모든 영역에서 사용할 수 있습니다. 함수나 메쏘드 안에서 접근하기 위해서 global $variable;를 할 필요가 없습니다.



$_FILES

$HTTP_POST_FILES [deprecated]

$_FILES -- $HTTP_POST_FILES [deprecated]HTTP File Upload variables

설명

An associative array of items uploaded to the current script via the HTTP POST method.

$HTTP_POST_FILES contains the same initial information, but is not a superglobal. (Note that $HTTP_POST_FILES and $_FILES are different variables and that PHP handles them as such)

변경점

버전 설명
4.1.0 Introduced $_FILES that deprecated $HTTP_POST_FILES.

주의

Note: 이는 '자동전역' 변수입니다. 스크립트의 모든 영역에서 사용할 수 있습니다. 함수나 메쏘드 안에서 접근하기 위해서 global $variable;를 할 필요가 없습니다.

참고



$_REQUEST

$_REQUESTHTTP Request variables

설명

An associative array that by default contains the contents of $_GET, $_POST 그리고 $_COOKIE.

변경점

버전 설명
5.3.0 Introduced request_order. This directive affects the contents of $_REQUEST.
4.3.0 $_FILES information was removed from $_REQUEST.
4.1.0 Introduced $_REQUEST.

주의

Note: 이는 '자동전역' 변수입니다. 스크립트의 모든 영역에서 사용할 수 있습니다. 함수나 메쏘드 안에서 접근하기 위해서 global $variable;를 할 필요가 없습니다.

Note: When running on the command line , this will not include the argv and argc entries; these are present in the $_SERVER array.

Note: The variables in $_REQUEST are provided to the script via the GET, POST, and COOKIE input mechanisms and therefore could be modified by the remote user and cannot be trusted. The presence and order of variables listed in this array is defined according to the PHP variables_order configuration directive.

참고



$_SESSION

$HTTP_SESSION_VARS [deprecated]

$_SESSION -- $HTTP_SESSION_VARS [deprecated]Session variables

설명

An associative array containing session variables available to the current script. See the Session functions documentation for more information on how this is used.

$HTTP_SESSION_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_SESSION_VARS and $_SESSION are different variables and that PHP handles them as such)

변경점

버전 설명
4.1.0 Introduced $_SESSION that deprecated $HTTP_SESSION_VARS.

주의

Note: 이는 '자동전역' 변수입니다. 스크립트의 모든 영역에서 사용할 수 있습니다. 함수나 메쏘드 안에서 접근하기 위해서 global $variable;를 할 필요가 없습니다.

참고



$_ENV

$HTTP_ENV_VARS [deprecated]

$_ENV -- $HTTP_ENV_VARS [deprecated]Environment variables

설명

An associative array of variables passed to the current script via the environment method.

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.

$HTTP_ENV_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_ENV_VARS and $_ENV are different variables and that PHP handles them as such)

변경점

버전 설명
4.1.0 Introduced $_ENV that deprecated $HTTP_ENV_VARS.

예제

Example #1 $_ENV example

<?php
echo 'My username is ' .$_ENV["USER"] . '!';
?>

Assuming "bjori" executes this script

위 예제의 출력 예시:

My username is bjori!

주의

Note: 이는 '자동전역' 변수입니다. 스크립트의 모든 영역에서 사용할 수 있습니다. 함수나 메쏘드 안에서 접근하기 위해서 global $variable;를 할 필요가 없습니다.

참고



$_COOKIE

$HTTP_COOKIE_VARS [deprecated]

$_COOKIE -- $HTTP_COOKIE_VARS [deprecated]HTTP Cookies

설명

An associative array of variables passed to the current script via HTTP Cookies.

$HTTP_COOKIE_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_COOKIE_VARS and $_COOKIE are different variables and that PHP handles them as such)

변경점

버전 설명
4.1.0 Introduced $_COOKIE that deprecated $HTTP_COOKIE_VARS.

예제

Example #1 $_COOKIE example

<?php
echo 'Hello ' htmlspecialchars($_COOKIE["name"]) . '!';
?>

Assuming the "name" cookie has been set earlier

위 예제의 출력 예시:

Hello Hannes!

주의

Note: 이는 '자동전역' 변수입니다. 스크립트의 모든 영역에서 사용할 수 있습니다. 함수나 메쏘드 안에서 접근하기 위해서 global $variable;를 할 필요가 없습니다.



$php_errormsg

$php_errormsgThe previous error message

설명

$php_errormsg is a variable containing the text of the last error message generated by PHP. This variable will only be available within the scope in which the error occurred, and only if the track_errors configuration option is turned on (it defaults to off).

Note: This variable is only available when track_errors is enabled in php.ini.

Warning

If a user defined error handler (set_error_handler()) is set $php_errormsg is only set if the error handler returns FALSE

예제

Example #1 $php_errormsg example

<?php
@strpos();
echo 
$php_errormsg;
?>

위 예제의 출력 예시:

Wrong parameter count for strpos()



$HTTP_RAW_POST_DATA

$HTTP_RAW_POST_DATARaw POST data

설명

$HTTP_RAW_POST_DATA contains the raw POST data. See always_populate_raw_post_data



$http_response_header

$http_response_headerHTTP response headers

설명

The $http_response_header array is similar to the get_headers() function. When using the HTTP wrapper, $http_response_header will be populated with the HTTP response headers.

예제

Example #1 $http_response_header example

<?php
file_get_contents
("http://example.com");
var_dump($http_response_header);
?>

위 예제의 출력 예시:

array(9) {
  [0]=>
  string(15) "HTTP/1.1 200 OK"
  [1]=>
  string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT"
  [2]=>
  string(29) "Server: Apache/2.2.3 (CentOS)"
  [3]=>
  string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"
  [4]=>
  string(27) "ETag: "280100-1b6-80bfd280""
  [5]=>
  string(20) "Accept-Ranges: bytes"
  [6]=>
  string(19) "Content-Length: 438"
  [7]=>
  string(17) "Connection: close"
  [8]=>
  string(38) "Content-Type: text/html; charset=UTF-8"
}



$argc

$argcThe number of arguments passed to script

설명

Contains the number of arguments passed to the current script when running from the command line.

Note: The script's filename is always passed as an argument to the script, therefore the minimum value of $argc is 1.

Note: This variable is only available when register_argc_argv is enabled.

예제

Example #1 $argc example

<?php
var_dump
($argc);
?>

When executing the example with: php script.php arg1 arg2 arg3

위 예제의 출력 예시:

int(4)



$argv

$argvArray of arguments passed to script

설명

Contains an array of all the arguments passed to the script when running from the command line.

Note: The first argument is always the current script's filename, therefore $argv[0] is the script's name.

Note: This variable is only available when register_argc_argv is enabled.

예제

Example #1 $argv example

<?php
var_dump
($argv);
?>

When executing the example with: php script.php arg1 arg2 arg3

위 예제의 출력 예시:

array(4) {
  [0]=>
  string(10) "script.php"
  [1]=>
  string(4) "arg1"
  [2]=>
  string(4) "arg2"
  [3]=>
  string(4) "arg3"
}


Table of Contents



Predefined Exceptions

Table of Contents

See also the SPL Exceptions


Exception

소개

Exception is the base class for all Exceptions.

클래스 개요

Exception
Exception {
/* Properties */
protected string $message ;
private string $string ;
protected int $code ;
protected string $file ;
protected int $line ;
private array $trace ;
/* Methods */
public __construct ([ string $message= "" [, int $code= 0 [, Exception $previous= NULL ]]] )
final public string getMessage ( void )
final public Exception getPrevious ( void )
final public int getCode ( void )
final public string getFile ( void )
final public int getLine ( void )
final public array getTrace ( void )
final public string getTraceAsString ( void )
public string __toString ( void )
final private void __clone ( void )
}

프로퍼티

message

The exception message

string

Internal Exception name

code

The Exception code

file

The filename where the exception was thrown

line

The line where the exception was thrown

trace

The stack trace


Exception::__construct

(PHP 5 >= 5.1.0)

Exception::__constructConstruct the exception

설명

public Exception::__construct ([ string $message= "" [, int $code= 0 [, Exception $previous= NULL ]]] )

Constructs the Exception.

인수

message

The Exception message to throw.

code

The Exception code.

previous

The previous exception used for the exception chaining.

변경점

버전 설명
5.3.0 The previous parameter was added.



Exception::getMessage

(PHP 5 >= 5.1.0)

Exception::getMessageGets the Exception message

설명

final public string Exception::getMessage ( void )

Returns the Exception message.

인수

이 함수는 인수가 없습니다.

반환값

Returns the Exception message as a string.

예제

Example #1 Exception::getMessage() example

<?php
try {
    throw new 
Exception("Some error message");
} catch(
Exception $e) {
    echo 
$e->getMessage();
}
?>

위 예제의 출력 예시:

Some error message



Exception::getPrevious

(PHP 5 >= 5.3.0)

Exception::getPreviousReturns previous Exception

설명

final public Exception Exception::getPrevious ( void )

Returns previous Exception (the third parameter of Exception::__construct).

인수

이 함수는 인수가 없습니다.

반환값

Returns the previous Exception if available or NULL otherwise.

예제

Example #1 Exception::getPrevious example

Looping over, and printing out, exception trace.

<?php
class MyCustomException extends Exception {}

function 
doStuff() {
    try {
        throw new 
InvalidArgumentException("You are doing it wrong!"112);
    } catch(
Exception $e) {
        throw new 
MyCustomException("Something happend"911$e);
    }
}


try {
    
doStuff();
} catch(
Exception $e) {
    do {
        
printf("%s:%d %s (%d) [%s]\n"$e->getFile(), $e->getLine(), $e->getMessage(), $e->getCode(), get_class($e));
    } while(
$e $e->getPrevious());
}
?>

위 예제의 출력 예시:

/home/bjori/ex.php:8 Something happend (911) [MyCustomException]
/home/bjori/ex.php:6 You are doing it wrong! (112) [InvalidArgumentException]



Exception::getCode

(PHP 5 >= 5.1.0)

Exception::getCodeGets the Exception code

설명

final public int Exception::getCode ( void )

Returns the Exception code.

인수

이 함수는 인수가 없습니다.

반환값

Returns the Exception code as a integer.

예제

Example #1 Exception::getCode() example

<?php
try {
    throw new 
Exception("Some error message"30);
} catch(
Exception $e) {
    echo 
"The exception code is: " $e->getCode();
}
?>

위 예제의 출력 예시:

The exception code is: 30



Exception::getFile

(PHP 5 >= 5.1.0)

Exception::getFileGets the file in which the exception occurred

설명

final public string Exception::getFile ( void )

Get the name of the file the exception was thrown from.

인수

이 함수는 인수가 없습니다.

반환값

Returns the filename in which the exception was thrown.

예제

Example #1 Exception::getFile() example

<?php
try {
    throw new 
Exception;
} catch(
Exception $e) {
    echo 
$e->getFile();
}
?>

위 예제의 출력 예시:

/home/bjori/tmp/ex.php



Exception::getLine

(PHP 5 >= 5.1.0)

Exception::getLineGets the line in which the exception occurred

설명

final public int Exception::getLine ( void )

Returns line number where the exception was thrown.

인수

이 함수는 인수가 없습니다.

반환값

Returns the line number where the exception was thrown.

예제

Example #1 Exception::getLine() example

<?php
try {
    throw new 
Exception("Some error message");
} catch(
Exception $e) {
    echo 
"The exception was thrown on line: " $e->getLine();
}
?>

위 예제의 출력 예시:

The exception was thrown on line: 3



Exception::getTrace

(PHP 5 >= 5.1.0)

Exception::getTraceGets the stack trace

설명

final public array Exception::getTrace ( void )

Returns the Exception stack trace.

인수

이 함수는 인수가 없습니다.

반환값

Returns the Exception stack trace as an array.

예제

Example #1 Exception::getTrace() example

<?php
function test() {
 throw new 
Exception;
}

try {
 
test();
} catch(
Exception $e) {
 
var_dump($e->getTrace());
}
?>

위 예제의 출력 예시:

array(1) {
  [0]=>
  array(4) {
    ["file"]=>
    string(22) "/home/bjori/tmp/ex.php"
    ["line"]=>
    int(7)
    ["function"]=>
    string(4) "test"
    ["args"]=>
    array(0) {
    }
  }
}



Exception::getTraceAsString

(PHP 5 >= 5.1.0)

Exception::getTraceAsStringGets the stack trace as a string

설명

final public string Exception::getTraceAsString ( void )

Returns the Exception stack trace as a string.

인수

이 함수는 인수가 없습니다.

반환값

Returns the Exception stack trace as a string.

예제

Example #1 Exception::getTraceAsString() example

<?php
function test() {
    throw new 
Exception;
}

try {
    
test();
} catch(
Exception $e) {
    echo 
$e->getTraceAsString();
}
?>

위 예제의 출력 예시:

#0 /home/bjori/tmp/ex.php(7): test()
#1 {main}



Exception::__toString

(PHP 5 >= 5.1.0)

Exception::__toStringString representation of the exception

설명

public string Exception::__toString ( void )

Returns the string representation of the exception.

인수

이 함수는 인수가 없습니다.

반환값

Returns the string representation of the exception.

예제

Example #1 Exception::__toString() example

<?php
try {
    throw new 
Exception("Some error message");
} catch(
Exception $e) {
    echo 
$e;
}
?>

위 예제의 출력 예시:

exception 'Exception' with message 'Some error message' in /home/bjori/tmp/ex.php:3
Stack trace:
#0 {main}



Exception::__clone

(PHP 5 >= 5.1.0)

Exception::__cloneClone the exception

설명

final private void Exception::__clone ( void )

Tries to clone the Exception, which results in Fatal error.

인수

이 함수는 인수가 없습니다.

반환값

값을 반환하지 않습니다.

오류/예외

Exceptions are not clonable.


Table of Contents



ErrorException

소개

An Error Exception.

클래스 개요

ErrorException
ErrorException extends Exception {
/* Properties */
protected int $severity ;
/* Methods */
public __construct ([ string $message [, int $code [, int $severity [, string $filename [, int $lineno ]]]]] )
final public int getSeverity ( void )
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public int Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

프로퍼티

severity

The severity of the exception

예제

Example #1 Use set_error_handler() to change error messages into ErrorException.

<?php
function exception_error_handler($errno$errstr$errfile$errline ) {
    throw new 
ErrorException($errstr0$errno$errfile$errline);
}
set_error_handler("exception_error_handler");

/* Trigger exception */
strpos();
?>

위 예제의 출력 예시:

Fatal error: Uncaught exception 'ErrorException' with message 'Wrong parameter count for strpos()' in /home/bjori/tmp/ex.php:8
Stack trace:
#0 [internal function]: exception_error_handler(2, 'Wrong parameter...', '/home/bjori/php...', 8, Array)
#1 /home/bjori/php/cleandocs/test.php(8): strpos()
#2 {main}
  thrown in /home/bjori/tmp/ex.php on line 8


ErrorException::__construct

(PHP 5 >= 5.1.0)

ErrorException::__constructConstruct the exception

설명

public ErrorException::__construct ([ string $message [, int $code [, int $severity [, string $filename [, int $lineno ]]]]] )

Constructs the Exception.

인수

message

The Exception message to throw.

code

The Exception code.

severity

The severity level of the exception.

filename

The filename where the exception is thrown.

lineno

The line number where the exception is thrown.



ErrorException::getSeverity

(PHP 5 >= 5.1.0)

ErrorException::getSeverityGets the exception severity

설명

final public int ErrorException::getSeverity ( void )

Returns the severity of the exception.

인수

이 함수는 인수가 없습니다.

반환값

Returns the severity level of the exception.

예제

Example #1 ErrorException::getSeverity() example

<?php
try {
    throw new 
ErrorException("Exception message"075);
} catch(
ErrorException $e) {
    echo 
"This exception severity is: " $e->getSeverity();
}
?>

위 예제의 출력 예시:

This exception severity is: 75


Table of Contents




Predefined Interfaces

Table of Contents

See also the SPL Interfaces


The Traversable interface

소개

Interface to detect if a class is traversable using foreach.

Abstract base interface that cannot be implemented alone. Instead it must be implemented by either IteratorAggregate or Iterator.

Note: Internal (built-in) classes that implement this interface can be used in a foreach construct and do not need to implement IteratorAggregate or Iterator.

Note: This is an internal engine interface which cannot be implemented in PHP scripts. Either IteratorAggregate or Iterator must be used instead.

인터페이스 개요

Traversable
Traversable {
}

This interface has no methods, its only purpose is to be the base interface for all traversable classes.



The Iterator interface

소개

Interface for external iterators or objects that can be iterated themselves internally.

인터페이스 개요

Iterator
Iterator extends Traversable {
/* Methods */
abstract public mixed current ( void )
abstract public scalar key ( void )
abstract public void next ( void )
abstract public void rewind ( void )
abstract public boolean valid ( void )
}

Example #1 Basic usage

This example demonstrates in which order methods are called when using foreach with an iterator.

<?php
class myIterator implements Iterator {
    private 
$position 0;
    private 
$array = array(
        
"firstelement",
        
"secondelement",
        
"lastelement",
    );  

    public function 
__construct() {
        
$this->position 0;
    }

    function 
rewind() {
        
var_dump(__METHOD__);
        
$this->position 0;
    }

    function 
current() {
        
var_dump(__METHOD__);
        return 
$this->array[$this->position];
    }

    function 
key() {
        
var_dump(__METHOD__);
        return 
$this->position;
    }

    function 
next() {
        
var_dump(__METHOD__);
        ++
$this->position;
    }

    function 
valid() {
        
var_dump(__METHOD__);
        return isset(
$this->array[$this->position]);
    }
}

$it = new myIterator;

foreach(
$it as $key => $value) {
    
var_dump($key$value);
    echo 
"\n";
}
?>

위 예제의 출력 예시:

string(18) "myIterator::rewind"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(0)
string(12) "firstelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(1)
string(13) "secondelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(2)
string(11) "lastelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"

Iterator::current

(PHP 5 >= 5.1.0)

Iterator::currentReturn the current element

설명

abstract public mixed Iterator::current ( void )

Returns the current element.

인수

이 함수는 인수가 없습니다.

반환값

Can return any type.



Iterator::key

(PHP 5 >= 5.1.0)

Iterator::keyReturn the key of the current element

설명

abstract public scalar Iterator::key ( void )

Returns the key of the current element.

인수

이 함수는 인수가 없습니다.

반환값

Returns scalar on success, integer 0 on failure.

오류/예외

Issues E_WARNING on failure.



Iterator::next

(PHP 5 >= 5.1.0)

Iterator::nextMove forward to next element

설명

abstract public void Iterator::next ( void )

Moves the current position to the next element.

Note: This method is called after each foreach loop.

인수

이 함수는 인수가 없습니다.

반환값

Any returned value is ignored.



Iterator::rewind

(PHP 5 >= 5.1.0)

Iterator::rewindRewind the Iterator to the first element

설명

abstract public void Iterator::rewind ( void )

Rewinds back to the first element of the Iterator.

Note: This is the first method called when starting a foreach loop. It will not be executed after foreach loops.

인수

이 함수는 인수가 없습니다.

반환값

Any returned value is ignored.



Iterator::valid

(PHP 5 >= 5.1.0)

Iterator::validChecks if current position is valid

설명

abstract public boolean Iterator::valid ( void )

This method is called after Iterator::rewind and Iterator::next to check if the current position is valid.

인수

이 함수는 인수가 없습니다.

반환값

The return value will be casted to boolean and then evaluated. 성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.


Table of Contents



The IteratorAggregate interface

소개

Interface to create an external Iterator.

인터페이스 개요

IteratorAggregate
IteratorAggregate extends Traversable {
/* Methods */
abstract public Traversable getIterator ( void )
}

Example #1 Basic usage

<?php
class myData implements IteratorAggregate {
    public 
$property1 "Public property one";
    public 
$property2 "Public property two";
    public 
$property3 "Public property three";

    public function 
__construct() {
        
$this->property4 "last property";
    }

    public function 
getIterator() {
        return new 
ArrayIterator($this);
    }
}

$obj = new myData;

foreach(
$obj as $key => $value) {
    
var_dump($key$value);
    echo 
"\n";
}
?>

위 예제의 출력 예시:

string(9) "property1"
string(19) "Public property one"

string(9) "property2"
string(19) "Public property two"

string(9) "property3"
string(21) "Public property three"

string(9) "property4"
string(13) "last property"


IteratorAggregate::getIterator

(PHP 5 >= 5.1.0)

IteratorAggregate::getIteratorRetrieve an external iterator

설명

abstract public Traversable IteratorAggregate::getIterator ( void )

Returns an external iterator.

인수

이 함수는 인수가 없습니다.

반환값

An instance of an object implementing Iterator or Traversable

오류/예외

Throws an Exception on failure.


Table of Contents



The ArrayAccess interface

소개

Interface to provide accessing objects as arrays.

인터페이스 개요

ArrayAccess
ArrayAccess {
/* Methods */
abstract public boolean offsetExists ( string $offset )
abstract public mixed offsetGet ( string $offset )
abstract public void offsetSet ( string $offset , string $value )
abstract public void offsetUnset ( string $offset )
}

Example #1 Basic usage

<?php
class obj implements arrayaccess {
    private 
$container = array();
    public function 
__construct() {
        
$this->container = array(
            
"one"   => 1,
            
"two"   => 2,
            
"three" => 3,
        );
    }
    public function 
offsetSet($offset$value) {
        
$this->container[$offset] = $value;
    }
    public function 
offsetExists($offset) {
        return isset(
$this->container[$offset]);
    }
    public function 
offsetUnset($offset) {
        unset(
$this->container[$offset]);
    }
    public function 
offsetGet($offset) {
        return isset(
$this->container[$offset]) ? $this->container[$offset] : null;
    }
}

$obj = new obj;

var_dump(isset($obj["two"]));
var_dump($obj["two"]);
unset(
$obj["two"]);
var_dump(isset($obj["two"]));
$obj["two"] = "A value";
var_dump($obj["two"]);

?>

위 예제의 출력 예시:

bool(true)
int(2)
bool(false)
string(7) "A value"

ArrayAccess::offsetExists

(PHP 5 >= 5.1.0)

ArrayAccess::offsetExistsWhether a offset exists

설명

abstract public boolean ArrayAccess::offsetExists ( string $offset )

Whether or not an offset exists.

This method is executed when using isset() or empty() on objects implementing ArrayAccess.

Note: When using empty() ArrayAccess::offsetGet() will be called and checked if empty only if ArrayAccess::offsetExists() returns TRUE.

인수

offset

An offset to check for.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

Note: The return value will be casted to boolean if non-boolean was returned.

예제

Example #1 ArrayAccess::offsetExists() example

<?php
class obj implements arrayaccess {
    public function 
offsetSet($offset$value) {
        
var_dump(__METHOD__);
    }
    public function 
offsetExists($var) {
        
var_dump(__METHOD__);
        if (
$var == "foobar") {
            return 
true;
        }
        return 
false;
    }
    public function 
offsetUnset($var) {
        
var_dump(__METHOD__);
    }
    public function 
offsetGet($var) {
        
var_dump(__METHOD__);
        return 
"value";
    }
}

$obj = new obj;

echo 
"Runs obj::offsetExists()\n";
var_dump(isset($obj["foobar"]));

echo 
"\nRuns obj::offsetExists() and obj::offsetGet()\n";
var_dump(empty($obj["foobar"]));

echo 
"\nRuns obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get\n";
var_dump(empty($obj["foobaz"]));
?>

위 예제의 출력 예시:

Runs obj::offsetExists()
string(17) "obj::offsetExists"
bool(true)

Runs obj::offsetExists() and obj::offsetGet()
string(17) "obj::offsetExists"
string(14) "obj::offsetGet"
bool(false)

Runs obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get
string(17) "obj::offsetExists"
bool(true)



ArrayAccess::offsetGet

(PHP 5 >= 5.1.0)

ArrayAccess::offsetGetOffset to retrieve

설명

abstract public mixed ArrayAccess::offsetGet ( string $offset )

Returns the value at specified offset.

This method is executed when checking if offset is empty().

인수

offset

The offset to retrieve.

반환값

Can return all value types.

참고



ArrayAccess::offsetSet

(PHP 5 >= 5.1.0)

ArrayAccess::offsetSetOffset to set

설명

abstract public void ArrayAccess::offsetSet ( string $offset , string $value )

Assigns a value to the specified offset.

인수

offset

The offset to assign the value to.

value

The value to set.

반환값

값을 반환하지 않습니다.



ArrayAccess::offsetUnset

(PHP 5 >= 5.1.0)

ArrayAccess::offsetUnsetOffset to unset

설명

abstract public void ArrayAccess::offsetUnset ( string $offset )

Unsets an offset.

Note: This method will not be called when type-casting to (unset)

인수

offset

The offset to unset.

반환값

값을 반환하지 않습니다.


Table of Contents



The Serializable interface

소개

Interface for customized serializing.

Classes that implement this interface no longer support __sleep() and __wakeup(). The method serialize is called whenever an instance needs to be serialized. This does not invoke __destruct() or has any other side effect unless programmed inside the method. When the data is unserialized the class is known and the appropriate unserialize() method is called as a constructor instead of calling __construct(). If you need to execute the standard constructor you may do so in the method.

인터페이스 개요

Serializable
Serializable {
/* Methods */
abstract public string serialize ( void )
abstract public mixed unserialize ( string $serialized )
}

Example #1 Basic usage

<?php
class obj implements Serializable {
    private 
$data;
    public function 
__construct() {
        
$this->data "My private data";
    }
    public function 
serialize() {
        return 
serialize($this->data);
    }
    public function 
unserialize($data) {
        
$this->data unserialize($data);
    }
    public function 
getData() {
        return 
$this->data;
    }
}

$obj = new obj;
$ser serialize($obj);

$newobj unserialize($ser);

var_dump($newobj->getData());
?>

위 예제의 출력 예시:

string(15) "My private data"

Serializable::serialize

(PHP 5 >= 5.1.0)

Serializable::serializeString representation of object

설명

abstract public string Serializable::serialize ( void )

Should return the string representation of the object.

Note: This method acts as the destructor of the object. The __destruct() method will not be called after this method.

인수

이 함수는 인수가 없습니다.

반환값

Returns the string representation of the object or NULL

오류/예외

Throws Exception when returning other types then strings and NULL

참고



Serializable::unserialize

(PHP 5 >= 5.1.0)

Serializable::unserializeConstructs the object

설명

abstract public mixed Serializable::unserialize ( string $serialized )

Called during unserialization of the object.

Note: This method acts as the constructor of the object. The __construct() method will not be called after this method.

인수

serialized

The string representation of the object.

반환값

Returns the original value unserialized.

참고


Table of Contents




컨텍스트 옵션과 인수

PHP는 모든 파일시스템과 스트림 래퍼에서 사용할 수 있는 다양한 컨텍스트 옵션과 인수를 제공합니다. 컨텍스트는 stream_context_create()로 생성됩니다. 옵션은 stream_context_set_option()으로 설정하고 인수는 stream_context_set_params()로 설정합니다.


Socket context options

Socket context optionsSocket context option listing

설명

Socket context options are available for all wrappers that work over sockets, like tcp, http and ftp.

옵션

bindto

Used to specify the IP address (either IPv4 or IPv6) and/or the port number that PHP will use to access the network. The syntax is ip:port. Setting the IP or the port to 0 will let the system choose the IP and/or port.

Note: As FTP creates two socket connections during normal operation, the port number cannot be specified using this option.

변경점

버전 설명
5.1.0 Added bindto.

예제

Example #1 Basic bindto usage example

<?php
// connect to the internet using the '192.168.0.100' IP
$opts = array(
    
'socket' => array(
        
'bindto' => '192.168.0.100:0',
    ),
);


// connect to the internet using the '192.168.0.100' IP and port '7000'
$opts = array(
    
'socket' => array(
        
'bindto' => '192.168.0.100:7000',
    ),
);


// connect to the internet using port '7000'
$opts = array(
    
'socket' => array(
        
'bindto' => '0:7000',
    ),
);


// create the context...
$context stream_context_create($opts);

// ...and use it to fetch the data
echo file_get_contents('http://www.example.com'false$context);

?>



HTTP context options

HTTP context optionsHTTP context option listing

설명

Context options for http:// and https:// transports.

옵션

method string

GET, POST, or any other HTTP method supported by the remote server.

Defaults to GET.

header string

Additional headers to be sent during request. Values in this option will override other values (such as User-agent:, Host:, and Authentication:).

user_agent string

Value to send with User-Agent: header. This value will only be used if user-agent is not specified in the header context option above.

By default the user_agent php.ini setting is used.

content string

Additional data to be sent after the headers. Typically used with POST or PUT requests.

proxy string

URI specifying address of proxy server. (e.g. tcp://proxy.example.com:5100).

request_fulluri boolean

When set to TRUE, the entire URI will be used when constructing the request. (i.e. GET http://www.example.com/path/to/file.html HTTP/1.0). While this is a non-standard request format, some proxy servers require it.

Defaults to FALSE.

max_redirects integer

The max number of redirects to follow. Value 1 or less means that no redirects are followed.

Defaults to 20.

protocol_version float

HTTP protocol version.

Defaults to 1.0.

Note: PHP prior to 5.3.0 does not implement chunked transfer decoding. If this value is set to 1.1 it is your responsibility to be 1.1 compliant.

timeout float

Read timeout in seconds, specified by a float (e.g. 10.5).

By default the default_socket_timeout php.ini setting is used.

ignore_errors boolean

Fetch the content even on failure status codes.

Defaults to FALSE

변경점

버전 설명
5.3.0 The protocol_version supports chunked transfer decoding when set to 1.1.
5.2.10 Added ignore_errors .
5.2.1 Added timeout .
5.2.10 The header can now be an numerically indexed array.
5.1.0 Added HTTPS proxying through HTTP proxies.
5.1.0 Added max_redirects .
5.1.0 Added protocol_version .

예제

Example #1 Fetch a page and send POST data

<?php

$postdata 
http_build_query(
    array(
        
'var1' => 'some content',
        
'var2' => 'doh'
    
)
);

$opts = array('http' =>
    array(
        
'method'  => 'POST',
        
'header'  => 'Content-type: application/x-www-form-urlencoded',
        
'content' => $postdata
    
)
);

$context  stream_context_create($opts);

$result file_get_contents('http://example.com/submit.php'false$context);

?>

주의

Note: Underlying socket stream context options
Additional context options may be supported by the underlying transport For http:// streams, refer to context options for the tcp:// transport. For https:// streams, refer to context options for the ssl:// transport.



FTP context options

FTP context optionsFTP context option listing

설명

Context options for ftp:// and ftps:// transports.

옵션

overwrite boolean

Allow overwriting of already existing files on remote server. Applies to write mode (uploading) only.

Defaults to FALSE.

resume_pos integer

File offset at which to begin transfer. Applies to read mode (downloading) only.

Defaults to 0 (Beginning of File).

proxy string

Proxy FTP request via http proxy server. Applies to file read operations only. Ex: tcp://squid.example.com:8000.

변경점

버전 설명
5.1.0 Added proxy .
5.0.0 Added overwrite and resume_pos .

주의

Note: Underlying socket stream context options
Additional context options may be supported by the underlying transport For ftp:// streams, refer to context options for the tcp:// transport. For ftps:// streams, refer to context options for the ssl:// transport.



SSL context options

SSL context optionsSSL context option listing

설명

Context options for ssl:// and tls:// transports.

옵션

verify_peer boolean

Require verification of SSL certificate used.

Defaults to FALSE.

allow_self_signed boolean

Allow self-signed certificates.

Defaults to FALSE

cafile string

Location of Certificate Authority file on local filesystem which should be used with the verify_peer context option to authenticate the identity of the remote peer.

capath string

If cafile is not specified or if the certificate is not found there, the directory pointed to by capath is searched for a suitable certificate. capath must be a correctly hashed certificate directory.

local_cert string

Path to local certificate file on filesystem. It must be a PEM encoded file which contains your certificate and private key. It can optionally contain the certificate chain of issuers.

passphrase string

Passphrase with which your local_cert file was encoded.

CN_match string

Common Name we are expecting. PHP will perform limited wildcard matching. If the Common Name does not match this, the connection attempt will fail.

verify_depth integer

Abort if the certificate chain is too deep.

Defaults to no verification.

ciphers string

Sets the list of available ciphers. The format of the string is described in » ciphers(1).

Defaults to DEFAULT.

capture_peer_cert boolean

If set to TRUE a peer_certificate context option will be created containing the peer certificate.

capture_peer_chain boolean

If set to TRUE a peer_certificate_chain context option will be created containing the certificate chain.

변경점

버전 설명
5.0.0 Added capture_peer_cert , capture_peer_chain and ciphers .

주의

Note: Because ssl:// is the underlying transport for the https:// and ftps:// wrappers, any context options which apply to ssl:// also apply to https:// and ftps://.



CURL context options

CURL context optionsCURL context option listing

설명

CURL context options are available when the CURL extension was compiled using the --with-curlwrappers configure option.

옵션

method string

GET, POST, or any other HTTP method supported by the remote server.

Defaults to GET.

header string

Additional headers to be sent during request. Values in this option will override other values (such as User-agent:, Host:, and Authentication:).

user_agent string

Value to send with User-Agent: header.

By default the user_agent php.ini setting is used.

content string

Additional data to be sent after the headers. This option is not used for GET or HEAD requests.

proxy string

URI specifying address of proxy server. (e.g. tcp://proxy.example.com:5100).

max_redirects integer

The max number of redirects to follow. Value 1 or less means that no redirects are followed.

Defaults to 20.

curl_verify_ssl_host boolean

Verify the host.

Defaults to FALSE

Note: This option is available for both the http and ftp protocol wrappers.

curl_verify_ssl_peer boolean

Require verification of SSL certificate used.

Defaults to FALSE

Note: This option is available for both the http and ftp protocol wrappers.

예제

Example #1 Fetch a page and send POST data

<?php

$postdata 
http_build_query(
    array(
        
'var1' => 'some content',
        
'var2' => 'doh'
    
)
);

$opts = array('http' =>
    array(
        
'method'  => 'POST',
        
'header'  => 'Content-type: application/x-www-form-urlencoded',
        
'content' => $postdata
    
)
);

$context  stream_context_create($opts);

$result file_get_contents('http://example.com/submit.php'false$context);

?>



Phar context options

Phar context optionsPhar context option listing

설명

Context options for phar:// wrapper.

옵션

compress int

One of Phar compression constants.

metadata mixed

Phar metadata. See Phar::setMetadata().



Context parameters

Context parametersContext parameter listing

설명

These parameters can be set on a context using the stream_context_set_params() function.

옵션

notification callback

A callback to be called when an event occurs on a stream.

See stream_notification_callback() for more details.


Table of Contents




보안


도입

PHP는 강력한 언어와 인터프리터입니다. 웹서버 모듈로 포함하거나 별도의 CGI 바이너리로 실행해서, 서버에서 파일에 접근하거나, 명령을 실행하거나, 네트워크 연결을 열 수 있게 해줍니다. 기본적으로 이러한 기능은 웹서버의 보안을 위협합니다. PHP는 펄이나 C로 쓰여진 CGI 프로그램에 비해서 더욱 안전한 언어로 설계되었습니다. 컴파일 시와 실행시 환경 설정 옵션의 적절한 선택과 충분한 코딩 능력은 자유와 보안의 조합을 얻을 수 있을 것입니다.

PHP를 이용하는 다른 방법들에 따라, 실행을 조절하는 많은 환경 설정 옵션이 존재합니다. 많은 옵션의 선택은 PHP를 여러 목적으로 사용할 수 있게 보장해주지만, 이러한 옵션과 서버 환경 설정의 조합에 따라서는 보안을 위협하는 결과를 가져올 수도 있습니다.

PHP 환경 설정의 유연성은 코드의 유연성과 상대적이 됩니다. PHP는 쉘 유저의 모든 권한을 가지는 완벽한 서버 어플리케이션을 작성할 수도 있고, 강력히 제어된 환경에서 적은 위험으로 단순한 서버측 포함으로 사용할 수도 있습니다. 어떻게 환경을 구축하고, 어떻게 보안을 유지하는 지는, 많은 부분이 PHP 개발자에 의존하고 있습니다.

이 챕터에서는 몇가지 일반적인 보안 조언으로 시작해서, 서로 다른 환경 설정 옵션의 조합과 안전하게 사용할 수 있는 상황, 그리고 보안 단계에 따라 코딩에서 고려할 점에 대해서 설명합니다.



일반적인 고려 사항

완벽한 보안 시스템은 불가능에 가깝기에, 보안 대책의 지향점은 보통 위험성과 사용성의 조화점입니다. 유저가 송신하는 모든 변수가 두가지 형태의 생물학적 인증(망막 스캔이나 지문 등)이 필요하다면, 매우 높은 수준의 보안을 얻을 수 있습니다. 그러나 이 방법은 매우 복잡한 폼을 채우기 위해 30여분의 시간을 필요로 할 것이며, 유저가 보안을 그냥 넘어갈 수 있는 방법을 찾도록 노력하게 할 것입니다.

필요 이상의 엄중한 보안은 종종 사용자가 작업을 하는 것을 방해하거나, 지나친 복잡함으로 코드 작성자에게 부담을 줍니다. 사실, 몇몇 보안 공격은 지나친 보안으로 인한 약점을 노리며, 시간을 들여 손상시키는 경향이 있습니다.

기억할만한 문구입니다: 시스템은 체인의 가장 약한 부분 정도에 불과하다. 모든 작업을 시간, 장소, 작업 종류 등으로 자세하게 기록을 한다고 하여도, 사용자 인증을 하나의 쿠키로만 처리한다면, 사용자에 대한 작업 기록은 매우 약해질 것입니다.

테스트를 할 때, 가장 간단한 페이지라 할지라도 모든 가능성을 테스트할 수는 없다는 것을 명심하십시오. 화가 난 고용인이나, 엄청난 시간을 가진 크랙커, 혹은 키보드 위를 걸어가는 고양이 등에 의해 기대했던 입력값과는 완전히 무관하게 될 수도 있습니다. 이것이 기대하지 않는 데이터를 분별하고, 그 뒤에 어떻게 변경하고, 줄이고, 늘릴지에 대해 논리적 관점에서 코드를 바라보아야 할 이유입니다.

인터넷은 당신의 코드를 부수고, 사이트를 파괴하고, 부적절한 내용을 게시하는 등 당신을 바쁘게 하는 사람들로 가득 차 있습니다. 사이트의 크기에 관계 없이, 온라인인 서버를 가지고 있다면 간단히 목표가 됩니다. 많은 크래킹 프로그램은 크기를 고려하지 않으며, 단지 IP 블럭에서 희생자를 찾을 뿐입니다. 희생자가 되지 마십시오.



CGI 바이너리로 설치

Table of Contents


가능한 공격

몇가지 이유로 인해 PHP를 서버 소프트웨어(아파치 등)의 모듈로 사용하지 않거나, 다른 종류의 CGI wrappers로 스크립트에 대해 안전한 chroot와 setuid 환경을 제공하기 위해 CGI 바이너리로 PHP를 사용하는 것을 선택할 수 있습니다. 이 설치는 보통 실행 가능한 PHP 바이너리를 웹서버 cgi-bin 디렉토리에 두는 것입니다. CERT 권고 » CA-96.11는 어떠한 인터프리터도 cgi-bin에 두지 않을 것을 권장합니다. PHP 바이너리는 독립 인터프리터로 사용할 수 있지만, 이러한 방법의 설치가 가능하도록 하는 몇가지 공격을 방지하도록 설계되어 있습니다.

  • 시스템 파일에의 접근: http://my.host/cgi-bin/php?/etc/passwd URL 후의 물음표(?)에 존재하는 질의 정보는 CGI 인터페이스에 의해 인터프리터에 명령줄 인수로 전해집니다. 보통 인터프리터는 명령줄의 첫 인수에 지정한 파일을 열고 실행합니다. CGI 바이너리로 호출할 때, PHP는 명령줄 인수를 해석하는 것을 거절합니다.
  • 서버의 어떠한 웹 문서로의 접근: http://my.host/cgi-bin/php/secret/doc.html PHP 바이너리 이름 뒤의 URL의 경로 정보 부분, /secret/doc.html는 일반적으로 CGI 프로그램에 의해 그 이름의 파일을 열고 해석하도록 사용합니다. 보통 몇몇 웹 서버 환경 설정 지시어(아파치: Action)는 PHP 인터프리터에 http://my.host/secret/script.php 등의 요청으로 리다이렉트하도록 합니다. 이러한 설치로는, 웹 서버는 우선 디렉토리 /secret에 대해 접근 권한을 확인하고, 리다이렉트된 요청 http://my.host/cgi-bin/php/secret/script.php을 생성합니다. 불행하게도, 이러한 형식으로 요청이 주어지면, /secret/script.php에 대한 접근 확인은 이루어지지 않고, 단순히 /cgi-bin/php 파일만을 확인합니다. 이 방법으로 /cgi-bin/php에 접근할 수 있는 어떠한 유저라도 웹 서버로 보호된 어떠한 문서라도 접근할 수 있습니다. PHP에서는, 서버 문서 트리에 접근 제한을 가진 어떠한 디렉토리가 존재한다면, 컴파일시의 환경설정 옵션 --enable-force-cgi-redirect, 실행시 환경설정 지시어 doc_rootuser_dir를 사용하여 이 공격을 방지할 수 있습니다. 여러가지 조합에 관한 자세한 설명은 아래쪽을 참고하십시오.


방법 1: 공개 파일만을 제공

서버가 패스워드나 IP 기반 접근 컨트롤로 제한하는 콘텐츠를 가지고 있지 않다면, 이러한 환경 설정 옵션을 사용할 필요가 없습니다. 웹 서버가 리다이렉트를 허용하지 않거나, 안전하게 리다이렉트된 요청에 대해서 PHP 바이너리와 통신할 방법을 가지고 있지 않다면, 설정 스크립트에 --enable-force-cgi-redirect 옵션을 지정할 수 있습니다. 하지만, 여전히 PHP 스크립트를 호출하는 방법으로 직접 호출 http://my.host/cgi-bin/php/dir/script.php이나 리다이렉션 호출 http://my.host/dir/script.php에 의존하고 있지 않음을 확인해야 할 것입니다.

아파치에서 리다이렉션은 AddHandler와 Action 지시어를 통해서 설정할 수 있습니다. (아래 참조)



방법 2: --enable-force-cgi-redirect 사용

이 컴파일시의 옵션은 누구라도 http://my.host/cgi-bin/php/secretdir/script.php와 같은 URL을 통해서 PHP를 직접 호출할 수 없게 합니다. 대신, 이 모드에서 PHP는 웹서버의 리다이렉트 규칙에 따를 때만 해석을 시도할 것입니다.

아파치에서 리다이렉션의 설정은 다음과 같은 지시어로 설정합니다:

Action php-script /cgi-bin/php
AddHandler php-script .php

이 옵션은 아파치 웹 서버에만 테스트되었고, 리다이렉트된 요청에 대해 아파치가 비표준 CGI 환경 변수 REDIRECT_STATUS를 설정하게 합니다. 웹 서버가 요청이 직접적인지 리다이렉트된 것인지의 구분을 제공하지 않는다면, 이 옵션을 사용할 수 없고, 이 문서에 제시된 다른 방법의 CGI 실행 방법을 이용해야 합니다.



방법 3: doc_root나 user_dir을 설정

스크립트나 실행 파일과 같은 활동적인 콘텐츠를 웹서버 디렉토리에 놓는 것은 때때로 비보안적인 행동으로 생각됩니다. 몇몇 환경 설정의 실수로 스크립트가 실행되지 않고 보통의 HTML 문서로 보여진다면, 지적 재산이나 패스워드와 같은 보안 정보를 노출시키는 결과를 가져올 수 있습니다. 그러므로 많은 시스템 관리자는 파일이 항상 해석이 되고 어떤 방법으로도 표시되어지지 않도록, PHP CGI를 통해서만 접근할 수 있는 스크립트를 위한 또 다른 디렉토리 구조를 만드는 것을 선호합니다.

또한, 앞의 섹션에서 설명한 방법으로 요청을 리다이렉트하지 않게 만드는게 불가능하다면, doc_root를 웹 문서 루트와 다른 장소로 설정할 필요가 있습니다.

PHP 스크립트 문서 루트를 설정 파일에서 지시어 doc_root나, 환경 변수 PHP_DOCUMENT_ROOT로 설정할 수 있습니다. 이를 설정하면, PHP의 CGI 버전은 항상 열 파일 이름 및 요청의 경로 정보를 doc_root 와 결합하여, 이 디렉토리 밖에서는 어떠한 스크립트도 실행하지 못하게 합니다. (아래의 user_dir 를 제외하고)

Another option usable here is user_dir. When user_dir is unset, only thing controlling the opened file name is doc_root . Opening an URL like http://my.host/~user/doc.php does not result in opening a file under users home directory, but a file called ~user/doc.php under doc_root (yes, a directory name starting with a tilde [~]).

If user_dir is set to for example public_php, a request like http://my.host/~user/doc.php will open a file called doc.php under the directory named public_php under the home directory of the user. If the home of the user is /home/user, the file executed is /home/user/public_php/doc.php.

user_dir expansion happens regardless of the doc_root setting, so you can control the document root and user directory access separately.



방법 4: 웹 트리 외부의 PHP 파서

매우 안전한 옵션은 PHP 파서 바이너리를 웹트리 밖에 위치시키는 것입니다. 예를 들면, /usr/local/bin 안에. 이 방법의 단 한가지 단점은 다음과 같은 줄을 PHP 태그를 포함하는 모든 파일의 첫번째 줄에 넣어야 한다는 점입니다:

#!/usr/local/bin/php

또한 파일을 실행 가능하게 해 둘 필요가 있습니다. 이것은 정확하게 실행을 위해서 #! 쉘 이스케이핑 메카니즘을 사용하는 펄이나 sh, 혹은 다른 일반적인 스크립팅 언어로 쓰여진 CGI 스크립트와 동일하게 취급합니다.

이 방법을 사용할 때, PHP가 PATH_INFOPATH_TRANSLATED를 올바르게 다룰 수 있게 하기 위해서는 PHP 파서를 컴파일 할 때, --enable-discard-path 옵션을 주어야 합니다.




아파치 모듈로 설치

PHP를 아파치 모듈로 사용할 때, 아파치의 사용자 권한(일반적으로 "nobody" 사용자)을 따릅니다. 이는 보안과 인증에 몇가지 영향을 줍니다. 예를 들어, PHP로 데이터베이스에 접근할 때, 데이터베이스에 내장 접근 제어가 없다면 데이터베이스에 "nobody" 사용자가 접근할 수 있게 해야 합니다. 이는 이상한 스크립트가 사용자이름과 패스워드 없이 데이터베이스에 접근하여 변경할 수 있다는 뜻입니다. 웹 스파이더가 데이터베이스 관리자 웹 페이지에 접근하여 모든 데이터베이스를 지울 수도 있습니다. 아파치 인증이나, LDAP, .htaccess 파일 등을 사용한 자체 접근 모델을 만들고, PHP 스크립트의 일부분으로 포함하여 이러한 일들에 대항할 수 있습니다.

종종, PHP 사용자(이 경우, 아파치 사용자) 시점에서 보안이 성립되어 위험이 줄지만, 이제 PHP가 사용자 디렉토리에 파일을 쓸 수 없는 점을 발견하게 됩니다. 또는 데이터베이스 접근과 변경이 막혀있을 수 있습니다. 정상 파일과 위험 파일, 또는 정상과 이상 데이터베이스 트랜젝션을 넣는 점에 대해서 동일한 보안 효과를 가지기 때문입니다.

이 시점에서 자주 일어나는 보안 실책은 아파치에 루트 권한을 주거나, 비슷한 기능을 실행할 수 있게 하는 것입니다.

아파치 사용자 권한을 루트로 올리는 것은 매우 위험하고, 전체 시스템을 위태롭게 합니다. 그러므로, sudo, chroot, 루트로 실행하기 등은 보안 전문가가 아닌 사람이 생각해서는 안됩니다.

간단한 해결책이 있습니다. open_basedir로 PHP에서 허용할 디렉토리를 제어하고 제한할 수 있습니다. 아파치 전용 구역을 설정해서, 모든 웹 기반 행동을 사용자, 시스템, 파일에 영향을 주지 않도록 제한할 수 있습니다.



Filesystem Security

Table of Contents

PHP is subject to the security built into most server systems with respect to permissions on a file and directory basis. This allows you to control which files in the filesystem may be read. Care should be taken with any files which are world readable to ensure that they are safe for reading by all users who have access to that filesystem.

Since PHP was designed to allow user level access to the filesystem, it's entirely possible to write a PHP script that will allow you to read system files such as /etc/passwd, modify your ethernet connections, send massive printer jobs out, etc. This has some obvious implications, in that you need to ensure that the files that you read from and write to are the appropriate ones.

Consider the following script, where a user indicates that they'd like to delete a file in their home directory. This assumes a situation where a PHP web interface is regularly used for file management, so the Apache user is allowed to delete files in the user home directories.

Example #1 Poor variable checking leads to....

<?php
// remove a file from the user's home directory
$username $_POST['user_submitted_name'];
$userfile $_POST['user_submitted_filename'];
$homedir  "/home/$username";

unlink("$homedir/$userfile");

echo 
"The file has been deleted!";
?>

Since the username and the filename are postable from a user form, they can submit a username and a filename belonging to someone else, and delete it even if they're not supposed to be allowed to do so. In this case, you'd want to use some other form of authentication. Consider what could happen if the variables submitted were "../etc/" and "passwd". The code would then effectively read:

Example #2 ... A filesystem attack

<?php
// removes a file from anywhere on the hard drive that
// the PHP user has access to. If PHP has root access:
$username $_POST['user_submitted_name']; // "../etc"
$userfile $_POST['user_submitted_filename']; // "passwd"
$homedir  "/home/$username"// "/home/../etc"

unlink("$homedir/$userfile"); // "/home/../etc/passwd"

echo "The file has been deleted!";
?>

There are two important measures you should take to prevent these issues.

  • Only allow limited permissions to the PHP web user binary.
  • Check all variables which are submitted.

Here is an improved script:

Example #3 More secure file name checking

<?php
// removes a file from the hard drive that
// the PHP user has access to.
$username $_SERVER['REMOTE_USER']; // using an authentication mechanisim
$userfile basename($_POST['user_submitted_filename']);
$homedir  "/home/$username";

$filepath "$homedir/$userfile";

if (
file_exists($filepath) && unlink($filepath)) {
    
$logstring "Deleted $filepath\n";
} else {
    
$logstring "Failed to delete $filepath\n";
}
$fp fopen("/home/logging/filedelete.log""a");
fwrite($fp$logstring);
fclose($fp);

echo 
htmlentities($logstringENT_QUOTES);

?>

However, even this is not without its flaws. If your authentication system allowed users to create their own user logins, and a user chose the login "../etc/", the system is once again exposed. For this reason, you may prefer to write a more customized check:

Example #4 More secure file name checking

<?php
$username     
$_SERVER['REMOTE_USER']; // using an authentication mechanisim
$userfile     $_POST['user_submitted_filename'];
$homedir      "/home/$username";

$filepath     "$homedir/$userfile";

if (!
ctype_alnum($username) || !preg_match('/^(?:[a-z0-9_-]|\.(?!\.))+$/iD'$userfile)) {
    die(
"Bad username/filename");
}

//etc...
?>

Depending on your operating system, there are a wide variety of files which you should be concerned about, including device entries (/dev/ or COM1), configuration files (/etc/ files and the .ini files), well known file storage areas (/home/, My Documents), etc. For this reason, it's usually easier to create a policy where you forbid everything except for what you explicitly allow.


Null bytes related issues

As PHP uses the underlying C functions for filesystem related operations, it may handle null bytes in a quite unexpected way. As null bytes denote the end of a string in C, strings containing them won't be considered entirely but rather only until a null byte occurs. The following example shows a vulnerable code that demonstrates this problem:

Example #1 Script vulnerable to null bytes

<?php
$file 
$_GET['file']; // "../../etc/passwd\0"
if (file_exists('/home/wwwrun/'.$file.'.php')) {
    
// file_exists will return true as the file /home/wwwrun/../../etc/passwd exists
    
include '/home/wwwrun/'.$file.'.php';
    
// the file /etc/passwd will be included
}
?>

Therefore, any tainted string that is used in a filesystem operation should always be validated properly. Here is a better version of the previous example:

Example #2 Correctly validating the input

<?php
$file 
$_GET['file']; 

// Whitelisting possible values
switch ($file) {
    case 
'main':
    case 
'foo':
    case 
'bar':
        include 
'/home/wwwrun/include/'.$file.'.php';
        break;
    default:
        include 
'/home/wwwrun/include/main.php';
}
?>



데이터베이스 보안

Table of Contents

최근에, 데이터베이스는 웹사이트에 다양한 동적 내용을 제공하기 위한 모든 웹 기반 어플리케이션의 기본 구성 요소입니다. 매우 민감하거나 비밀스러운 정보가 데이터베이스에 저장될 수 있으므로, 데이터베이스의 보호에 대하여 심각하게 고려해야 합니다.

어떠한 정보를 가져오거나 넣으려면 데이터베이스에 접속하고, 적합한 질의를 전송하고, 결과를 가져오고, 접속을 닫습니다. 최근에, 이 작업에 가장 많이 사용하는 질의 언어는 구조적 질의 언어(SQL)입니다. 어떻게 공격자가 SQL 질의를 건들일 수 있는지 확인하십시오.

예측할 수 있듯이, PHP는 데이터베이스 자체를 보호할 수 없습니다. 다음 섹션은 PHP 스크립트에서 데이터베이스에 접근하고 조작하는 방법에 대한 매우 기초적인 설명입니다.

간단한 규칙을 명심하십시오: 철저하게 방어. 더 많은 위치에서 데이터베이스의 보호를 증가하기 위한 작업을 한다면, 공격자가 저장된 정보를 빼낼 수 있는 성공 가능성이 줄어듭니다. 데이터베이스 스키마와 어플리케이션 처리의 좋은 디자인은 최대한의 공포와 함께 하는 것입니다.


데이터베이스 설계하기

첫번째 단계는 항상 데이터베이스를 생성하는 것입니다. 써드 파티의 데이터베이스를 사용할 수도 있습니다. 데이터베이스를 생성할 때, 데이터베이스는 생성 구문을 실행한 오너에게 할당됩니다. 보통, 오너(또는 슈퍼유저)만 그 데이터베이스의 객체를 다룰 수 있습니다. 다른 사용자가 사용할 수 있게 하려면, 권한을 주어야 합니다.

어플리케이션은 데이터베이스에 오너나 슈퍼유저로 접속해서는 안됩니다. 이러한 사용자는 스키마를 변경하거나(예. 테이블 드롭) 전체 내용을 지울 수 있기 때문입니다.

어플리케이션이 데이터베이스 객체에 필요한 최소한의 권한만 가지도록, 다른 데이터베이스 사용자를 만듭니다. 최소한도로 필요한 권한만 주고, 동일한 사용자가 다른 사용을 하지 못하도록 합니다. 이로써 침입자가 어플리케이션 권한으로 데이터베이스 사용 권한을 습득해도, 어플리케이션이 할 수 있는 변경밖에 하지 못하도록 합니다.

모든 비지니스 로직을 웹 어플리케이션(즉, 스크립트)에 넣지 않기를 권합니다. 대신, 뷰, 트리거, 룰을 사용한 데이터베이스 스키마를 사용하십시오. 시스템이 발전하면, 새 클라이언트가 데이터베이스를 여는 경향이 있고, 각 데이터베이스 클라이언트에 로직을 다시 구현해야 합니다. 반복하는 대신에, 트리거로 자동적으로 투명하게 필드를 다룰 수 있습니다. 이는 종종 어플리케이션의 디버그 문제를 해결하기 쉽게 하거나 트랜젝션을 추적하기 쉽게 합니다.



데이터베이스 접속하기

보안을 증가하기 위하여, 클라이언트/서버 간 통신을 암호화하는 SSL 접속을 할 수 있습니다. 또는 클라이언트와 데이터베이스 서버간의 네트워크 접속을 암호화하기 위하여 ssh를 사용할 수 있습니다. 어떠한 방법을 사용하건, 공격자가 트래픽 감시로 데이터베이스에 관한 정보를 얻기 어렵게 합니다.



암호화 저장 모델

SSL/SSH는 클라이언트에서 서버로 전송되는 데이터를 보호하지만, SSL/SSH가 데이터베이스에 저장된 지속 데이터를 보호하지는 않습니다. SSL는 연결용 프로토콜입니다.

공격자가 (웹 서버를 건너뛰고) 데이터베이스에 직접 접근할 수 있게 되면, 정보를 데이터베이스 자체에서 보호하지 않는 한 저장된 민감한 데이터가 유출되거나 오용될 수 있습니다. 데이터 암호화로 이런 위험을 줄일 수 있으나, 매우 적은 데이터베이스만 이러한 데이터 암호화를 지원합니다.

이 문제를 해결하기 위한 가장 쉬운 방법은 자체 암호화 패키지를 만들어, PHP 스크립트에서 사용하는 것입니다. PHP는 McryptMhash처럼, 다양한 암호화 알고리즘을 지원하는 확장으로 이 일을 도와줍니다. 스크립트에서 데이터베이스에 삽입하기 전에 데이터를 암호화하고, 꺼내올 때 해독합니다. 아래 에제를 참고해서 어떻게 암호화가 작동하는 지 확인하십시오.

원 표현이 필요하지 않은(즉, 표시되지 않는) 정말로 감춰진 데이터에 대해서는, 해시를 생각할 수 있습니다. 해시의 잘 알려진 예는 패스워드 대신에, 패스워드의 MD5 해시를 데이터베이스에 저장하는 것입니다. crypt()md5()를 참고하십시오.

Example #1 해시 패스워드 필드 사용하기

<?php

// 패스워드 해시 저장
$query  sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
            
pg_escape_string($username), md5($password));
$result pg_query($connection$query);

// 사용자가 올바른 패스워드를 입력했는지 질의
$query sprintf("SELECT 1 FROM users WHERE name='%s' AND pwd='%s';",
            
pg_escape_string($username), md5($password));
$result pg_query($connection$query);

if (
pg_num_rows($result) > 0) {
    echo 
'Welcome, $username!';
} else {
    echo 
'Authentication failed for $username.';
}

?>


SQL 인젝션

많은 웹 개발자가 SQL 질의가 공격받을 수 있다는 점을 간과하고, SQL 질의를 신뢰할 수 있는 명령으로 가정합니다. 이로 인해 SQL 질의에서 접근 제어를 우회할 수 있여, 일반적인 인증과 인증 확인을 무시하고, 종종 SQL 질의가 OS 단계 명령을 할 수 있도록 합니다.

직접 SQL 명령 인젝션은 공격자가 숨겨진 데이터를 노출하거나, 취약한 부분을 덮어쓰거나, 데이터베이스에 위험한 시스템 단계 명령을 실행하게 하는 SQL 명령을 생성하거나 대체하는 기술입니다. 어플리케이션이 사용자 입력을 받아서, 이를 SQL 질의를 만들 떄 정적 인수로 조합함으로써 일어납니다. 유감스럽게도, 아래 예제들은 실제 이야기를 기반으로 하고 있습니다.

입력 검증이 없고 데이터베이스에 슈퍼유저나 사용자를 만들 수 있는 사용자로 접속하는 경우, 공격자가 데이터베이스에 슈퍼유저를 만들 수 있습니다.

Example #1 결과셋을 페이지로 나눔 ... 그리고 슈퍼유저 만들기 (PostgreSQL)

<?php

$offset 
$argv[0]; // 주의, 입력 검증 없음!
$query  "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
$result pg_query($conn$query);

?>

일반 사용자는 URL에 $offset이 인코드되어 있는 'next', 'prev' 링크를 클릭합니다. 스크립트는 $offset이 정수라고 생각합니다. 그러나, 누군가가 다음처럼 URL에 추가적인 urlencode() 형식을 덧붙이면 어떻게 될까요?

0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
    select 'crack', usesysid, 't','t','crack'
    from pg_shadow where usename='postgres';
--

이렇게 되면, 스크립트에서 슈퍼유저 권한을 공격자에게 주게 됩니다. 0;가 유효한 offset으로 제공되어 원래 질의를 유효하게 하고 정료하는 점에 주의하십시오.

Note: SQL 해석기에서 개발자가 쓴 쿼리의 나머지 부분을 무시하게 하는 일반적인 방법은 --를 붙이는 것이며, 이는 SQL에서 주석 부호입니다.

패스워드를 얻는 방법 중 하나는 검색 결과 페이지를 우회하는 것입니다. 공격자에게 필요한 것은 제출한 변수 중 하나라도 제대로 다뤄지지 않으면서 SQL 구문에 사용되는 것입니다. 이러한 필터는 일반적으로 SELECT 구문에서 WHERE, ORDER BY, LIMIT, OFFSET에 사용됩니다. 데이터베이스가 UNION 구조를 지원하면, 공격자는 원래 질의에 전체 질의를 덧붙여서 임의의 테이블에서 패스워드를 얻을 수 있습니다. 암호화된 패스워드 필드를 강력히 권합니다.

Example #2 글을 출력함 ... 그리고 패스워드도 (모든 데이터베이스 서버)

<?php

$query  
"SELECT id, name, inserted, size FROM products
                  WHERE size = '
$size'
                  ORDER BY 
$order LIMIT $limit$offset;";
$result odbc_exec($conn$query);

?>

질의에서 정적인 부분은 모든 패스워드를 가져오는 SELECT 구문과 조합될 수 있습니다:

'
union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable;
--

이 질의('--로 다룸)가 $query에서 사용하는 변수 중 하나에 할당되면, 질의 괴물이 깨어납니다.

SQL UPDATE도 공격받을 수 있습니다. 이런 질의를 잘라내어서 완전한 새 질의를 덧붙일 수 있습니다. 또한 공격자가 SET 절을 다룰 수도 있습니다. 이 경우 질의를 성공적으로 변경하기 위하여 일부 스키마 정보를 가지고 있어야 합니다. 이는 폼 변수명을 조사하거나, 브루트 포스로 얻을 수 있습니다. 패스워드와 사용자이름을 저장하는 필드의 이름 규칙은 그리 많지 않습니다.

Example #3 패스워드 재설정에서 ... 더 많은 권한 얻기 (모든 데이터베이스 서버)

<?php
$query 
"UPDATE usertable SET pwd='$pwd' WHERE uid='$uid';";
?>

악의적인 사용자가 $uid' or uid like'%admin'; -- 값을 넣어서 관리자 패스워드를 변경하거나, $pwd"hehehe', admin='yes', trusted=100 "(마지막 공백 포함)을 설정하여 권한을 얻을 수도 있습니다. 그러면, 질의가 다음처럼 꼬입니다:

<?php

// $uid == ' or uid like'%admin%'; --
$query "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%'; --";

// $pwd == "hehehe', admin='yes', trusted=100 "
$query "UPDATE usertable SET pwd='hehehe', admin='yes', trusted=100 WHERE
...;"
;

?>

데티어베이스 호스트의 OS 등급 명령에 접근하는 섬뜩한 예제입니다.

Example #4 데이터베이스 호스트 OS 공격하기 (MSSQL 서버)

<?php

$query  
"SELECT * FROM products WHERE id LIKE '%$prod%'";
$result mssql_query($query);

?>

공격자가 $proda%' exec master..xp_cmdshell 'net user test testpass /ADD' -- 값을 제출하면, $query는:

<?php

$query  
"SELECT * FROM products
                    WHERE id LIKE '%a%'
                    exec master..xp_cmdshell 'net user test testpass /ADD'--"
;
$result mssql_query($query);

?>

MSSQL 서버는 로컬 계정 데이터베이스에 새 사용자를 추가하는 명령을 포함한 SQL 구문을 실행하게 됩니다. 어플리케이션이 sa로 실행되고 MSSQLSERVER 서비스가 적합한 권한을 가지고 있으면, 공격자는 머신에 접근할 수 있는 계정을 가지게 됩니다.

Note: 위 예제 중 일부는 특정 데이터베이스 서버에 묶여 있습니다. 이것은 다른 서버에 유사한 공격이 불가능하다는 의미가 아닙니다. 데이터베이스 서버가 다른 방식으로 비슷한 취약점을 가질 수 있습니다.

기술 피하기

대부분의 예제에서 공격자가 데이터베이스 스키마에 대한 정보를 가지고 있어야 한다고 말할 수 있을겁니다. 맞습니다, 그러나 스키마가 어떻게 유출되는지 알 수 없습니다. 그리고 유출되면, 데이터베이스가 노출됩니다. 오픈 소스를 사용하거나 CMS나 포럼에 공개되어 있는 데이터베이스 접근 패키지를 가지고 있으면, 침입자가 간단히 코드의 사본을 구할 수 있습니다. 나쁘게 디자인되어 있으면 그 자체로도 보안 위협이 됩니다.

이러한 공격은 주로 보안을 염두에 두지 않고 쓰여진 코드 취약점에 기반하고 있습니다. 어떠한 입력도 믿지 마십시오. 특히 클라이언트측에서 오는 입력은 믿지 마십시오. select, hidden input 필드, 쿠키도 마찬가지입니다. 첫번째 예제에서 그러한 질의가 재앙을 일으킬 수 있는 점을 보여주고 있습니다.

  • 데이터베이스에 슈퍼유저나 데이터베이스 주인으로 접속하지 마십시오. 항상 매우 제한된 권한을 가진 특별 사용자를 사용하십시오.
  • 주어진 입력이 기대한 자료형인지 확인하십시오. PHP는 넓은 범위의 입력 검증 함수를 가지고 있습니다. 가장 간단한 변수 관련 함수문자형 함수(예. 각각 is_numeric(), ctype_digit())부터 펄 호환 정규표현식 지원까지 있습니다.
  • 어플리케이션이 숫자 입력을 기다린다면, is_numeric()으로 데이터를 검사하거나, settype()으로 자료형을 바꾸거나, sprintf()에서 숫자 표현을 사용하십시오.

    Example #5 페이지 질의를 작성하는 더 안전한 방법

    <?php

    settype
    ($offset'integer');
    $query "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";

    // please note %d in the format string, using %s would be meaningless
    $query sprintf("SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET %d;",
                     
    $offset);

    ?>

  • 숫자가 아닌 사용자 제공 값은 데이터베이스 한정 문자열 회피 함수로 인용하십시오. (예. mysql_real_escape_string(), sql_escape_string() 등) 데이터베이스 한정 문자열 회피 함수가 없으면, addslashes()str_replace() 함수를 사용할 수 있습니다. (데이터베이스 형식에 따릅니다) 첫번째 예제를 확인하십시오. 예제가 보여주듯이, 질의의 정적 부분에 따옴표를 붙이는건 충분하지 않으며, 질의를 쉽게 깰 수 있습니다.
  • 어떠한 데이터베이스 한정 정보라도 출력하지 마십시오. 특히, 스키마에 대해서는 어떠한 경우라도 안됩니다. 오류 보고오류 다루기와 기록 함수를 참고하십시오.
  • 저장된 프로시저와 이전에 정의한 커서를 사용해서 추상적인 데이터 접근을 할 수도 있습니다. 이로써 사용자가 직접 테이블이나 뷰에 접근할 수 없게 할 수 있지만, 이 해결책은 다른 문제가 있습니다.

다만, 스크립트 안에서나 (기록을 지원한다면) 데이터베이스에서 질의를 기록하는 것이 도움이 됩니다. 반면, 기록은 유해한 시도를 방지하지는 못합니다. 그러나 어떠한 어플리케이션이 우회되었는지 추적할 때는 도움이 됩니다. 기록 자체는 유용하지 않으며, 포함한 정보가 중요합니다. 일반적으로 더 자세한 정보가 낫습니다.




Error Reporting

With PHP security, there are two sides to error reporting. One is beneficial to increasing security, the other is detrimental.

A standard attack tactic involves profiling a system by feeding it improper data, and checking for the kinds, and contexts, of the errors which are returned. This allows the system cracker to probe for information about the server, to determine possible weaknesses. For example, if an attacker had gleaned information about a page based on a prior form submission, they may attempt to override variables, or modify them:

Example #1 Attacking Variables with a custom HTML page

<form method="post" action="attacktarget?username=badfoo&amp;password=badfoo">
<input type="hidden" name="username" value="badfoo" />
<input type="hidden" name="password" value="badfoo" />
</form>

The PHP errors which are normally returned can be quite helpful to a developer who is trying to debug a script, indicating such things as the function or file that failed, the PHP file it failed in, and the line number which the failure occurred in. This is all information that can be exploited. It is not uncommon for a php developer to use show_source(), highlight_string(), or highlight_file() as a debugging measure, but in a live site, this can expose hidden variables, unchecked syntax, and other dangerous information. Especially dangerous is running code from known sources with built-in debugging handlers, or using common debugging techniques. If the attacker can determine what general technique you are using, they may try to brute-force a page, by sending various common debugging strings:

Example #2 Exploiting common debugging variables

<form method="post" action="attacktarget?errors=Y&amp;showerrors=1&amp;debug=1">
<input type="hidden" name="errors" value="Y" />
<input type="hidden" name="showerrors" value="1" />
<input type="hidden" name="debug" value="1" />
</form>

Regardless of the method of error handling, the ability to probe a system for errors leads to providing an attacker with more information.

For example, the very style of a generic PHP error indicates a system is running PHP. If the attacker was looking at an .html page, and wanted to probe for the back-end (to look for known weaknesses in the system), by feeding it the wrong data they may be able to determine that a system was built with PHP.

A function error can indicate whether a system may be running a specific database engine, or give clues as to how a web page or programmed or designed. This allows for deeper investigation into open database ports, or to look for specific bugs or weaknesses in a web page. By feeding different pieces of bad data, for example, an attacker can determine the order of authentication in a script, (from the line number errors) as well as probe for exploits that may be exploited in different locations in the script.

A filesystem or general PHP error can indicate what permissions the web server has, as well as the structure and organization of files on the web server. Developer written error code can aggravate this problem, leading to easy exploitation of formerly "hidden" information.

There are three major solutions to this issue. The first is to scrutinize all functions, and attempt to compensate for the bulk of the errors. The second is to disable error reporting entirely on the running code. The third is to use PHP's custom error handling functions to create your own error handler. Depending on your security policy, you may find all three to be applicable to your situation.

One way of catching this issue ahead of time is to make use of PHP's own error_reporting(), to help you secure your code and find variable usage that may be dangerous. By testing your code, prior to deployment, with E_ALL, you can quickly find areas where your variables may be open to poisoning or modification in other ways. Once you are ready for deployment, you should either disable error reporting completely by setting error_reporting() to 0, or turn off the error display using the php.ini option display_errors, to insulate your code from probing. If you choose to do the latter, you should also define the path to your log file using the error_log ini directive, and turn log_errors on.

Example #3 Finding dangerous variables with E_ALL

<?php
if ($username) {  // Not initialized or checked before usage
    
$good_login 1;
}
if (
$good_login == 1) { // If above test fails, not initialized or checked before usage
    
readfile ("/highly/sensitive/data/index.html");
}
?>



Using Register Globals

Warning

이 기능은 PHP 5.3.0부터 배제되고 PHP 6.0.0부터 제거됩니다. 이 기능에 의존하지 않기를 권합니다.

Perhaps the most controversial change in PHP is when the default value for the PHP directive register_globals went from ON to OFF in PHP » 4.2.0. Reliance on this directive was quite common and many people didn't even know it existed and assumed it's just how PHP works. This page will explain how one can write insecure code with this directive but keep in mind that the directive itself isn't insecure but rather it's the misuse of it.

When on, register_globals will inject your scripts with all sorts of variables, like request variables from HTML forms. This coupled with the fact that PHP doesn't require variable initialization means writing insecure code is that much easier. It was a difficult decision, but the PHP community decided to disable this directive by default. When on, people use variables yet really don't know for sure where they come from and can only assume. Internal variables that are defined in the script itself get mixed up with request data sent by users and disabling register_globals changes this. Let's demonstrate with an example misuse of register_globals:

Example #1 Example misuse with register_globals = on

<?php
// define $authorized = true only if user is authenticated
if (authenticated_user()) {
    
$authorized true;
}

// Because we didn't first initialize $authorized as false, this might be
// defined through register_globals, like from GET auth.php?authorized=1
// So, anyone can be seen as authenticated!
if ($authorized) {
    include 
"/highly/sensitive/data.php";
}
?>

When register_globals = on, our logic above may be compromised. When off, $authorized can't be set via request so it'll be fine, although it really is generally a good programming practice to initialize variables first. For example, in our example above we might have first done $authorized = false. Doing this first means our above code would work with register_globals on or off as users by default would be unauthorized.

Another example is that of sessions. When register_globals = on, we could also use $username in our example below but again you must realize that $username could also come from other means, such as GET (through the URL).

Example #2 Example use of sessions with register_globals on or off

<?php
// We wouldn't know where $username came from but do know $_SESSION is
// for session data
if (isset($_SESSION['username'])) {

    echo 
"Hello <b>{$_SESSION['username']}</b>";

} else {

    echo 
"Hello <b>Guest</b><br />";
    echo 
"Would you like to login?";

}
?>

It's even possible to take preventative measures to warn when forging is being attempted. If you know ahead of time exactly where a variable should be coming from, you can check to see if the submitted data is coming from an inappropriate kind of submission. While it doesn't guarantee that data has not been forged, it does require an attacker to guess the right kind of forging. If you don't care where the request data comes from, you can use $_REQUEST as it contains a mix of GET, POST and COOKIE data. See also the manual section on using variables from external sources.

Example #3 Detecting simple variable poisoning

<?php
if (isset($_COOKIE['MAGIC_COOKIE'])) {

    
// MAGIC_COOKIE comes from a cookie.
    // Be sure to validate the cookie data!

} elseif (isset($_GET['MAGIC_COOKIE']) || isset($_POST['MAGIC_COOKIE'])) {

   
mail("admin@example.com""Possible breakin attempt"$_SERVER['REMOTE_ADDR']);
   echo 
"Security violation, admin has been alerted.";
   exit;

} else {

   
// MAGIC_COOKIE isn't set through this REQUEST

}
?>

Of course, simply turning off register_globals does not mean your code is secure. For every piece of data that is submitted, it should also be checked in other ways. Always validate your user data and initialize your variables! To check for uninitialized variables you may turn up error_reporting() to show E_NOTICE level errors.

For information about emulating register_globals being On or Off, see this FAQ.

Note: 자동 전역: 사용상 주의
$_GET, $_POST, $_SERVER 등의 자동 전역 배열은 PHP 4.1.0부터 사용할 수 있습니다. 자세한 내용은 매뉴얼의 superglobals 섹션을 읽어보십시오.



User Submitted Data

The greatest weakness in many PHP programs is not inherent in the language itself, but merely an issue of code not being written with security in mind. For this reason, you should always take the time to consider the implications of a given piece of code, to ascertain the possible damage if an unexpected variable is submitted to it.

Example #1 Dangerous Variable Usage

<?php
// remove a file from the user's home directory... or maybe
// somebody else's?
unlink ($evil_var);

// Write logging of their access... or maybe an /etc/passwd entry?
fwrite ($fp$evil_var);

// Execute something trivial.. or rm -rf *?
system ($evil_var);
exec ($evil_var);

?>

You should always carefully examine your code to make sure that any variables being submitted from a web browser are being properly checked, and ask yourself the following questions:

  • Will this script only affect the intended files?
  • Can unusual or undesirable data be acted upon?
  • Can this script be used in unintended ways?
  • Can this be used in conjunction with other scripts in a negative manner?
  • Will any transactions be adequately logged?

By adequately asking these questions while writing the script, rather than later, you prevent an unfortunate re-write when you need to increase your security. By starting out with this mindset, you won't guarantee the security of your system, but you can help improve it.

You may also want to consider turning off register_globals, magic_quotes, or other convenience settings which may confuse you as to the validity, source, or value of a given variable. Working with PHP in error_reporting(E_ALL) mode can also help warn you about variables being used before they are checked or initialized (so you can prevent unusual data from being operated upon).



Magic Quotes

Table of Contents

Warning

이 기능은 PHP 5.3.0부터 배제되고 PHP 6.0.0부터 제거됩니다. 이 기능에 의존하지 않기를 권합니다.

Magic Quotes is a process that automagically escapes incoming data to the PHP script. It's preferred to code with magic quotes off and to instead escape the data at runtime, as needed.


What are Magic Quotes

When on, all ' (single-quote), " (double quote), \ (backslash) and NULL characters are escaped with a backslash automatically. This is identical to what addslashes() does.

There are three magic quote directives:

  • magic_quotes_gpc Affects HTTP Request data (GET, POST, and COOKIE). Cannot be set at runtime, and defaults to on in PHP. See also get_magic_quotes_gpc().
  • magic_quotes_runtime If enabled, most functions that return data from an external source, including databases and text files, will have quotes escaped with a backslash. Can be set at runtime, and defaults to off in PHP. See also set_magic_quotes_runtime() and get_magic_quotes_runtime().
  • magic_quotes_sybase If enabled, a single-quote is escaped with a single-quote instead of a backslash. If on, it completely overrides magic_quotes_gpc. Having both directives enabled means only single quotes are escaped as ''. Double quotes, backslashes and NULL's will remain untouched and unescaped. See also ini_get() for retrieving its value.


Why did we use Magic Quotes

Warning

이 기능은 PHP 5.3.0부터 배제되고 PHP 6.0.0부터 제거됩니다. 이 기능에 의존하지 않기를 권합니다.

  • There is no reason to use magic quotes because they are no longer a supported part of PHP. However, they did exist and did help a few beginners blissfully and unknowingly write better (more secure) code. But, when dealing with code that relies upon this behavior it's better to update the code instead of turning magic quotes on. So why did this feature exist? Simple, to help prevent SQL Injection. Today developers are better aware of security and end up using database specific escaping mechanisms and/or prepared statements instead of relying upon features like magical quotes.


Why not to use Magic Quotes

Warning

이 기능은 PHP 5.3.0부터 배제되고 PHP 6.0.0부터 제거됩니다. 이 기능에 의존하지 않기를 권합니다.

  • Portability Assuming it to be on, or off, affects portability. Use get_magic_quotes_gpc() to check for this, and code accordingly.
  • Performance Because not every piece of escaped data is inserted into a database, there is a performance loss for escaping all this data. Simply calling on the escaping functions (like addslashes()) at runtime is more efficient. Although php.ini-dist enables these directives by default, php.ini-recommended disables it. This recommendation is mainly due to performance reasons.
  • Inconvenience Because not all data needs escaping, it's often annoying to see escaped data where it shouldn't be. For example, emailing from a form, and seeing a bunch of \' within the email. To fix, this may require excessive use of stripslashes().


Disabling Magic Quotes

Warning

이 기능은 PHP 5.3.0부터 배제되고 PHP 6.0.0부터 제거됩니다. 이 기능에 의존하지 않기를 권합니다.

The magic_quotes_gpc directive may only be disabled at the system level, and not at runtime. In otherwords, use of ini_set() is not an option.

Example #1 Disabling magic quotes server side

An example that sets the value of these directives to Off in php.ini. For additional details, read the manual section titled How to change configuration settings.

; Magic quotes
;

; Magic quotes for incoming GET/POST/Cookie data.
magic_quotes_gpc = Off

; Magic quotes for runtime-generated data, e.g. data from SQL, from exec(), etc.
magic_quotes_runtime = Off

; Use Sybase-style magic quotes (escape ' with '' instead of \').
magic_quotes_sybase = Off

If access to the server configuration is unavailable, use of .htaccess is also an option. For example:

php_flag magic_quotes_gpc Off

In the interest of writing portable code (code that works in any environment), like if setting at the server level is not possible, here's an example to disable magic_quotes_gpc at runtime. This method is inefficient so it's preferred to instead set the appropriate directives elsewhere.

Example #2 Disabling magic quotes at runtime

<?php
if (get_magic_quotes_gpc()) {
    function 
stripslashes_deep($value)
    {
        
$value is_array($value) ?
                    
array_map('stripslashes_deep'$value) :
                    
stripslashes($value);

        return 
$value;
    }

    
$_POST array_map('stripslashes_deep'$_POST);
    
$_GET array_map('stripslashes_deep'$_GET);
    
$_COOKIE array_map('stripslashes_deep'$_COOKIE);
    
$_REQUEST array_map('stripslashes_deep'$_REQUEST);
}
?>




Hiding PHP

In general, security by obscurity is one of the weakest forms of security. But in some cases, every little bit of extra security is desirable.

A few simple techniques can help to hide PHP, possibly slowing down an attacker who is attempting to discover weaknesses in your system. By setting expose_php to off in your php.ini file, you reduce the amount of information available to them.

Another tactic is to configure web servers such as apache to parse different filetypes through PHP, either with an .htaccess directive, or in the apache configuration file itself. You can then use misleading file extensions:

Example #1 Hiding PHP as another language

# Make PHP code look like other code types
AddType application/x-httpd-php .asp .py .pl

Or obscure it completely:

Example #2 Using unknown types for PHP extensions

# Make PHP code look like unknown types
AddType application/x-httpd-php .bop .foo .133t

Or hide it as HTML code, which has a slight performance hit because all HTML will be parsed through the PHP engine:

Example #3 Using HTML types for PHP extensions

# Make all PHP code look like HTML
AddType application/x-httpd-php .htm .html

For this to work effectively, you must rename your PHP files with the above extensions. While it is a form of security through obscurity, it's a minor preventative measure with few drawbacks.



최신 버전 따라가기

PHP는 다른 거대 시스템과 마찬가지로, 지속적으로 검증하고 향상됩니다. 메이저와 마이너 변경을 포함한 각 새 버전은 보안을 향상하고 결함을 수정하며, 설정 실수나 전체 시스템의 보안과 안정성을 향상시킵니다.

다른 시스템급 스크립트 언어나 프로그램처럼, 가장 좋은 방법은 자주 업데이트하고, 최신 버전과 변경점을 인식하여 보강하는 일입니다.




기능


PHP로 HTTP 인증하기

PHP를 이용한 HTTP 인증은 아파치 모듈로 실행할때만 사용할 수 있으며, CGI 버전에서는 사용할 수 없습니다. 아파치 모듈에서 PHP 스크립트가 header() 함수를 이용하여 "인증 요구" 메세지를 클라이언트 브라우저에 전송함으로써, 사용자명/패스워드 입력창을 띄울 수 있습니다. 사용자가 사용자명과 패스워드를 입력하면, PHP 스크립트의 URL이 다시 호출하고, 예약 정의 변수 PHP_AUTH_USER, PHP_AUTH_PW, AUTH_TYPE에 사용자명, 패스워드, 인증 형식이 들어갑니다. 이 예약 정의 변수들은 $_SERVER$HTTP_SERVER_VARS 배열로 확인할 수 있습니다. "Basic"과 "Digest"(PHP 5.1.0부터) 인증 방식 모두를 지원합니다. 자세한 정보는 header() 함수를 참고하십시오.

Note: PHP 버전 주의
$_SERVER 등의 자동 전역 변수는 PHP » 4.1.0부터 사용할 수 있습니다.

다음은 페이지에 대해 클라이언트 인증을 강제하는 예제 스크립트입니다:

Example #1 Basic HTTP 인증 예제

<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    
header('WWW-Authenticate: Basic realm="My Realm"');
    
header('HTTP/1.0 401 Unauthorized');
    echo 
'사용자가 취소 버튼을 눌렀을 때 전송되는 텍스트';
    exit;
} else {
    echo 
"<p>안녕하세요, {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo 
"<p>{$_SERVER['PHP_AUTH_PW']}를 패스워드로 접속했습니다.</p>";
}
?>

Example #2 Digest HTTP 인증 예제

이 예제는 어떻게 Digest HTTP 인증을 하는 지 간단하게 보여줍니다. 자세한 정보는 » RFC 2617을 읽어 보십시오.

<?php
$realm 
'제한 영역';

//user => password
$users = array('admin' => 'mypass''guest' => 'guest);


if (empty($_SERVER['
PHP_AUTH_DIGEST'])) {
    header('
HTTP/1.1 401 Unauthorized');
    header('
WWW-AuthenticateDigest realm="'.$realm.
           '"
,qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');

    die('
사용자가 취소 버튼을 눌렀을 때 보내지는 텍스트');
}


// PHP_AUTH_DIGEST 변수 조사
if (!($data = http_digest_parse($_SERVER['
PHP_AUTH_DIGEST'])) ||
    !isset($users[$data['
username']]))
    die('
Wrong Credentials!');

// ok, 유효한 username & password
echo $data['
username'] . '으로 로그인 되었습니다.';


// http auth 헤더를 처리하는 함수
function http_digest_parse($txt)
{
    // 빠진 데이터에 대한 보호
    $needed_parts = array('
nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
    $data = array();

    preg_match_all('
@(\w+)=(?:([\'"])([^\2]+)]\2|([^\s,]+))@'$txt$matchesPREG_SET_ORDER);

    foreach (
$matches as $m) {
        
$data[$m[1]] = $m[3] ? $m[3] : $m[4];
        unset(
$needed_parts[$m[1]);
    }

    return 
$needed_parts false $data;
}
?>

Note: 호환성 주의
HTTP 헤더열을 코딩할때는 주의를 기울이십시오. 모든 클라이언트에 대해 최대의 호환성을 보장받기 위해서는, 키워드 "Basic"은 대문자 "B"로 쓰여져야하고, 렐름 메세지는 이중 인용 부호(")로 감싸져야하며, HTTP/1.0 401 헤더열에서 401 코드는 정확히 하나의 스페이스를 가져야합니다. 인증 인수는 위 digest 예제에서 볼 수 있듯이, 쉼표로 구분해야 합니다.

위 예제와 같이 단순히 PHP_AUTH_USERPHP_AUTH_PW를 출력하는 대신, 유저네임과 패스워드를 확인해서 인증을 할 수 있습니다. 데이터베이스에 요구를 하거나, dbm 파일에서 유저를 찾아낼 수 있습니다.

인터넷 익스플로러 브라우저의 버그에 주의하십시오. 헤더의 순서에 매우 까다롭습니다. WWW-Authenticate 헤더를 HTTP/1.0 401 헤더 전에 전송하는 것이 현재 사용 가능한 방법입니다.

PHP 4.3.0부터, 전통적인 외부 메카니즘을 통해서 인증된 페이지의 패스워드를 누출하는 스크립트의 작성을 방지하기 위해서, 각각의 페이지에 대한 외부 인증과 안전 모드가 활성화되었을때, PHP_AUTH 변수를 설정하지 않습니다. 대신, 외부 인증 유저를 확인하기 위해서 REMOTE_USER를 사용할 수 있습니다. 그러므로, $_SERVER['REMOTE_USER']를 사용하십시오.

Note: 설정 주의
PHP는 외부 인증을 검증할 때 AuthType 지시어의 존재를 확인합니다.

이 방식은 비인증 URL을 조작해서 같은 서버의 인증 URL의 패스워드를 훔치는 것은 방지할 수 없다는 점에 주의하십시오.

넷스케이프 네비게이터와 인터넷 익스플로러는 서버 응답 401을 받았을 때, 로컬 브라우저창의 인증 캐시를 클리어합니다. 이것은 강제로 유저네임과 패스워드를 재입력하게 함으로써, 사용자를 '로그 아웃'하는 효과를 가집니다. 몇몇 사람들은 이것을 "시간 제한" 로그인이나, "로그 아웃" 버튼을 제공을 통해 사용합니다.

Example #3 새 이름/패스워드를 강제하는 HTTP 인증 예제

<?php
function authenticate() {
    
header('WWW-Authenticate: Basic realm="테스트 인증 시스템"');
    
header('HTTP/1.0 401 Unauthorized');
    echo 
"이 자원에 접근하기 위해서는 유효한 로그인 ID와 패스워드를 입력해야 합니다.\n";
    exit;
}
 
if (!isset(
$_SERVER['PHP_AUTH_USER']) ||
    (
$_POST['SeenBefore'] == && $_POST['OldAuth'] == $_SERVER['PHP_AUTH_USER'])) {
   
authenticate();
} else {
    echo 
"<p>어서오십시오: {$_SERVER['PHP_AUTH_USER']}<br />";
    echo 
"이전: {$_REQUEST['OldAuth']}";
    echo 
"<form action='{$_SERVER['PHP_SELF']}' METHOD='post'>\n";
    echo 
"<input type='hidden' name='SeenBefore' value='1' />\n";
    echo 
"<input type='hidden' name='OldAuth' value='{$_SERVER['PHP_AUTH_USER']}' />\n";
    echo 
"<input type='submit' value='재인증' />\n";
    echo 
"</form></p>\n";
}
?>

이 행동은 HTTP Basic 인증 표준에 필요하지 않기 때문에, 이것에 의존해서는 안됩니다. Lynx로 테스트 했을때, Lynx는 401 서버 응답에 인증 정보를 클리어하지 않기에, 이전의 인증 정보를 그대로 이용해서 자원을 얻으려고 시도합니다. 대신, 사용자가 '_' 키를 누름으로써 인증 정보를 삭제할 수 있습니다.

PHP 4.3.3까지, 마이크로소프트의 IIS 서버를 CGI 버전의 PHP로 사용할 때, IIS의 제약으로 인하여 HTTP 인증은 작동하지 않습니다. PHP 4.3.3 이상에서 작동하게 하려면, IIS 환경 설정 "디렉토리 보안"을 수정해야 합니다. "수정"을 클릭하고, "익명 접근"만을 체크하고, 다른 모든 필드는 체크를 해제하십시오.

IIS 모듈(ISAPI)과 PHP 4를 사용할 때 다른 제약은, PHP_AUTH_* 변수를 사용할 수 없는 대신, HTTP_AUTHORIZATION 변수를 사용하게 됩니다. 즉, 다음의 코드를 고려해야합니다. list($user, $pw) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));

Note: IIS 주의:
IIS에서 HTTP 인증을 작동하게 하려면, PHP 지시어 cgi.rfc2616_headers0(초기값)으로 설정해야 합니다.

Note: 안전 모드에서는 스크립트의 uid가 WWW-Authenticate 헤더의 realm 부분에 추가됩니다.



쿠키

PHP는 HTTP 쿠키를 투명하게 지원합니다. 쿠키는 원격 브라우저에 데이터를 저장하여 다시 온 사용자를 추적하거나 식별하는 메카니즘입니다. setcookie()setrawcookie() 함수를 사용하여 쿠키를 설정할 수 있습니다. 쿠키는 HTTP 헤더의 일부분이기에, setcookie()는 브라우저에 어떠한 출력이 이루어지기 전에 호출해야 합니다. 이는 header()가 가지고 있는 것과 동일한 제약입니다. 출력 버퍼링 함수를 사용하여 쿠키 설정이나 헤더 전송을 결정할때까지 스크립트 출력을 지연할 수 있습니다.

클라이언트에서 보내진 모든 쿠키는 variables_order에 "C"가 있으면 자동적으로 $_COOKIE에 들어갑니다. 하나의 쿠키에 여러 값을 할당하고 싶으면, 쿠키 이름에 []을 붙이면 됩니다.

register_globals에 따라서, 쿠키에서 일반 PHP 변수가 생성됩니다. 그러나 이 기능은 보안 문제로 인하여 꺼 놓는 것을 추천합니다. 오래된 PHP 버전에서는 track_vars 설정 변수가 켜져 있으면, $HTTP_COOKIE_VARS도 생성됩니다. (PHP 4.0.3부터 이 설정은 항상 켜져있습니다)

브라우저 버그에 대한 정보를 포함한 더 자세한 내용은 setcookie()setrawcookie() 함수를 참고하십시오.



세션

PHP의 세션 지원은 지속적으로 이루어지는 접근에 대해 특정한 데이터를 보존하는 방법입니다. 이는 더욱 개별화된 어플리케이션을 작성할 수 있게 하고, 웹 사이트의 인상을 깊게 해 줍니다. 모든 정보는 세션 레퍼런스 섹션에 있습니다.



XForms 다루기

» XForms는 전통적인 웹 폼의 다른 형태를 정의합니다. 보다 많은 플랫폼과 브라우저에서 사용할 수 있고, 심지어 전통적인 매체가 아닌 PDF 문서 등에서도 사용할 수 있습니다.

XForms의 첫번째 차이는 폼이 클라이언트에게 전달되는 방법입니다. » HTML 작성자를 위한 XForms에 XForms를 생성하는 자세한 설명이 있으므로, 여기에서는 간단한 예제만 살펴봅니다.

Example #1 간단한 XForms 검색 폼

<h:html xmlns:h="http://www.w3.org/1999/xhtml"
        xmlns="http://www.w3.org/2002/xforms">
<h:head>
 <h:title>Search</h:title>
 <model>
  <submission action="http://example.com/search"
              method="post" id="s"/>
 </model>
</h:head>
<h:body>
 <h:p>
  <input ref="q"><label>Find</label></input>
  <submit submission="s"><label>Go</label></submit>
 </h:p>
</h:body>
</h:html>

위 폼은 텍스트 입력 상자(이름은 q )와 제출 버튼을 표시합니다. 제출 버튼을 클릭하면, 폼은 action으로 지정한 페이지로 전송됩니다.

여기에서 웹 응용 프로그램 관점에서 차이를 살펴봅시다. 보통의 HTML 폼에서는 데이터가 application/x-www-form-urlencoded로 전송되지만, XForms 세계에서는 XML 형식 데이터로 전송됩니다.

데이터를 XML로 취급한다면 XForms로 작업을 하고 싶을 겁니다. 이 경우, $HTTP_RAW_POST_DATA를 살펴보면 브라우저가 생성한 XML 문서를 찾을 수 있습니다. 그대로 좋아하는 XSLT 엔진이나 문서 해석기로 넘길 수 있습니다.

이러한 형식화에 관심이 없고, 전통적인 $_POST 변수로 데이터를 받고 싶으면, method 속성을 urlencoded-post로 바꿔서 클라이언트 브라우저가 application/x-www-form-urlencoded로 보내게 할 수 있습니다.

Example #2 XForm을 사용하여 $_POST 생성하기

<h:html xmlns:h="http://www.w3.org/1999/xhtml"
        xmlns="http://www.w3.org/2002/xforms">
<h:head>
 <h:title>Search</h:title>
 <model>
  <submission action="http://example.com/search"
              method="urlencoded-post" id="s"/>
 </model>
</h:head>
<h:body>
 <h:p>
  <input ref="q"><label>Find</label></input>
  <submit submission="s"><label>Go</label></submit>
 </h:p>
</h:body>
</h:html>

Note: 이 글을 쓰는 시점에서, 많은 브라우저가 XForms를 지원하지 않습니다. 위 예제가 실패한다면 브라우저 버전을 확인해보십시오.



파일 업로드 다루기

Table of Contents


POST 방식 업로드

이 기능은 사람들이 텍스트와 바이너리 파일을 올릴 수 있게 합니다. PHP의 인증과 파일 조작 함수로, 누군가에게 업로드를 허용하거나, 업로드한 파일에 대한 모든 조작을 할 수 있습니다.

PHP는 RFC-1867 호환 브라우저(넷스케이프 네비게이터 3 이상, 마이크로소프트 인터넷 익스플로러 3+패치나 패치 없이 그 이상 버전을 포함)라면 파일 업로드를 받을 수 있는 능력을 가지고 있습니다.

Note: 관련 환경설정
php.inifile_uploads, upload_max_filesize, upload_tmp_dir, post_max_size, max_input_time 지시어를 참고하십시오.

PHP는 넷스케이프 컴포저와 W3C의 Amaya 클라이언트가 사용하는 PUT 방식 파일 업로드도 지원합니다. 자세한 내용은 PUT 방식 지원을 참고하십시오.

Example #1 파일 업로드 폼

파일 업로드 화면은 다음과 같은 특별한 폼으로 만들어집니다:

<!-- 데이터 인코딩형 enctype은 꼭 아래처럼 설정해야 합니다 -->
<form enctype="multipart/form-data" action="_URL_" method="POST">
    <!-- MAX_FILE_SIZE는 file 입력 필드보다 먼저 나와야 합니다 -->
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    <!-- input의 name은 $_FILES 배열의 name을 결정합니다 -->
    이 파일을 전송합니다: <input name="userfile" type="file" />
    <input type="submit" value="파일 전송" />
</form>

위 예제에서 사용한 __URL__은 PHP 파일을 지정하도록 교체해야 합니다.

숨겨진 MAX_FILE_SIZE(바이트로 측정) 필드는 file 입력 필드보다 먼저 나와야하며, PHP가 받아들이는 최대 파일 크기값을 가집니다. 브라우저에서 이 값을 속이는건 매우 간단하므로, 이 기능으로 이보다 큰 파일이 막힐거라고 생각하지 마십시오. 대신, 최대 크기에 대한 PHP 설정은 속일 수 없습니다. 이 폼 요소는 사용자가 큰 파일이 전송되는걸 기다린 후에서야 파일이 너무 커서 전송에 실패한다는걸 알게 되는걸 방지하기 위해서 사용해야 합니다.

Note: 파일 업로드 폼이 enctype="multipart/form-data"를 가졌는지 확인하십시오. 그렇지 않으면 파일 업로드는 작동하지 않습니다.

전역 $_FILES가 PHP 4.1.0부터 존재합니다. (이전 버전에서는 $HTTP_POST_FILES를 사용하십시오) 이 배열은 업로드된 파일 정보를 가지고 있습니다.

예제 폼에서 $_FILES의 내용은 다음과 같습니다. 위 예제 스크립트에서 사용한 파일 업로드 이름 userfile로 표현함에 주의하십시오. 어떠한 이름이라도 가질 수 있습니다.

$_FILES['userfile']['name']

클라이언트 머신에 존재하는 파일의 원래 이름.

$_FILES['userfile']['type']

브라우저가 이 정보를 제공할 경우에, 파일의 mime 형식. 예를 들면 "image/gif". 그러나 이 mime 형은 PHP 측에서 확인하지 않으므로 이 값을 신용하지 마십시오.

$_FILES['userfile']['size']

업로드된 파일의 바이트로 표현한 크기.

$_FILES['userfile']['tmp_name']

서버에 저장된 업로드된 파일의 임시 파일 이름.

$_FILES['userfile']['error']

파일 업로드에 관련한 에러 코드. PHP 4.2.0에서 추가되었습니다.

php.ini에서 upload_tmp_dir을 이용하여 다른 위치를 지정하지 않는 한, 파일은 서버의 기본 임시 디렉토리에 저장됩니다. 서버의 기본 디렉토리는 PHP를 실행하는 환경의 환경 변수 TMPDIR을 통해서 변경할 수 있습니다. PHP 스크립트 내부에서 putenv()를 통해서 설정하는 것은 작동하지 않습니다. 물론, 이 환경 변수는 업로드된 파일에 다른 작업을 할 때 사용할 수 있습니다.

Example #2 파일 업로드 확인하기

추가 정보는 is_uploaded_file()move_uploaded_file()에 대한 함수 정보를 참고하십시오. 다음 예제는 폼에서 전송된 파일 업로드를 처리합니다.

<?php
// 4.1.0 이전의 PHP에서는, $_FILES 대신에 $HTTP_POST_FILES를
// 사용해야 합니다.

$uploaddir '/var/www/uploads/';
$uploadfile $uploaddir basename($_FILES['userfile']['name']);

echo 
'<pre>';
if (
move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo 
"파일이 유효하고, 성공적으로 업로드 되었습니다.\n";
} else {
    print 
"파일 업로드 공격의 가능성이 있습니다!\n";
}

echo 
'자세한 디버깅 정보입니다:';
print_r($_FILES);

print 
"</pre>";

?>

업로드된 파일을 받는 PHP 스크립트는 업로드된 파일로 무엇을 할 지 결정하는 로직을 포함하고 있어야 합니다. 예를 들면, $_FILES['userfile']['size'] 변수는 너무 작거나 큰 파일을 처리하는데 이용할 수 있습니다. $_FILES['userfile']['type'] 변수는 형식 기준에 맞지 않는 파일을 처리하는데 이용할 수 있습니다. 그러나 이것은 확인 작업 중 하나가 되어야 합니다. 이 값은 완전히 클라이언트에서 만들어지며, PHP 측에서 확인하지 않습니다. PHP 4.2.0부터, $_FILES['userfile']['error']를 이용하여 에러 코드에 따라서 처리하게 할 수 있습니다. 어떠한 로직이건 간에, 임시 디렉토리로부터 파일을 지우거나 다른 곳으로 이동해야 합니다.

폼에서 어떠한 파일도 선택하지 않으면, PHP는 $_FILES['userfile']['size']를 0으로, $_FILES['userfile']['tmp_name']은 없습니다.

요청이 끝날 때, 이동하거나 이름을 변경하지 않은 임시 디렉토리의 파일은 삭제됩니다.

Example #3 파일 배열 업로드하기

PHP는 파일에서도 HTML 배열 기능을 지원합니다.

<form action="" method="post" enctype="multipart/form-data">
<p>그림들:
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="submit" name="전송" />
</p>
</form>
<?php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if (
$error UPLOAD_ERR_OK) {
        
$tmp_name $_FILES["pictures"]["tmp_name"][$key];
        
$name $_FILES["pictures"]["name"][$key];
        
move_uploaded_file($tmp_name"data/$name");
    }
}
?>

apc.rfc1867에 따라서 파일 업로드 진행바를 적용할 수 있습니다.



에러 메세지 설명

PHP 4.2.0부터, PHP는 파일 배열에 적절한 에러 코드를 반환합니다. 에러 코드는 PHP로 파일을 업로드 했을때 만들어지는 파일 배열의 error 세그먼트에서 확인할 수 있습니다. 예를 들면, $_FILES['userfile']['error']에서 확인할 수 있을겁니다.

UPLOAD_ERR_OK

값: 0; 오류 없이 파일 업로드가 성공했습니다.

UPLOAD_ERR_INI_SIZE

값: 1; 업로드한 파일이 php.ini upload_max_filesize 지시어보다 큽니다.

UPLOAD_ERR_FORM_SIZE

값: 2; 업로드한 파일이 HTML 폼에서 지정한 MAX_FILE_SIZE 지시어보다 큽니다.

UPLOAD_ERR_PARTIAL

값: 3; 파일이 일부분만 전송되었습니다.

UPLOAD_ERR_NO_FILE

값: 4; 파일이 전송되지 않았습니다.

UPLOAD_ERR_NO_TMP_DIR

값: 6; 임시 폴더가 없습니다. PHP 4.3.10과 PHP 5.0.3에서 추가.

UPLOAD_ERR_CANT_WRITE

값: 7; 디스크에 파일 쓰기를 실패했습니다. PHP 5.1.0에서 추가.

UPLOAD_ERR_EXTENSION

값: 8; 확장에 의해 파일 업로드가 중지되었습니다. PHP 5.2.0에서 추가.

Note: 이들은 PHP 4.3.0에서 PHP 상수가 되었습니다.



일반적인 문제

MAX_FILE_SIZE는 ini 설정 upload_max_filesize보다 큰 파일 크기를 지정할 수 없습니다. 기본값은 2 메가바이트입니다.

메모리 제한을 활성화하면, 큰 값의 memory_limit가 필요합니다. memory_limit를 충분히 크게 설정했는지 확인하십시오.

max_execution_time을 너무 작게 설정하면, 스크립트 실행 시간이 이 값을 초과합니다. max_execution_time을 충분히 크게 설정했는지 확인하십시오.

Note: max_execution_time은 스크립트 자신의 실행 시간에만 영향을 미칩니다. system(), sleep() 함수 등의 시스템 호출, 데이터베이스 쿼리, 파일 업로드 과정에 걸리는 시간 등 스크립트 외부 실행에 소모하는 시간은 스크립트 최대 실행 시간을 측정할 때 포함하지 않습니다.

Warning

max_input_time은 스크립트가 입력을 받아들이는 최대 시간을 초 단위로 지정합니다; 이는 파일 업로드를 포함합니다. 커다란 파일이나 여러 개의 파일을 전송하거나, 사용자가 느린 회선을 사용한다면 기본값인 60초를 초과할 수 있습니다.

post_max_size을 너무 작게 설정하면, 큰 파일은 업로드할 수 없습니다. post_max_size을 충분히 크게 설정했는지 확인해보십시오.

파일에 대한 검증을 하지 않으면, 사용자가 다른 디렉토리의 중요한 정보에 접근할 수 있습니다.

CERN httpd는 클라이언트에서 보내지는 content-type 마임 헤더 첫번째 공백을 제거합니다. 이 문제로 인해서, CERN httpd는 파일 업로드 기능을 지원하지 않습니다.

많은 양의 디렉토리 목록 형식으로 인해, 확장 형식의 이름(공백을 포함하는 등의)을 가지는 파일을 정상적으로 다룰 수 있는 보장은 없습니다.

하나의 폼 변수에 (입력 이름으로 foo[] 등을 사용하여) 보통의 입력 필드와 파일 업로드 필드를 섞어서는 안됩니다.



복수 파일 전송하기

복수 파일은 input에서 다른 name을 사용해서 업로드 할 수 있습니다.

동시에 복수 파일을 업로드하고 배열로 조직화한 정보를 얻을 수 있습니다. 이를 위해서는, HTML 폼에 복수 선택이나 체크박스와 동일한 방식으로 동일한 이름의 배열형 구문을 갖추면 됩니다:

Example #1 복수 파일 전송하기

<form action="file-upload.php" method="post" enctype="multipart/form-data">
  이 파일들을 전송합니다:<br />
  <input name="userfile[]" type="file" /><br />
  <input name="userfile[]" type="file" /><br />
  <input type="submit" value="파일 전송" />
</form>

위 폼을 전송하면, 배열 $_FILES['userfile'], $_FILES['userfile']['name'], $_FILES['userfile']['size']가 초기화됩니다. (버전 4.1.0 이전에는 $HTTP_POST_FILES) register_globals가 on이라면, 전송된 파일들에 대한 전역 변수도 초기화됩니다. 이 각각에 대해서 전송된 파일에 따른 숫자로 정렬된 배열을 가지게 됩니다.

예를 들어, /home/test/review.html/home/test/xwp.out가 전송되었다고 합시다. 이 경우에, $_FILES['userfile']['name'][0]의 값은 review.html이고, $_FILES['userfile']['name'][1]의 값은 xwp.out가 됩니다. 마찬가지로, $_FILES['userfile']['size'][0]review.html의 크기를 가지게 되며, 나머지도 마찬가지입니다.

$_FILES['userfile']['name'][0], $_FILES['userfile']['tmp_name'][0], $_FILES['userfile']['size'][0], $_FILES['userfile']['type'][0]이 설정됩니다.



PUT 방식 지원

PHP는 몇몇 클라이언트에서 서버에 파일을 저장하기 위해서 사용하는 HTTP PUT 방식을 지원합니다. PUT 요청은 POST 요청을 이용한 파일 업로드보다 단순하며, 다음과 같은 식으로 이루어집니다:

PUT /path/filename.html HTTP/1.1

일반적으로 원격 클라이언트가 웹 트리의 /path/filename.html에 내용을 저장하는걸 의미합니다. 아파치나 PHP가 웹 트리의 모든 파일에 누구나 자동적으로 덮어쓰게 하는 것은 좋은 생각이 아닙니다. 그래서, 웹 서버에 이러한 요청이 들어왔을때, PHP 스크립트를 통해서 다루도록 할 수 있습니다. 아파치에서는 Script 지시어를 통해 지정할 수 있습니다. 아파치 환경 설정 파일의 거의 모든 곳에서 지정할 수 있습니다. 일반적으로는 <Directory> 블록이나 <VirtualHost> 블록의 내부에 위치하게 됩니다. 다음 줄을 추가하면 됩니다:

Script PUT /put.php

이는 아파치가 이 줄이 들어가 있는 URI에 해당하는 모든 PUT 요청을 put.php 스크립트에 전달하게 합니다. 물론, .php 확장자에 대해 PHP를 사용할 수 있어야 합니다. 이 스크립트로 전해지는 모든 PUT 요청은 스크립트 자신이여야 하며, 업로드된 파일 이름이 존재해서는 안됩니다.

PHP로 put.php 안에 다음과 같은 일을 할 수 있습니다. 여기서는 업로드한 파일의 내용을 서버의 myputfile.ext으로 복사합니다. 이 파일 복사 전에 몇가지 확인을 하거나 사용자 인증을 할 수도 있습니다.

Example #1 HTTP PUT 파일 저장하기

<?php
/* PUT 데이터는 stdin 스트림으로 옵니다 */
$putdata fopen("php://input""r");

/* 파일 쓰기를 위해 열기 */
$fp fopen("myputfile.ext""w");

/* 한번에 1KB씩 읽어서 파일로 쓰기 */
while ($data fread($putdata1024))
  
fwrite($fp$data);

/* 스트림 닫기 */
fclose($fp);
fclose($putdata);
?>




원격 파일 사용하기

php.ini에서 allow_url_fopen 을 활성화하면, 대부분의 함수에서 파일명 인수로 HTTPFTP URL을 사용할 수 있습니다. 이와 더불어 URL을 include(), include_once(), require(), require_once() 구문에서 사용할수 있다. (PHP 5.2.0부터, 이 기능을 사용하려면 allow_url_include를 활성화해야 합니다) PHP가 지원하는 프로토콜에 대한 정보는 지원 프로토콜/래퍼 목록를 참고하십시오.

Note: PHP 4.0.3 이하에서 URL 래퍼(wrapper)를 사용하기 위해서는 configure 옵션으로 --enable-url-fopen-wrapper을 명시할 필요가 있다.

Note: PHP 4.3 이하 버전의 PHP 윈도우 버전은 다음 함수에서 원격 파일 접근을 지원하지 않는다: include(), include_once(), require(), require_once(), 그리고 GD and Image 함수 목록 내의 imagecreatefromXXX 함수.

예를 들어, 이 기능을 사용하여 원격 웹 서버가 출력하는 내용을 파일로 열고, 그 출력 내용에서 원하는 데이타를 분석하여, 이 원하는 데이타로 데이타베이스 질의에 사용하거나, 웹 사이트에 맞는 모양으로 변형 시켜 출력할 수 있다

Example #1 원격 페이지의 제목을 가져오기

<?php
$file 
fopen ("http://www.php.net/""r");
if (!
$file) {
    echo 
"<p>Unable to open remote file.\n";
    exit;
}
while (!
feof ($file)) {
    
$line fgets ($file1024);
    
/* This only works if the title and its tags are on one line */
    
if (preg_match ("@\<title\>(.*)\</title\>@i"$line$out)) {
        
$title $out[1];
        break;
    }
}
fclose($file);
?>

해당 서버에 권한이 있는 사용자로 접속할수 있다면 FTP를 이용해 파일에 작성할 수도 있다. 이 방법으로 새로운 파일만 생성할수 있다. 기존의 파일을 덮어쓰려고 하면, fopen() 호출시에 실패하게 될것이다.

'anonymous'가 아닌 사용자로 접속하려면, URL내에 username을 (필요하다면 password도) 다음과 같이 명시해야 한다 : 'ftp://user:password@ftp.example.com/path/to/file'. (또한 HTTP에서 Basic authentication을 사용한 인증을 요구하는 경우에도 이와 같은 문법을 사용할 수 있다.)

Example #2 원격 서버에 데이터 저장하기

<?php
$file 
fopen ("ftp://ftp.php.net/incoming/outputfile""w");
if (!
$file) {
    echo 
"<p>원격 파일을 쓰도록 열 수 없습니다.\n";
    exit;
}
/* 여기에서 데이터를 씁니다. */
fwrite ($file"$HTTP_USER_AGENT\n");
fclose ($file);
?>

Note: 위의 예제를 보고, 이 테크닉을 사용하여 remote log를 작성할 수 있겠다고 생각할 수도 있다. 그러나 불행하게도 원격 파일이 이미 존재하면 fopen() 호출은 실패할것이기 때문에 동작하지 않을것이다. 그와 같은 분산 log를 수행하려면 syslog()를 참고하도록 한다.



접속 다루기

PHP는 내부적으로 접속 상태를 관리합니다. 3가지 상태가 존재합니다:

  • 0 - NORMAL
  • 1 - ABORTED
  • 2 - TIMEOUT

PHP 스크립트가 정상적으로 작동하고 있으면, NORMAL 상태가 활성화됩니다. 원격 클라이언트가 접속을 끊으면 ABORTED 상태 플래그가 켜집니다. 원격 클라이언트의 접속 차단은 보통 사용자가 중지 버튼을 누르는 경우입니다. PHP 내장 시간 제한(set_time_limit())에 걸리면, TIMEOUT 상태 플래그가 켜집니다.

클라이언트 접속 차단으로 인해 스크립트를 중단할 지 여부를 결정할 수 있습니다. 때때로 원격 브라우저가 출력을 받아들이지 않더라도 스크립트가 동작을 마쳐야 할 수 있습니다. 기본 동작은 원격 클라이언트 접속 차단 시에 스크립트를 중단합니다. 이 동작은 php.ini에서 ignore_user_abort 지시어나, , 아파치 .conf php_value ignore_user_abort 지시어, ignore_user_abort() 함수로 설정할 수 있습니다. PHP에 사용자 중단을 무시하도록 하지 않고 사용자가 중단하면, 스크립트는 종료됩니다. 한가지 예외는 register_shutdown_function()을 사용하여 종료 함수를 등록했을 경우입니다. 종료 함수가 있으면 사용자가 중단 버튼을 눌렀을 때, 스크립트에서 무언가를 출력하려 해서 PHP가 접속이 중단되었음을 알게 되었을 경우 종료 함수가 호출됩니다. 이 종료 함수는 정상적으로 스크립트 마지막에 종료될 때도 호출되므로, 클라이언트 접속 차단시 다른 동작을 하려면 connection_aborted() 함수를 이용할 수 있습니다. 이 함수는 접속이 취소되었을 때 TRUE를 반환합니다.

스크립트는 내장 스크립트 타이머에 의해 종료될 수도 있습니다. 기본 시간 제한은 30초입니다. 이는 php.ini max_execution_time 지시어나, 아파치 .conf php_value max_execution_time 지시어, set_time_limit() 함수로 바꿀 수 있습니다. 타이머가 초과되면 스크립트는 중단되고, 위의 클라이언트 접속 차단의 경우와 마찬가지로 종료함수가 있으면 호출됩니다. 종료 함수에서 connection_status() 함수를 호출하여 시간 초과가 종료 함수 호출을 유발하였는지 확인할 수 있습니다. 이 함수는 시간 초과가 원인으로 종료 함수를 호출하였을 때 2를 반환합니다.

ABORTED와 TIMEOUT 상태가 동시에 일어날 수 있는 점에 주의해야 합니다. 이는 PHP에 사용자 중단을 무시하도록 했을 때 일어날 수 있습니다. PHP는 사용자가 접속을 끊었음을 기록하지만, 스크립트는 계속 실행됩니다. 그리고 시간 제한에 도달하여 취소되면 종료 함수가 존재할 경우 호출됩니다. 이 경우 connection_status()가 3을 반환합니다.



지속적인 데이터베이스 접속

지속적인 접속은 스크립트 수행이 종료되어도 연결을 끊지 않는 접속을 말한다. 지속적인 접속이 요청되면, PHP는 기존의 (이전에 열어 두었던) 동일한(identical) 지속적인 접속이 있는지 검사한다. 만약 있다면 기존의 것을 사용하고, 없다면 새로운 연결을 생성한다. '동일한' 접속이란 같은 호스트에 같은 사용자명과 같은 암호를 사용하여 열린 접속을 말한다.

가끔 웹서버의 작동과 작업의 할당에 대해 잘 알고 있지 못하는 사람들은 지속적인 접속이 사실은 별 것 아니라고 오해하기도 한다. 특히, 지속적인 접속이 동일한 연결에서 'user sessions'를 여는데 별 나을 것도 없다라던가, transaction을 효율적으로 처리하는 것도 아니다라던가, 혹은 다른 어떤 특별한 것을 하는 것도 아니라고 한다. 사실, 이런 말들에 대해 명백히 말하자면, 지속적인 접속은 비지속적인 접속에 비해 어떠한 기능적인 향상도 주지 못한다.

왜?

이것은 웹서버의 동작 방식에 따라 다른 효과를 낸다. 여러분의 웹서버가 웹 페이지를 만들기위해 PHP를 이용하는데는 3가지 방법이 있다.

첫 번째 방법은 PHP를 CGI "래퍼(wrapper)"의 형태로 사용하는 것이다. 이 방법의 경우, 웹서버에 매 PHP 페이지가 요구될 때 마다, PHP 인터프리터의 실행이 만들어지고 사리진다. 따라서 매 요구가 종료될 때마다 인터프리터의 실행이 종료되므로, 실행 중 만들었던(SQL 연결를 포함) 모든 자원은 실행 종료와 함께 해제된다. 이 경우 지속적인 접속을 사용하여 어떤 이득도 얻을 수 없다. 다르게 말하면 이 경우는 지속적인 접속을 해도 지속적이지 않다.

두 번째 방법은 가장 대중적인 방법인데, PHP를 다중프로세스 웹서버의 모듈로 사용하는 것이다. (현재는 아파치가 유일하다) 다중프로세스 서버는 보통 한 개의 부모 프로세스와, 이와 유기적으로 연결되어 웹 페이지를 실제로 만드는 작업을 하는 여러개의 자식 프로세스들을 가지고 있다. 클라이언트에서 요청이 왔을 때, 다른 클라이언트를 처리하고 있지 않은 자식 프로레스로 넘겨집니다. 이는 동일한 클라이언트가 서버에 두번째 요청을 하였을 때, 처음과 다른 자식 프로세스에서 처리할 수 있다는 의미입니다. 지속적인 접속을 열면, SQL 서비스를 요구하는 모든 페이지에서 동일한 SQL 서버 접속을 재사용할 수 있습니다.

마지막 방법은 PHP를 멀티쓰레드 웹서버의 플러그인 형태로 작동시키는 것이다. 현재 PHP4는 윈도우 환경에서 ISAPI 혹은 WSAPI, NSAPI의 방법을 사용하여 Netscape FastTrack, Microsoft's Internet Information Server (IIS), O'Reilly's WebSite Pro 등의 멀티쓰레드 웹서버에서 플러그인으로 동작한다. 이 동작은 앞에서 설명한 다중프로세스 모델과 동일합니다.

지속적인 접속이 실제로 어떠한 기능적인 향상도 주지 못한다면, 이것을 사용해 어떤 이점이 있나요?

이것에 대한 간단한 답은 효율성이다. 지속적인 접속은 SQL 서버와의 연결을 만드는 것에 따른 overhead가 클 경우에 유용하다. 이 overhead는 많은 요인에 따라 커지기도 하고 작아지기도 한다. 어떤 종류의 데이터베이스인가? 웹서버와 같은 컴퓨터에 데이터베이스 서버가 있는가? SQL 서버가 어떻게 사용되고 있는가? 등에 따라 크게 달라진다. 접속에 따른 overhead가 클 경우에 지속적인 접속은 적지 않은 도움을 줄 것이다. 이것은 자식 process에서 SQL 서버에 접속을 요청할 때 마다 접속을 만드는 대신, 이 프로세스가 종료될 때 까지 살아있는 한 개의 접속 만을 사용한다. 이것은 모든 지속적인 접속을 사용한 프로세스는, 그에 해당하는 한 개의 지속적인 접속을 가지고 있다는 것을 의미한다. 예를 들어 SQL 서버에 대하여 지속적인 접속을 사용하는 스크립트를 실행하였던 20개의 다른 자식 프로세스가 있다면, 아마도 각각의 자식 프로세스에 대해 1개씩, 20개의 SQL 접속이 있을 것이다.

이 방법은 지속적인 접속의 개수가 데이타베이스 서버가 허용하는 접속수를 초과해서 설정되어 있는 경우 문제가 될 수 있다. 만약 데이타베이스가 16개의 동시 접속을 허용하고, 이 서버 세션들이 모두 사용중이면, 17번째 thread는 연결을 시도하다가 실패할 것이다. 만약 여러분이 만든 스크립트에 이런 경우에 대비한 특별한 대책이 없이 재시도를 반복하다보면 가능한 모든 connection을 사용하여 복구할 수 없게 된다. 이런 abandoned 혹은 idle connection을 다루는 자세한 설명은 데이타베이스 문서를 참조하기 바란다.

Warning

지속적인 접속을 사용할때 두가지 추가적인 경고를 염두에 두고 있어야 한다 한가지는 지속적인 접속에서 테이블 락킹(locking)을 사용할때이다. 스크립트가 어떤 이유로 락을 풀수 없을때, 같은 접속을 사용하는 다음 스크립트는 무한정 block될것이고 이 경우에는 httpd 서버나 데이터베이스 서버를 재시작시켜야 할수도 있다. 다른 한가지는 트랜잭션을 사용할때이다. 트랜잭션 블록은 그 트랜잭션 블록이 수행되기 전에 스크립트가 수행을 종료하면 그 접속을 사용하는 다음 스크립트에 이월하게 된다. 각각의 경우에, register_shutdown_function()을 사용하여 테이블 unlock하거나 트랜잭션을 롤백하는 해제 함수를 등록 할수 있다. 이런 문제를 완전히 회피하기 위한 더 좋은 방법은 지속적인 접속을 사용하는 스크립트에서 테이블 락이나 트랜젝션을 사용하지 않는 것이다 (어느 곳에서는 그것을 사용할수 있다)

중요한 언급 한가지! 지속적인 접속은 일반적인 접속에 일대일로 대응되도록 설계되었다. 이것은 스크립트의 다른 부분은 그대로 두고, 언제라도 비지속적인 접속을 지속적인 접속으로 대치할 수 있다는 것을 의미한다. 이기능으로 아마도 스크립트의 동작이 아니라 효율을 향상시킬 수도 있을 것이다.

fbsql_pconnect(), ibase_pconnect(), ifx_pconnect(), ingres_pconnect(), msql_pconnect(), mssql_pconnect(), mysql_pconnect(), ociplogon(), odbc_pconnect(), oci_pconnect(), pfsockopen(), pg_pconnect(), sybase_pconnect() 참고.



안전 모드

Table of Contents

PHP 안전 모드는 공유-서버 보안 문제를 풀려는 시도이다. 이 문제를 PHP 수준에서 풀려고 하는것은 구조적으로 올바르지 않다. 그러나 웹서버와 OS 수준에서의 차선책이 아주 현실적이지는 않기 때문에, 많은 사람, 특히 ISP, 들이 현재 안전 모드를 사용한다.

Warning

안전 모드는 PHP 6.0.0에서 제거되었습니다.


보안과 안전 모드

보안과 안전 모드 설정 지시어
지시어명 기본값 변경값 변경점
safe_mode "0" PHP_INI_SYSTEM PHP 6.0.0에서 제거.
safe_mode_gid "0" PHP_INI_SYSTEM PHP 4.1.0부터 존재. PHP 6.0.0에서 제거.
safe_mode_include_dir NULL PHP_INI_SYSTEM PHP 4.1.0부터 존재. PHP 6.0.0에서 제거.
safe_mode_exec_dir "" PHP_INI_SYSTEM PHP 6.0.0에서 제거.
safe_mode_allowed_env_vars "PHP_" PHP_INI_SYSTEM PHP 6.0.0에서 제거.
safe_mode_protected_env_vars "LD_LIBRARY_PATH" PHP_INI_SYSTEM PHP 6.0.0에서 제거.
open_basedir NULL PHP_INI_ALL PHP < 5.3.0에서 PHP_INI_SYSTEM
disable_functions "" php.ini PHP 4.0.1부터 존재.
disable_classes "" php.ini PHP 4.3.2부터 존재.

PHP_INI_* 모드에 대한 상세와 정의는 환경 설정을 바꿀 수 있는 곳를 참고하십시오.

위 설정 지시어에 대한 간단한 설명입니다.

safe_mode boolean

PHP의 안전 모드 활성화 여부. PHP가 --enable-safe-mode로 컴파일 되면 기본값 On, 아니면 Off.

safe_mode_gid boolean

기본값, 안전 모드는 파일이 열릴 때 UID 비교 검사를 수행한다. 이 설정을 GID 비교로 완화하려면, safe_mode_gid을 켜도록 한다. 파일 접근에 대해 UID (FALSE) 검사를 하는지, GID (TRUE) 검사를 하는지의 여부.

safe_mode_include_dir string

이 디렉토리와 하위디렉토리에서 파일을 include할 때에는 UID/GID 검사가 무시된다 (디렉토리는 include_path나 include되는 전체 경로가 되어야 한다).

PHP 4.2.0부터 이 지시어는 include_path 지시어와 같은 방식으로, 콜론(윈도우에서는 세미콜론)으로 구분하여 복수의 경로를 가질 수 있습니다. 설정 제한은 실질적으로 디렉토리명이 아닌 앞첨자(prefix)가 된다. 이말의 의미는 "safe_mode_include_dir = /dir/incl"는 "/dir/include"와 "/dir/incls"가 존재하기만 한다면 그 디렉토리도 접근이 허용된 다는 것이다. 특정 디렉토리만으로 접근을 제한하고자 하면, 슬래시로 끝내면 된다. 예를 들면: "safe_mode_include_dir = /dir/incl/" 이 지시어 값이 비어 있으면, PHP 4.2.3과 PHP 4.3.3부터 다른 UID/GID 값을 가지는 파일을 포함할 수 없습니다. 이 이전 버전에서는 모든 파일을 포함할 수 있었습니다.
safe_mode_exec_dir string

PHP가 안전 모드를 사용중이라면, system()과 그 외의 시스템 프로그램을 실행하는 함수는 이 디렉토리에 있지 않으면 프로그램 시작이 거부된다. 윈도우를 포함한 모든 환경에서 디렉토리 구분은 /를 이용해야 합니다.

safe_mode_allowed_env_vars string

특정 환경 변수를 설정하는것은 잠재적인 보안 구멍이 될수 있다. 이 지시어는 콤마-구분자 리스트의 앞첨자(prefix)를 포함한다. 안전 모드에서, 유저는 여기서 제공되는 앞첨자로 시작하는 이름을 갖는 환경변수만 변경할수 있을것이다. 기본값으로, 유저는 PHP_로 시작하는 환경 변수만 설정할수 있다. (e.g. PHP_FOO=BAR).

Note: 이 지시어가 비어있으면, PHP는 유저가 모든 환경 변수를 변경할수 없게 할것이다!

safe_mode_protected_env_vars string

이 지시어는 엔드 유저가 putenv()를 사용하여 변경할수 없는 콤마-구분자 리스트의 환경 변수를 포함한다. 이 변수들은 safe_mode_allowed_env_vars가 그들을 변경할수 있도록 설정되어있을지라도 보호될것이다.

open_basedir string

PHP가 열수 있는 파일을 특정 디렉토리-트리로 제한한다. 이 지시어는 안전 모드가 켜졌는지 꺼졌는지와는 상관이 없다.

스크립트가 예를 들면, fopen() 이나 gzopen()으로 파일을 열려고 시도할때, 파일의 위치를 검사한다. 파일이 설정된 디렉토리-트리의 밖에 있다면, PHP는 그 파일을 여는것을 거부할것이다. 모든 심볼릭 링크가 검사되기 때문에, symlink로 이 제한을 회피할수 없다. 파일이 존재하지 않아서 symlink로 풀어낼 수 없으면 파일 이름을 (풀어낸) open_basedir 와 비교합니다.

특수한 값 . 은 스크립트가 작업하는 디렉토리를 기본 디렉토리로 사용합니다. 이는 스크립트의 작업 디렉토리가 chdir()을 통해 쉽게 바뀔 수 있기 때문에 조금 위험합니다.

httpd.conf에서, 다른 지시어와 같은 방식으로 "php_admin_value open_basedir none"을 사용해서 open_basedir을 끌 수 있습니다. (특정 가상 호스트를 위해 사용할 수 있습니다)

윈도우에서는 세미콜론으로 디렉토리를 구분한다. 그외 모든 시스템은, 콜론으로 디렉토리를 구분한다. 아파치 모듈에서, 부모 디렉토리부터의 open_basedir 경로는 현재 자동적으로 상속된다.

open_basedir로 설정된 제한은 실질적으로 디렉토리명이 아닌, 앞첨자(prefix)가 된다. 이 말의 의미는 "open_basedir = /dir/incl"는 "/dir/include" 과 "/dir/incls" 디렉토리가 존재한다면 그 두 디렉토리로의 접근도 허용한다는것이다. 특정 디렉토리로만 접근을 제한하고자 한다면, 슬래시로 끝내면 된다. For example: "open_basedir = /dir/incl/"

기본값은 모든 파일이 열릴수 있도록 허용되어 있다.

Note: PHP 5.3.0부터 open_basedir을 실행시에 강화할 수 있습니다. 즉, open_basedir이 php.ini에서 /www/로 설정되어 있다면, 스크립트 실행시에 ini_set()으로 /www/tmp/로 설정을 강화할 수 있습니다.

disable_functions string
이 지시어는 보안 때문에 특정 함수를 비활성화시켜준다. 컴마로 구분된 함수명의 리스트를 취한다. disable_functions는 안전 모드에 의해 영향을 받지 않는다. 이 지시어는 php.ini에서 설정되어야 한다. 예를 들면, 이 값을 httpd.conf에서 설정할수 없다.
disable_classes string
이 지시어는 보안적인 측면때문에 특정 클래스를 비활성화시켜준다. 컴마로 구분된 클래스명의 리스트를 취한다. disable_classes는 안전 모드에 의해 영향을 받지 않는다. 이 지시어는 php.ini에서 설정되어야 한다. 예를 들면, 이 값을 httpd.conf에서 설정할수 없다.

Note: Availability note
이 지시어는 PHP 4.3.2부터 사용가능하게 되었다.

참고: register_globals, display_errors, log_errors.

safe_mode가 켜져 있으면, PHP는 현재 스크립트의 소유자(owner)가 파일 함수에 의해 제어되는 파일의 소유자(owner)나 그 디렉토리와 일치하는지 검사한다. 예를 들면:

-rw-rw-r--    1 rasmus   rasmus       33 Jul  1 19:20 script.php 
-rw-r--r--    1 root     root       1116 May 26 18:01 /etc/passwd

script.php를 실행:

<?php
 readfile
('/etc/passwd'); 
?>

안전 모드가 활성화되어 있으면 다음 에러가 보여진다.

Warning: SAFE MODE Restriction in effect. The script whose uid is 500 is not 
allowed to access /etc/passwd owned by uid 0 in /docroot/script.php on line 2

엄격한 UID 검사가 적절하지 않고, 완화된 GID 검사가 효율적인 환경일수 있다. 이런 경우는 safe_mode_gid 스위치 방식으로 지원된다. On으로 설정하면 완화된 GID 검사가 수행되고, Off (기본값)로 설정되면 UID 검사가 수행된다.

safe_mode 대신에, open_basedir 디렉토리를 설정하면, 모든 파일 제어가 특정 디렉토리 밑의 파일로만 제한됩니다. 예를 들면(아파치 httpd.conf 예):

<Directory /docroot>
  php_admin_value open_basedir /docroot 
</Directory>

open_basedir 설정으로 동일한 script.php를 실행하면 결과는 다음과 같다:

Warning: open_basedir restriction in effect. File is in wrong directory in 
/docroot/script.php on line 2 

또한 각각의 함수들을 비활성화시킬수 있다. disable_functions 지시어는 php.ini 파일 밖에서 사용될수 없다. 그래서 httpd.conf 파일의 per-virtualhost 나 per-directory 기반의 함수를 비활성화시킬수 없다. 이 지시어를 php.ini에 추가하면:

disable_functions = readfile,system

다음의 결과가 나온다:

Warning: readfile() has been disabled for security reasons in 
/docroot/script.php on line 2 

Warning

물론, 이러한 PHP 제한은 실행 중인 바이너리에선 유효하지 않습니다.



안전 모드에 의해 제한되는/비활성화되는 함수들

다음은 아직 완전하지 않고 부정확할 수도 있는 안전 모드에 의해 제한되는 함수 목록이다.

안전 모드 제한 함수들
함수 제한점
dbmopen() 작업하려는 파일이나 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다.
dbase_open() 작업하려는 파일이나 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다.
filepro() 작업하려는 파일이나 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다.
filepro_rowcount() 작업하려는 파일이나 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다.
filepro_retrieve() 작업하려는 파일이나 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다.
ifx_* sql_safe_mode 제한, (!= safe mode)
ingres_* sql_safe_mode 제한, (!= safe mode)
mysql_* sql_safe_mode 제한, (!= safe mode)
pg_lo_import() 작업하려는 파일이나 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다.
posix_mkfifo() 작업하려는 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다.
putenv() safe_mode_protected_env_vars 와 safe_mode_allowed_env_vars ini-지시어에 따름. putenv() 문서 참고.
move_uploaded_file() 작업하려는 파일이나 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다.
chdir() 작업하려는 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다.
dl() 이 함수는 PHP가 안전 모드일 때는 사용할 수 없습니다.
backtick operator 이 함수는 PHP가 안전 모드일 때는 사용할 수 없습니다.
shell_exec() (functional equivalent of backticks) 이 함수는 PHP가 안전 모드일 때는 사용할 수 없습니다.
exec() safe_mode_exec_dir안의 실행파일만 실행할수 있다. 실무적인 이유로 현재는 실행파일에 대한 경로에 ..을 허용하지 않는다. 이 함수의 인수에는 escapeshellcmd()를 실행합니다.
system() safe_mode_exec_dir안의 실행파일만 실행할수 있다. 실무적인 이유로 현재는 실행파일에 대한 경로에 ..을 허용하지 않는다. 이 함수의 인수에는 escapeshellcmd()를 실행합니다.
passthru() safe_mode_exec_dir안의 실행파일만 실행할수 있다. 실무적인 이유로 현재는 실행파일에 대한 경로에 ..을 허용하지 않는다. 이 함수의 인수에는 escapeshellcmd()를 실행합니다.
popen() safe_mode_exec_dir안의 실행파일만 실행할수 있다. 실무적인 이유로 현재는 실행파일에 대한 경로에 ..을 허용하지 않는다. 이 함수의 인수에는 escapeshellcmd()를 실행합니다.
fopen() 작업하려는 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다.
mkdir() 작업하려는 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다.
rmdir() 작업하려는 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다.
rename() 작업하려는 파일이나 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다. 작업하려는 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다.
unlink() 작업하려는 파일이나 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다. 작업하려는 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다.
copy() 작업하려는 파일이나 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다. 작업하려는 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다. (sourcetarget 에서)
chgrp() 작업하려는 파일이나 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다.
chown() 작업하려는 파일이나 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다.
chmod() 작업하려는 파일이나 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다. 추가적으로, SUID, SGID와 sticky 비트를 설정할수 없다
touch() 작업하려는 파일이나 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다. 작업하려는 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다.
symlink() 작업하려는 파일이나 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다. 작업하려는 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다. (주의: 타겟만 검사됨)
link() 작업하려는 파일이나 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다. 작업하려는 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다. (주의: 타겟만 검사됨)
apache_request_headers() 안전 모드에서, 'authorization' (대소문자 구별안함)로 시작하는 헤더를 반환하지 않습니다.
header() 안전 모드에서, WWW-Authenticate(HTTP 인증에서 사용됨)를 설정하면, 이 헤더의 realm부분에 스크립트의 uid가 추가된다.
PHP_AUTH variables 안전 모드에서는, 변수 PHP_AUTH_USER와, PHP_AUTH_PW, AUTH_TYPE$_SERVER 안에서 사용될수 없다. 그와 상관 없이, USER에 대해서 REMOTE_USER을 사용할수 있다 (주의: PHP 4.3.0 이후에서만 적용됨)
highlight_file(), show_source() 작업하려는 파일이나 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다. 작업하려는 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다. (주의: PHP 4.2.1 이후에서만 적용됨)
parse_ini_file() 작업하려는 파일이나 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다. 작업하려는 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다. (note: PHP 4.2.1 이후에서만 적용됨)
set_time_limit() PHP가 안전 모드에서 실행되면 아무 효과가 없음.
max_execution_time PHP가 안전 모드에서 실행되면 아무 효과가 없음.
mail() 안전 모드에서, 다섯번째 인수는 사용할 수 없습니다. (주의: PHP 4.2.3부터 적용)
session_start() 기본값인 files session.save_handler를 사용할 때 스트립트 소유자는 session.save_path 디렉토리 소유자와 같아야 합니다.
모든 파일시스템과 스트림 함수. 작업하려는 파일이나 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다. 작업하려는 디렉토리가 실행 중인 스크립트와 같은 UID (owner)를 가지고 있는지 확인합니다. (safe_mode_include_dir php.ini 옵션 참고)




명령줄에서 PHP 사용하기

버전 4.3.0부터 PHP는 Command Line Interface를 의미하는 CLI라는 이름의 새로운 SAPI(Server Application Programming Interface) 형식을 지원한다. 이 SAPI는 이름에서 내포하듯이, 핵심 용도는 셀(또는 데스크탑) 응용프로그램을 PHP로 개발하는것에 맞춰져있다. 이 장에서 설명하는 CLI SAPISAPI사이에는 많은 차이가 있다. CLICGI는 많은 부분에 있어서 같은 동작을 하지만, 서로 다른 SAPI들이라는 것이다.

CLI SAPI는 PHP 4.2.0에서 처음으로 릴리즈되었다. 그러나 아직 실험적이었고 ./configure를 실행할때 --enable-cli을 명시해 주어야 했다. PHP 4.3.0부터 CLI SAPI는 더이상 실험적이지 않고 기본값으로 --enable-cli가 활성화되어있다. 그리고 --disable-cli로 비활성화시킬수 있다.

PHP 4.3.0부터, CLI/CGI 바이너리의 이름과 위치, 존재여부는 PHP가 시스템에 어떻게 설치되느냐에 따라 달라질 것이다. 기본값으로 make를 수행할때, CGI와 CLI 모두 빌드되고 각각 sapi/cgi/phpsapi/cli/php에 위치하게 된다. 둘 다 php라는 이름이 붙는다는것에 주의해야 할것이다. configure 줄에 따라 make install 시에 무슨일이 일어날까. configure 시에 모듈로 SAPI를 선택했다면, 즉 apxs를 사용하거나, 또는 --disable-cgi 옵션을 사용하면 CLI는 make install시에 {PREFIX}/bin/php에 복사된다. 예를 들면, --with-apxs가 configure 줄에 포함되면 make install시에 CLI는 {PREFIX}/bin/php에 복사된다. CGI 바이너리 설치를 오버라이드하고 싶다면 make install 이후에 make install-cli를 사용한다. 차선책으로 configure 줄에 --disable-cgi를 설정할수 있다.

Note: --enable-cli--enable-cgi는 모두 기본값으로 켜져 있기 때문에, 단순히 configure줄에 --enable-cli를 넣는것이 make install시에 {PREFIX}/bin/php에 CLI를 복사할것이라는 것을 의미하지 않는다.

PHP 4.2.0 과 PHP 4.2.3 사이의 윈도우 패키지는 CLI를 php-cli.exe로 제공한다. CGI인 php.exe와 같은 폴더에 존재한다. PHP 4.3.0부터 윈도우 패키지 배포판은 CLI를 별개의 폴더 cliphp.exe를 놓으므로, cli/php.exe가 됩니다. PHP 5부터, CLI는 메인 폴더에 php.exe로 배포됩니다. CGI 버전은 php-cgi.exe로 배포됩니다.

PHP 5부터, 새로운 php-win.exe 파일이 배포됩니다. 이는 CLI 버전과 동일하지만, php-win은 아무것도 출력하지 않으므로, 콘솔을 제공하지 않습니다. (화면에 "도스 박스"가 나타나지 않습니다) 이 동작은 php-gtk와 비슷합니다. --enable-cli-win32로 configure해야 합니다.

Note: 현재 사용중인 SAPI는 무엇인가?
셀에서, php -v를 쳐넣으면 php가 CGI인지 CLI인지 알수 있을것이다. php_sapi_name()과 상수PHP_SAPI도 참고.

Note: PHP 4.3.2에서 유닉스 manual 페이지가 추가되었다. 셀 환경에서 man php를 침으로써 이 페이지를 볼수 있을것이다.

다른 SAPI와 비교한 CLI SAPI의 현저한 차이점:

  • CGI SAPI와는 달리, 출력에 헤더를 쓰지 않는다.

    CGI SAPI가 HTTP 헤더를 제거하는 방법을 제공하지만, CLI SAPI에서는 헤더를 활성화시킬수 있는 스위치가 존재하지 않는다.

    CLI는 기본적으로 정숙 모드로 시작된다. 그러나 구버전의 CGI 스크립트와의 호환성을 위해 -q 스위치를 유지하고 있다.

    작업 디렉토리가 스크립트의 디렉토리로 변경되지 않는다 (-C--no-chdir 스위치는 호환성을 유지됩니다)

    일반 텍스트 에러 메시지 (HTML 포맷이 아님)

  • 셀 환경에 맞지 않는 것들 때문에 CLI SAPI에 의해 오버로드되는 php.ini 지시어가 몇가지 존재한다.

    php.ini 지시어 오버로드
    지시어 CLI SAPI 기본값 주석
    html_errors FALSE 셀에서 에러메시지를 읽을때 의미없는 HTML태그로 뒤범벅이 되면 에러메시지를 읽기가 매우 어려울수 있다. 따라서 이 지시어의 기본값은 FALSE다.
    implicit_flush TRUE print(), echo() 와 비슷한 함수들의 출력은 모두 즉시 출력으로 쓰기 되고 버퍼에 캐시되지 않는다. 표준 출력을 지연시키거나 조작하고 싶다면 output buffering을 사용할수도 있다.
    max_execution_time 0 (무제한) 셀 환경에서 PHP를 무한하게 사용할 가능성때문에, 최대 실행 시간은 무제한으로 설정된다. 웹 응용프로그램은 대부분 매우 빨리 실행이 끝나는 반면에 셀 응용프로그램은 더 많은 시간이 필요한 경우가 많다.
    register_argc_argv TRUE

    이 설정은 TRUE이기 때문에 CLI SAPI에서는 항상 argc (응용프로그램에 전달되는 인수의 수) 와 argv (응용프로그램에 전단되는 인수의 배열)을 사용할수 있을것이다.

    PHP 4.3.0부터, CLI SAPI는 PHP 변수 $argc$argv가 등록되고 적절한 값으로 채워지게 된다. 이 변수의 생성은 CGIMODULE 버전과 같이 register_globalson되어 있어야 한다. 버전이나 register_globals의 설정에 관계없이, $_SERVER$HTTP_SERVER_VARS로 그 값에 접근할수 있다. Example: $_SERVER['argv']

    Note: 이 지시어는 설정 파일 php.ini나 사용자 설정으로부터 온 다른 값으로 초기화될수 없다. 모든 설정 파일이 해석되고 난 후에 기본값이 적용되기 때문에 이 것은 제한이 된다. 하지만, 각 값은 런타임동안에 변경될수 있다. (위 지시어 중 환경과 맞지 않는것 e.g. register_argc_argv).

  • 셀 환경에서의 작업을 편하게 하기 위해, 다음 상수가 정의되었다:

    CLI 전용 상수
    상수 설명
    STDIN

    stdin에 이미 열려진 스트림. 이 상수는 다음처럼 여는것을 간단하게 해준다.

    <?php

    $stdin 
    fopen('php://stdin''r');

    ?>

    stdin에서 한 줄을 읽으려면, 다음처럼 할 수 있습니다.

    <?php
    $line 
    trim(fgets(STDIN)); // STDIN에서 한 줄을 읽습니다
    fscanf(STDIN"%d\n"$number); // STDIN에서 수를 읽습니다
    ?>

    STDOUT

    stdout에 이미 열려진 스트림. 이 상수는 다음처럼 여는것을 간단하게 해준다.

    <?php

    $stdout 
    fopen('php://stdout''w');

    ?>

    STDERR

    stderr에 이미 열려진 스트림. 이 상수는 다음처럼 여는것을 간단하게 해준다.

    <?php

    $stderr 
    fopen('php://stderr''w');

    ?>

    위에서 설명한대로 예를 들면 stderr에 대한 스트림을 직업 열필요가 없다. 스트림 자원 대신 단순하게 상수를 사용하면 된다.

    php -r 'fwrite(STDERR, "stderr\n");'

    이 스트림을 명시적으로 닫을 필요가 없다. 스크립트가 끝날때 PHP에 의해 자동적으로 닫히기 때문이다.

    Note: 이 상수들은 PHP 스크립트를 stdin에서 읽을 경우에는 사용할 수 없습니다.

  • CLI SAPI는 현재 디렉토리를 실행중인 스크립트의 디렉토리로 변경 하지않는다!

    다음예는 CGI SAPI와의 차이점을 보여준다:

    <?php
    // Our simple test application named test.php
    echo getcwd(), "\n";
    ?>

    CGI 버전을 사용할때, 출력은:

    $ pwd
    /tmp
    
    $ php -q another_directory/test.php
    /tmp/another_directory
    

    이 예제코드는 PHP가 현재 디렉토리를 실행스크립트의 디렉토리로 변경하는것을 보여준다.

    CLI SAPI를 사용할때는 다음과 같다:

    $ pwd
    /tmp
    
    $ php -f another_directory/test.php
    /tmp
    

    이것은 PHP에서 셀 툴을 제작할때 좀더 많은 유연성을 허용한다.

    Note: CGI SAPI 는 명령줄에서 실행할때 -C 스위치를 사용하여 CLI SAPI의 동작을 지원한다.

PHP 바이너리에 의해 제공되는 명령줄 옵션의 리스트는 PHP를 -h 스위치와 함께 실행하므로써 어느때든 질의를 할수 있다.

Usage: php [options] [-f] <file> [--] [args...]
       php [options] -r <code> [--] [args...]
       php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]
       php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]
       php [options] -- [args...]
       php [options] -a

  -a               Run interactively
  -c <path>|<file> Look for php.ini file in this directory
  -n               No php.ini file will be used
  -d foo[=bar]     Define INI entry foo with value 'bar'
  -e               Generate extended information for debugger/profiler
  -f <file>        Parse and execute <file>.
  -h               This help
  -i               PHP information
  -l               Syntax check only (lint)
  -m               Show compiled in modules
  -r <code>        Run PHP <code> without using script tags <?..?>
  -B <begin_code>  Run PHP <begin_code> before processing input lines
  -R <code>        Run PHP <code> for every input line
  -F <file>        Parse and execute <file> for every input line
  -B <begin_code>  Run PHP <end_code> after processing all input lines
  -H               Hide any passed arguments from external tools.
  -s               Display colour syntax highlighted source.
  -v               Version number
  -w               Display source with stripped comments and whitespace.
  -z <file>        Load Zend extension <file>.

  args...          Arguments passed to script. Use -- args when first argument 
                   starts with - or script is read from stdin

  --ini            Show configuration file names

  --rf <name>      Show information about function <name>.
  --rc <name>      Show information about class <name>.
  --re <name>      Show information about extension <name>.
  --ri <name>      Show configuration for extension <name>.

CLI SAPI는 실행하고자 하는 PHP 코드를 취하는 3가지의 방법을 사용한다.

  1. PHP에게 특정 파일을 실행하도록 지정함.

    php my_script.php
    
    php -f my_script.php
    

    두 방법 (-f 스위치를 사용하거나 안하는것)은 모두 my_script.php을 실행한다. 실행하고자하는 파일을 선택할수 있다 - PHP 스크립트는 .php 확장자 로 끝날필요없이 어떤 이름이나 원하는 확장자를 갖을수 있다.

    Note: 스크립트에 인수를 전달해야 할 때, -f 스위치를 사용할 경우 --을 첫번째 인수로 전달해야 합니다.

  2. 명령줄에서 실행하고자 하는 PHP 코드를 직접 전달함.

    php -r 'print_r(get_defined_constants());'
    

    셀 변수 변환과 따옴표 사용에 있어서 특별한 주의가 필요하다.

    Note: 예제 코드를 주의깊게 읽으면, 시작과 끝 태그가 존재하지 않는다! -r 스위치는 그 태그들이 필요하지 않다. 그 태그들을 사용하면 해석 에러가 발생할것이다.

  3. 표준 입력(stdin)을 통해 수행되는 PHP 코드를 제공함

    이 방식은 동적인 PHP 코드를 생성할수 있는 강력한 기능을 부여하고 바이너리에 그 코드를 넘겨준다. 다음 (가상의) 예제코드에서 보여주는 바와 같다.

    $ some_application | some_filter | php | sort -u >final_output.txt
    

코드를 수행하기 위한 세 가지 방법의 어떤것도 조합할수 없다.

모든 셀 응용 프로그램처럼, PHP 바이너리는 많은수의 인수를 허용하고 PHP 스크립트도 인수를 받을수 있다. 스크립트로 전달할수 있는 인수의 갯수는 PHP에 의해 제한받지 않는다. (셀은 전달할수 있는 문자 갯수의 제한을 갖는다; 보통 이 제한을 넘지 않을것이다) 스크립트로 전달할수 있는 인수는 전역 배열 $argv에 존재한다. 제로 인덱스는 항상 스크립트 명을 포함한다 (PHP 코드가 표준 입력이나 명령줄 스위치 -r로부터 온 경우에는 - ). 두번째로 등록된 전역 변수는 $argv배열의 구성요소 수를 갖는 $argc이다 (스크립트로 전달되는 인수의 수가 아니다)

스크립트로 전달하려는 인수가 -문자로 시작되지 않는한, 특별하게 조심할 필요는 없다. -로 시작하는 인수를 스크립트에 전달하면 문제가 발생할 소지가 있다 왜냐하면 PHP는 그 인수를 PHP가 제어해야 한다고 생각하기 때문이다. 이런일이 발생하지 않기 위해서는, -- 구분자의 인수 리스트를 사용한다. 이 구분자가 PHP에 의해 해석된 후에, 그 뒤의 모든 인수가 스크립트로 온전히 전달된다.

# This will not execute the given code but will show the PHP usage
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] <file> [args...]
[...]

# This will pass the '-h' argument to your script and prevent PHP from showing it's usage
$ php -r 'var_dump($argv);' -- -h
array(2) {
  [0]=>
  string(1) "-"
  [1]=>
  string(2) "-h"
}

하지만, 셀 스크립트에서 PHP를 사용하는 다른 방법이 있다. 첫번째 줄을 #!/usr/bin/php로 시작하는 스크립트를 작성할수 있다. 이 줄 뒤에는 PHP의 시작과 끝 태그 안에 포함된 일반적인 PHP 코드를 놓을수 있다. 이 파일에 적절하게 실행 속성을 설정하면 (e.g. chmod +x test) 스크립트는 보통의 셀이나 펄 스크립트처럼 실행될수 있다:

Example #1 PHP 스크립트를 쉘 스크립트처럼 실행하기

<?php
var_dump
($argv);
?>

이 파일이 현재 디렉토리에서 test라는 이름을 가졌다고 가정하면 다음과 같이 할수 있다.

$ chmod +x test
$ ./test -h -- foo
array(4) {
  [0]=>
  string(6) "./test"
  [1]=>
  string(2) "-h"
  [2]=>
  string(2) "--"
  [3]=>
  string(3) "foo"
}

위와 같은 경우에 -로 시작하는 인수를 스크립트로 전달할때에도 주의할 필요가 없다.

긴 옵션은 PHP 4.3.3부터 사용할 수 있습니다.

명령줄 옵션
옵션 긴 옵션 설명
-a --interactive

PHP를 대화적으로 실행합니다. PHP를 Readline 확장과 함께 컴파일했다면(윈도우에서는 불가능), 자동 완성 기능(예. 변수명의 시작 부분을 치고 TAB을 누르면 PHP가 이름을 완성해줍니다)과 화살표 키로 사용할 수 있는 타이핑 기록을 가진 멋진 쉘을 가지게 됩니다. 기록은 ~/.php_history 파일에 저장됩니다.

Note: auto_prepend_fileauto_append_file은 이 모드에서 해석되지만 약간의 제한이 존재합니다 - 예. 함수는 호출하기 전에 정의되어야 합니다.

Note: PHP를 CLI 대화 모드로 사용할 때, 자동 적재를 사용할 수 없습니다.

-c --php-ini

이 옵션으로 php.ini를 찾을 디렉토리를 지정하거나, 사용자 INI 파일(php.ini라는 이름을 가질 필요는 없습니다)을 지정할 수 있습니다. 예를 들면:

$ php -c /custom/directory/ my_script.php

$ php -c /custom/directory/custom-file.ini my_script.php

이 옵션을 지정하지 않으면, 파일을 기본 위치에서 찾습니다.

-n --no-php-ini

php.ini를 무시합니다. 이 스위치는 PHP 4.3.0부터 사용할 수 있습니다.

-d --define

이 옵션은 php.ini에서 허용된 설정 지시어에 대해서 사용자정의 값을 설정하도록 해줌. 문법은 다음과 같다:

-d configuration_directive[=value]

예제 (표시 관계로 줄바꿈을 하였습니다):

# Omitting the value part will set the given configuration directive to "1"
$ php -d max_execution_time
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(1) "1"

# Passing an empty value part will set the configuration directive to ""
php -d max_execution_time=
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(0) ""

# The configuration directive will be set to anything passed after the '=' character
$  php -d max_execution_time=20
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(2) "20"
$  php
        -d max_execution_time=doesntmakesense
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(15) "doesntmakesense"

-e --profile-info

디버거/프로파일러에서 사용할 수 있는 확장 정보 모드를 켭니다.

-f --file

-f 옵션으로 주어진 파일명을 해석하여 실행합니다. 이 스위치는 선택적으로 생략할 수 있습니다. 단지 실행할 파일명만 제공해도 됩니다.

Note: 스크립트에 인수를 전달할 때, 첫번째 인수는 --이여야 합니다. 그렇지 않으면 PHP는 그들을 PHP 옵션으로 해석합니다.

-h 와 -? --help 와 --usage 이 옵션으로, 실제 명령줄 옵션 목록과 작동에 관한 한 줄 설명에 대한 정보를 얻을 수 있습니다.
-i --info 이 명령줄 옵션은 phpinfo()를 호출하여, 그 결과를 출력합니다. PHP가 제대로 작동하지 않으면, php -i를 사용하여 어떠한 오류 메세지가 시작시나 정보표에 나오는지 확인할 수 있습니다. CGI 모드를 사용하면 출력은 HTML이고 매우 큰 점에 주의하십시오.
-l --syntax-check

이 옵션은 주어진 PHP 코드의 문법 검사만 수행하게 하는 편리한 방법을 제공함. 성공하면, No syntax errors detected in <filename>라는 메시지가 표준 출력으로 쓰여지고 셀의 리턴 코드는 0이다. 실패하면, 내부적인 해석기 에러와 함께 Errors parsing <filename>라는 메시지가 표준 출력으로 쓰여지고 셀의 리턴 코드는 -1이 된다.

이 옵션은 치명적인 에러를 발견할수 없을것이다 (undefined functions 같은). -f 옵션을 사용하면 치명적인 에러도 함께 찾을수 있을것이다.

Note: 이 옵션은 -r 옵션과 함께 사용할수 없다.

-m --modules

이 옵션을 사용하여, PHP는 내장(로드된)된 PHP 모듈과 Zend 모듈을 출력한다.

$ php -m
[PHP Modules]
xml
tokenizer
standard
session
posix
pcre
overload
mysql
mbstring
ctype

[Zend Modules]

-r --run

이 옵션은 명령줄에서 직접 PHP를 수행하도록 해줌. PHP의 시작과 끝 태그 (<?php?>)는 필요하지 않다. 만약 존재한다면 해석 에러가 발생할것이다.

Note: 이런 형태의 PHP를 사용할때 셀에 의해 수행되는 커맨드라인의 변수 치환과 충돌하지 않도록 주의가 필요하다.

해석 오류를 보여주는 예제

$ php -r "$foo = get_defined_constants();"
Command line code(1) : Parse error - parse error, unexpected '='

여기서의 문제점은 sh/bash는 큰따옴표 "를 사용할지라도 변수 치환을 수행한다는것이다. 변수 $foo는 정의되지 않았기 때문에, 실질적인 읽기를 수행하는데 있어서 PHP로 전달되는 코드가 아무것도 없다:

$ php -r " = get_defined_constants();"

확실한 방법은 작은 따옴표 '를 사용하는 것이다. 작은 따옴표로 둘러싼 문자열안의 변수는 sh/bash에 의해 치환되지 않는다.

$ php -r '$foo = get_defined_constants(); var_dump($foo);'
array(370) {
  ["E_ERROR"]=>
  int(1)
  ["E_WARNING"]=>
  int(2)
  ["E_PARSE"]=>
  int(4)
  ["E_NOTICE"]=>
  int(8)
  ["E_CORE_ERROR"]=>
  [...]

sh/bash가 아닌 다른 셀을 사용 중이라면, 좀더 많은 다른 경험을 했을수 있다. » http://bugs.php.net/에서 버그 보고를 하시면 됩니다. 아직도 코드내로 셀변수를 취하려고 하거나 회피를 위한 역슬래시를 사용해서 어려움을 격기 쉽다. 분명히 경고했다.

Note: -rCLI SAPI에서만 사용가능하다. CGI SAPI 에서는 사용할수 없다.

Note: 이 옵션은 매우 기본적인 기능을 의미합니다. 그러므로 몇몇 설정 지시어(예. auto_prepend_fileauto_append_file)는 이 모드에서 무시됩니다.

-B --process-begin

stdin을 처리하기 전에 실행할 PHP 코드. PHP 5에서 추가.

-R --process-code

매 입력줄마다 실행할 PHP 코드. PHP 5에서 추가.

이 모드에서 사용할 수 있는 두가지 특별한 변수가 있습니다: $argn$argi. $argn은 현 시점에서 PHP가 처리하는 줄을 가지고, $argi은 줄 번호를 가집니다.

-F --process-file

매 입력줄마다 실행할 PHP 파일. PHP 5에서 추가.

-E --process-end

입력을 처리한 후에 실행할 PHP 코드. PHP 5에서 추가.

Example #2 프로젝트 줄 수를 세기 위해 -B, -R, -E 옵션 사용하기.

$ find my_proj | php -B '$l=0;' -R '$l += count(@file($argn));' -E 'echo "Total Lines: $l\n";'
Total Lines: 37328

-s --syntax-highlight 와 --syntax-highlighting

색으로 구문을 강조한 소스를 표시합니다.

이 옵션은 파일을 해석하는 내부 메커니즘을 사용하여 강조된 HTML 버전을 생성하여 표준 출력에 씁니다. 이로써 만들어지는 것은 HTML <code> [...] </code> 태그 블럭만이고, HTML 헤더는 출력하지 않습니다.

Note: 이 옵션은 -r 옵션과 함께 사용할 수 없습니다.

-v --version

PHP, PHP SAPI, 젠드 버전을 표준 출력으로 씁니다. 예를 들면,

$ php -v
PHP 4.3.0 (cli), Copyright (c) 1997-2002 The PHP Group
Zend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies

-w --strip

주석과 공백을 제거한 소스를 표시합니다.

Note: 이 옵션은 -r 옵션과 함께 사용할 수 없습니다.

-z --zend-extension

젠드 확장을 적재합니다. 파일명만 주어지면, PHP는 시스템의 기본 라이브러리 경로(보통 리눅스 시스템에서 /etc/ld.so.conf로 지정)에서 확장을 적재하려고 시도합니다. 절대 경로 정보와 파일명을 넘겨주면 시스템 라이브러리 검색 경로를 사용하지 않습니다. 디렉토리 정보와 함께 상대적인 파일명을 사용하면 PHP는 현재 디렉토리에서 상대적인 경로에서만 확장 적재를 시도합니다.

  --ini

설정 파일명과 검색한 디렉토리를 표시합니다. PHP 5.2.3부터 사용할 수 있습니다.

Example #3 --ini 예제

$ php --ini
Configuration File (php.ini) Path: /usr/dev/php/5.2/lib
Loaded Configuration File:         /usr/dev/php/5.2/lib/php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)

--rf --rfunction

주어진 함수나 클래스 메쏘드에 대한 정보(예. 인수의 갯수와 이름)를 보여줍니다. PHP 5.1.2부터 사용할 수 있습니다.

이 옵션은 PHP를 Reflection과 함께 컴파일했을 경우에만 사용할 수 있습니다.

Example #4 기본 --rf 사용법

$ php --rf var_dump
Function [ <internal> public function var_dump ] {

  - Parameters [2] {
    Parameter #0 [ <required> $var ]
    Parameter #1 [ <optional> $... ]
  }
}

--rc --rclass

주어진 클래스에 대한 정보(상수, 프로퍼티, 메쏘드의 목록)를 보여줍니다. PHP 5.1.2부터 사용할 수 있습니다.

이 옵션은 PHP를 Reflection과 함께 컴파일했을 경우에만 사용할 수 있습니다.

Example #5 --rc 예제

$ php --rc Directory
Class [ <internal:standard> class Directory ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [0] {
  }

  - Methods [3] {
    Method [ <internal> public method close ] {
    }

    Method [ <internal> public method rewind ] {
    }

    Method [ <internal> public method read ] {
    }
  }
}

--re --rextension

주어진 확장에 대한 정보(php.ini 옵션, 정의된 함수, 상수, 클래스의 목록)를 보여줍니다. PHP 5.1.2부터 사용할 수 있습니다.

이 옵션은 PHP를 Reflection과 함께 컴파일했을 경우에만 사용할 수 있습니다.

Example #6 --re 예제

$ php --re json
Extension [ <persistent> extension #19 json version 1.2.1 ] {

  - Functions {
    Function [ <internal> function json_encode ] {
    }
    Function [ <internal> function json_decode ] {
    }
  }
}

--ri --rextinfo

주어진 확장의 설정 정보(phpinfo()의 반환 정보와 동일)를 보여줍니다. PHP 5.2.2부터 사용할 수 있습니다. 핵심 설정 정보는 확장 이름으로 "main"을 사용해서 확인할 수 있습니다.

Example #7 --ri 예제

$ php --ri date

date

date/time support => enabled
"Olson" Timezone Database Version => 2007.5
Timezone Database => internal
Default timezone => Europe/Oslo

Directive => Local Value => Master Value
date.timezone => Europe/Oslo => Europe/Oslo
date.default_latitude => 59.22482 => 59.22482
date.default_longitude => 11.018084 => 11.018084
date.sunset_zenith => 90.583333 => 90.583333
date.sunrise_zenith => 90.583333 => 90.583333

PHP 실행 파일은 웹서버와 절대적으로 독립적인 PHP 스크립트를 실행하기 위해 사용될수 있다. 유닉스 시스템에 있다면, PHP 스크립트의 첫번째 줄에 특별한 것을 추가해야 하고, 실행가능하게 해서, 무슨 프로그램이 스크립트를 수행시킬지 시스템이 알수 있도록 한다. 윈도우 플랫폼에서는 .php파일의 더블 클릭 옵션을 갖는 php.exe와 연관시킬수 있거나, PHP를 통해 그 스크립트를 수행하도록 배치 파일을 만들수 있다. 유닉스에서 실행시키기위해 추가된 첫번째 줄은 윈도우에 아무런 해가 없을것이다. 그래서 이 방법을 사용하여 플랫폼 프로그램을 번갈아 작성할수 있다. 명령줄 PHP 프로그램을 작성하는 단순한 에제 코드를 아래에서 볼수 있다.

Example #8 명령줄에서 실행되도록 의도된 스크립트(script.php)

<?php

if ($argc != || in_array($argv[1], array('--help''-help''-h''-?'))) {
?>

This is a command line PHP script with one option.

  Usage:
  <?php echo $argv[0]; ?> <option>

  <option> can be some word you would like
  to print out. With the --help, -help, -h,
  or -? options, you can get this help.

<?php
} else {
    echo 
$argv[1];
}
?>

위 스크립트에서, 특별한 첫번째 줄을 사용하여 이 파일이 PHP에 의해 실행되어야 한다는 것을 가리킨다. CLI 버전을 사용한다면, HTTP 헤더가 존재하지 않을것이다. PHP 의 커맨드라인 응용프로그램을 작성할때 사용할수 있는 두개의 변수가 존재한다:$argc$argv. 첫번째 변수는 인수 갯수에 하나(스크립트명)가 추가된 값이다. 두번째 변수는 인수들를 포함하는 배열인데, 이 배열은 제로 ($argv[0])에 스크립트명을 갖으면 시작된다.

위 프로그램에서는 인수가 하나 이하인가 이상인가를 체크한다. 인수가 --help나, -help, -h, -?이면, help 메시지를 출력하고, 스크립트명을 동적으로 출력한다. 다른 인수를 받게 되면, 그 인수를 출력한다.

유닉스에서 위 스크립트를 수행하려 하면, 그 파일을 실행가능하게 해서 단순히 script.php echothisscript.php -h를 호출하면 된다. 윈도우에서는, 이 작업을 위해 배치 파일을 만들수 있다.

Example #9 명령줄의 PHP 스크립트를 수행하기 위한 배치 파일(script.bat)

@C:\php\php.exe script.php %1 %2 %3 %4

위 프로그램이 script.php이란 이름을 갖고, C:\php\php.exe 안에 CLI php.exe를 갖는다면 이 배치 파일은 추가된 옵션과 함께 실행이 될것이다: script.bat echothisscript.bat -h.

PHP의 명령줄 응용 프로그램의 기능을 확장하기 위한 좀더 많은 함수를 보기위해 Readline 확장에 대한 문서도 참고한다.




함수 레퍼런스

Tip

참고 확장 분류.


Affecting PHP's Behaviour


Alternative PHP Cache


소개

The Alternative PHP Cache (APC) is a free and open opcode cache for PHP. Its goal is to provide a free, open, and robust framework for caching and optimizing PHP intermediate code.



설치/설정

Table of Contents


요구 조건

이 확장을 빌드할 때 외부 라이브러리가 필요하지 않습니다.



설치

» PECL 확장은 PHP 배포판에서 제공하지 않습니다.

PECL 확장 설치에 관한 정보는 매뉴얼의 PECL 확장 설치에 있습니다. 새 릴리즈, 내려받기, 소스파일, 개발자 정보, CHANGELOG 등의 추가 정보는 여기에 있습니다: » http://pecl.php.net/package/apc.

PECL 확장에 대한 DLL은 현재 사용할 수 없습니다. 윈도우에서 빌드하기 섹션을 참고하십시오.

Note: On Windows, APC needs a temp path to exist, and be writable by the web server. It checks TMP, TEMP, USERPROFILE environment variables in that order and finally tries the WINDOWS directory if none of those are set.

Note: For more in-depth, highly technical implementation details, see the » developer-supplied TECHNOTES file .



실행시 설정

이 함수의 작동은 php.ini 설정에 영향을 받습니다.

Although the default APC settings are fine for many installations, serious users should consider tuning the following parameters.

There are two primary decisions to be made configuring APC. First, how much memory is going to be allocated to APC; and second, whether APC will check if a file has been modified on every request. The two ini directives that control these settings are apc.shm_size and apc.stat, respectively. Read the sections on these two directive carefully below.

Once the server is running, the apc.php script that is bundled with the extension should be copied somewhere into the docroot and viewed with a browser as it provides a detailed analysis of the internal workings of APC. If GD is enabled in PHP, it will even display some interesting graphs. The first thing to ensure, of course, is that it is actually caching files. If APC is working, the Cache full count number (on the left) will display the number of times the cache has reached maximum capacity and has had to forcefully clean any entries that haven't been accessed in the last apc.ttl seconds. This number is minimized in a well-configured cache. If the cache is constantly being filled, and thusly forcefully freed, the resulting churning will have disparaging effects on script performance. The easiest way to minimize this number is to allocate more memory for APC. Barring that, the apc.filters ought to be used to cache fewer scripts.

APC configuration options
Name Default Changeable Changelog
apc.enabled "1" PHP_INI_SYSTEM PHP_INI_SYSTEM in APC 2. PHP_INI_ALL in APC <= 3.0.12.
apc.shm_segments "1" PHP_INI_SYSTEM  
apc.shm_size "30" PHP_INI_SYSTEM  
apc.optimization "0" PHP_INI_ALL PHP_INI_SYSTEM in APC 2. Removed in APC 3.0.13.
apc.num_files_hint "1000" PHP_INI_SYSTEM  
apc.user_entries_hint "4096" PHP_INI_SYSTEM Available since APC 3.0.0.
apc.ttl "0" PHP_INI_SYSTEM Available since APC 3.0.0.
apc.user_ttl "0" PHP_INI_SYSTEM Available since APC 3.0.0.
apc.gc_ttl "3600" PHP_INI_SYSTEM  
apc.cache_by_default "1" PHP_INI_ALL PHP_INI_SYSTEM in APC <= 3.0.12. Available since APC 3.0.0.
apc.filters NULL PHP_INI_SYSTEM  
apc.mmap_file_mask NULL PHP_INI_SYSTEM  
apc.slam_defense "0" PHP_INI_SYSTEM Available since APC 3.0.0.
apc.file_update_protection "2" PHP_INI_SYSTEM Available since APC 3.0.6.
apc.enable_cli "0" PHP_INI_SYSTEM Available since APC 3.0.7.
apc.max_file_size "1M" PHP_INI_SYSTEM Available since APC 3.0.7.
apc.stat "1" PHP_INI_SYSTEM Available since APC 3.0.10.
apc.write_lock "1" PHP_INI_SYSTEM Available since APC 3.0.11.
apc.report_autofilter "0" PHP_INI_SYSTEM Available since APC 3.0.11.
apc.include_once_override "0" PHP_INI_SYSTEM Available since APC 3.0.12.
apc.rfc1867 "0" PHP_INI_SYSTEM Available since APC 3.0.13.
apc.rfc1867_prefix "upload_" PHP_INI_SYSTEM  
apc.rfc1867_name "APC_UPLOAD_PROGRESS" PHP_INI_SYSTEM  
apc.rfc1867_freq "0" PHP_INI_SYSTEM  
apc.localcache "0" PHP_INI_SYSTEM Available since APC 3.0.14.
apc.localcache.size "512" PHP_INI_SYSTEM Available since APC 3.0.14.
apc.coredump_unmap "0" PHP_INI_SYSTEM Available since APC 3.0.16.
apc.stat_ctime "0" PHP_INI_SYSTEM Available since APC 3.0.13.

PHP_INI_* 모드에 대한 상세와 정의는 환경 설정을 바꿀 수 있는 곳를 참고하십시오.

위 설정 지시어에 대한 간단한 설명입니다.

apc.enabled boolean

apc.enabled can be set to 0 to disable APC. This is primarily useful when APC is statically compiled into PHP, since there is no other way to disable it (when compiled as a DSO, the extension line in php.ini can just be commented-out).

apc.shm_segments integer

The number of shared memory segments to allocate for the compiler cache. If APC is running out of shared memory but apc.shm_size is set as high as the system allows, raising this value might prevent APC from exhausting its memory.

apc.shm_size integer

The size of each shared memory segment in MB. By default, some systems (including most BSD variants) have very low limits on the size of a shared memory segment.

apc.optimization integer

The optimization level. Zero disables the optimizer, and higher values use more aggressive optimizations. Expect very modest speed improvements. This is experimental.

apc.num_files_hint integer

A "hint" about the number of distinct source files that will be included or requested on your web server. Set to zero or omit if unsure; this setting is mainly useful for sites that have many thousands of source files.

apc.user_entries_hint integer

Just like apc.num_files_hint, a "hint" about the number of distinct user cache variables to store. Set to zero or omit if not sure.

apc.ttl integer

The number of seconds a cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that APC's cache could potentially fill up with stale entries while newer entries won't be cached. In the event of a cache running out of available memory, the cache will be completely expunged if ttl is equal to 0. Otherwise, if the ttl is greater than 0, APC will attempt to remove expired entries.

apc.user_ttl integer

The number of seconds a cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that APC's cache could potentially fill up with stale entries while newer entries won't be cached. In the event of a cache running out of available memory, the cache will be completely expunged if ttl is equal to 0. Otherwise, if the ttl is greater than 0, APC will attempt to remove expired entries.

apc.gc_ttl integer

The number of seconds that a cache entry may remain on the garbage-collection list. This value provides a fail-safe in the event that a server process dies while executing a cached source file; if that source file is modified, the memory allocated for the old version will not be reclaimed until this TTL reached. Set to zero to disable this feature.

apc.cache_by_default boolean

On by default, but can be set to off and used in conjunction with positive apc.filters so that files are only cached if matched by a positive filter.

apc.filters string

A comma-separated list of POSIX extended regular expressions. If any pattern matches the source filename, the file will not be cached. Note that the filename used for matching is the one passed to include/require, not the absolute path. If the first character of the expression is a + then the expression will be additive in the sense that any files matched by the expression will be cached, and if the first character is a - then anything matched will not be cached. The - case is the default, so it can be left off.

apc.mmap_file_mask string

If compiled with MMAP support by using --enable-mmap this is the mktemp-style file_mask to pass to the mmap module for determining whether your mmap'ed memory region is going to be file-backed or shared memory backed. For straight file-backed mmap, set it to something like /tmp/apc.XXXXXX (exactly 6 Xs). To use POSIX-style shm_open/mmap put a .shm somewhere in your mask. e.g. /apc.shm.XXXXXX You can also set it to /dev/zero to use your kernel's /dev/zero interface to anonymous mmap'ed memory. Leaving it undefined will force an anonymous mmap.

apc.slam_defense integer

On very busy servers whenever you start the server or modify files you can create a race of many processes all trying to cache the same file at the same time. This option sets the percentage of processes that will skip trying to cache an uncached file. Or think of it as the probability of a single process to skip caching. For example, setting apc.slam_defense to 75 would mean that there is a 75% chance that the process will not cache an uncached file. So, the higher the setting the greater the defense against cache slams. Setting this to 0 disables this feature.

Deprecated by apc.write_lock.

apc.file_update_protection integer

When a file is modified on a live web server it really ought to be done in an atomic manner. That is, written to a temporary file and renamed (mv) the file into its permanent position when it is ready. Many text editors, cp, tar and other such programs don't do this. This means that there is a chance that a file is accessed (and cached) while it is still being written to. This apc.file_update_protection setting puts a delay on caching brand new files. The default is 2 seconds, which means that if the modification timestamp (mtime) on a file shows that it is less than 2 seconds old when it is accessed, it will not be cached. The unfortunate person who accessed this half-written file will still see weirdness, but at least it won't persist. If all of the webserver's files are atomically updated, via some method like rsync (which updates correctly), this protection can be disabled by setting this directive to 0. If the system is flooded with i/o and some update procedures are taking longer than 2 seconds, this setting should be increased to enable the protection on those slower update operations.

apc.enable_cli integer

Mostly for testing and debugging. Setting this enables APC for the CLI version of PHP. Under normal circumstances, it is not ideal to create, populate and destroy the APC cache on every CLI request, but for various test scenarious it is useful to be able to enable APC for the CLI version of PHP easily.

apc.max_file_size integer

Prevent files larger than this value from getting cached. Defaults to 1M.

apc.stat integer

Be careful changing this setting. This defaults to on, forcing APC to stat (check) the script on each request to determine if it has been modified. If it has been modified it will recompile and cache the new version. If this setting is off, APC will not check, which usually means that to force APC to recheck files, the web server will have to be restarted or the cache will have to be manually cleared. Note that FastCGI web server configurations may not clear the cache on restart. On a production server where the script files rarely change, a significant performance boost can be achieved by disabled stats.

For included/required files this option applies as well, but note that for relative path includes (any path that doesn't start with / on Unix) APC has to check in order to uniquely identify the file. If you use absolute path includes APC can skip the stat and use that absolute path as the unique identifier for the file.

apc.write_lock boolean

On busy servers, when the web server is first started, or when many files have been modified at the same time, APC may try to compile and cache the same file multiple times. Write_lock guaranttes that only one process will attempt to compile and cache an uncached script. The other processes attempting to use the script will run without using the opcode cache, rather than locking and waiting for the cache to prime.

apc.report_autofilter boolean

Logs any scripts that were automatically excluded from being cached due to early/late binding issues.

apc.include_once_override boolean

Optimize include_once() and require_once() calls and avoid the expensive system calls used.

apc.rfc1867 boolean

RFC1867 File Upload Progress hook handler is only available if APC was compiled against PHP 5.2.0 or later. When enabled, any file uploads which includes a field called APC_UPLOAD_PROGRESS before the file field in an upload form will cause APC to automatically create an upload_key user cache entry where key is the value of the APC_UPLOAD_PROGRESS form entry.

Note that the hidden field specified by APC_UPLOAD_PROGRESS must come before the file field, otherwise the upload progress will not work correctly.

Note that the file upload tracking is not threadsafe at this point, so new uploads that happen while a previous one is still going will disable the tracking for the previous.

Example #1 An apc.rfc1867 example

<?php
print_r
(apc_fetch("upload_$_POST[APC_UPLOAD_PROGRESS]"));
?>

위 예제의 출력 예시:

Array
(
    [total] => 1142543
    [current] => 1142543
    [rate] => 1828068.8
    [filename] => test
    [name] => file
    [temp_filename] => /tmp/php8F
    [cancel_upload] => 0
    [done] => 1
)

apc.rfc1867_prefix string

Key prefix to use for the user cache entry generated by rfc1867 upload progress functionality.

apc.rfc1867_name string

Specify the hidden form entry name that activates APC upload progress and specifies the user cache key suffix.

apc.rfc1867_freq string

The frequency that updates should be made to the user cache entry for upload progress. This can take the form of a percentage of the total file size or a size in bytes optionally suffixed with "k", "m", or "g" for kilobytes, megabytes, or gigabytes respectively (case insensitive). A setting of 0 updates as often as possible, which may cause slower uploads.

apc.localcache boolean

This enables a lock-free local process shadow-cache which reduces lock contention when the cache is being written to.

apc.localcache.size integer

The size of the local process shadow-cache, should be set to a sufficiently large value, approximately half of apc.num_files_hint.

apc.coredump_unmap boolean

Enables APC handling of signals, such as SIGSEGV, that write core files when signaled. When these signals are received, APC will attempt to unmap the shared memory segment in order to exclude it from the core file. This setting may improve system stability when fatal signals are received and a large APC shared memory segment is configured.

Warning

This feature is potentially dangerous. Unmapping the shared memory segment in a fatal signal handler may cause undefined behaviour if a fatal error occurs.

Note: Although some kernels may provide a facility to ignore various types of shared memory when generating a core dump file, these implementations may also ignore important shared memory segments such as the Apache scoreboard.

apc.stat_ctime integer

Verification with ctime will avoid problems caused by programs such as svn or rsync by making sure inodes haven't changed since the last stat. APC will normally only check mtime.



자원형

이 확장은 리소스형을 정의하지 않습니다.




예약 상수

이 확장은 상수를 정의하지 않습니다.



APC 함수 목록


apc_add

(PECL apc >= 3.0.13)

apc_add Cache a variable in the data store

설명

bool apc_add ( string $key , mixed $var [, int $ttl= 0 ] )

Caches a variable in the data store, only if it's not already stored.

Note: Unlike many other mechanisms in PHP, variables stored using apc_add() will persist between requests (until the value is removed from the cache).

인수

key

Store the variable using this name. key s are cache-unique, so attempting to use apc_add() to store data with a key that already exists will not overwrite the existing data, and will instead return FALSE. (This is the only difference between apc_add() and apc_store().)

var

The variable to store

ttl

Time To Live; store var in the cache for ttl seconds. After the ttl has passed, the stored variable will be expunged from the cache (on the next request). If no ttl is supplied (or if the ttl is 0), the value will persist until it is removed from the cache manually, or otherwise fails to exist in the cache (clear, restart, etc.).

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 A apc_add() example

<?php
$bar 
'BAR';
apc_add('foo'$bar);
var_dump(apc_fetch('foo'));
echo 
"\n";
$bar 'NEVER GETS SET';
apc_add('foo'$bar);
var_dump(apc_fetch('foo'));
echo 
"\n";
?>

위 예제의 출력:

string(3) "BAR"
string(3) "BAR"

참고



apc_cache_info

(PECL apc >= 2.0.0)

apc_cache_info Retrieves cached information from APC's data store

설명

array apc_cache_info ([ string $cache_type [, bool $limited= false ]] )

Retrieves cached information and meta-data from APC's data store.

반환값

Array of cached data (and meta-data), or FALSE on failure

Note: apc_cache_info() will raise a warning if it is unable to retrieve APC cache data. This typically occurs when APC is not enabled.

인수

cache_type

If cache_type is "user", information about the user cache will be returned.

If cache_type is "filehits", information about which files have been served from the bytecode cache for the current request will be returned. This feature must be enabled at compile time using --enable-filehits.

If an invalid or no cache_type is specified, information about the system cache (cached files) will be returned.

limited

If limited is TRUE, the return value will exclude the individual list of cache entries. This is useful when trying to optimize calls for statistics gathering.

변경점

버전 설명
3.0.11 The limited parameter was introduced.
3.0.16 The "filehits" option for the cache_type parameter was introduced.

예제

Example #1 A apc_cache_info() example

<?php
print_r
(apc_cache_info());
?>

위 예제의 출력 예시:

Array
(
    [num_slots] => 2000
    [ttl] => 0
    [num_hits] => 9
    [num_misses] => 3
    [start_time] => 1123958803
    [cache_list] => Array
        (
            [0] => Array
                (
                    [filename] => /path/to/apc_test.php
                    [device] => 29954
                    [inode] => 1130511
                    [type] => file
                    [num_hits] => 1
                    [mtime] => 1123960686
                    [creation_time] => 1123960696
                    [deletion_time] => 0
                    [access_time] => 1123962864
                    [ref_count] => 1
                    [mem_size] => 677
                )
            [1] => Array (...iterates for each cached file)
)



apc_clear_cache

(PECL apc >= 2.0.0)

apc_clear_cache Clears the APC cache

설명

bool apc_clear_cache ([ string $cache_type ] )

Clears the user/system cache.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

인수

cache_type

If cache_type is "user", the user cache will be cleared; otherwise, the system cache (cached files) will be cleared.

참고



apc_compile_file

(PECL apc >= 3.0.13)

apc_compile_file Stores a file in the bytecode cache, bypassing all filters.

설명

bool apc_compile_file ( string $filename )

Stores a file in the bytecode cache, bypassing all filters.

인수

filename

Full or relative path to a PHP file that will be compiled and stored in the bytecode cache.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.



apc_define_constants

(PECL apc >= 3.0.0)

apc_define_constants Defines a set of constants for retrieval and mass-definition

설명

bool apc_define_constants ( string $key , array $constants [, bool $case_sensitive= true ] )

define() is notoriously slow. Since the main benefit of APC is to increase the performance of scripts/applications, this mechanism is provided to streamline the process of mass constant definition. However, this function does not perform as well as anticipated.

For a better-performing solution, try the » hidef extension from PECL.

Note: To remove a set of stored constants (without clearing the entire cache), an empty array may be passed as the constants parameter, effectively clearing the stored value(s).

인수

key

The key serves as the name of the constant set being stored. This key is used to retrieve the stored constants in apc_load_constants().

constants

An associative array of constant_name => value pairs. The constant_name must follow the normal constant naming rules. value must evaluate to a scalar value.

case_sensitive

The default behaviour for constants is to be declared case-sensitive; i.e. CONSTANT and Constant represent different values. If this parameter evaluates to FALSE the constants will be declared as case-insensitive symbols.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 apc_define_constants() example

<?php
$constants 
= array(
    
'ONE'   => 1,
    
'TWO'   => 2,
    
'THREE' => 3,
);
apc_define_constants('numbers'$constants);
echo 
ONETWOTHREE;
?>

위 예제의 출력:

123

참고



apc_delete

(PECL apc >= 3.0.0)

apc_delete Removes a stored variable from the cache

설명

bool apc_delete ( string $key )

Removes a stored variable from the cache.

인수

key

The key used to store the value (with apc_store()).

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 A apc_delete() example

<?php
$bar 
'BAR';
apc_store('foo'$bar);
apc_delete('foo');
// this is obviously useless in this form
?>

참고



apc_fetch

(PECL apc >= 3.0.0)

apc_fetch Fetch a stored variable from the cache

설명

mixed apc_fetch ( string $key [, bool &$success ] )

Fetchs a stored variable from the cache.

인수

key

The key used to store the value (with apc_store()).

success

Set to TRUE in success and FALSE in failure.

반환값

The stored variable on success; FALSE on failure

예제

Example #1 A apc_fetch() example

<?php
$bar 
'BAR';
apc_store('foo'$bar);
var_dump(apc_fetch('foo'));
?>

위 예제의 출력:

string(3) "BAR"

참고



apc_load_constants

(PECL apc >= 3.0.0)

apc_load_constants Loads a set of constants from the cache

설명

bool apc_load_constants ( string $key [, bool $case_sensitive= true ] )

Loads a set of constants from the cache.

인수

key

The name of the constant set (that was stored with apc_define_constants()) to be retrieved.

case_sensitive

The default behaviour for constants is to be declared case-sensitive; i.e. CONSTANT and Constant represent different values. If this parameter evaluates to FALSE the constants will be declared as case-insensitive symbols.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 apc_load_constants() example

<?php
$constants 
= array(
    
'ONE'   => 1,
    
'TWO'   => 2,
    
'THREE' => 3,
);
apc_define_constants('numbers'$constants);
apc_load_constants('numbers');
echo 
ONETWOTHREE;
?>

위 예제의 출력:

123

참고



apc_sma_info

(PECL apc >= 2.0.0)

apc_sma_info Retrieves APC's Shared Memory Allocation information

설명

array apc_sma_info ([ bool $limited= false ] )

Retrieves APC's Shared Memory Allocation information.

인수

limited

When set to FALSE (default) apc_sma_info() will return a detailed information about each segment.

반환값

Array of Shared Memory Allocation data; FALSE on failure.

예제

Example #1 A apc_sma_info() example

<?php
print_r
(apc_sma_info());
?>

위 예제의 출력 예시:

Array
(
    [num_seg] => 1
    [seg_size] => 31457280
    [avail_mem] => 31448408
    [block_lists] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [size] => 31448408
                            [offset] => 8864
                        )

                )

        )

)



apc_store

(PECL apc >= 3.0.0)

apc_store Cache a variable in the data store

설명

bool apc_store ( string $key , mixed $var [, int $ttl= 0 ] )

Cache a variable in the data store.

Note: Unlike many other mechanisms in PHP, variables stored using apc_store() will persist between requests (until the value is removed from the cache).

인수

key

Store the variable using this name. key s are cache-unique, so storing a second value with the same key will overwrite the original value.

var

The variable to store

ttl

Time To Live; store var in the cache for ttl seconds. After the ttl has passed, the stored variable will be expunged from the cache (on the next request). If no ttl is supplied (or if the ttl is 0), the value will persist until it is removed from the cache manually, or otherwise fails to exist in the cache (clear, restart, etc.).

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 A apc_store() example

<?php
$bar 
'BAR';
apc_store('foo'$bar);
var_dump(apc_fetch('foo'));
?>

위 예제의 출력:

string(3) "BAR"

참고


Table of Contents




Advanced PHP debugger


소개

APD is the Advanced PHP Debugger. It was written to provide profiling and debugging capabilities for PHP code, as well as to provide the ability to print out a full stack backtrace. APD supports interactive debugging, but by default it writes data to trace files. It also offers event based logging so that varying levels of information (including function calls, arguments passed, timings, etc.) can be turned on or off for individual scripts.

Caution

APD is a Zend Extension, modifying the way the internals of PHP handle function calls, and thus may or may not be compatible with other Zend Extensions (for example Zend Optimizer).



설치/설정

Table of Contents


요구 조건

이 확장을 빌드할 때 외부 라이브러리가 필요하지 않습니다.



설치

APD is currently available as a PECL extension from » http://pecl.php.net/package/apd.

Run the following command to download, build, and install the latest stable version of APD:

pear install apd

This automatically installs the APD Zend module into your PHP extensions directory. It is not mandatory to keep it there; you can store the module in any directory PHP can read as long as you set the zend_extension parameter accordingly.

Windows users will enable php_apd.dll inside of php.ini in order to use these functions. 이 PECL 확장에 대한 DLL은 현재 사용할 수 없습니다. 윈도우에서 빌드하기 섹션을 참고하십시오.

In your INI file, add the following lines:

zend_extension = /absolute/path/to/apd.so
apd.dumpdir = /absolute/path/to/trace/directory
apd.statement_tracing = 0

Depending on your PHP build, the zend_extension directive can be one of the following:

zend_extension              (non ZTS, non debug build)
zend_extension_ts           (    ZTS, non debug build)
zend_extension_debug        (non ZTS,     debug build)
zend_extension_debug_ts     (    ZTS,     debug build)



Building on Win32

To build APD under Windows you need a working PHP compilation environment as described on http://php.net/ -- basically, it requires you to have Microsoft Visual C++, win32build.zip, bison/flex, and some know how to get it to work. Also ensure that adp.dsp has DOS line endings; if it has unix line endings, Microsoft Visual C++ will complain about it.



실행시 설정

이 함수의 작동은 php.ini 설정에 영향을 받습니다.

APD Configuration Options
Name Default Changeable Changelog
apd.dumpdir NULL PHP_INI_ALL  
apd.statement_tracing "0" PHP_INI_ALL Available since apd 0.9.

PHP_INI_* 모드에 대한 상세와 정의는 환경 설정을 바꿀 수 있는 곳를 참고하십시오.

위 설정 지시어에 대한 간단한 설명입니다.

apd.dumpdir string

Sets the directory in which APD writes profile dump files. You can specify an absolute path or a relative path.

You can specify a different directory as an argument to apd_set_pprof_trace().

apd.statement_tracing boolean

Specfies whether or not to do per-line tracings. Turning this on (1) will impact the performance of your application.



자원형

이 확장은 리소스형을 정의하지 않습니다.




예약 상수

이 확장은 다음의 상수들을 정의합니다. 이 확장을 PHP에 내장했거나, 실행시에 동적으로 읽어들일 경우에만 사용할 수 있습니다.

APD constants
Constant Value Description
FUNCTION_TRACE (integer) 1  
ARGS_TRACE (integer) 2  
ASSIGNMENT_TRACE (integer) 4  
STATEMENT_TRACE (integer) 8  
MEMORY_TRACE (integer) 16  
TIMING_TRACE (integer) 32  
SUMMARY_TRACE (integer) 64  
ERROR_TRACE (integer) 128  
PROF_TRACE (integer) 256  
APD_VERSION (string) example: 1.0.2-dev  


예제

Table of Contents


How to use PHP-APD in your scripts

  1. As the first line of your PHP script, call the apd_set_pprof_trace() function to start the trace:

    apd_set_pprof_trace();

    You can insert the line anywhere in your script, but if you do not start tracing at the beginning of your script you discard profile data that might otherwise lead you to a performance bottleneck.

  2. Now run your script. The dump output will be written to apd.dumpdir/pprof_pid.ext.

    Tip

    If you're running the CGI version of PHP, you will need to add the '-e' flag to enable extended information for apd to work properly. For example: php -e -f script.php

  3. To display formatted profile data, issue the pprofp command with the sort and display options of your choice. The formatted output will look something like:

    bash-2.05b$ pprofp -R /tmp/pprof.22141.0
    
    Trace for /home/dan/testapd.php
    Total Elapsed Time = 0.00
    Total System Time  = 0.00
    Total User Time    = 0.00
    
    
    Real         User        System             secs/    cumm
    %Time (excl/cumm)  (excl/cumm)  (excl/cumm) Calls    call    s/call  Memory Usage Name
    --------------------------------------------------------------------------------------
    100.0 0.00 0.00  0.00 0.00  0.00 0.00     1  0.0000   0.0009            0 main
    56.9 0.00 0.00  0.00 0.00  0.00 0.00     1  0.0005   0.0005            0 apd_set_pprof_trace
    28.0 0.00 0.00  0.00 0.00  0.00 0.00    10  0.0000   0.0000            0 preg_replace
    14.3 0.00 0.00  0.00 0.00  0.00 0.00    10  0.0000   0.0000            0 str_replace
    

    The -R option used in this example sorts the profile table by the amount of real time the script spent executing a given function. The "cumm call" column reveals how many times each function was called, and the "s/call" column reveals how many seconds each call to the function required, on average.

  4. To generate a calltree file that you can import into the KCacheGrind profile analysis application, issue the pprof2calltree comand.




APD 함수 목록

Contact information

If you have comments, bugfixes, enhancements or want to help developing this beast, you can send an mail to » apd@mail.communityconnect.com. Any help is very welcome.


apd_breakpoint

(PECL apd >= 0.2)

apd_breakpointStops the interpreter and waits on a CR from the socket

설명

bool apd_breakpoint ( int $debug_level )

This can be used to stop the running of your script, and await responses on the connected socket. To step the program, just send enter (a blank line), or enter a php command to be executed.

인수

debug_level

XXX_TRACE 상수에 해당하는 정수값.

MEMORY_TRACE 사용은 권장하지 않습니다. 매우 느리고 정확하지 않습니다. ASSIGNMENT_TRACE는 아직 지원하지 않습니다.

모든 추적(TIMING, FUNCTIONS, ARGS SUMMARTY (strace -c))를 사용하기 위해서는 99를 사용하십시오.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 Typical session using tcplisten

bash#tcplisten localhost 7777

APD - Advanced PHP Debugger Trace File
---------------------------------------------------------------------------
Process Pid (6118)
Trace Begun at Sun Mar 10 23:13:12 2002
---------------------------------------------------------------------------
(  0.000000): apd_set_session_trace called at /home/alan/Projects/project2/test. 
php:5
(  0.074824): apd_set_session_trace_socket() at /home/alan/Projects/project2/tes 
t.php:5 returned.  Elapsed (0.074824)
(  0.074918): apd_breakpoint() /home/alan/Projects/project2/test.php:7
              ++ argv[0] $(??) = 9
apd_breakpoint() at /home/alan/Projects/project2/test.php:7 returned.  Elapsed ( 
-2089521468.1073275368)
>\n 
statement: /home/alan/Projects/project2/test.php:8
>\n 
statement: /home/alan/Projects/project2/test.php:8
>\n 
statement: /home/alan/Projects/project2/test.php:10
>apd_echo($i);
EXEC: apd_echo($i);
0
>apd_echo(serialize(apd_get_active_symbols()));
EXEC:  apd_echo(serialize(apd_get_active_symbols()));
a:47:{i:0;s:4:"PWD";i:1;s:10:"COLORFGBG";i:2;s:11:"XAUTHORITY";i:3;s:14:"
COLORTERM_BCE";i:4;s:9:"WINDOWID";i:5;s:14:"ETERM_VERSION";i:6;s:16:"SE
SSION_MANAGER";i:7;s:4:"PS1";i:8;s:11:"GDMSESSION";i:9;s:5:"USER";i:10;s:5:"
MAIL";i:11;s:7:"OLDPWD";i:12;s:5:"LANG";i:13;s:10:"COLORTERM";i:14;s:8:"DISP
LAY";i:15;s:8:"LOGNAME";i:16;s:6:"
>apd_echo(system('ls /home/mydir'));
........
>apd_continue(0);



apd_callstack

(PECL apd 0.2-0.4)

apd_callstackReturns the current call stack as an array

설명

array apd_callstack ( void )

Returns the current call stack as an array

반환값

An array containing the current call stack.

예제

Example #1 apd_callstack() example

<?php
print_r
(apd_callstack());
?>



apd_clunk

(PECL apd 0.2-0.4)

apd_clunkThrow a warning and a callstack

설명

void apd_clunk ( string $warning [, string $delimiter ] )

Behaves like perl's Carp::cluck. Throw a warning and a callstack.

인수

warning

The warning to throw.

delimiter

The delimiter. Default to <BR />.

반환값

값을 반환하지 않습니다.

예제

Example #1 apd_clunk() example

<?php
apd_clunk
("Some Warning""<br/>");
?>

참고

  • apd_croak() - Throw an error, a callstack and then exit



apd_continue

(PECL apd >= 0.2)

apd_continueRestarts the interpreter

설명

bool apd_continue ( int $debug_level )

Usually sent via the socket to restart the interpreter.

인수

debug_level

XXX_TRACE 상수에 해당하는 정수값.

MEMORY_TRACE 사용은 권장하지 않습니다. 매우 느리고 정확하지 않습니다. ASSIGNMENT_TRACE는 아직 지원하지 않습니다.

모든 추적(TIMING, FUNCTIONS, ARGS SUMMARTY (strace -c))를 사용하기 위해서는 99를 사용하십시오.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 apd_continue() example

<?php
apd_continue
(0);
?>



apd_croak

(PECL apd 0.2-0.4)

apd_croakThrow an error, a callstack and then exit

설명

void apd_croak ( string $warning [, string $delimiter ] )

Behaves like perl's Carp::croak. Throw an error, a callstack and then exit.

인수

warning

The warning to throw.

delimiter

The delimiter. Default to <BR />.

반환값

값을 반환하지 않습니다.

예제

Example #1 apd_croak() example

<?php
apd_croak
("Some Warning","<P>");
?>

참고



apd_dump_function_table

(Unknown)

apd_dump_function_tableOutputs the current function table

설명

void apd_dump_function_table ( void )

Outputs the current function table.

반환값

값을 반환하지 않습니다.

예제

Example #1 apd_dump_function_table() example

<?php
apd_dump_function_table
();
?>



apd_dump_persistent_resources

(PECL apd 0.2-0.4)

apd_dump_persistent_resourcesReturn all persistent resources as an array

설명

array apd_dump_persistent_resources ( void )

Return all persistent resources as an array.

반환값

An array containing the current call stack.

예제

Example #1 apd_dump_persistent_resources() example

<?php
print_r
(apd_dump_persistent_resources());
?>

참고



apd_dump_regular_resources

(PECL apd 0.2-0.4)

apd_dump_regular_resourcesReturn all current regular resources as an array

설명

array apd_dump_regular_resources ( void )

Return all current regular resources as an array.

반환값

An array containing the current regular resources.

예제

Example #1 apd_dump_regular_resources() example

<?php
print_r
(apd_dump_regular_resources());
?>

참고



apd_echo

(PECL apd >= 0.2)

apd_echoEcho to the debugging socket

설명

bool apd_echo ( string $output )

Usually sent via the socket to request information about the running script.

인수

output

The debugged variable.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 apd_echo() example

<?php
apd_echo
($i);
?>



apd_get_active_symbols

(PECL apd 0.2)

apd_get_active_symbolsGet an array of the current variables names in the local scope

설명

array apd_get_active_symbols ( void )

Returns the names of all the variables defined in the active scope, (not their values).

반환값

A multidimensional array with all the variables.

예제

Example #1 apd_get_active_symbols() example

<?php
apd_echo
(apd_get_active_symbols());
?>



apd_set_pprof_trace

(PECL apd >= 0.2)

apd_set_pprof_traceStarts the session debugging

설명

string apd_set_pprof_trace ([ string $dump_directory [, string $fragment= "pprof" ]] )

Starts debugging to pprof_{process_id} in the dump directory.

인수

dump_directory

The directory in which the profile dump file is written. If not set, the apd.dumpdir setting from the php.ini file is used.

fragment

반환값

Returns path of the destination file.

예제

Example #1 apd_set_pprof_trace() example

<?php
apd_set_pprof_trace
();
?>

참고



apd_set_session_trace_socket

(PECL apd >= 0.2)

apd_set_session_trace_socketStarts the remote session debugging

설명

bool apd_set_session_trace_socket ( string $tcp_server , int $socket_type , int $port , int $debug_level )

Connects to the specified tcp_server (eg. tcplisten) and sends debugging data to the socket.

인수

tcp_server

IP or Unix Domain socket (like a file) of the TCP server.

socket_type

Can be AF_UNIX for file based sockets or APD_AF_INET for standard tcp/ip.

port

You can use any port, but higher numbers are better as most of the lower numbers may be used by other system services.

debug_level

XXX_TRACE 상수에 해당하는 정수값.

MEMORY_TRACE 사용은 권장하지 않습니다. 매우 느리고 정확하지 않습니다. ASSIGNMENT_TRACE는 아직 지원하지 않습니다.

모든 추적(TIMING, FUNCTIONS, ARGS SUMMARTY (strace -c))를 사용하기 위해서는 99를 사용하십시오.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 apd_set_session_trace_socket() example

<?php
  apd_set_session_trace_socket
("127.0.0.1",APD_AF_INET,7112,0);
?>



apd_set_session_trace

(PECL apd 0.2-0.4)

apd_set_session_traceStarts the session debugging

설명

void apd_set_session_trace ( int $debug_level [, string $dump_directory ] )

Starts debugging to apd_dump_{process_id} in the dump directory.

인수

debug_level

XXX_TRACE 상수에 해당하는 정수값.

MEMORY_TRACE 사용은 권장하지 않습니다. 매우 느리고 정확하지 않습니다. ASSIGNMENT_TRACE는 아직 지원하지 않습니다.

모든 추적(TIMING, FUNCTIONS, ARGS SUMMARTY (strace -c))를 사용하기 위해서는 99를 사용하십시오.

dump_directory

The directory in which the profile dump file is written. If not set, the apd.dumpdir setting from the php.ini file is used.

반환값

값을 반환하지 않습니다.

예제

Example #1 apd_set_session_trace() example

<?php
apd_set_session_trace
(99);
?>



apd_set_session

(PECL apd 0.2-0.4)

apd_set_sessionChanges or sets the current debugging level

설명

void apd_set_session ( int $debug_level )

This can be used to increase or decrease debugging in a different area of your application.

인수

debug_level

XXX_TRACE 상수에 해당하는 정수값.

MEMORY_TRACE 사용은 권장하지 않습니다. 매우 느리고 정확하지 않습니다. ASSIGNMENT_TRACE는 아직 지원하지 않습니다.

모든 추적(TIMING, FUNCTIONS, ARGS SUMMARTY (strace -c))를 사용하기 위해서는 99를 사용하십시오.

반환값

값을 반환하지 않습니다.

예제

Example #1 apd_set_session() example

<?php
apd_set_session
(9);
?>



override_function

(PECL apd >= 0.2)

override_functionOverrides built-in functions

설명

bool override_function ( string $function_name , string $function_args , string $function_code )

Overrides built-in functions by replacing them in the symbol table.

인수

function_name

The function to override.

function_args

The function arguments, as a coma separated string.

Usually you will want to pass this parameter, as well as the function_code parameter, as a single quote delimited string. The reason for using single quoted strings, is to protect the variable names from parsing, otherwise, if you use double quotes there will be a need to escape the variable names, e.g. \$your_var.

function_code

The new code for the function.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 override_function() example

<?php
override_function
('test''$a,$b''echo "DOING TEST"; return $a * $b;');
?>



rename_function

(PECL apd >= 0.2)

rename_functionRenames orig_name to new_name in the global function table

설명

bool rename_function ( string $original_name , string $new_name )

Renames a orig_name to new_name in the global function table. Useful for temporarily overriding built-in functions.

인수

original_name

The original function name.

new_name

The new name for the original_name function.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 rename_function() example

<?php
rename_function
('mysql_connect''debug_mysql_connect' );
?>


Table of Contents




PHP bytecode Compiler


소개

Warning

이 확장 모듈은 실험적입니다. 이 확장 모듈의 작동(함수의 이름과 이 확장 모듈에 관련된 모든 문서 자료)은 이후의 PHP 릴리즈에서 예고 없이 변경될 수 있습니다. 이 확장 모듈의 사용은 사용자의 책임하에 이루어집니다.

Bcompiler was written for several reasons:

  • To encode entire script in a proprietary PHP application
  • To encode some classes and/or functions in a proprietary PHP application
  • To enable the production of php-gtk applications that could be used on client desktops, without the need for a php.exe.
  • To do the feasibility study for a PHP to C converter

The first of these goals is achieved using the bcompiler_write_header(), bcompiler_write_file() and bcompiler_write_footer() functions. The bytecode files can be written as either uncompressed or plain. To use the generated bytecode, you can simply include it with include or require statements.

The second of these goals is achieved using the bcompiler_write_header(), bcompiler_write_class(), bcompiler_write_footer(), bcompiler_read(), and bcompiler_load() functions. The bytecode files can be written as either uncompressed or plain. The bcompiler_load() reads a bzip compressed bytecode file, which tends to be 1/3 of the size of the original file.

To create EXE type files, bcompiler has to be used with a modified sapi file or a version of PHP which has been compiled as a shared library. In this scenario, bcompiler reads the compressed bytecode from the end of the exe file.

bcompiler can improve performance by about 30% when used with uncompressed bytecodes only. But keep in mind that uncompressed bytecode can be up to 5 times larger than the original source code. Using bytecode compression can save your space, but decompression requires much more time than parsing a source. bcompiler also does not do any bytecode optimization, this could be added in the future...

In terms of code protection, it is safe to say that it would be impossible to recreate the exact source code that it was built from, and without the accompanying source code comments. It would effectively be useless to use the bcompiler bytecodes to recreate and modify a class. However it is possible to retrieve data from a bcompiled bytecode file - so don't put your private passwords or anything in it.



설치/설정

Table of Contents


요구 조건

이 확장을 빌드할 때 외부 라이브러리가 필요하지 않습니다.



설치

short installation note:

  • You need at least PHP 4.3.0 for the compression to work
  • To install on PHP 4.3.0 and later at the Unix command prompt type pear install bcompiler
  • To install on Windows, until the binary package distribution mechanism is finished please search the archives of the pear-general mailing list for pre-built packages. (or send an email to it if you could not find a reference)
  • To install on older versions you need to make some slight changes to the build.
  • untar the bcompiler.tgz archive into php4/ext.(Get it directly from PECL » http://pecl.php.net/get/bcompiler)
  • If the new directory is now called something like bcompiler-0.x, then you should rename it to bcompiler (except you only want to build it as self-contained php-module).
  • If you are using versions before PHP 4.3.0, the you will need to copy the Makefile.in.old to Makefile.in and config.m4.old to config.m4.
  • run phpize in ext/bcompiler
  • run ./buildconf in php4
  • run configure with --enable-bcompiler (and your other options)
  • make; make install
  • that's it.



실행시 설정

이 확장은 php.ini 설정이 존재하지 않습니다.



자원형

이 확장은 리소스형을 정의하지 않습니다.




예약 상수

이 확장은 상수를 정의하지 않습니다.



bcompiler 함수 목록

Contact Information

If you have comments, bugfixes, enhancements or want to help developing this beast, you can drop me a mail at » alan_k@php.net. Any help is very welcome.


bcompiler_load_exe

(PECL bcompiler >= 0.4)

bcompiler_load_exeReads and creates classes from a bcompiler exe file

설명

bool bcompiler_load_exe ( string $filename )

Reads data from a bcompiler exe file and creates classes from the bytecodes.

인수

filename

The exe file path, as a string.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 bcompiler_load_exe() example

<?php

bcompiler_load_exe
("/tmp/example.exe");
print_r(get_defined_classes());

?>

주의

Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

참고



bcompiler_load

(PECL bcompiler >= 0.4)

bcompiler_loadReads and creates classes from a bz compressed file

설명

bool bcompiler_load ( string $filename )

Reads data from a bzcompressed file and creates classes from the bytecodes.

인수

filename

The bzcompressed file path, as a string.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 bcompiler_load() example

<?php

bcompiler_load
("/tmp/example");

print_r(get_defined_classes());

?>

주의

Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

Note: Please use include or require statements to parse bytecodes, it's more portable and convenient way than using this function.
Please note that this function won't execute script body code contained in the bytecode file.

참고



bcompiler_parse_class

(PECL bcompiler >= 0.4)

bcompiler_parse_classReads the bytecodes of a class and calls back to a user function

설명

bool bcompiler_parse_class ( string $class , string $callback )

Reads the bytecodes of a class and calls back to a user function.

인수

class

The class name, as a string.

callback

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 bcompiler_parse_class() example

<?php

function readByteCodes($data) {
    
print_r($data);
}

bcompiler_parse_class("DB","readByteCodes");

?>

주의

Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

Note: This function has been removed from bcompiler and is no longer available as of bcompiler 0.5.



bcompiler_read

(PECL bcompiler >= 0.4)

bcompiler_readReads and creates classes from a filehandle

설명

bool bcompiler_read ( resource $filehandle )

Reads data from a open file handle and creates classes from the bytecodes.

인수

filehandle

A file handle as returned by fopen().

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 bcompiler_read() example

<?php
$fh 
fopen("/tmp/example","r");
bcompiler_read($fh);
fclose($fh);
print_r(get_defined_classes());

?>

주의

Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

Note: Please use include or require statements to parse bytecodes, it's more portable and convenient way than using this function.
Please note that this function won't execute script body code contained in the bytecode file.



bcompiler_write_class

(PECL bcompiler >= 0.4)

bcompiler_write_classWrites an defined class as bytecodes

설명

bool bcompiler_write_class ( resource $filehandle , string $className [, string $extends ] )

Reads the bytecodes from PHP for an existing class, and writes them to the open file handle.

인수

filehandle

A file handle as returned by fopen().

className

The class name, as a string.

extends

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 bcompiler_write_class() example

<?php
$fh 
fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
// you must write DB_common before DB_mysql, as DB_mysql extends DB_common.
bcompiler_write_class($fh,"DB_common");
bcompiler_write_class($fh,"DB_mysql");
bcompiler_write_footer($fh);
fclose($fh);

?>

주의

Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

Note: This function does not perform dependency checking, so make sure you write the classes in an order that will not result in an undefined class error occurring when you load it.

참고



bcompiler_write_constant

(PECL bcompiler >= 0.5)

bcompiler_write_constantWrites a defined constant as bytecodes

설명

bool bcompiler_write_constant ( resource $filehandle , string $constantName )

Reads the bytecodes from PHP for an existing constant, and writes them to the open file handle.

인수

filehandle

A file handle as returned by fopen().

constantName

The name of the defined constant, as a string.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 bcompiler_write_constant() example

<?php
define
("MODULE_MAX"30);

$fh fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_constant($fh,"MODULE_MAX");
bcompiler_write_footer($fh);
fclose($fh);

?>

주의

Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

참고




bcompiler_write_file

(PECL bcompiler >= 0.6)

bcompiler_write_fileWrites a php source file as bytecodes

설명

bool bcompiler_write_file ( resource $filehandle , string $filename )

This function complies specified source file into bytecodes, and writes them to the open file handle.

인수

filehandle

A file handle as returned by fopen().

filename

The source file path, as a string.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 bcompiler_write_file() example

<?php
$fh 
fopen("example.phb""w");
bcompiler_write_header($fh);
bcompiler_write_file($fh"example.php");
bcompiler_write_footer($fh);
fclose($fh);
/* the following should be equivalent:
include "example.php";
   and
include "example.phb";
*/
?>

주의

Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

참고




bcompiler_write_function

(PECL bcompiler >= 0.5)

bcompiler_write_functionWrites an defined function as bytecodes

설명

bool bcompiler_write_function ( resource $filehandle , string $functionName )

Reads the bytecodes from PHP for an existing function, and writes them to the open file handle. Order is not important, (eg. if function b uses function a, and you compile it like the example below, it will work perfectly OK).

인수

filehandle

A file handle as returned by fopen().

functionName

The function name, as a string.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 bcompiler_write_function() example

<?php
$fh 
fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_function($fh,"my_function_a");
bcompiler_write_function($fh,"my_function_b");
bcompiler_write_footer($fh);
fclose($fh);

?>

주의

Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

참고



bcompiler_write_functions_from_file

(PECL bcompiler >= 0.5)

bcompiler_write_functions_from_fileWrites all functions defined in a file as bytecodes

설명

bool bcompiler_write_functions_from_file ( resource $filehandle , string $fileName )

Searches for all functions declared in the given file, and writes their correspondent bytecodes to the open file handle.

인수

filehandle

A file handle as returned by fopen().

fileName

The file to be compiled. You must always include or require the file you intend to compile.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 bcompiler_write_functions_from_file() example

<?php
require('module.php');

$fh fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_functions_from_file($fh,'module.php');
bcompiler_write_footer($fh);
fclose($fh);

?>

주의

Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

참고



bcompiler_write_header

(PECL bcompiler >= 0.3)

bcompiler_write_headerWrites the bcompiler header

설명

bool bcompiler_write_header ( resource $filehandle [, string $write_ver ] )

Writes the header part of a bcompiler file.

인수

filehandle

A file handle as returned by fopen().

write_ver

Can be used to write bytecode in a previously used format, so that you can use it with older versions of bcompiler.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 bcompiler_write_header() example

<?php
$fh 
fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
bcompiler_write_footer($fh);
fclose($fh);

?>

주의

Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

참고



bcompiler_write_included_filename

(PECL bcompiler >= 0.5)

bcompiler_write_included_filenameWrites an included file as bytecodes

설명

bool bcompiler_write_included_filename ( resource $filehandle , string $filename )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

주의

Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.


Table of Contents




Error Handling and Logging


소개

These are functions dealing with error handling and logging. They allow you to define your own error handling rules, as well as modify the way the errors can be logged. This allows you to change and enhance error reporting to suit your needs.

With the logging functions, you can send messages directly to other machines, to an email (or email to pager gateway!), to system logs, etc., so you can selectively log and monitor the most important parts of your applications and websites.

The error reporting functions allow you to customize what level and kind of error feedback is given, ranging from simple notices to customized functions returned during errors.



설치/설정

Table of Contents


요구 조건

이 확장을 빌드할 때 외부 라이브러리가 필요하지 않습니다.



설치

이 함수들은 설치하지 않아도 사용할 수 있습니다; PHP 코어의 일부입니다.



실행시 설정

이 함수의 작동은 php.ini 설정에 영향을 받습니다.

Errors and Logging Configuration Options
Name Default Changeable Changelog
error_reporting NULL PHP_INI_ALL  
display_errors "1" PHP_INI_ALL  
display_startup_errors "0" PHP_INI_ALL  
log_errors "0" PHP_INI_ALL  
log_errors_max_len "1024" PHP_INI_ALL Available since PHP 4.3.0.
ignore_repeated_errors "0" PHP_INI_ALL Available since PHP 4.3.0.
ignore_repeated_source "0" PHP_INI_ALL Available since PHP 4.3.0.
report_memleaks "1" PHP_INI_ALL Available since PHP 4.3.0.
track_errors "0" PHP_INI_ALL  
html_errors "1" PHP_INI_ALL PHP_INI_SYSTEM in PHP <= 4.2.3.
xmlrpc_errors "0" PHP_INI_SYSTEM Available since PHP 4.1.0.
xmlrpc_error_number "0" PHP_INI_ALL Available since PHP 4.1.0.
docref_root "" PHP_INI_ALL Available since PHP 4.3.0.
docref_ext "" PHP_INI_ALL Available since PHP 4.3.2.
error_prepend_string NULL PHP_INI_ALL  
error_append_string NULL PHP_INI_ALL  
error_log NULL PHP_INI_ALL  

PHP_INI_* 모드에 대한 상세와 정의는 환경 설정을 바꿀 수 있는 곳를 참고하십시오.

위 설정 지시어에 대한 간단한 설명입니다.

error_reporting integer

Set the error reporting level. The parameter is either an integer representing a bit field, or named constants. The error_reporting levels and constants are described in Predefined Constants, and in php.ini. To set at runtime, use the error_reporting() function. See also the display_errors directive.

In PHP 4 and PHP 5 the default value is E_ALL & ~E_NOTICE. This setting does not show E_NOTICE level errors. You may want to show them during development.

Note: Enabling E_NOTICE during development has some benefits. For debugging purposes: NOTICE messages will warn you about possible bugs in your code. For example, use of unassigned values is warned. It is extremely useful to find typos and to save time for debugging. NOTICE messages will warn you about bad style. For example, $arr[item] is better to be written as $arr['item'] since PHP tries to treat "item" as constant. If it is not a constant, PHP assumes it is a string index for the array.

Note: In PHP 5 a new error level E_STRICT is available. As E_STRICT is not included within E_ALL you have to explicitly enable this kind of error level. Enabling E_STRICT during development has some benefits. STRICT messages will help you to use the latest and greatest suggested method of coding, for example warn you about using deprecated functions.

Note: PHP Constants outside of PHP
Using PHP Constants outside of PHP, like in httpd.conf, will have no useful meaning so in such cases the integer values are required. And since error levels will be added over time, the maximum value (for E_ALL) will likely change. So in place of E_ALL consider using a larger value to cover all bit fields from now and well into the future, a numeric value like 2147483647.

display_errors string

This determines whether errors should be printed to the screen as part of the output or if they should be hidden from the user.

Value "stderr" sends the errors to stderr instead of stdout. The value is available as of PHP 5.2.4. In earlier versions, this directive was of type boolean.

Note: This is a feature to support your development and should never be used on production systems (e.g. systems connected to the internet).

Note: Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.

display_startup_errors boolean

Even when display_errors is on, errors that occur during PHP's startup sequence are not displayed. It's strongly recommended to keep display_startup_errors off, except for debugging.

log_errors boolean

Tells whether script error messages should be logged to the server's error log or error_log. This option is thus server-specific.

Note: You're strongly advised to use error logging in place of error displaying on production web sites.

log_errors_max_len integer

Set the maximum length of log_errors in bytes. In error_log information about the source is added. The default is 1024 and 0 allows to not apply any maximum length at all. This length is applied to logged errors, displayed errors and also to $php_errormsg.

integer 형이 사용될 때, 바이트로 값을 측정합니다. FAQ에 나와 있는 단축어를 사용할 수도 있습니다.
ignore_repeated_errors boolean

Do not log repeated messages. Repeated errors must occur in the same file on the same line unless ignore_repeated_source is set true.

ignore_repeated_source boolean

Ignore source of message when ignoring repeated messages. When this setting is On you will not log errors with repeated messages from different files or sourcelines.

report_memleaks boolean

If this parameter is set to Off, then memory leaks will not be shown (on stdout or in the log). This has only effect in a debug compile, and if error_reporting includes E_WARNING in the allowed list

track_errors boolean

If enabled, the last error message will always be present in the variable $php_errormsg.

html_errors boolean

Turn off HTML tags in error messages. The new format for HTML errors produces clickable messages that direct the user to a page describing the error or function in causing the error. These references are affected by docref_root and docref_ext.

xmlrpc_errors boolean

Turns off normal error reporting and formats errors as XML-RPC error message.

xmlrpc_error_number integer

Used as the value of the XML-RPC faultCode element.

docref_root string

The new error format contains a reference to a page describing the error or function causing the error. In case of manual pages you can download the manual in your language and set this ini directive to the URL of your local copy. If your local copy of the manual can be reached by "/manual/" you can simply use docref_root=/manual/ . Additional you have to set docref_ext to match the fileextensions of your copy docref_ext=.html . It is possible to use external references. For example you can use docref_root=http://manual/en/ or docref_root="http://landonize.it/?how=url&theme=classic&filter=Landon &url=http%3A%2F%2Fwww.php.net%2F"

Most of the time you want the docref_root value to end with a slash "/". But see the second example above which does not have nor need it.

Note: This is a feature to support your development since it makes it easy to lookup a function description. However it should never be used on production systems (e.g. systems connected to the internet).

docref_ext string

See docref_root.

Note: The value of docref_ext must begin with a dot ".".

error_prepend_string string

String to output before an error message.

error_append_string string

String to output after an error message.

error_log string

Name of the file where script errors should be logged. The file should be writable by the web server's user. If the special value syslog is used, the errors are sent to the system logger instead. On Unix, this means syslog(3) and on Windows NT it means the event log. The system logger is not supported on Windows 95. See also: syslog(). If this directive is not set, errors are sent to the SAPI error logger. For example, it is an error log in Apache or stderr in CLI.



자원형

이 확장은 리소스형을 정의하지 않습니다.




예약 상수

아래 상수들은 PHP 코어의 일부로, 항상 사용할 수 있습니다.

Note: You may use these constant names in php.ini but not outside of PHP, like in httpd.conf, where you'd use the bitmask values instead.

Errors and Logging
Value Constant Description Note
1 E_ERROR (integer) Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted.  
2 E_WARNING (integer) Run-time warnings (non-fatal errors). Execution of the script is not halted.  
4 E_PARSE (integer) Compile-time parse errors. Parse errors should only be generated by the parser.  
8 E_NOTICE (integer) Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script.  
16 E_CORE_ERROR (integer) Fatal errors that occur during PHP's initial startup. This is like an E_ERROR, except it is generated by the core of PHP. since PHP 4
32 E_CORE_WARNING (integer) Warnings (non-fatal errors) that occur during PHP's initial startup. This is like an E_WARNING, except it is generated by the core of PHP. since PHP 4
64 E_COMPILE_ERROR (integer) Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine. since PHP 4
128 E_COMPILE_WARNING (integer) Compile-time warnings (non-fatal errors). This is like an E_WARNING, except it is generated by the Zend Scripting Engine. since PHP 4
256 E_USER_ERROR (integer) User-generated error message. This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error(). since PHP 4
512 E_USER_WARNING (integer) User-generated warning message. This is like an E_WARNING, except it is generated in PHP code by using the PHP function trigger_error(). since PHP 4
1024 E_USER_NOTICE (integer) User-generated notice message. This is like an E_NOTICE, except it is generated in PHP code by using the PHP function trigger_error(). since PHP 4
2048 E_STRICT (integer) Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. since PHP 5
4096 E_RECOVERABLE_ERROR (integer) Catchable fatal error. It indicates that a probably dangerous error occured, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle (see also set_error_handler()), the application aborts as it was an E_ERROR. since PHP 5.2.0
8192 E_DEPRECATED (integer) Run-time notices. Enable this to receive warnings about code that will not work in future versions. since PHP 5.3.0
16384 E_USER_DEPRECATED (integer) User-generated warning message. This is like an E_DEPRECATED, except it is generated in PHP code by using the PHP function trigger_error(). since PHP 5.3.0
30719 E_ALL (integer) All errors and warnings, as supported, except of level E_STRICT in PHP < 6. 32767 in PHP 6, 30719 in PHP 5.3.x, 6143 in PHP 5.2.x, 2047 previously

The above values (either numerical or symbolic) are used to build up a bitmask that specifies which errors to report. You can use the bitwise operators to combine these values or mask out certain types of errors. Note that only '|', '~', '!', '^' and '&' will be understood within php.ini.



예제

Below we can see an example of using the error handling capabilities in PHP. We define an error handling function which logs the information into a file (using an XML format), and e-mails the developer in case a critical error in the logic happens.

Example #1 Using error handling in a script

<?php
// we will do our own error handling
error_reporting(0);

// user defined error handling function
function userErrorHandler($errno$errmsg$filename$linenum$vars
{
    
// timestamp for the error entry
    
$dt date("Y-m-d H:i:s (T)");

    
// define an assoc array of error string
    // in reality the only entries we should
    // consider are E_WARNING, E_NOTICE, E_USER_ERROR,
    // E_USER_WARNING and E_USER_NOTICE
    
$errortype = array (
                
E_ERROR              => 'Error',
                
E_WARNING            => 'Warning',
                
E_PARSE              => 'Parsing Error',
                
E_NOTICE             => 'Notice',
                
E_CORE_ERROR         => 'Core Error',
                
E_CORE_WARNING       => 'Core Warning',
                
E_COMPILE_ERROR      => 'Compile Error',
                
E_COMPILE_WARNING    => 'Compile Warning',
                
E_USER_ERROR         => 'User Error',
                
E_USER_WARNING       => 'User Warning',
                
E_USER_NOTICE        => 'User Notice',
                
E_STRICT             => 'Runtime Notice',
                
E_RECOVERABLE_ERROR  => 'Catchable Fatal Error'
                
);
    
// set of errors for which a var trace will be saved
    
$user_errors = array(E_USER_ERRORE_USER_WARNINGE_USER_NOTICE);
    
    
$err "<errorentry>\n";
    
$err .= "\t<datetime>" $dt "</datetime>\n";
    
$err .= "\t<errornum>" $errno "</errornum>\n";
    
$err .= "\t<errortype>" $errortype[$errno] . "</errortype>\n";
    
$err .= "\t<errormsg>" $errmsg "</errormsg>\n";
    
$err .= "\t<scriptname>" $filename "</scriptname>\n";
    
$err .= "\t<scriptlinenum>" $linenum "</scriptlinenum>\n";

    if (
in_array($errno$user_errors)) {
        
$err .= "\t<vartrace>" wddx_serialize_value($vars"Variables") . "</vartrace>\n";
    }
    
$err .= "</errorentry>\n\n";
    
    
// for testing
    // echo $err;

    // save to the error log, and e-mail me if there is a critical user error
    
error_log($err3"/usr/local/php4/error.log");
    if (
$errno == E_USER_ERROR) {
        
mail("phpdev@example.com""Critical User Error"$err);
    }
}


function 
distance($vect1$vect2
{
    if (!
is_array($vect1) || !is_array($vect2)) {
        
trigger_error("Incorrect parameters, arrays expected"E_USER_ERROR);
        return 
NULL;
    }

    if (
count($vect1) != count($vect2)) {
        
trigger_error("Vectors need to be of the same size"E_USER_ERROR);
        return 
NULL;
    }

    for (
$i=0$i<count($vect1); $i++) {
        
$c1 $vect1[$i]; $c2 $vect2[$i];
        
$d 0.0;
        if (!
is_numeric($c1)) {
            
trigger_error("Coordinate $i in vector 1 is not a number, using zero"
                            
E_USER_WARNING);
            
$c1 0.0;
        }
        if (!
is_numeric($c2)) {
            
trigger_error("Coordinate $i in vector 2 is not a number, using zero"
                            
E_USER_WARNING);
            
$c2 0.0;
        }
        
$d += $c2*$c2 $c1*$c1;
    }
    return 
sqrt($d);
}

$old_error_handler set_error_handler("userErrorHandler");

// undefined constant, generates a warning
$t I_AM_NOT_DEFINED;

// define some "vectors"
$a = array(23"foo");
$b = array(5.54.3, -1.6);
$c = array(1, -3);

// generate a user error
$t1 distance($c$b) . "\n";

// generate another user error
$t2 distance($b"i am not an array") . "\n";

// generate a warning
$t3 distance($a$b) . "\n";

?>



Error Handling 함수 목록

참고

See also syslog().


debug_backtrace

(PHP 4 >= 4.3.0, PHP 5)

debug_backtraceGenerates a backtrace

설명

array debug_backtrace ([ bool $provide_object= true ] )

debug_backtrace() generates a PHP backtrace.

인수

provide_object

Whether or not to populate the "object" index. Defaults to TRUE.

반환값

Returns an associative array. The possible returned elements are as follows:

Possible returned elements from debug_backtrace()
이름 자료형 설명
function string The current function name. See also __FUNCTION__.
line integer The current line number. See also __LINE__.
file string The current file name. See also __FILE__.
class string The current class name. See also __CLASS__
object object The current object.
type string The current call type. If a method call, "->" is returned. If a static method call, "::" is returned. If a function call, nothing is returned.
args array If inside a function, this lists the functions arguments. If inside an included file, this lists the included file name(s).

변경점

버전 설명
5.2.5 Added the optional parameter provide_object .
5.1.1 Added the current object as a possible return element.

예제

Example #1 debug_backtrace() example

<?php
// filename: /tmp/a.php

function a_test($str)
{
    echo 
"\nHi: $str";
    
var_dump(debug_backtrace());
}

a_test('friend');
?>

<?php
// filename: /tmp/b.php
include_once '/tmp/a.php';
?>

Results similar to the following when executing /tmp/b.php:

Hi: friend
array(2) {
[0]=>
array(4) {
    ["file"] => string(10) "/tmp/a.php"
    ["line"] => int(10)
    ["function"] => string(6) "a_test"
    ["args"]=>
    array(1) {
      [0] => &string(6) "friend"
    }
}
[1]=>
array(4) {
    ["file"] => string(10) "/tmp/b.php"
    ["line"] => int(2)
    ["args"] =>
    array(1) {
      [0] => string(10) "/tmp/a.php"
    }
    ["function"] => string(12) "include_once"
  }
}

참고



debug_print_backtrace

(PHP 5)

debug_print_backtrace Prints a backtrace

설명

void debug_print_backtrace ( void )

debug_print_backtrace() prints a PHP backtrace. It prints the function calls, included/required files and eval()ed stuff.

인수

This function has no parameters.

반환값

값을 반환하지 않습니다.

예제

Example #1 debug_print_backtrace() example

<?php
// include.php file

function a() {
    
b();
}

function 
b() {
    
c();
}

function 
c(){
    
debug_print_backtrace();
}

a();

?>
<?php
// test.php file
// this is the file you should run

include 'include.php';
?>

위 예제의 출력 예시:

#0  eval() called at [/tmp/include.php:5]
#1  a() called at [/tmp/include.php:17]
#2  include(/tmp/include.php) called at [/tmp/test.php:3]

#0  c() called at [/tmp/include.php:10]
#1  b() called at [/tmp/include.php:6]
#2  a() called at [/tmp/include.php:17]
#3  include(/tmp/include.php) called at [/tmp/test.php:3]

참고



error_get_last

(PHP 5 >= 5.2.0)

error_get_lastGet the last occurred error

설명

array error_get_last ( void )

Gets information about the last error that occurred.

반환값

Returns an associative array describing the last error with keys "type", "message", "file" and "line". Returns NULL if there hasn't been an error yet.

예제

Example #1 An error_get_last() example

<?php
echo $a;
print_r(error_get_last());
?>

위 예제의 출력 예시:

Array
(
    [type] => 8
    [message] => Undefined variable: a
    [file] => C:\WWW\index.php
    [line] => 2
)



error_log

(PHP 4, PHP 5)

error_logSend an error message somewhere

설명

bool error_log ( string $message [, int $message_type= 0 [, string $destination [, string $extra_headers ]]] )

Sends an error message to the web server's error log, a TCP port or to a file.

인수

message

The error message that should be logged.

message_type

Says where the error should go. The possible message types are as follows:

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. This is the default option.
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.
2 No longer an option.
3 message is appended to the file destination . A newline is not automatically added to the end of the message string.
4 message is sent directly to the SAPI logging handler.

destination

The destination. Its meaning depends on the message_type parameter as described above.

extra_headers

The extra headers. It's used when the message_type parameter is set to 1. This message type uses the same internal function as mail() does.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

변경점

버전 설명
5.2.7 The possible value of 4 was added to message_type .

예제

Example #1 error_log() examples

<?php
// 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@example.com");
}

// another way to call error_log():
error_log("You messed up!"3"/var/tmp/my-errors.log");
?>



error_reporting

(PHP 4, PHP 5)

error_reportingSets which PHP errors are reported

설명

int error_reporting ([ int $level ] )

The error_reporting() function sets the error_reporting directive at runtime. PHP has many levels of errors, using this function sets that level for the duration (runtime) of your script.

인수

level

The new error_reporting level. It takes on either a bitmask, or named constants. Using named constants is strongly encouraged to ensure compatibility for future versions. As error levels are added, the range of integers increases, so older integer-based error levels will not always behave as expected.

The available error level constants and the actual meanings of these error levels are described in the predefined constants.

반환값

Returns the old error_reporting level.

변경점

버전 설명
5.0.0 E_STRICT introduced (not part of E_ALL).
5.2.0 E_RECOVERABLE_ERROR introduced.
5.3.0 E_DEPRECATED and E_USER_DEPRECATED introduced.
6.0.0 E_STRICT became part of E_ALL.

예제

Example #1 error_reporting() examples

<?php

// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR E_WARNING E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR E_WARNING E_PARSE E_NOTICE);

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL E_NOTICE);

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting'E_ALL);

?>

주의

Warning

Most of E_STRICT errors are evaluated at the compile time thus such errors are not reported in the file where error_reporting is enhanced to include E_STRICT errors (and vice versa).

Tip

Passing in the value -1 will show every possible error, even when new levels and constants are added in future PHP versions. The E_ALL constant also behaves this way as of PHP 6.

참고



restore_error_handler

(PHP 4 >= 4.0.1, PHP 5)

restore_error_handlerRestores the previous error handler function

설명

bool restore_error_handler ( void )

Used after changing the error handler function using set_error_handler(), to revert to the previous error handler (which could be the built-in or a user defined function).

반환값

This function always returns TRUE.

예제

Example #1 restore_error_handler() example

Decide if unserialize() caused an error, then restore the original error handler.

<?php
function unserialize_handler($errno$errstr)
{
    echo 
"Invalid serialized value.\n";
}

$serialized 'foo';
set_error_handler('unserialize_handler');
$original unserialize($serialized);
restore_error_handler();
?>

위 예제의 출력:

Invalid serialized value.

주의

Note: Calling restore_error_handler() from the error_handler function is ignored.

참고



restore_exception_handler

(PHP 5)

restore_exception_handler Restores the previously defined exception handler function

설명

bool restore_exception_handler ( void )

Used after changing the exception handler function using set_exception_handler(), to revert to the previous exception handler (which could be the built-in or a user defined function).

반환값

This function always returns TRUE.

예제

Example #1 restore_exception_handler() example

<?php
    
function exception_handler_1(Exception $e)
    {
        echo 
'[' __FUNCTION__ '] ' $e->getMessage();
    }

    function 
exception_handler_2(Exception $e)
    {
        echo 
'[' __FUNCTION__ '] ' $e->getMessage();
    }

    
set_exception_handler('exception_handler_1');
    
set_exception_handler('exception_handler_2');

    
restore_exception_handler();

    throw new 
Exception('This triggers the first exception handler...');
?>

위 예제의 출력:

[exception_handler_1] This triggers the first exception handler...

참고



set_error_handler

(PHP 4 >= 4.0.1, PHP 5)

set_error_handlerSets a user-defined error handler function

설명

mixed set_error_handler ( callback $error_handler [, int $error_types= E_ALL | E_STRICT ] )

Sets a user function (error_handler ) to handle errors in a script.

This function can be used for defining your own way of handling errors during runtime, for example in applications in which you need to do cleanup of data/files when a critical error happens, or when you need to trigger an error under certain conditions (using trigger_error()).

It is important to remember that the standard PHP error handler is completely bypassed. error_reporting() settings will have no effect and your error handler will be called regardless - however you are still able to read the current value of error_reporting and act appropriately. Of particular note is that this value will be 0 if the statement that caused the error was prepended by the @ error-control operator.

Also note that it is your responsibility to die() if necessary. If the error-handler function returns, script execution will continue with the next statement after the one that caused an error.

The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.

If errors occur before the script is executed (e.g. on file uploads) the custom error handler cannot be called since it is not registered at that time.

인수

error_handler

The user function needs to accept two parameters: the error code, and a string describing the error. Then there are three optional parameters that may be supplied: the filename in which the error occurred, the line number in which the error occurred, and the context in which the error occurred (an array that points to the active symbol table at the point the error occurred). The function can be shown as:

handler ( int $errno , string $errstr [, string $errfile [, int $errline [, array $errcontext ]]] )

errno
The first parameter, errno , contains the level of the error raised, as an integer.
errstr
The second parameter, errstr , contains the error message, as a string.
errfile
The third parameter is optional, errfile , which contains the filename that the error was raised in, as a string.
errline
The fourth parameter is optional, errline , which contains the line number the error was raised at, as an integer.
errcontext
The fifth parameter is optional, errcontext , which is an array that points to the active symbol table at the point the error occurred. In other words, errcontext will contain an array of every variable that existed in the scope the error was triggered in. User error handler must not modify error context.

If the function returns FALSE then the normal error handler continues.

error_types

Can be used to mask the triggering of the error_handler function just like the error_reporting ini setting controls which errors are shown. Without this mask set the error_handler will be called for every error regardless to the setting of the error_reporting setting.

반환값

Returns a string containing the previously defined error handler (if any). If the built-in error handler is used NULL is returned. NULL is also returned in case of an error such as an invalid callback. If the previous error handler was a class method, this function will return an indexed array with the class and the method name.

변경점

버전 설명
5.2.0 The error handler must return FALSE to populate $php_errormsg.
5.0.0 The error_types parameter was introduced.
4.3.0 Instead of a function name, an array containing an object reference and a method name can also be supplied as the error_handler .
4.0.2 Three optional parameters for the error_handler user function was introduced. These are the filename, the line number, and the context.

예제

Example #1 Error handling with set_error_handler() and trigger_error()

The example below shows the handling of internal exceptions by triggering errors and handling them with a user defined function:

<?php
// error handler function
function myErrorHandler($errno$errstr$errfile$errline)
{
    switch (
$errno) {
    case 
E_USER_ERROR:
        echo 
"<b>My ERROR</b> [$errno$errstr<br />\n";
        echo 
"  Fatal error on line $errline in file $errfile";
        echo 
", PHP " PHP_VERSION " (" PHP_OS ")<br />\n";
        echo 
"Aborting...<br />\n";
        exit(
1);
        break;

    case 
E_USER_WARNING:
        echo 
"<b>My WARNING</b> [$errno$errstr<br />\n";
        break;

    case 
E_USER_NOTICE:
        echo 
"<b>My NOTICE</b> [$errno$errstr<br />\n";
        break;

    default:
        echo 
"Unknown error type: [$errno$errstr<br />\n";
        break;
    }

    
/* Don't execute PHP internal error handler */
    
return true;
}

// function to test the error handling
function scale_by_log($vect$scale)
{
    if (!
is_numeric($scale) || $scale <= 0) {
        
trigger_error("log(x) for x <= 0 is undefined, you used: scale = $scale"E_USER_ERROR);
    }

    if (!
is_array($vect)) {
        
trigger_error("Incorrect input vector, array of values expected"E_USER_WARNING);
        return 
null;
    }

    
$temp = array();
    foreach(
$vect as $pos => $value) {
        if (!
is_numeric($value)) {
            
trigger_error("Value at position $pos is not a number, using 0 (zero)"E_USER_NOTICE);
            
$value 0;
        }
        
$temp[$pos] = log($scale) * $value;
    }

    return 
$temp;
}

// set to the user defined error handler
$old_error_handler set_error_handler("myErrorHandler");

// trigger some errors, first define a mixed array with a non-numeric item
echo "vector a\n";
$a = array(23"foo"5.543.321.11);
print_r($a);

// now generate second array
echo "----\nvector b - a notice (b = log(PI) * a)\n";
/* Value at position $pos is not a number, using 0 (zero) */
$b scale_by_log($aM_PI);
print_r($b);

// this is trouble, we pass a string instead of an array
echo "----\nvector c - a warning\n";
/* Incorrect input vector, array of values expected */
$c scale_by_log("not array"2.3);
var_dump($c); // NULL

// this is a critical error, log of zero or negative number is undefined
echo "----\nvector d - fatal error\n";
/* log(x) for x <= 0 is undefined, you used: scale = $scale" */
$d scale_by_log($a, -2.5);
var_dump($d); // Never reached
?>

위 예제의 출력 예시:

vector a
Array
(
    [0] => 2
    [1] => 3
    [2] => foo
    [3] => 5.5
    [4] => 43.3
    [5] => 21.11
)
----
vector b - a notice (b = log(PI) * a)
<b>My NOTICE</b> [1024] Value at position 2 is not a number, using 0 (zero)<br />
Array
(
    [0] => 2.2894597716988
    [1] => 3.4341896575482
    [2] => 0
    [3] => 6.2960143721717
    [4] => 49.566804057279
    [5] => 24.165247890281
)
----
vector c - a warning
<b>My WARNING</b> [512] Incorrect input vector, array of values expected<br />
NULL
----
vector d - fatal error
<b>My ERROR</b> [256] log(x) for x <= 0 is undefined, you used: scale = -2.5<br />
  Fatal error on line 35 in file trigger_error.php, PHP 5.2.1 (FreeBSD)<br />
Aborting...<br />

참고



set_exception_handler

(PHP 5)

set_exception_handler Sets a user-defined exception handler function

설명

string set_exception_handler ( callback $exception_handler )

Sets the default exception handler if an exception is not caught within a try/catch block. Execution will stop after the exception_handler is called.

인수

exception_handler

Name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler(). This handler function needs to accept one parameter, which will be the exception object that was thrown.

반환값

Returns the name of the previously defined exception handler, or NULL on error. If no previous handler was defined, NULL is also returned.

예제

Example #1 set_exception_handler() example

<?php
function exception_handler($exception) {
  echo 
"Uncaught exception: " $exception->getMessage(), "\n";
}

set_exception_handler('exception_handler');

throw new 
Exception('Uncaught Exception');
echo 
"Not Executed\n";
?>

참고



trigger_error

(PHP 4 >= 4.0.1, PHP 5)

trigger_errorGenerates a user-level error/warning/notice message

설명

bool trigger_error ( string $error_msg [, int $error_type= E_USER_NOTICE ] )

Used to trigger a user error condition, it can be used by in conjunction with the built-in error handler, or with a user defined function that has been set as the new error handler (set_error_handler()).

This function is useful when you need to generate a particular response to an exception at runtime.

인수

error_msg

The designated error message for this error. It's limited to 1024 characters in length. Any additional characters beyond 1024 will be truncated.

error_type

The designated error type for this error. It only works with the E_USER family of constants, and will default to E_USER_NOTICE.

반환값

This function returns FALSE if wrong error_type is specified, TRUE otherwise.

예제

Example #1 trigger_error() example

See set_error_handler() for a more extensive example.

<?php
if (assert($divisor == 0)) {
    
trigger_error("Cannot divide by zero"E_USER_ERROR);
}
?>

참고



user_error

(PHP 4, PHP 5)

user_errorAlias of trigger_error()

설명

이 함수는 다음 함수의 별칭입니다: trigger_error().


Table of Contents




htaccess-like support for all SAPIs


소개

The htscanner extension gives the possibility to use htaccess-like file to configure PHP per directory, just like apache's htaccess. It is especially useful with fastcgi (ISS5/6/7, lighttpd, etc.).



설치/설정

Table of Contents


요구 조건

PHP version 5.2.0 or greater.



설치

PECL 확장 설치에 관한 정보는 매뉴얼의 PECL 확장 설치에 있습니다. 새 릴리즈, 내려받기, 소스파일, 개발자 정보, CHANGELOG 등의 추가 정보는 여기에 있습니다: » http://pecl.php.net/package/htscanner



실행시 설정

이 함수의 작동은 php.ini 설정에 영향을 받습니다.

htscanner 설정 옵션
이름 기본값 가변성 Changelog
htscanner.config_file ".htscanner" PHP_INI_SYSTEM  
htscanner.default_docroot "/" PHP_INI_SYSTEM  
htscanner.default_ttl "300" PHP_INI_SYSTEM  
htscanner."stop_on_error" "Off" PHP_INI_SYSTEM  

PHP_INI_* 모드에 대한 상세와 정의는 환경 설정을 바꿀 수 있는 곳를 참고하십시오.

위 설정 지시어에 대한 간단한 설명입니다.

htscanner.config_file string

Filename to use as configuration file.

htscanner.default_docroot string

Default document root.

htscanner.default_ttl int

Cache time out for the configuration data, in seconds.

htscanner.stop_on_error int

Stop on error (parse error, cannot set an ini setting).



자원형

이 확장은 리소스형을 정의하지 않습니다.





Inclusion hierarchy viewer


소개

Traces through and dumps the hierarchy of file inclusions and class inheritance at runtime.

The files may have been included using include(), include_once(), require(), or require_once().

Class inheritance dependencies are also reported.



설치/설정

Table of Contents


요구 조건

PHP version 5.1.0 or greater.

The included gengraph.php file utilizes the » graphviz library, however, this is not required.



설치

PECL 확장 설치에 관한 정보는 매뉴얼의 PECL 확장 설치에 있습니다. 새 릴리즈, 내려받기, 소스파일, 개발자 정보, CHANGELOG 등의 추가 정보는 여기에 있습니다: » http://pecl.php.net/package/inclued



실행시 설정

이 함수의 작동은 php.ini 설정에 영향을 받습니다.

inclued 설정 옵션
이름 기본값 가변성 Changelog
inclued.enabled Off PHP_INI_*  
inclued.dumpdir Off PHP_INI_*  

PHP_INI_* 모드에 대한 상세와 정의는 환경 설정을 바꿀 수 있는 곳를 참고하십시오.

위 설정 지시어에 대한 간단한 설명입니다.

inclued.enabled int

Whether or not to enable inclued.

inclued.dumpdir int

Location (path) to the directory that stores inclued files. If set, each PHP request will create a file.

Caution

Because every request creates a file, this directory may fill up fast!



자원형

이 확장은 리소스형을 정의하지 않습니다.




예약 상수

이 확장은 다음의 상수들을 정의합니다. 이 확장을 PHP에 내장했거나, 실행시에 동적으로 읽어들일 경우에만 사용할 수 있습니다.

이 확장은 상수를 정의하지 않습니다.



예제

Table of Contents


Example that implements inclued into an application

This example demonstrates the process of implementing inclued into an existing application, and viewing the results.

Example #1 Getting the data from inclued

<?php
// File to store the inclued information
$fp fopen('/tmp/wp.json''w');
if (
$fp) {
    
$clue inclued_get_data();
    if (
$clue) {
        
fwrite($fpjson_encode($clue));
    }
    
fclose($fp);
}
?>

Now that some data exists, it's time to make sense of it in the form of a graph. The inclued extension includes a PHP file named gengraph.php that creates a dot file that requires the » graphviz library. However, this form is not required.

Example #2 Example use of gengraph.php

This example creates an image named inclued.png that shows the inclued data.

# First, create the dot file
$ php graphviz.php -i /tmp/wp.json -o wp.dot

# Next, create the image
$ dot -Tpng -o inclued.png wp.dot




inclued 함수 목록


inclued_get_data

(PECL inclued >= 0.1.0)

inclued_get_dataGet the inclued data

설명

array inclued_get_data ( void )

Get the inclued data.

인수

이 함수는 인수가 없습니다.

반환값

The inclued data.

예제

Example #1 inclued_get_data() example

See the inclued examples section for ways to create a graphs with this data.

<?php 
include 'x.php';

$clue inclued_get_data();

print_r($clue);
?>

위 예제의 출력 예시:

Array
(
  [includes] => Array
    (
      [0] => Array
        (
          [operation] => include
          [op_type] => 2
          [filename] => x.php
          [opened_path] => /tmp/x.php
          [fromfile] => /tmp/z.php
          [fromline] => 2
        )
    )
)

참고


Table of Contents




PHP Options and Information


소개

This functions enable you to get a lot of information about PHP itself, e.g. runtime configuration, loaded extensions, version and much more. You'll also find functions to set options for your running PHP. The probably best known function of PHP - phpinfo() - can be found here.



설치/설정

Table of Contents


요구 조건

이 확장을 빌드할 때 외부 라이브러리가 필요하지 않습니다.



설치

이 함수들은 설치하지 않아도 사용할 수 있습니다; PHP 코어의 일부입니다.



실행시 설정

이 함수의 작동은 php.ini 설정에 영향을 받습니다.

PHP 옵션/정보 설정 옵션
이름 기본값 설정권한 변경점
assert.active "1" PHP_INI_ALL  
assert.bail "0" PHP_INI_ALL  
assert.warning "1" PHP_INI_ALL  
assert.callback NULL PHP_INI_ALL  
assert.quiet_eval "0" PHP_INI_ALL  
enable_dl "1" PHP_INI_SYSTEM PHP 6.0.0에서 제거.
max_execution_time "30" PHP_INI_ALL  
max_input_time "-1" PHP_INI_PERDIR PHP 4.3.0부터 사용할 수 있습니다.
max_input_nesting_level "64" PHP_INI_SYSTEM|PHP_INI_PERDIR PHP 4.4.8부터 가능. PHP 5.0.0에서 제거.
magic_quotes_gpc "1" PHP_INI_PERDIR PHP <=4.2.3에서 PHP_INI_ALL. PHP 6.0.0에서 제거.
magic_quotes_runtime "0" PHP_INI_ALL PHP 6.0.0에서 제거.
zend.enable_gc "1" PHP_INI_ALL PHP 5.3.0부터 사용할 수 있습니다.

PHP_INI_* 모드에 대한 상세와 정의는 환경 설정을 바꿀 수 있는 곳를 참고하십시오.

위 설정 지시어에 대한 간단한 설명입니다.

assert.active boolean

assert() 평가를 활성화합니다.

assert.bail boolean

assertion 실패시에 스크립트 실행을 종료합니다.

assert.warning boolean

실패하는 assertion마다 PHP 경고를 발생합니다.

assert.callback string

assertion 실패시에 호출할 사용자 함수.

assert.quiet_eval boolean

assertion 표현 평가 중에 error_reporting()의 현재 설정을 사용합니다. 활성화하면, 평가 도중에 에러가 보여지지 않습니다. (error_reporting(0)에 상당) 비활성화하면, 에러는 error_reporting() 설정에 따라 보여집니다.

enable_dl boolean

이 지시어는 PHP의 아파치 모듈 버전에서만 유용합니다. dl()로 PHP 확장 모듈을 동적으로 읽어들일 수 있는지 여부를, 가상 서버나 디렉토리 단위로 설정할 수 있습니다.

동적 로딩을 끄는 주 이유는 보안입니다. 동적 로딩으로, 모든 open_basedir 제한을 무시할 수 있습니다. 기본값은 안전 모드를 사용할 때를 제외하고 동적 로딩을 허용합니다. 안전 모드에서는 항상 dl()을 사용할 수 없습니다.

max_execution_time integer

스크립트가 실행할 수 있는 최대 시간을 설정합니다. 이는 잘못 쓰여진 스크립트가 서버를 멈추는 것을 방지합니다. 기본값은 30입니다. PHP를 명령줄에서 실행할 때 기본값은 0입니다.

최대 실행 시간은 시스템 호출, 스트림 작업 등에는 영향을 받지 않습니다. 자세한 내용은 set_time_limit()를 참고하십시오.

안전 모드로 실행할 때는 이 설정을 ini_set()으로 변경할 수 없습니다. 안전 모드를 끄거나 php.ini에서 시간 제한을 변경해야 합니다.

웹 서버가 다른 시간 초과 설정을 가져서, PHP 실행을 중단할 수 있습니다. 아파치는 Timeout 지시어가 있고, IIS는 CGI timeout 함수가 있습니다. 둘 다 기본값은 300초입니다. 자세한 사항은 웹 서버 문서를 참고하십시오.

max_input_time integer

POST, GET, 파일 업로드 등의 입력 데이터 처리에 허용하는 최대 시간을 설정합니다.

max_input_nesting_level integer

입력 변수(즉, $_GET, $_POST..)의 최대 중첩 깊이를 설정합니다.

magic_quotes_gpc boolean
Warning

이 기능은 PHP 5.3.0부터 배제되고 PHP 6.0.0부터 제거됩니다. 이 기능에 의존하지 않기를 권합니다.

GPC (Get/Post/쿠키) 작동의 magic_quotes 상태를 설정합니다. magic_quotes가 on이면, 모든 ' (작은 따옴표), " (큰 따옴표), \ (백슬래시), NUL은 자동적으로 백슬래시로 이스케이프됩니다.

Note: PHP 4에서는 $_ENV도 이스케이프 되었습니다.

Note: magic_quotes_sybase 지시어도 ON이면 magic_quotes_gpc가 완전히 교체됩니다. 두 지시어를 모두 활성화하면 작은 따음표는 ''로 이스케이프합니다. 큰 따옴표, 백슬래시, NUL은 건들이지 않고, 이스케이프 하지 않습니다.

참고: get_magic_quotes_gpc()

magic_quotes_runtime boolean
Warning

이 기능은 PHP 5.3.0부터 배제되고 PHP 6.0.0부터 제거됩니다. 이 기능에 의존하지 않기를 권합니다.

magic_quotes_runtime 를 활성화하면, 데이터베이스나 텍스트 파일를 포함한, 어떠한 외부 소스에서 데이터를 가져오는 대부분의 함수는 백슬래시로 인용됩니다. magic_quotes-sybase도 on이면, 작은 따옴표는 백슬래시 대신 작은 따옴표로 이스케이프합니다.

zend.enable_gc boolean

순환 참조 수집기의 활성화 여부.



자원형

이 확장은 리소스형을 정의하지 않습니다.




예약 상수

아래 상수들은 PHP 코어의 일부로, 항상 사용할 수 있습니다.

Pre-defined phpcredits() constants
Constant Value Description
CREDITS_GROUP 1 A list of the core developers
CREDITS_GENERAL 2 General credits: Language design and concept, PHP authors and SAPI module.
CREDITS_SAPI 4 A list of the server API modules for PHP, and their authors.
CREDITS_MODULES 8 A list of the extension modules for PHP, and their authors.
CREDITS_DOCS 16 The credits for the documentation team.
CREDITS_FULLPAGE 32 Usually used in combination with the other flags. Indicates that a complete stand-alone HTML page needs to be printed including the information indicated by the other flags.
CREDITS_QA 64 The credits for the quality assurance team.
CREDITS_ALL -1 All the credits, equivalent to using: CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_QA CREDITS_FULLPAGE. It generates a complete stand-alone HTML page with the appropriate tags. This is the default value.
phpinfo() constants
Constant Value Description
INFO_GENERAL 1 The configuration line, php.ini location, build date, Web Server, System and more.
INFO_CREDITS 2 PHP Credits. See also phpcredits().
INFO_CONFIGURATION 4 Current Local and Master values for PHP directives. See also ini_get().
INFO_MODULES 8 Loaded modules and their respective settings.
INFO_ENVIRONMENT 16 Environment Variable information that's also available in $_ENV.
INFO_VARIABLES 32 Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server).
INFO_LICENSE 64 PHP License information. See also the » license faq.
INFO_ALL -1 Shows all of the above. This is the default value.

Assert constants, these values are used to set the assertion options in assert_options().

assert() constants
Constant INI Setting Description
ASSERT_ACTIVE assert.active Enable assert() evaluation.
ASSERT_CALLBACK assert.callback Callback to call on failed assertions.
ASSERT_BAIL assert.bail Terminate execution on failed assertions.
ASSERT_WARNING assert.warning Issues a PHP warning for each failed assertion
ASSERT_QUITE_EVAL assert.quiet_eval Disable error_reporting during assertion expression evaluation.

The following constants are only available if the host operating system is Windows, and can tell different versioning information so its possible to detect various features and make use of them. They are all available as of PHP 5.3.0.

Windows specific constants
Constant Description
PHP_WINDOWS_VERSION_MAJOR The major version of Windows, this can be either 4 (NT4/ME/98/95), 5 (XP/2003 R2/2003/2000) or 6 (Vista/2008).
PHP_WINDOWS_VERSION_MINOR The minor version of Windows, this can be either 0 (Vista/2008/2000/NT4/95), 1 (XP), 2 (2003 R2/2003/XP x64), 10 (98) or 90 (ME).
PHP_WINDOWS_VERSION_BUILD The Windows build number (for example, Windows Vista with SP1 applied is build 6001)
PHP_WINDOWS_VERSION_PLATFORM The platform that PHP currently is running on, this value is 2 on Windows Vista/XP/2000/NT4, Server 2008/2003 and on Windows ME/98/95 this value is 1.
PHP_WINDOWS_VERSION_SP_MAJOR The major version of the service pack installed, this value is 0 if no service pack is installed. For example, Windows XP with service pack 3 installed will make this value 3.
PHP_WINDOWS_VERSION_SP_MINOR The minor version of the service pack installed, this value is 0 if no service pack is installed.
PHP_WINDOWS_VERSION_SUITEMASK The suitemask is a bitmask that can tell if various features of Windows is installed, see the table below for possible bitfield values.
PHP_WINDOWS_VERSION_PRODUCTTYPE This contains the value used to determine the PHP_WINDOWS_NT_* constants. This value may be one of the PHP_WINDOWS_NT_* constants indicating the platform type.
PHP_WINDOWS_NT_DOMAIN_CONTROLLER This is a domain controller
PHP_WINDOWS_NT_SERVER This is a server system (eg. Server 2008/2003/2000), note that if this is a domain controller its reported as PHP_WINDOWS_NT_DOMAIN_CONTROLLER.
PHP_WINDOWS_NT_WORKSTATION This is a workstation system (eg. Vista/XP/2000/NT4)

This table shows a list of features that can be checked for using the PHP_WINDOWS_VERSION_SUITEMASK bitmask.

Windows suitemask bitfields
Bits Description
0x00000004 Microsoft BackOffice components are installed.
0x00000400 Windows Server 2003, Web Edition is installed.
0x00004000 Windows Server 2003, Compute Cluster Edition is installed.
0x00000080 Windows Server 2008 Datacenter, Windows Server 2003, Datacenter Edition or Windows 2000 Datacenter Server is installed.
0x00000002 Windows Server 2008 Enterprise, Windows Server 2003, Enterprise Edition, Windows 2000 Advanced Server, or Windows NT Server 4.0 Enterprise Edition is installed.
0x00000040 Windows XP Embedded is installed.
0x00000200 Windows Vista Home Premium, Windows Vista Home Basic, or Windows XP Home Edition is installed.
0x00000100 Remote Desktop is supported, but only one interactive session is supported. This value is set unless the system is running in application server mode.
0x00000001 Microsoft Small Business Server was once installed on the system, but may have been upgraded to another version of Windows.
0x00000020 Microsoft Small Business Server is installed with the restrictive client license in force.
0x00002000 Windows Storage Server 2003 R2 or Windows Storage Server 2003 is installed.
0x00000010 Terminal Services is installed. This value is always set. If this value is set but 0x00000100 is not set, then the system is running in application server mode.
0x00008000 Windows Home Server is installed.


PHP Options/Info 함수 목록


assert_options

(PHP 4, PHP 5)

assert_optionsSet/get the various assert flags

설명

mixed assert_options ( int $what [, mixed $value ] )

Set the various assert() control options or just query their current settings.

인수

what

Assert Options
Option INI Setting Default value Description
ASSERT_ACTIVE assert.active 1 enable assert() evaluation
ASSERT_WARNING assert.warning 1 issue a PHP warning for each failed assertion
ASSERT_BAIL assert.bail 0 terminate execution on failed assertions
ASSERT_QUIET_EVAL assert.quiet_eval 0 disable error_reporting during assertion expression evaluation
ASSERT_CALLBACK assert.callback (NULL) Callback to call on failed assertions

value

An optional new value for the option.

반환값

Returns the original setting of any option or FALSE on errors.

예제

Example #1 assert_options() example

<?php
// This is our function to handle 
// assert failures
function assert_failure()
{
    echo 
'Assert failed';
}

// This is our test function
function test_assert($parameter)
{
    
assert(is_bool($parameter));
}

// Set our assert options
assert_options(ASSERT_ACTIVE,    true);
assert_options(ASSERT_BAIL,     true);
assert_options(ASSERT_WARNING,     false);
assert_options(ASSERT_CALLBACK'assert_failure');

// Make an assert that would fail
test_assert(1);

// This is never reached due to ASSERT_BAIL 
// being true
echo 'Never reached';
?>

참고

  • assert() - Checks if assertion is FALSE



assert

(PHP 4, PHP 5)

assertChecks if assertion is FALSE

설명

bool assert ( mixed $assertion )

assert() will check the given assertion and take appropriate action if its result is FALSE.

If the assertion is given as a string it will be evaluated as PHP code by assert(). The advantages of a string assertion are less overhead when assertion checking is off and messages containing the assertion expression when an assertion fails. This means that if you pass a boolean condition as assertion this condition will not show up as parameter to the assertion function which you may have defined with the assert_options() function, the condition is converted to a string before calling that handler function, and the boolean FALSE is converted as the empty string.

Assertions should be used as a debugging feature only. You may use them for sanity-checks that test for conditions that should always be TRUE and that indicate some programming errors if not or to check for the presence of certain features like extension functions or certain system limits and features.

Assertions should not be used for normal runtime operations like input parameter checks. As a rule of thumb your code should always be able to work correctly if assertion checking is not activated.

The behavior of assert() may be configured by assert_options() or by .ini-settings described in that functions manual page.

The assert_options() function and/or ASSERT_CALLBACK configuration directive allow a callback function to be set to handle failed assertions.

assert() callbacks are particularly useful for building automated test suites because they allow you to easily capture the code passed to the assertion, along with information on where the assertion was made. While this information can be captured via other methods, using assertions makes it much faster and easier!

The callback function should accept three arguments. The first argument will contain the file the assertion failed in. The second argument will contain the line the assertion failed on and the third argument will contain the expression that failed (if any - literal values such as 1 or "two" will not be passed via this argument)

인수

assertion

The assertion.

반환값

FALSE if the assertion is false, TRUE otherwise.

예제

Example #1 Handle a failed assertion with a custom handler

<?php
// Active assert and make it quiet
assert_options(ASSERT_ACTIVE1);
assert_options(ASSERT_WARNING0);
assert_options(ASSERT_QUIET_EVAL1);

// Create a handler function
function my_assert_handler($file$line$code)
{
    echo 
"<hr>Assertion Failed:
        File '
$file'<br />
        Line '
$line'<br />
        Code '
$code'<br /><hr />";
}

// Set up the callback
assert_options(ASSERT_CALLBACK'my_assert_handler');

// Make an assertion that should fail
assert('mysql_query("")');
?>

참고



dl

(PHP 4, PHP 5)

dlLoads a PHP extension at runtime

설명

int dl ( string $library )

Loads the PHP extension given by the parameter library .

Use extension_loaded() to test whether a given extension is already available or not. This works on both built-in extensions and dynamically loaded ones (either through php.ini or dl()).

인수

library

This parameter is only the filename of the extension to load which also depends on your platform. For example, the sockets extension (if compiled as a shared module, not the default!) would be called sockets.so on Unix platforms whereas it is called php_sockets.dll on the Windows platform.

The directory where the extension is loaded from depends on your platform:

Windows - If not explicitly set in the php.ini, the extension is loaded from c:\php4\extensions\ by default.

Unix - If not explicitly set in the php.ini, the default extension directory depends on

  • whether PHP has been built with --enable-debug or not
  • whether PHP has been built with (experimental) ZTS (Zend Thread Safety) support or not
  • the current internal ZEND_MODULE_API_NO (Zend internal module API number, which is basically the date on which a major module API change happened, e.g. 20010901)

Taking into account the above, the directory then defaults to <install-dir>/lib/php/extensions/ <debug-or-not>-<zts-or-not>-ZEND_MODULE_API_NO, e.g. /usr/local/php/lib/php/extensions/debug-non-zts-20010901 or /usr/local/php/lib/php/extensions/no-debug-zts-20010901.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다. If the functionality of loading modules is not available (see Note) or has been disabled (either by turning it off enable_dl or by enabling 안전 모드 in php.ini) an E_ERROR is emitted and execution is stopped. If dl() fails because the specified library couldn't be loaded, in addition to FALSE an E_WARNING message is emitted.

예제

Example #1 dl() examples

<?php
// Example loading an extension based on OS
if (!extension_loaded('sqlite')) {
    if (
strtoupper(substr(PHP_OS03)) === 'WIN') {
        
dl('php_sqlite.dll');
    } else {
        
dl('sqlite.so');
    }
}

// Or, the PHP_SHLIB_SUFFIX constant is available as of PHP 4.3.0
if (!extension_loaded('sqlite')) {
    
$prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' '';
    
dl($prefix 'sqlite.' PHP_SHLIB_SUFFIX);
}
?>

변경점

버전 설명
5.3.0 This function now throws an E_DEPRECATED notice on all sapi's except for CLI, CGI and Embed.

주의

Note: dl() is not supported in multithreaded Web servers. Use the extensions statement in your php.ini when operating under such an environment. However, the CGI and CLI build are not affected !

Note: As of PHP 5, the dl() function is deprecated in every SAPI except CLI. Use Extension Loading Directives method instead.

Note: Since PHP 6 this function is disabled in all SAPIs, except CLI, CGI and embed.

Note: dl() is case sensitive on Unix platforms.

Note: 이 함수는 PHP가 안전 모드일 때는 사용할 수 없습니다.

참고



extension_loaded

(PHP 4, PHP 5)

extension_loadedFind out whether an extension is loaded

설명

bool extension_loaded ( string $name )

Finds out whether the extension is loaded.

인수

name

The extension name.

You can see the names of various extensions by using phpinfo() or if you're using the CGI or CLI version of PHP you can use the -m switch to list all available extensions:

$ php -m
[PHP Modules]
xml
tokenizer
standard
sockets
session
posix
pcre
overload
mysql
mbstring
ctype

[Zend Modules]

반환값

Returns TRUE if the extension identified by name is loaded, FALSE otherwise.

예제

Example #1 extension_loaded() example

<?php
if (!extension_loaded('gd')) {
    if (!
dl('gd.so')) {
        exit;
    }
}
?>

주의

Note: extension_loaded() uses the internal extension name to test whether a certain extension is available or not. Most internal extension names are written in lower case but there may be extension available which also use uppercase letters. Be warned that this function compares case sensitive !

참고



gc_collect_cycles

(PHP 5 >= 5.3.0)

gc_collect_cyclesForces collection of any existing garbage cycles

설명

int gc_collect_cycles ( void )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

Forces collection of any existing garbage cycles.

인수

이 함수는 인수가 없습니다.

반환값

Returns number of collected cycles.



gc_disable

(PHP 5 >= 5.3.0)

gc_disableDeactivates the circular reference collector

설명

void gc_disable ( void )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

Deactivates the circular reference collector.

인수

이 함수는 인수가 없습니다.

반환값

값을 반환하지 않습니다.



gc_enable

(PHP 5 >= 5.3.0)

gc_enableActivates the circular reference collector

설명

void gc_enable ( void )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

Activates the circular reference collector.

인수

이 함수는 인수가 없습니다.

반환값

값을 반환하지 않습니다.



gc_enabled

(PHP 5 >= 5.3.0)

gc_enabledReturns status of the circular reference collector

설명

bool gc_enabled ( void )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

Returns status of the circular reference collector.

인수

이 함수는 인수가 없습니다.

반환값

Returns TRUE if the garbage collector is enabled, FALSE otherwise.



get_cfg_var

(PHP 4, PHP 5)

get_cfg_varPHP 설정 옵션의 값 얻기

설명

string get_cfg_var ( string $option )

PHP 설정 option 값을 얻습니다.

이 함수는 PHP 컴파일시에 설정했거나, 아파치 설정 파일에서 읽는 정보는 반환하지 않습니다.

시스템이 어떤 설정 파일를 사용하는지 확인하려면, cfg_file_path 설정값을 확인해보십시오. 존재한다면, 그 설정 파일을 사용합니다.

인수

option

설정 옵션 이름.

반환값

option 으로 지정한 PHP 설정 변수의 현재 값을 반환하거나, 오류가 발생하면 FALSE를 반환합니다.

변경점

버전 설명
5.3.0 get_cfg_var()가 "array" ini 옵션을 반환할 수 있도록 수정되었습니다.

참고



get_current_user

(PHP 4, PHP 5)

get_current_user현재 PHP 스크립트 소유자의 이름을 얻습니다

설명

string get_current_user ( void )

현재 PHP 스크립트 소유자의 이름을 반환합니다.

반환값

사용자 이름을 문자열로 반환합니다.

예제

Example #1 get_current_user() 예제

<?php
echo '현재 스크립트 주인: ' get_current_user();
?>

위 예제의 출력 예시:

현재 스크립트 주인: SYSTEM

참고



get_defined_constants

(PHP 4 >= 4.1.0, PHP 5)

get_defined_constants모든 상수와 그 값의 연관 배열을 반환합니다

설명

array get_defined_constants ([ bool $categorize ] )

현재 정의된 모든 상수의 이름과 값을 반환합니다. 여기에는 확장 모듈에서 작성한 상수와 define() 함수로 작성한 상수를 포함합니다.

인수

categorize

분류를 1차원 키로 사용하고, 상수와 값을 2차원에 넣는 다차원 배열을 반환하도록 합니다.

<?php
define
("MY_CONSTANT"1);
print_r(get_defined_constants(true));
?>

위 예제의 출력 예시:

Array
(
    [internal] => Array
        (
            [E_ERROR] => 1
            [E_WARNING] => 2
            [E_PARSE] => 4
            [E_NOTICE] => 8
            [E_CORE_ERROR] => 16
            [E_CORE_WARNING] => 32
            [E_COMPILE_ERROR] => 64
            [E_COMPILE_WARNING] => 128
            [E_USER_ERROR] => 256
            [E_USER_WARNING] => 512
            [E_USER_NOTICE] => 1024
            [E_ALL] => 2047
            [TRUE] => 1
        )

    [pcre] => Array
        (
            [PREG_PATTERN_ORDER] => 1
            [PREG_SET_ORDER] => 2
            [PREG_OFFSET_CAPTURE] => 256
            [PREG_SPLIT_NO_EMPTY] => 1
            [PREG_SPLIT_DELIM_CAPTURE] => 2
            [PREG_SPLIT_OFFSET_CAPTURE] => 4
            [PREG_GREP_INVERT] => 1
        )

    [user] => Array
        (
            [MY_CONSTANT] => 1
        )

)

반환값

변경점

버전 설명
5.0.0 categorize 인수가 추가되었습니다.

예제

Example #1 get_defined_constants() 예제

<?php
print_r
(get_defined_constants());
?>

위 예제의 출력 예시:

Array
(
    [E_ERROR] => 1
    [E_WARNING] => 2
    [E_PARSE] => 4
    [E_NOTICE] => 8
    [E_CORE_ERROR] => 16
    [E_CORE_WARNING] => 32
    [E_COMPILE_ERROR] => 64
    [E_COMPILE_WARNING] => 128
    [E_USER_ERROR] => 256
    [E_USER_WARNING] => 512
    [E_USER_NOTICE] => 1024
    [E_ALL] => 2047
    [TRUE] => 1
)

참고



get_extension_funcs

(PHP 4, PHP 5)

get_extension_funcs모듈 함수명을 배열로 반환

설명

array get_extension_funcs ( string $module_name )

module_name 으로 지정한 모듈에 정의된 모든 함수명을 반환합니다.

인수

module_name

모듈명.

Note: 이 인수는 반드시 소문자이여야 합니다.

반환값

모든 함수를 가진 배열을 반환하거나, module_name 이 유효한 확장이 아닐 경우에는 FALSE를 반환합니다.

예제

Example #1 XML 함수 출력

<?php
print_r
(get_extension_funcs("xml"));
?>

위 예제의 출력 예시:

Array
(
    [0] => xml_parser_create
    [1] => xml_parser_create_ns
    [2] => xml_set_object
    [3] => xml_set_element_handler
    [4] => xml_set_character_data_handler
    [5] => xml_set_processing_instruction_handler
    [6] => xml_set_default_handler
    [7] => xml_set_unparsed_entity_decl_handler
    [8] => xml_set_notation_decl_handler
    [9] => xml_set_external_entity_ref_handler
    [10] => xml_set_start_namespace_decl_handler
    [11] => xml_set_end_namespace_decl_handler
    [12] => xml_parse
    [13] => xml_parse_into_struct
    [14] => xml_get_error_code
    [15] => xml_error_string
    [16] => xml_get_current_line_number
    [17] => xml_get_current_column_number
    [18] => xml_get_current_byte_index
    [19] => xml_parser_free
    [20] => xml_parser_set_option
    [21] => xml_parser_get_option
    [22] => utf8_encode
    [23] => utf8_decode
)

참고



get_include_path

(PHP 4 >= 4.3.0, PHP 5)

get_include_pathGets the current include_path configuration option

설명

string get_include_path ( void )

Gets the current include_path configuration option value.

반환값

Returns the path, as a string.

예제

Example #1 get_include_path() example

<?php
// Works as of PHP 4.3.0
echo get_include_path();

// Works in all PHP versions
echo ini_get('include_path');
?>

참고



get_included_files

(PHP 4, PHP 5)

get_included_filesinclude나 require한 파일명의 배열을 반환

설명

array get_included_files ( void )

include(), include_once(), require(), require_once()를 사용하여 포함한 모든 파일명을 얻습니다.

반환값

모든 파일명의 배열을 반환합니다.

호출한 스크립트 파일은 "포함한 파일"로 처리하기에, include() 등으로 참조한 파일과 함께 나옵니다.

여러번 include나 require한 파일은 반환하는 배열에 한번만 나옵니다.

변경점

버전 설명
4.0.1 PHP 4.0.1과 이전 버전에서 이 함수는 .php 확장자로 끝나는 파일만 반환하고, 다른 확장자를 가지는 파일은 반환하지 않았습니다. get_included_files()include()include_once()로 포함한 파일만 가지는 연관 배열을 반환했습니다.

예제

Example #1 get_included_files() 예제

<?php
// 이 파일은 abc.php 입니다

include 'test1.php';
include_once 
'test2.php';
require 
'test3.php';
require_once 
'test4.php';

$included_files get_included_files();

foreach (
$included_files as $filename) {
    echo 
"$filename\n";
}

?>

위 예제의 출력:

abc.php
test1.php
test2.php
test3.php
test4.php

주의

Note: auto_prepend_file 설정 지시어를 사용하여 포함한 파일은 반환 배열에 나오지 않습니다.

참고



get_loaded_extensions

(PHP 4, PHP 5)

get_loaded_extensions적재된 모든 모듈명을 배열로 반환합니다

설명

array get_loaded_extensions ([ bool $zend_extensions= FALSE ] )

PHP 인터프리터에 적재된 모든 모듈명을 반환합니다.

인수

zend_extensions

zend_extensions 반환 여부, 기본값은 FALSE (zend_extensions 목록이 나오지 않음)

반환값

모든 모듈명의 배열을 반환합니다.

변경점

버전 설명
5.2.4 선택적인 zend_extensions 인수 추가

예제

Example #1 get_loaded_extensions() 예제

<?php
print_r
(get_loaded_extensions());
?>

위 예제의 출력 예시:

Array
(
   [0] => xml
   [1] => wddx
   [2] => standard
   [3] => session
   [4] => posix
   [5] => pgsql
   [6] => pcre
   [7] => gd
   [8] => ftp
   [9] => db
   [10] => calendar
   [11] => bcmath
)

참고



get_magic_quotes_gpc

(PHP 4, PHP 5)

get_magic_quotes_gpcGets the current configuration setting of magic quotes gpc

설명

int get_magic_quotes_gpc ( void )

Returns the current configuration setting of magic_quotes_gpc

Keep in mind that the setting magic_quotes_gpc will not work at runtime.

For more information about magic_quotes, see this security section.

반환값

Returns 0 if magic quotes gpc are off, 1 otherwise.

예제

Example #1 get_magic_quotes_gpc() example

<?php
echo get_magic_quotes_gpc();         // 1
echo $_POST['lastname'];             // O\'reilly
echo addslashes($_POST['lastname']); // O\\\'reilly

if (!get_magic_quotes_gpc()) {
    
$lastname addslashes($_POST['lastname']);
} else {
    
$lastname $_POST['lastname'];
}

echo 
$lastname// O\'reilly
$sql "INSERT INTO lastnames (lastname) VALUES ('$lastname')";
?>

주의

Note: If the directive magic_quotes_sybase is ON it will completely override magic_quotes_gpc. So even when get_magic_quotes_gpc() returns TRUE neither double quotes, backslashes or NUL's will be escaped. Only single quotes will be escaped. In this case they'll look like: ''

참고



get_magic_quotes_runtime

(PHP 4, PHP 5)

get_magic_quotes_runtimeGets the current active configuration setting of magic_quotes_runtime

설명

int get_magic_quotes_runtime ( void )

Returns the current active configuration setting of magic_quotes_runtime.

반환값

Returns 0 if magic quotes runtime is off, 1 otherwise.

예제

Example #1 get_magic_quotes_runtime() example

<?php
// Check if magic_quotes_runtime is active
if(get_magic_quotes_runtime())
{
    
// Deactive
    
set_magic_quotes_runtime(false);
}
?>

참고



get_required_files

(PHP 4, PHP 5)

get_required_files별칭: get_included_files()

설명

이 함수는 다음 함수의 별칭입니다: get_included_files().



getenv

(PHP 4, PHP 5)

getenv환경 변수 값을 얻습니다

설명

string getenv ( string $varname )

환경 변수 값을 얻습니다.

모든 환경 변수 목록을 phpinfo()를 사용하여 볼 수 있습니다. 대부분의 의미는 » CGI 규정에서, 정확히는 » 환경 변수 페이지에서 확인할 수 있습니다.

인수

varname

변수 이름.

반환값

환경 변수 varname 의 값을 반환하거나, 에러가 있을 경우 FALSE를 반환합니다.

예제

Example #1 getenv() 예제

<?php
// getenv() 용례
$ip getenv('REMOTE_ADDR');

// 혹은 간단히 자동 변역 사용 ($_SERVER 나 $_ENV)
$ip $_SERVER['REMOTE_ADDR'];
?>

참고



getlastmod

(PHP 4, PHP 5)

getlastmod페이지를 수정한 최종 시간을 얻습니다

설명

int getlastmod ( void )

현재 페이지의 마지막 수정 시간을 얻습니다.

다른 파일의 수정 시간을 얻고자 한다면, filemtime()을 사용하십시오.

반환값

현재 페이지를 마지막으로 수정한 시간을 반환합니다. 반환값은 date()에 적합한 유닉스 타임스탬프입니다. 오류가 발생하면 FALSE를 반환합니다.

Example #1 getlastmod() 예제

<?php
// 출력 예. 'Last modified: March 04 1998 20:43:59.'
echo "Last modified: " date ("F d Y H:i:s."getlastmod());
?>

참고



getmygid

(PHP 4 >= 4.1.0, PHP 5)

getmygidGet PHP script owner's GID

설명

int getmygid ( void )

Gets the group ID of the current script.

반환값

Returns the group ID of the current script, or FALSE on error.

참고



getmyinode

(PHP 4, PHP 5)

getmyinodeGets the inode of the current script

설명

int getmyinode ( void )

Gets the inode of the current script.

반환값

Returns the current script's inode as an integer, or FALSE on error.

참고



getmypid

(PHP 4, PHP 5)

getmypidGets PHP's process ID

설명

int getmypid ( void )

Gets the current PHP process ID.

반환값

Returns the current PHP process ID, or FALSE on error.

주의

Warning

Process IDs are not unique, thus they are a weak entropy source. We recommend against relying on pids in security-dependent contexts.

참고



getmyuid

(PHP 4, PHP 5)

getmyuidGets PHP script owner's UID

설명

int getmyuid ( void )

Gets the user ID of the current script.

반환값

Returns the user ID of the current script, or FALSE on error.

참고



getopt

(PHP 4 >= 4.3.0, PHP 5)

getoptGets options from the command line argument list

설명

array getopt ( string $options [, array $longopts ] )

Parses options passed to the script.

인수

options
Each character in this string will be used as option characters and matched against options passed to the script starting with a single hyphen (-). For example, an option string "x" recognizes an option -x.
longopts
An array of options. Each element in this array will be used as option strings and matched against options passed to the script starting with two hyphens (--). For example, an longopts element "opt" recognizes an option --opt.

Note: Prior to PHP5.3.0 this parameter was only available on few systems

The options parameter may contain the following elements:

  • Individual characters (do not accept values)
  • Characters followed by a colon (parameter requires value)
  • Characters followed by two colons (optional value)

Option values are the first argument after the string. It does not matter if a value has leading white space or not.

Note: Optional values do not accept " " (space) as a separator.

Note: The format for the options and longopts is almost the same, the only difference is that longopts takes an array of options (where each element is the option) where as options takes a string (where each character is the option).

반환값

This function will return an array of option / argument pairs or FALSE on failure.

변경점

버전 설명
5.3.0 Added support for "=" as argument/value separator.
5.3.0 Added support for optional values (specified with "::").
5.3.0 This function is no longer system dependent and works on Windows too.

예제

Example #1 getopt() example

<?php
$options 
getopt("f:hp:");
var_dump($options);
?>

Running the above script with php script.php -fvalue -h will output:

array(2) {
  ["f"]=>
  string(5) "value"
  ["h"]=>
  bool(false)
}

Example #2 getopt() example#2

<?php
$shortopts  
"";
$shortopts .= "f:";  // Required value
$shortopts .= "v::"// Optional value
$shortopts .= "abc"// These options do not accept values

$longopts  = array(
    
"required:",     // Required value
    
"optional::",    // Optional value
    
"option",        // No value
    
"opt",           // No value
);
$options getopt($shortopts$longopts);
var_dump($options);
?>

Running the above script with php script.php -f "value for f" -v -a --required value --optional="optional value" --option will output:

array(6) {
  ["f"]=>
  string(11) "value for f"
  ["v"]=>
  bool(false)
  ["a"]=>
  bool(false)
  ["required"]=>
  string(5) "value"
  ["optional"]=>
  string(14) "optional value"
  ["option"]=>
  bool(false)
}

Example #3 getopt() example#3

Passing multiple options as one

<?php
$options 
getopt("abc");
var_dump($options);
?>

Running the above script with php script.php -aaac will output:

array(2) {
  ["a"]=>
  array(3) {
    [0]=>
    bool(false)
    [1]=>
    bool(false)
    [2]=>
    bool(false)
  }
  ["c"]=>
  bool(false)
}



getrusage

(PHP 4, PHP 5)

getrusageGets the current resource usages

설명

array getrusage ([ int $who= 0 ] )

This is an interface to getrusage(2). It gets data returned from the system call.

인수

who

If who is 1, getrusage will be called with RUSAGE_CHILDREN.

반환값

Returns an associative array containing the data returned from the system call. All entries are accessible by using their documented field names.

예제

Example #1 getrusage() example

<?php
$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)
?>

주의

Note: 이 함수는 윈도우 플랫폼에서는 작동하지 않습니다.

참고

  • Your system's man page on getrusage(2)



ini_alter

(PHP 4, PHP 5)

ini_alter별칭: ini_set()

설명

이 함수는 다음 함수의 별칭입니다: ini_set().



ini_get_all

(PHP 4 >= 4.2.0, PHP 5)

ini_get_all모든 설정 옵션을 얻습니다

설명

array ini_get_all ([ string $extension [, bool $details ]] )

등록된 모든 설정 옵션을 반환합니다.

인수

extension

선택적인 확장명. 설정하면, 그 확장에 사용되는 옵션만 반환합니다.

details

자세한 설정을 얻거나 각 설정의 현재 값만 가져옵니다. 기본값은 TRUE입니다. (자세한 설정)

반환값

지시어 이름을 키로 가지는 연관 배열을 반환합니다.

detailsTRUE(기본값)이면, 배열은 global_value(php.ini에서 설정), local_value(ini_set()이나 .htaccess로 설정), access(접근 레벨)를 가지는 배열을 반환합니다.

detailsFALSE이면 옵션의 현재 값만 얻습니다.

접근 레벨에 대한 의미는 매뉴얼 섹션을 참고하십시오.

Note: 지시어가 복수의 접근 레벨을 가질 수 있기에, access는 적절한 비트마스트 값을 가집니다.

변경점

버전 설명
5.3.0 details 추가.

예제

Example #1 ini_get_all() 예제

<?php
print_r
(ini_get_all("pcre"));
print_r(ini_get_all());
?>

위 예제의 출력 예시:

Array
(
    [pcre.backtrack_limit] => Array
        (
            [global_value] => 100000
            [local_value] => 100000
            [access] => 7
        )

    [pcre.recursion_limit] => Array
        (
            [global_value] => 100000
            [local_value] => 100000
            [access] => 7
        )

)
Array
(
    [allow_call_time_pass_reference] => Array
        (
            [global_value] => 0
            [local_value] => 0
            [access] => 6
        )

    [allow_url_fopen] => Array
        (
            [global_value] => 1
            [local_value] => 1
            [access] => 4
        )

    ...

)

Example #2 details 끄기

<?php
print_r
(ini_get_all("pcre"false)); // PHP 5.3.0에서 추가
print_r(ini_get_all(nullfalse)); // PHP 5.3.0에서 추가

위 예제의 출력 예시:

Array
(
    [pcre.backtrack_limit] => 100000
    [pcre.recursion_limit] => 100000
)
Array
(
    [allow_call_time_pass_reference] => 0
    [allow_url_fopen] => 1
    ...
)

참고



ini_get

(PHP 4, PHP 5)

ini_getGets the value of a configuration option

설명

string ini_get ( string $varname )

Returns the value of the configuration option on success.

인수

varname

The configuration option name.

반환값

Returns the value of the configuration option as a string on success, or an empty string on failure or for null values.

예제

Example #1 A few ini_get() examples

<?php
/*
Our php.ini contains the following settings:

display_errors = On
register_globals = Off
post_max_size = 8M
*/

echo 'display_errors = ' ini_get('display_errors') . "\n";
echo 
'register_globals = ' ini_get('register_globals') . "\n";
echo 
'post_max_size = ' ini_get('post_max_size') . "\n";
echo 
'post_max_size+1 = ' . (ini_get('post_max_size')+1) . "\n";
echo 
'post_max_size in bytes = ' return_bytes(ini_get('post_max_size'));

function 
return_bytes($val) {
    
$val trim($val);
    
$last strtolower($val[strlen($val)-1]);
    switch(
$last) {
        
// The 'G' modifier is available since PHP 5.1.0
        
case 'g':
            
$val *= 1024;
        case 
'm':
            
$val *= 1024;
        case 
'k':
            
$val *= 1024;
    }

    return 
$val;
}

?>

위 예제의 출력 예시:


display_errors = 1
register_globals = 0
post_max_size = 8M
post_max_size+1 = 9
post_max_size in bytes = 8388608

주의

Note: When querying boolean values
A boolean ini value of off will be returned as an empty string or "0" while a boolean ini value of on will be returned as "1". The function can also return the literal string of INI value.

Note: When querying memory size values
Many ini memory size values, such as upload_max_filesize, are stored in the php.ini file in shorthand notation. ini_get() will return the exact string stored in the php.ini file and NOT its integer equivalent. Attempting normal arithmetic functions on these values will not have otherwise expected results. The example above shows one way to convert shorthand notation into bytes, much like how the PHP source does it.

참고



ini_restore

(PHP 4, PHP 5)

ini_restore설정 옵션 값을 복구

설명

void ini_restore ( string $varname )

주어진 설정 옵션을 원래 값으로 복구합니다.

인수

varname

설정 옵션 이름.

반환값

값을 반환하지 않습니다.

예제

Example #1 ini_restore() 예제

<?php
$setting 
'y2k_compliance';

echo 
'Current value for \'' $setting '\': ' ini_get($setting), PHP_EOL;

ini_set($settingini_get($setting) ? 1);
echo 
'New value for \'' $setting '\': ' ini_get($setting), PHP_EOL;

ini_restore($setting);
echo 
'Original value for \'' $setting '\': ' ini_get($setting), PHP_EOL;
?>

위 예제의 출력:

Current value for 'y2k_compliance': 1
New value for 'y2k_compliance': 0
Original value for 'y2k_compliance': 1

참고

  • ini_get() - Gets the value of a configuration option
  • ini_get_all() - 모든 설정 옵션을 얻습니다
  • ini_set() - Sets the value of a configuration option



ini_set

(PHP 4, PHP 5)

ini_setSets the value of a configuration option

설명

string ini_set ( string $varname , string $newvalue )

Sets the value of the given configuration option. The configuration option will keep this new value during the script's execution, and will be restored at the script's ending.

인수

varname

Not all the available options can be changed using ini_set(). There is a list of all available options in the appendix.

newvalue

The new value for the option.

반환값

Returns the old value on success, FALSE on failure.

예제

Example #1 Setting an ini option

<?php
echo ini_get('display_errors');

if (!
ini_get('display_errors')) {
    
ini_set('display_errors'1);
}

echo 
ini_get('display_errors');
?>

참고



magic_quotes_runtime

(PHP 4, PHP 5)

magic_quotes_runtime별칭: set_magic_quotes_runtime()

설명

이 함수는 다음 함수의 별칭입니다: set_magic_quotes_runtime()



main

mainDummy for main()

설명

There is no function named main() except in the PHP source. In PHP 4.3.0, a new type of error handling in the PHP source (php_error_docref) was introduced. One feature is to provide links to a manual page in PHP error messages when the PHP directives html_errors (on by default) and docref_root (on by default until PHP 4.3.2) are set.

Sometimes error messages refer to a manual page for the function main() which is why this page exists. If you discover such a reference, please » file a bug report, indicating the PHP function caused the error that linked to main() and it will be fixed and properly documented.

Known errors that point to main()
Function name No longer points here as of
include() 5.1.0
include_once() 5.1.0
require() 5.1.0
require_once() 5.1.0



memory_get_peak_usage

(PHP 5 >= 5.2.0)

memory_get_peak_usageReturns the peak of memory allocated by PHP

설명

int memory_get_peak_usage ([ bool $real_usage= false ] )

Returns the peak of memory, in bytes, that's been allocated to your PHP script.

인수

real_usage

Set this to TRUE to get the real size of memory allocated from system. If not set or FALSE only the memory used by emalloc() is reported.

반환값

Returns the memory peak in bytes.

변경점

버전 설명
5.2.1 Compiling with --enable-memory-limit is no longer required for this function to exist.
5.2.0 real_usage was added.

참고



memory_get_usage

(PHP 4 >= 4.3.2, PHP 5)

memory_get_usageReturns the amount of memory allocated to PHP

설명

int memory_get_usage ([ bool $real_usage= false ] )

Returns the amount of memory, in bytes, that's currently being allocated to your PHP script.

인수

real_usage

Set this to TRUE to get the real size of memory allocated from system. If not set or FALSE only the memory used by emalloc() is reported.

반환값

Returns the memory amount in bytes.

변경점

버전 설명
5.2.1 Compiling with --enable-memory-limit is no longer required for this function to exist.
5.2.0 real_usage was added.

예제

Example #1 A memory_get_usage() example

<?php
// This is only an example, the numbers below will
// differ depending on your system

echo memory_get_usage() . "\n"// 36640

$a str_repeat("Hello"4242);

echo 
memory_get_usage() . "\n"// 57960

unset($a);

echo 
memory_get_usage() . "\n"// 36744

?>

참고



php_ini_loaded_file

(PHP 5 >= 5.2.4)

php_ini_loaded_fileRetrieve a path to the loaded php.ini file

설명

string php_ini_loaded_file ( void )

Check if a php.ini file is loaded, and retrieve its path.

인수

이 함수는 인수가 없습니다.

반환값

The loaded php.ini path, or FALSE if one is not loaded.

예제

Example #1 php_ini_loaded_file() example

<?php
$inipath 
php_ini_loaded_file();

if (
$inipath) {
    echo 
'Loaded php.ini: ' $inipath;
} else {
    echo 
'A php.ini file is not loaded';
}
?>

위 예제의 출력 예시:

Loaded php.ini: /usr/local/php/php.ini

참고



php_ini_scanned_files

(PHP 4 >= 4.3.0, PHP 5)

php_ini_scanned_filesReturn a list of .ini files parsed from the additional ini dir

설명

string php_ini_scanned_files ( void )

php_ini_scanned_files() returns a comma-separated list of configuration files parsed after php.ini. These files are found in a directory defined by the --with-config-file-scan-dir option which is set during compilation.

The returned configuration files also include the path as declared in the --with-config-file-scan-dir option.

반환값

Returns a comma-separated string of .ini files on success. Each comma is followed by a newline. If the directive --with-config-file-scan-dir wasn't set, FALSE is returned. If it was set and the directory was empty, an empty string is returned. If a file is unrecognizable, the file will still make it into the returned string but a PHP error will also result. This PHP error will be seen both at compile time and while using php_ini_scanned_files().

예제

Example #1 A simple example to list the returned ini files

<?php
if ($filelist php_ini_scanned_files()) {
    if (
strlen($filelist) > 0) {
        
$files explode(','$filelist);

        foreach (
$files as $file) {
            echo 
"<li>" trim($file) . "</li>\n";
        }
    }
}
?>

참고



php_logo_guid

(PHP 4, PHP 5)

php_logo_guidGets the logo guid

설명

string php_logo_guid ( void )

This function returns the ID which can be used to display the PHP logo using the built-in image. Logo is displayed only if expose_php is On.

반환값

Returns PHPE9568F34-D428-11d2-A769-00AA001ACF42.

예제

Example #1 php_logo_guid() example

<?php

echo '<img src="' $_SERVER['PHP_SELF'] .
     
'?=' php_logo_guid() . '" alt="PHP Logo !" />';

?>

참고



php_sapi_name

(PHP 4 >= 4.0.1, PHP 5)

php_sapi_name웹 서버와 PHP 사이의 인터페이스 형식을 반환

설명

string php_sapi_name ( void )

PHP가 사용하는 인터페이스(서버 API, SAPI) 형식을 나타내는 소문자 문자열을 반환합니다. 예를 들어, CLI PHP에서 이 문자열은 "cli"이고, 아파치에서는 사용하는 SAPI에 따라 여러 값일 수 있습니다. 가능한 값은 아래 목록에 있습니다.

반환값

인터페이스 형식을 소문자 문자열로 반환합니다.

완전하진 않지만, 가능한 반환값은 aolserver, apache, apache2filter, apache2handler, caudium, cgi(PHP 5.3까지), cgi-fcgi, cli, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, webjames를 포함합니다.

예제

Example #1 php_sapi_name() 예제

이 예제는 서브문자열 cgi를 확인합니다. cgi-fcgi일 수도 있기 때문입니다.

<?php
$sapi_type 
php_sapi_name();
if (
substr($sapi_type03) == 'cgi') {
    echo 
"CGI PHP를 사용하고 있습니다.\n";
} else {
    echo 
"CGI PHP를 사용하고 있지 않습니다.\n";
}
?>

주의

Note: 대체 접근법
PHP 상수 PHP_SAPIphp_sapi_name()과 같은 값을 가집니다.

Tip

이런 일이!

정의된 SAPI는 명백하지 않을 수 있습니다. 예를 들면, apache 대신 apache2handlerapache2filter로 정의될 수 있기 때문입니다.

참고



php_uname

(PHP 4 >= 4.0.2, PHP 5)

php_unameReturns information about the operating system PHP is running on

설명

string php_uname ([ string $mode= "a" ] )

php_uname() returns a description of the operating system PHP is running on. This is the same string you see at the very top of the phpinfo() output. For the name of just the operating system, consider using the PHP_OS constant, but keep in mind this constant will contain the operating system PHP was built on.

On some older UNIX platforms, it may not be able to determine the current OS information in which case it will revert to displaying the OS PHP was built on. This will only happen if your uname() library call either doesn't exist or doesn't work.

인수

mode

mode is a single character that defines what information is returned:

  • 'a': This is the default. Contains all modes in the sequence "s n r v m".
  • 's': Operating system name. eg. FreeBSD.
  • 'n': Host name. eg. localhost.example.com.
  • 'r': Release name. eg. 5.1.2-RELEASE.
  • 'v': Version information. Varies a lot between operating systems.
  • 'm': Machine type. eg. i386.

반환값

Returns the description, as a string.

예제

Example #1 Some php_uname() examples

<?php
echo php_uname();
echo 
PHP_OS;

/* Some possible outputs:
Linux localhost 2.4.21-0.13mdk #1 Fri Mar 14 15:08:06 EST 2003 i686
Linux

FreeBSD localhost 3.2-RELEASE #15: Mon Dec 17 08:46:02 GMT 2001
FreeBSD

Windows NT XN1 5.1 build 2600
WINNT
*/

if (strtoupper(substr(PHP_OS03)) === 'WIN') {
    echo 
'This is a server using Windows!';
} else {
    echo 
'This is a server not using Windows!';
}

?>

There are also some related Predefined PHP constants that may come in handy, for example:

Example #2 A few OS related constant examples

<?php
// *nix
echo DIRECTORY_SEPARATOR// /
echo PHP_SHLIB_SUFFIX;    // so
echo PATH_SEPARATOR;      // :

// Win*
echo DIRECTORY_SEPARATOR// \
echo PHP_SHLIB_SUFFIX;    // dll
echo PATH_SEPARATOR;      // ;
?>

참고



phpcredits

(PHP 4, PHP 5)

phpcreditsPrints out the credits for PHP

설명

bool phpcredits ([ int $flag= CREDITS_ALL ] )

This function prints out the credits listing the PHP developers, modules, etc. It generates the appropriate HTML codes to insert the information in a page.

인수

flag

To generate a custom credits page, you may want to use the flag parameter. flag is optional, and it defaults to CREDITS_ALL.

Pre-defined phpcredits() flags
name description
CREDITS_ALL All the credits, equivalent to using: CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_FULLPAGE. It generates a complete stand-alone HTML page with the appropriate tags.
CREDITS_DOCS The credits for the documentation team
CREDITS_FULLPAGE Usually used in combination with the other flags. Indicates that a complete stand-alone HTML page needs to be printed including the information indicated by the other flags.
CREDITS_GENERAL General credits: Language design and concept, PHP 4.0 authors and SAPI module.
CREDITS_GROUP A list of the core developers
CREDITS_MODULES A list of the extension modules for PHP, and their authors
CREDITS_SAPI A list of the server API modules for PHP, and their authors

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 Prints the general credits

<?php
phpcredits
(CREDITS_GENERAL);
?>

Example #2 Prints the core developers and the documentation group

<?php
phpcredits
(CREDITS_GROUP CREDITS_DOCS CREDITS_FULLPAGE);
?>

Example #3 Printing all the credits

<html>
 <head>
  <title>My credits page</title>
 </head>
 <body>
<?php
// some code of your own
phpcredits(CREDITS_ALL CREDITS_FULLPAGE);
// some more code
?>
 </body>
</html>

참고



phpinfo

(PHP 4, PHP 5)

phpinfoOutputs lots of PHP information

설명

bool phpinfo ([ int $what= INFO_ALL ] )

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 PHP License.

Because every system is setup differently, phpinfo() is commonly used to check configuration settings and for available predefined variables on a given system.

phpinfo() is also a valuable debugging tool as it contains all EGPCS (Environment, GET, POST, Cookie, Server) data.

인수

what

The output may be customized by passing one or more of the following constants bitwise values summed together in the optional what parameter. One can also combine the respective constants or bitwise values together with the or operator.

phpinfo() options
Name (constant) Value Description
INFO_GENERAL 1 The configuration line, php.ini location, build date, Web Server, System and more.
INFO_CREDITS 2 PHP Credits. See also phpcredits().
INFO_CONFIGURATION 4 Current Local and Master values for PHP directives. See also ini_get().
INFO_MODULES 8 Loaded modules and their respective settings. See also get_loaded_extensions().
INFO_ENVIRONMENT 16 Environment Variable information that's also available in $_ENV.
INFO_VARIABLES 32 Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server).
INFO_LICENSE 64 PHP License information. See also the » license FAQ.
INFO_ALL -1 Shows all of the above. This is the default value.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

변경점

버전 설명
5.2.2 The "Loaded Configuration File" information was added, when before only "Configuration File (php.ini) Path" existed.

예제

Example #1 phpinfo() Example

<?php

// Show all information, defaults to INFO_ALL
phpinfo();

// Show just the module information.
// phpinfo(8) yields identical results.
phpinfo(INFO_MODULES);

?>

주의

Note: Parts of the information displayed are disabled when the expose_php configuration setting is set to off. This includes the PHP and Zend logos, and the credits.

Note: phpinfo() outputs plain text instead of HTML when using the CLI mode.

참고



phpversion

(PHP 4, PHP 5)

phpversionGets the current PHP version

설명

string phpversion ([ string $extension ] )

Returns a string containing the version of the currently running PHP parser or extension.

인수

extension

An optional extension name.

반환값

If the optional extension parameter is specified, phpversion() returns the version of that extension, or FALSE if there is no version information associated or the extension isn't enabled.

예제

Example #1 phpversion() example

<?php
// prints e.g. 'Current PHP version: 4.1.1'
echo 'Current PHP version: ' phpversion();

// prints e.g. '2.0' or nothing if the extension isn't enabled
echo phpversion('tidy');
?>

Example #2 PHP_VERSION_ID example and usage

<?php
// PHP_VERSION_ID is available as of PHP 5.2.7, if our 
// version is lower than that, then emulate it
if(!defined('PHP_VERSION_ID'))
{
    
$version PHP_VERSION;

    
define('PHP_VERSION_ID', ($version{0} * 10000 $version{2} * 100 $version{4}));
}

// PHP_VERSION_ID is defined as a number, where the higher the number 
// is, the newer a PHP version is used. Its defined as used in the above 
// expression:
//
// $version_id = $major_version * 10000 + $minor_version * 100 + $release_version;
//
// Now with PHP_VERSION_ID we can check for features this PHP version 
// may have, this doesn't require to use version_compare() everytime 
// you check if the current php version may not support a feature.
//
// For example, we may here define the PHP_VERSION_* constants thats 
// not available in versions prior to 5.2.7

if(PHP_VERSION_ID 50207)
{
    
define('PHP_MAJOR_VERSION',     $version{0});
    
define('PHP_MINOR_VERSION',     $version{2});
    
define('PHP_RELEASE_VERSION',     $version{4});

    
// and so on, ...
}
?>

주의

Note: This information is also available in the predefined constant PHP_VERSION. More versioning information is available using the PHP_VERSION_* constants.

참고



putenv

(PHP 4, PHP 5)

putenvSets the value of an environment variable

설명

bool putenv ( string $setting )

Adds setting to the server environment. The environment variable will only exist for the duration of the current request. At the end of the request the environment is restored to its original state.

Setting certain environment variables may be a potential security breach. The safe_mode_allowed_env_vars directive contains a comma-delimited list of prefixes. In Safe Mode, the user may only alter environment variables whose names begin with the prefixes supplied by this directive. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR). Note: if this directive is empty, PHP will let the user modify ANY environment variable!

The safe_mode_protected_env_vars directive contains a comma-delimited list of environment variables, that the end user won't be able to change using putenv(). These variables will be protected even if safe_mode_allowed_env_vars is set to allow to change them.

인수

setting

The setting, like "FOO=BAR"

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 Setting an environment variable

<?php
putenv
("UNIQID=$uniqid");
?>

주의

Warning

These directives have only effect when safe-mode itself is enabled!

참고

  • getenv() - 환경 변수 값을 얻습니다



restore_include_path

(PHP 4 >= 4.3.0, PHP 5)

restore_include_pathRestores the value of the include_path configuration option

설명

void restore_include_path ( void )

Restores the include_path configuration option back to its original master value as set in php.ini

반환값

값을 반환하지 않습니다.

예제

Example #1 restore_include_path() example

<?php

echo get_include_path();  // .:/usr/local/lib/php

set_include_path('/inc');

echo 
get_include_path();  // /inc

// Works as of PHP 4.3.0
restore_include_path();

// Works in all PHP versions
ini_restore('include_path');

echo 
get_include_path();  // .:/usr/local/lib/php

?>

참고



set_include_path

(PHP 4 >= 4.3.0, PHP 5)

set_include_pathSets the include_path configuration option

설명

string set_include_path ( string $new_include_path )

Sets the include_path configuration option for the duration of the script.

인수

new_include_path

The new value for the include_path

반환값

Returns the old include_path on success or FALSE on failure.

예제

Example #1 set_include_path() example

<?php
// Works as of PHP 4.3.0
set_include_path('/inc');

// Works in all PHP versions
ini_set('include_path''/inc');
?>

Example #2 Adding to the include path

Making use of the PATH_SEPARATOR constant, it is possible to extend the include path regardless of the operating system.

In this example we add /usr/lib/pear to the end of the existing include_path.

<?php
$path 
'/usr/lib/pear';
set_include_path(get_include_path() . PATH_SEPARATOR $path);
?>

참고



set_magic_quotes_runtime

(PHP 4, PHP 5)

set_magic_quotes_runtimeSets the current active configuration setting of magic_quotes_runtime

설명

bool set_magic_quotes_runtime ( bool $new_setting )

Set the current active configuration setting of magic_quotes_runtime.

인수

new_setting

FALSE for off, TRUE for on.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 set_magic_quotes_runtime() example

<?php
// Create a temporary file pointer
$fp tmpfile();

// Write some data to the pointer
fwrite($fp'\'PHP\' is a Recursive acronym');

// Without magic_quotes_runtime
rewind($fp);
set_magic_quotes_runtime(false);

echo 
'Without magic_quotes_runtime: ' fread($fp64), PHP_EOL;

// With magic_quotes_runtime
rewind($fp);
set_magic_quotes_runtime(true);

echo 
'With magic_quotes_runtime: ' fread($fp64), PHP_EOL;

// Clean up
fclose($fp);
?>

위 예제의 출력:

Without magic_quotes_runtime: 'PHP' is a Recursive acronym
With magic_quotes_runtime: \'PHP\' is a Recursive acronym

참고



set_time_limit

(PHP 4, PHP 5)

set_time_limit최대 실행 시간을 제한

설명

void set_time_limit ( int $seconds )

스크립트가 실행 가능한 시간을 초 단위로 설정합니다. 이 시간에 도달하면 스크립트는 치명적인 오류를 발생합니다. 기본 제한은 30초이거나, php.ini에 정의한 max_execution_time 값입니다.

호출할 때, set_time_limit()는 종료 시간을 0부터 다시 시작합니다. 즉, 기본 설정이 30초이고, 25초간 스크립트가 실행한 시점에서 set_time_limit(20)을 호출하면, 스크립트는 시간 제한까지 총 45초간 실행됩니다.

인수

seconds

초 단위의 최대 실행 시간. 0으로 설정하면, 무제한입니다.

반환값

값을 반환하지 않습니다.

주의

Warning

set_time_limit()는 PHP가 안전 모드일 때는 작동하지 않습니다. 이 경우, 안전 모드를 설정하지 않거나, php.ini에서 시간 제한을 변경해야 합니다.

Note: set_time_limit() 함수와 설정 지시어 max_execution_time는 스크립트 자신의 실행 시간에만 영향을 줍니다. system()을 사용한 시스템 호출이나, 스트림 연산, 데이터베이스 질의 등 스크립트 밖에서 발생하는 작동은 스크립트 실행 시간을 측정할 때 포함하지 않습니다.



sys_get_temp_dir

(PHP 5 >= 5.2.1)

sys_get_temp_dirReturns directory path used for temporary files

설명

string sys_get_temp_dir ( void )

Returns the path of the directory PHP stores temporary files in by default.

반환값

Returns the path of the temporary directory.

예제

Example #1 sys_get_temp_dir() example

<?php
// Create a temporary file in the temporary 
// files directory using sys_get_temp_dir()
$temp_file tempnam(sys_get_temp_dir(), 'Tux');

echo 
$temp_file;
?>

위 예제의 출력 예시:

C:\Windows\Temp\TuxA318.tmp

참고



version_compare

(PHP 4 >= 4.1.0, PHP 5)

version_compareCompares two "PHP-standardized" version number strings

설명

mixed version_compare ( string $version1 , string $version2 [, string $operator ] )

version_compare() compares two "PHP-standardized" version number strings. This is useful if you would like to write programs working only on some versions of PHP.

The function first replaces _, - and + with a dot . in the version strings and also inserts dots . before and after any non number so that for example '4.3.2RC1' becomes '4.3.2.RC.1'. Then it splits the results like if you were using explode('.', $ver). Then it compares the parts starting from left to right. If a part contains special version strings these are handled in the following order: dev < alpha = a < beta = b < RC < pl. This way not only versions with different levels like '4.1' and '4.1.2' can be compared but also any PHP specific version containing development state.

인수

version1

First version number.

version2

Second version number.

operator

If you specify the third optional operator argument, you can test for a particular relationship. The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively.

This parameter is case-sensitive, so values should be lowercase.

반환값

By default, version_compare() returns -1 if the first version is lower than the second, 0 if they are equal, and 1 if the second is lower.

When using the optional operator argument, the function will return TRUE if the relationship is the one specified by the operator, FALSE otherwise.

예제

The examples below use the PHP_VERSION constant, because it contains the value of the PHP version that is executing the code.

Example #1 version_compare() examples

<?php
if (version_compare(PHP_VERSION'6.0.0') === 1) {
    echo 
'I am at least PHP version 6.0.0, my version: ' PHP_VERSION "\n";
}

if (
version_compare(PHP_VERSION'5.3.0') === 1) {
    echo 
'I am at least PHP version 5.3.0, my version: ' PHP_VERSION "\n";
}

if (
version_compare(PHP_VERSION'5.0.0''>')) {
    echo 
'I am using PHP 5, my version: ' PHP_VERSION "\n";
}

if (
version_compare(PHP_VERSION'5.0.0''<')) {
    echo 
'I am using PHP 4, my version: ' PHP_VERSION "\n";
}
?>

주의

Note: The PHP_VERSION constant holds current PHP version.

Note: Note that pre-release versions, such as 5.3.0-dev, are considered lower than their final release counterparts (like 5.3.0).

참고



zend_logo_guid

(PHP 4, PHP 5)

zend_logo_guidGets the Zend guid

설명

string zend_logo_guid ( void )

This function returns the ID which can be used to display the Zend logo using the built-in image.

반환값

Returns PHPE9568F35-D428-11d2-A769-00AA001ACF42.

예제

Example #1 zend_logo_guid() example

<?php

echo '<img src="' $_SERVER['PHP_SELF'] .
     
'?=' zend_logo_guid() . '" alt="Zend Logo !" />';

?>

참고



zend_thread_id

(PHP 5)

zend_thread_idReturns a unique identifier for the current thread

설명

int zend_thread_id ( void )

This function returns a unique identifier for the current thread.

반환값

Returns the thread id as an integer.

예제

Example #1 zend_thread_id() example

<?php
$thread_id 
zend_thread_id();

echo 
'Current thread id is: ' $thread_id;
?>

위 예제의 출력 예시:

Current thread id is: 7864

주의

Note: This function is only available if PHP has been built with ZTS (Zend Thread Safety) support and debug mode (--enable-debug).



zend_version

(PHP 4, PHP 5)

zend_version현재 젠드 엔진의 버전을 얻습니다

설명

string zend_version ( void )

현재 실행 중인 젠드 엔진 버전을 가지는 문자열을 반환합니다.

반환값

젠드 엔진 버전을 문자열로 반환합니다.

예제

Example #1 zend_version() 예제

<?php
echo "젠드 엔진 버전: " zend_version();
?>

위 예제의 출력 예시:

젠드 엔진 버전: 2.2.0

참고


Table of Contents




Memtrack


소개

The purpose of this extension is to detect the most memory hungry scripts and functions.

memtrack tracks memory consumption in PHP scripts and produces reports (warnings) when the consumption reaches certain levels set by the user. This is achieved by replacing default executor function by a special function which compares memory usage before and after running the original executor - this way we can tell how much the memory usage has changed during the execution of the current part of the code.

Zend Engine runs its executor for each opcode array (op_array), which usually means function, plain script and such, so memtrack doesn't have any noticeable effect on performance.

memtrack doesn't provide any functions, there are only INI directives which allow you to configure the way it should work.

Warning

이 확장 모듈은 실험적입니다. 이 확장 모듈의 작동(함수의 이름과 이 확장 모듈에 관련된 모든 문서 자료)은 이후의 PHP 릴리즈에서 예고 없이 변경될 수 있습니다. 이 확장 모듈의 사용은 사용자의 책임하에 이루어집니다.



설치/설정

Table of Contents


요구 조건

이 확장을 빌드할 때 외부 라이브러리가 필요하지 않습니다.



설치

PECL 확장 설치에 관한 정보는 매뉴얼의 PECL 확장 설치에 있습니다. 새 릴리즈, 내려받기, 소스파일, 개발자 정보, CHANGELOG 등의 추가 정보는 여기에 있습니다: » http://pecl.php.net/package/memtrack



실행시 설정

이 함수의 작동은 php.ini 설정에 영향을 받습니다.

Memtrack Configuration Options
Name Default Changeable
memtrack.enabled "0" PHP_INI_SYSTEM
memtrack.soft_limit "0" PHP_INI_ALL
memtrack.hard_limit "0" PHP_INI_ALL
memtrack.vm_limit "0" PHP_INI_ALL
memtrack.ignore_functions "" PHP_INI_SYSTEM

PHP_INI_* 모드에 대한 상세와 정의는 환경 설정을 바꿀 수 있는 곳를 참고하십시오.

위 설정 지시어에 대한 간단한 설명입니다.

memtrack.enabled boolean

Disables or enables the extension. Default value is 0, i.e. disabled.

memtrack.soft_limit int

Soft memory limit.

The extension checks memory consumption before and after executing an op_array and produces a warning is the difference between the two values is equal to or greater than the soft limit, but only if the function is not ignored.

Setting this option to 0 also disables both soft and hard limit warnings. Default value is 0, i.e. no warnings is produced.

memtrack.hard_limit int

Hard memory limit.

The extension checks memory consumption before and after executing an op_array and produces a warning is the difference between the two values is equal to or greater than the hard limit, even if the function is ignored. Setting this option to 0 disables hard limit warnings completely. Default value is 0, i.e. no hard limit warnings is produced.

memtrack.vm_limit int

Virtual memory limit (set on a process).

This limit is checked only on shutdown and a warning is produced if the value is greater than or equal to the limit.

This option is currently supported only on OSes where mallinfo() function is available (i.e. Linux).

memtrack.ignore_functions string

A comma or whitespace-separated list of functions which are to be ignored by soft_limit. The values are case-insensitive, for class methods use class::method syntax.



자원형

이 확장은 리소스형을 정의하지 않습니다.




예약 상수

이 확장은 상수를 정의하지 않습니다.



예제

Table of Contents


Basic example on using memtrack extension:

Example #1 Creating large array in a function

<?php

/* /tmp/example1.php */

function foo() {
    
$a = array();
    for (
$i 0$i 10000$i++) $a[] = "test";
    return 
$a;
}
$arr foo();

?>

Run the example with the following command:

php -d memtrack.enabled=1 -d memtrack.soft_limit=1M -d memtrack.vm_limit=3M /tmp/example1.php

위 예제의 출력 예시:

Warning: [memtrack] [pid 26177] user function foo() executed in /tmp/example1.php on line 10 allocated 4194304 bytes in /tmp/example1.php on line 0
Warning: [memtrack] [pid 26177] virtual memory usage on shutdown: 32911360 bytes in Unknown on line 0




Object property and method call overloading


소개

The purpose of this extension is to allow overloading of object property access and method calls. Only one function is defined in this extension, overload() which takes the name of the class that should have this functionality enabled. The class named has to define appropriate methods if it wants to have this functionality: __get(), __set() and __call() respectively for getting/setting a property, or calling a method. This way overloading can be selective. Inside these handler functions the overloading is disabled so you can access object properties normally.

Warning

이 확장 모듈은 실험적입니다. 이 확장 모듈의 작동(함수의 이름과 이 확장 모듈에 관련된 모든 문서 자료)은 이후의 PHP 릴리즈에서 예고 없이 변경될 수 있습니다. 이 확장 모듈의 사용은 사용자의 책임하에 이루어집니다.

Warning

This extension is not a part of PHP 5. PHP 5 supports __get(), __set() and __call() natively. See the Overloading in PHP 5 page for more information.



설치/설정

Table of Contents


요구 조건

이 확장을 빌드할 때 외부 라이브러리가 필요하지 않습니다.



설치

In order to use these functions, you must compile PHP with the --enable-overload option. Starting with PHP 4.3.0 this extension is enabled by default. You can disable overload support with --disable--overload.

PHP 윈도우 버전에서는 이 확장에 대한 지원이 포함되어 있습니다. 이 함수들을 이용하기 위해서 추가로 확장을 읽어들일 필요가 없습니다.

Note: Builtin support for overload is available with PHP 4.3.0.



실행시 설정

이 확장은 php.ini 설정이 존재하지 않습니다.



자원형

이 확장은 리소스형을 정의하지 않습니다.




예약 상수

이 확장은 상수를 정의하지 않습니다.



예제

Table of Contents


Some simple examples on using the overload() function:

Example #1 Overloading a PHP class

<?php

class OO {
   var 
$a 111;
   var 
$elem = array('b' => 9'c' => 42);

   
// Callback method for getting a property
   
function __get($prop_name, &$prop_value
   {
       if (isset(
$this->elem[$prop_name])) {
           
$prop_value $this->elem[$prop_name];
           return 
true;
       } else {
           return 
false;
       }
   }

   
// Callback method for setting a property
   
function __set($prop_name$prop_value
   {
       
$this->elem[$prop_name] = $prop_value;
       return 
true;
   }
}

// Here we overload the OO object
overload('OO');

$o = new OO;
echo 
"\$o->a: $o->a\n"// print: $o->a: 111
echo "\$o->b: $o->b\n"// print: $o->b: 9
echo "\$o->c: $o->c\n"// print: $o->c: 42
echo "\$o->d: $o->d\n"// print: $o->d:

// add a new item to the $elem array in OO
$o->56

// instantiate stdclass (it is built-in in PHP 4)
// $val is not overloaded!
$val = new stdclass;
$val->prop 555;

// Set "a" to be an array with the $val object in it
// But __set() will put this in the $elem array
$o->= array($val);
var_dump($o->a[0]->prop);

?>




Object overloading 함수 목록


overload

(PHP 4 >= 4.3.0)

overloadEnable property and method call overloading for a class

설명

void overload ( string $class_name )

The overload() function will enable property and method call overloading for a class identified by class_name .

인수

class_name

The overloaded class name, as a string

반환값

값을 반환하지 않습니다.

예제

See an example in the introductory section of this part.


Table of Contents

  • overload — Enable property and method call overloading for a class



Output Buffering Control


소개

The Output Control functions allow you to control when output is sent from the script. This can be useful in several different situations, especially if you need to send headers to the browser after your script has began outputting data. The Output Control functions do not affect headers sent using header() or setcookie(), only functions such as echo() and data between blocks of PHP code.

Note: When upgrading from PHP 4.1.x (and 4.2.x) to 4.3.x due to a bug in earlier versions you must ensure that implict_flush is OFF in your php.ini, otherwise any output with ob_start() will not be hidden from output.



설치/설정

Table of Contents


요구 조건

이 확장을 빌드할 때 외부 라이브러리가 필요하지 않습니다.



설치

이 함수들은 설치하지 않아도 사용할 수 있습니다; PHP 코어의 일부입니다.



실행시 설정

이 함수의 작동은 php.ini 설정에 영향을 받습니다.

출력 제어 설정 옵션
이름 기본값 설정권한 변경점
output_buffering "0" PHP_INI_PERDIR  
output_handler NULL PHP_INI_PERDIR PHP 4.0.4부터 사용할 수 있습니다.
implicit_flush "0" PHP_INI_ALL PHP <= 4.2.3에서는 PHP_INI_PERDIR입니다.

PHP_INI_* 모드에 대한 상세와 정의는 환경 설정을 바꿀 수 있는 곳를 참고하십시오.

위 설정 지시어에 대한 간단한 설명입니다.

output_buffering boolean/integer

이 지시어를 'On'으로 설정하여 모든 파일에 출력 버퍼링을 활성화 할 수 있습니다. 버퍼의 크기를 제한하려면 이 지시어의 값으로 'On' 대신 최대 바이트 수를 사용하십시오. (예. output_buffering=4096) PHP 4.3.5부터 PHP-CLI에서는 이 지시어가 항상 Off입니다.

output_handler string

스크립트의 모든 출력을 어떤 함수를 통하게 할 수 있습니다. 예를 들면, output_handler를 mb_output_handler()로 설정하면, 문자 인코딩을 지정한 인코딩으로 변경할 수 있습니다. 출력 핸들러 설정은 자동적으로 출력 버퍼링을 켭니다.

Note: mb_output_hadler()ob_iconv_handler()를 동시에 사용할 수 없고, ob_gzhandler()zlib.output_compression도 동시에 사용할 수 없습니다.

Note: 이 지시어로는 내장 함수만 사용할 수 있습니다. 사용자 정의 함수에 대해서는 ob_start()를 사용하십시오.

implicit_flush boolean

기본값으로 FALSE입니다. TRUE로 변경하면 PHP가 모든 출력 블럭 뒤에 바로 전송하도록 출력 레이어를 설정합니다. 이는 PHP 함수 flush()를 모든 printf(), echo(), HTML 블럭 뒤에 호출하는 것과 동일합니다.

PHP를 웹 환경에서 사용할 때, 이 옵션을 켜는 것은 심각한 성능 저하를 일으킵니다. 일반적으로 디버깅 목적으로만 사용할 것을 권장합니다. CLI SAPI에서는 기본값으로 TRUE입니다.

참고: ob_implicit_flush().



자원형

이 확장은 리소스형을 정의하지 않습니다.




예약 상수

이 확장은 상수를 정의하지 않습니다.



예제

Table of Contents


예제

Example #1 Output Control example

<?php

ob_start
();
echo 
"Hello\n";

setcookie("cookiename""cookiedata");

ob_end_flush();

?>

In the above example, the output from echo() would be stored in the output buffer until ob_end_flush() was called. In the mean time, the call to setcookie() successfully stored a cookie without causing an error. (You can not normally send headers to the browser after data has already been sent.)




Output Control 함수 목록

참고

See also header() and setcookie().


flush

(PHP 4, PHP 5)

flush출력 버퍼를 비웁니다

설명

void flush ( void )

PHP가 사용하는 백엔드(CGI, 웹 서버 등)에 관계 없이 PHP의 출력 버퍼를 비웁니다. 이는 사실상 모든 출력을 사용자 브라우저에 보냅니다.

flush()는 웹 서버나 클라이언트 브라우저의 버퍼링 방식에는 영향을 주지 않습니다. 그러므로 출력 버퍼를 비우려면 ob_flush()flush()를 모두 호출해야 합니다.

몇몇 서버들은, 특히 Win32에서, 스크립트가 종료할 때까지 결과를 브라우저에 전송하지 않고 버퍼를 지속합니다.

아파치 mod_gzip 등의 서버 모듈은 자신의 버퍼를 가지고 있기에, flush()는 데이터를 클라이언트에 즉시 전송할 수 없습니다.

브라우저도 표시하기 전에 입력을 받아들이는 버퍼를 가질 수 있습니다. 예를 들어, 넷스케이프는 줄이 끝나거나 태그가 시작할때까지 텍스트를 버퍼에 보관하고, 표는 </table>가 나올때까지 표시를 하지 않습니다.

마이크로소프트 Internet Explorer의 몇몇 버전은 256바이트의 출력을 받았을 때만 페이지를 표시하기 시작하기에, 이러한 브라우저가 바로 표시를 나타나게 하려면 여분의 공백을 전송해두어야 합니다.

반환값

값을 반환하지 않습니다.



ob_clean

(PHP 4 >= 4.2.0, PHP 5)

ob_clean출력 버퍼를 지웁니다

설명

void ob_clean ( void )

출력 버퍼의 모든 내용을 버립니다.

이 함수는 ob_enc_clean()처럼 출력 버퍼를 파괴하지는 않습니다.

반환값

값을 반환하지 않습니다.

참고

  • ob_flush() - 출력 버퍼를 전송합니다
  • ob_end_flush() - 출력 버퍼를 전송하고 출력 버퍼링을 종료
  • ob_end_clean() - 출력 버퍼를 지우고 출력 버퍼링을 종료



ob_end_clean

(PHP 4, PHP 5)

ob_end_clean출력 버퍼를 지우고 출력 버퍼링을 종료

설명

bool ob_end_clean ( void )

이 함수는 가장 최근의 출력 버퍼의 내용을 버리고 그 출력 버퍼링을 종료합니다. ob_end_clean()를 호출하면 버퍼 내용은 버려지기 때문에, 버퍼의 내용으로 다른 작업을 하기 위해서는 ob_end_clean()를 호출하기 전에 ob_get_contents()를 호출해야 합니다.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다. 실패하는 경우는 활성화된 버퍼가 없는 상태에서 호출하거나 버퍼를 지울 수 없는 경우(특수 버퍼일 경우)입니다.

오류/예외

함수가 실패하면 E_NOTICE가 발생합니다.

변경점

버전 설명
4.2.0 논리 반환값 추가.

예제

다음 예제는 모든 출력 버퍼를 제거하는 간단한 방법입니다:

Example #1 ob_end_clean() 예제

<?php
ob_start
();
echo 
'Text that won\'t get displated.';
ob_end_clean();
?>

참고



ob_end_flush

(PHP 4, PHP 5)

ob_end_flush출력 버퍼를 전송하고 출력 버퍼링을 종료

설명

bool ob_end_flush ( void )

이 함수는 (존재한다면) 최상위 출력 버퍼의 내용을 전송하고 출력 버퍼를 종료합니다. ob_end_flush()를 호출하면 버퍼의 내용이 비워지기 때문에, 버퍼의 내용으로 다른 작업을 하려면 ob_end_flush()를 호출하기 전에 ob_get_contents()를 호출해야 합니다.

Note: 이 함수는 ob_get_flush()가 버퍼를 문자열로 반환하는 점을 제외하면, ob_get_flush()와 동일합니다.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다. 실패하는 경우는 활성화된 버퍼가 없는 상태에서 호출하거나 버퍼를 지울 수 없는 경우(특수 버퍼일 경우)입니다.

오류/예외

함수가 실패하면 E_NOTICE가 발생합니다.

변경점

버전 설명
4.2.0 논리 반환값 추가.

예제

Example #1 ob_end_flush() 예제

다음 예제는 모든 출력 버퍼를 전송 및 종료하는 간단한 방법을 보여줍니다:

<?php
  
while (@ob_end_flush());
?>

참고



ob_flush

(PHP 4 >= 4.2.0, PHP 5)

ob_flush출력 버퍼를 전송합니다

설명

void ob_flush ( void )

(존재한다면) 출력 버퍼의 내용을 전송합니다. ob_flush()를 호출하면 버퍼 내용이 비워지기 때문에, 버퍼의 내용으로 다른 작업을 하려면 ob_flush()를 호출하기 전에 ob_get_contents()를 호출해야 합니다.

이 함수는 ob_end_flush()처럼 출력 버퍼를 종료하지는 않습니다.

반환값

값을 반환하지 않습니다.



ob_get_clean

(PHP 4 >= 4.3.0, PHP 5)

ob_get_clean현재 버퍼 내용을 얻고 현재 출력 버퍼를 삭제

설명

string ob_get_clean ( void )

현재 버퍼 내용을 얻고 현재 출력 버퍼를 지웁니다.

ob_get_clean()ob_get_contents()ob_end_clean()을 실행한 것과 동일합니다.

반환값

출력 버퍼의 내용을 반환하고 출력 버퍼링을 종료합니다. 출력 버퍼링이 존재하지 않으면 FALSE를 반환합니다.

예제

Example #1 간단한 ob_get_clean() 예제

<?php

ob_start
();

echo 
"Hello World";

$out ob_get_clean();
$out strtolower($out);

var_dump($out);
?>

위 예제의 출력:


string(11) "hello world"

참고



ob_get_contents

(PHP 4, PHP 5)

ob_get_contents출력 버퍼의 내용을 반환

설명

string ob_get_contents ( void )

출력 버퍼를 지우지 않으면서 내용을 얻습니다.

반환값

출력 버퍼의 내용이나, 출력 버퍼링이 없을 경우 FALSE를 반환합니다.

예제

Example #1 간단한 ob_get_contents() 예제

<?php

ob_start
();

echo 
"Hello ";

$out1 ob_get_contents();

echo 
"World";

$out2 ob_get_contents();

ob_end_clean();

var_dump($out1$out2);
?>

위 예제의 출력:

string(6) "Hello "
string(11) "Hello World"

참고



ob_get_flush

(PHP 4 >= 4.3.0, PHP 5)

ob_get_flushFlush the output buffer, return it as a string and turn off output buffering

설명

string ob_get_flush ( void )

ob_get_flush() flushes the output buffer, return it as a string and turns off output buffering.

Note: This function is similar to ob_end_flush(), except that this function returns the buffer as a string.

반환값

Returns the output buffer or FALSE if no buffering is active.

예제

Example #1 ob_get_flush() example

<?php
//using output_buffering=On
print_r(ob_list_handlers());

//save buffer in a file
$buffer ob_get_flush();
file_put_contents('buffer.txt'$buffer);

print_r(ob_list_handlers());
?>

위 예제의 출력:

Array
(
    [0] => default output handler
)
Array
(
)

참고



ob_get_length

(PHP 4 >= 4.0.2, PHP 5)

ob_get_length출력 버퍼의 길이를 반환

설명

int ob_get_length ( void )

출력 버퍼 내용의 길이를 반환합니다.

반환값

출력 버퍼 내용의 길이를 반환하거나, 버퍼링이 없을 경우 FALSE를 반환합니다.

예제

Example #1 간단한 ob_get_length() 예제

<?php

ob_start
();

echo 
"Hello ";

$len1 ob_get_length();

echo 
"World";

$len2 ob_get_length();

ob_end_clean();

echo 
$len1 ", ." $len2;
?>

위 예제의 출력:

6, 11

참고



ob_get_level

(PHP 4 >= 4.2.0, PHP 5)

ob_get_level출력 버퍼링 메커니즘의 중첩 단계를 반환

설명

int ob_get_level ( void )

출력 버퍼링 메커니즘의 중첩 단계를 반환합니다.

반환값

출력 버퍼링 핸들러의 중첩 단계나, 출력 버퍼링이 없을 경우 0을 반환합니다.

참고



ob_get_status

(PHP 4 >= 4.2.0, PHP 5)

ob_get_status출력 버퍼의 상태를 얻습니다

설명

array ob_get_status ([ bool $full_status = FALSE ] )

ob_set_status()는 최고 레벨 출력 버퍼의 상태 정보를 반환합니다. full_statusTRUE로 설정하면 모든 활성 출력 버퍼의 상태를 반환합니다.

인수

full_status

TRUE이면 모든 활성 출력 버퍼의 상태를 반환합니다. FALSE나 설정하지 않으면 최고 레벨 출력 버퍼만 반환합니다.

반환값

full_status 인수 없이, 혹은 full_status = FALSE로 호출하면 다음 요소를 포함하는 간단한 배열을 반환합니다:

Array
(
    [level] => 2
    [type] => 0
    [status] => 0
    [name] => URL-Rewriter
    [del] => 1
)

간단한 ob_get_status() 결과
키:level
값:출력 중첩 레벨
키:type
값:PHP_OUTPUT_HANDLER_INTERNAL (0)이나 PHP_OUTPUT_HANDLER_USER (1)
키:status
값:PHP_OUTPUT_HANDLER_START (0), PHP_OUTPUT_HANDLER_CONT (1), PHP_OUTPUT_HANDLER_END (2) 중 하나
키:name
값:활성 출력 핸들러의 이름이나, 설정하지 않았을 경우에는 'default output handler'
키:del
값:ob_start()가 설정하는 Erase 플래그

full_status = TRUE로 호출하면, 각 활성 출력 버퍼가 하나의 원소인 배열을 반환합니다. 최상위 배열은 출력 레벨을 키로 가지고, 각 배열 원소는 활성 출력 레벨에 대한 상태 정보를 가지는 또 다른 배열입니다.

Array
(
    [0] => Array
        (
            [chunk_size] => 0
            [size] => 40960
            [block_size] = > 10240
            [type] => 1
            [status] => 0
            [name] => default output handler
            [del] => 1
        )

    [1] => Array
        (
            [chunk_size] => 0
            [size] => 40960
            [block_size] = > 10240
            [type] => 0
            [buffer_size] => 0
            [status] => 0
            [name] => URL-Rewriter
            [del] => 1
        )

)

전체 출력은 세가지 추가 원소를 가집니다:

전체 ob_get_status() 결과
키:chunk_size
값:ob_start()가 설정한 덩어리 크기
키:size
값:...
키:blocksize
값:...

참고



ob_gzhandler

(PHP 4 >= 4.0.4, PHP 5)

ob_gzhandlergzip 출력 버퍼를 위한 ob_start 콜백 함수

설명

string ob_gzhandler ( string $buffer , int $mode )

ob_gzhandler()는 웹 페이지 압축을 지원하는 웹 브라우저에 gz-인코드 데이터를 전송하기 위한 ob_start()의 콜백 함수로 사용하도록 준비되었습니다. ob_gzhandler()가 실제로 압축 데이터를 전송하기 전에, 브라우저가 어떠한 내용 인코딩 형태("gzip", "deflate", 그 외에는 none)를 받아들이는지 확인하여, 그에 따라서 출력합니다. 웹 페이지 압축을 허용하는 올바른 헤더를 전송하는 모든 브라우저를 지원합니다. 브라우저가 압축 페이지를 지원하지 않으면, 이 함수는 FALSE를 반환합니다.

인수

buffer

mode

반환값

변경점

버전 설명
4.0.5 mode 인수 추가.

예제

Example #1 ob_gzhandler() 예제

<?php

ob_start
("ob_gzhandler");

?>
<html>
<body>
<p>This should be a compressed page.</p>
</html>
<body>

주의

Note: ob_gzhandler()zlib 확장이 필요합니다.

Note: ob_gzhandler()zlib.output_compression을 둘 다 사용할 수는 없습니다. ob_gzhandler()보다 zlib.output_compression을 권장합니다.

참고



ob_implicit_flush

(PHP 4, PHP 5)

ob_implicit_flush즉시 출력의 여부를 결정

설명

void ob_implicit_flush ([ int $flag ] )

ob_implicit_flush()는 즉시 출력을 켜거나 끕니다. 즉시 출력은 모든 출력 호출 뒤에 flush 작동을 하기에, 따로 flush()을 호출할 필요가 없습니다.

인수

flag

TRUE로 즉시 출력을 켜고, FALSE로 끕니다. 기본값은 TRUE입니다.

반환값

값을 반환하지 않습니다.

참고

  • flush() - 출력 버퍼를 비웁니다
  • ob_start() - 출력 버퍼링을 켭니다
  • ob_end_flush() - 출력 버퍼를 전송하고 출력 버퍼링을 종료



ob_list_handlers

(PHP 4 >= 4.3.0, PHP 5)

ob_list_handlersList all output handlers in use

설명

array ob_list_handlers ( void )

Lists all output handlers in use.

반환값

This will return an array with the output handlers in use (if any). If output_buffering is enabled or an anonymous function was used with ob_start(), ob_list_handlers() will return "default output handler".

예제

Example #1 ob_list_handlers() example

<?php
//using output_buffering=On
print_r(ob_list_handlers());
ob_end_flush();

ob_start("ob_gzhandler");
print_r(ob_list_handlers());
ob_end_flush();

// anonymous functions
ob_start(create_function('$string''return $string;'));
print_r(ob_list_handlers());
ob_end_flush();
?>

위 예제의 출력:

Array
(
    [0] => default output handler
)

Array
(
    [0] => ob_gzhandler
)

Array
(
    [0] => default output handler
)

참고

  • ob_end_clean() - 출력 버퍼를 지우고 출력 버퍼링을 종료
  • ob_end_flush() - 출력 버퍼를 전송하고 출력 버퍼링을 종료
  • ob_get_flush() - Flush the output buffer, return it as a string and turn off output buffering
  • ob_start() - 출력 버퍼링을 켭니다



ob_start

(PHP 4, PHP 5)

ob_start출력 버퍼링을 켭니다

설명

bool ob_start ([ callback $output_callback [, int $chunk_size [, bool $erase ]]] )

출력 버퍼링을 켭니다. 출력 버퍼링을 활성화하면, (헤더를 제외한) 스크립트의 모든 출력을 내부 버퍼에 저장하고, 실제로 전송하지 않습니다.

이 내부 버퍼의 내용은 ob_get_contents()를 이용해서 문자열 변수로 복사할 수 있습니다. 내부 버퍼에 들어있는 내용을 출력하려면, ob_end_flush()를 사용하십시오. 반대로, ob_end_clean()은 버퍼 내용을 출력 없이 지웁니다.

Warning

몇몇 웹 서버(아파치 등)는 콜백 함수를 호출할 때 스크립트의 작업 디렉토리를 바꿉니다. 콜백 함수 안에서 chdir(dirname($_SERVER['SCRIPT_FILENAME'])) 등을 사용하여 복귀할 수 있습니다.

출력 버퍼는 쌓을 수 있습니다. 즉, ob_start()가 작동중일 때, 다른 ob_start()를 호출할 수 있습니다. 정확한 횟수의 ob_end_flush()을 호출하면 아무런 문제가 없습니다. 여러 개의 출력 콜백 함수가 작동중이면, 출력은 감싸여진 순서대로 필터링됩니다.

인수

output_callback

선택적인 output_callback 함수를 지정할 수 있습니다. 이 함수는 문자열을 인수로 받고, 문자열을 반환해야 합니다. 이 함수는 (ob_flush(), ob_clean() 등의 함수로) 출력 버퍼를 보내거나(전송) 비울 때, 또는 요청 마지막에 출력 버퍼를 브라우저로 보낼 때 호출됩니다. output_callback 이 호출되면, 출력 버퍼의 내용을 인수로 받고, 브라우저로 전송할 새 출력 버퍼를 결과로 반환하여 작동합니다. output_callback 이 호출할 수 있는 함수가 아니라면, 이 함수는 FALSE를 반환합니다.

콜백 함수가 두 인수를 가지고 있으면, 두번째 인수는 PHP_OUTPUT_HANDLER_START, PHP_OUTPUT_HANDLER_CONT, PHP_OUTPUT_HANDLER_END로 구성된 비트 필드로 채워집니다.

output_callbackFALSE를 반환하면, 원 입력이 브라우저로 전송됩니다.

output_callback 인수는 NULL 값을 넘겨서 지나갈 수 있습니다.

ob_end_clean(), ob_end_flush(), ob_clean(), ob_flush(), ob_start()는 콜백 함수에서 호출할 수 없습니다. 이 함수들을 콜백 함수에서 호출하면, 그 동작은 정의되어 있지 않습니다. 버퍼 내용을 지우고 싶으면, 콜백 함수에서 ""(빈 문자열)을 반환하면 됩니다. 또한, 출력 버퍼링 함수를 사용하는 print_r($expression, true), highlight_file($filename, true) 등의 함수도 콜백 함수에서 호출할 수 없습니다.

Note: PHP 4.0.4에서, ob_gzhandler()가 웹 페이지 압축을 지원하는 웹 브라우저에 gz-인코드 데이터를 전송하기 위한 방법으로 생겼습니다. ob_gzhandler()는 브라우저가 허용하는 내용 인코딩 형태를 확인하고 그에 따라 출력합니다.

chunk_size

선택적인 chunk_size 인수가 전달되면, 버퍼 길이가 chunk_size 와 같거나 초과하게 되는 출력 호출 후에 버퍼가 전송됩니다. 기본값인 0은 함수를 마지막에만 호출하며, 특수값 1은 chunk_size 를 4096으로 설정합니다.

erase

선택적인 erase 인수를 FALSE로 설정하면, 스크립트가 종료될 때 까지 버퍼가 지워지지 않습니다. (PHP 4.3.0부터)

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

변경점

버전 설명
4.3.2 output_callback 가 실행될 수 없을 때, FALSE를 반환하게 되었습니다.

예제

Example #1 사용자 정의 콜백 함수 예제

<?php

function callback($buffer)
{
  
// 모든 apples를 oranges로 치환합니다.
  
return (str_replace("apples""oranges"$buffer));
}

ob_start("callback");

?>

<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>

<?php

ob_end_flush
();

?>

위 예제의 출력:

<html>
<body>
<p>It's like comparing oranges to oranges.</p>
</body>
</html>

참고



output_add_rewrite_var

(PHP 4 >= 4.3.0, PHP 5)

output_add_rewrite_varAdd URL rewriter values

설명

bool output_add_rewrite_var ( string $name , string $value )

This function adds another name/value pair to the URL rewrite mechanism. The name and value will be added to URLs (as GET parameter) and forms (as hidden input fields) the same way as the session ID when transparent URL rewriting is enabled with session.use_trans_sid. Please note that absolute URLs (http://example.com/..) aren't rewritten.

This function's behavior is controlled by the url_rewriter.tags php.ini parameter.

Note: Calling this function will implicitly start output buffering if it is not active already.

인수

name

The variable name.

value

The variable value.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 output_add_rewrite_var() example

<?php
output_add_rewrite_var
('var''value');

// some links
echo '<a href="file.php">link</a>
<a href="http://example.com">link2</a>'
;

// a form
echo '<form action="script.php" method="post">
<input type="text" name="var2" />
</form>'
;

print_r(ob_list_handlers());
?>

위 예제의 출력:

<a href="file.php?var=value">link</a>
<a href="http://example.com">link2</a>

<form action="script.php" method="post">
<input type="hidden" name="var" value="value" />
<input type="text" name="var2" />
</form>

Array
(
    [0] => URL-Rewriter
)

참고



output_reset_rewrite_vars

(PHP 4 >= 4.3.0, PHP 5)

output_reset_rewrite_varsReset URL rewriter values

설명

bool output_reset_rewrite_vars ( void )

This function resets the URL rewriter and removes all rewrite variables previously set by the output_add_rewrite_var() function or the session mechanism (if session.use_trans_sid was set on session_start()).

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 output_reset_rewrite_vars() example

<?php
session_start
();
output_add_rewrite_var('var''value');

echo 
'<a href="file.php">link</a>';
ob_flush();

output_reset_rewrite_vars();
echo 
'<a href="file.php">link</a>';
?>

위 예제의 출력:

<a href="file.php?PHPSESSID=xxx&var=value">link</a>
<a href="file.php">link</a>

참고


Table of Contents




runkit


소개

The runkit extension provides means to modify constants, user-defined functions, and user-defined classes. It also provides for custom superglobal variables and embeddable sub-interpreters via sandboxing.

This package is meant as a feature added replacement for the » classkit package. When compiled with the --enable-runkit=classkit option to ./configure, it will export classkit compatible function definitions and constants.



예약 상수

이 확장은 다음의 상수들을 정의합니다. 이 확장을 PHP에 내장했거나, 실행시에 동적으로 읽어들일 경우에만 사용할 수 있습니다.

RUNKIT_IMPORT_FUNCTIONS (integer)
runkit_import() flag indicating that normal functions should be imported from the specified file.
RUNKIT_IMPORT_CLASS_METHODS (integer)
runkit_import() flag indicating that class methods should be imported from the specified file.
RUNKIT_IMPORT_CLASS_CONSTS (integer)
runkit_import() flag indicating that class constants should be imported from the specified file. Note that this flag is only meaningful in PHP versions 5.1.0 and above.
RUNKIT_IMPORT_CLASS_PROPS (integer)
runkit_import() flag indicating that class standard properties should be imported from the specified file.
RUNKIT_IMPORT_CLASSES (integer)
runkit_import() flag representing a bitwise OR of the RUNKIT_IMPORT_CLASS_* constants.
RUNKIT_IMPORT_OVERRIDE (integer)
runkit_import() flag indicating that if any of the imported functions, methods, constants, or properties already exist, they should be replaced with the new definitions. If this flag is not set, then any imported definitions which already exist will be discarded.
RUNKIT_ACC_PUBLIC (integer)
PHP 5 specific flag to runkit_method_add()
RUNKIT_ACC_PROTECTED (integer)
PHP 5 specific flag to runkit_method_add()
RUNKIT_ACC_PRIVATE (integer)
PHP 5 specific flag to runkit_method_add()
CLASSKIT_ACC_PUBLIC (integer)
PHP 5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.
CLASSKIT_ACC_PROTECTED (integer)
PHP 5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.
CLASSKIT_ACC_PRIVATE (integer)
PHP 5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.
CLASSKIT_AGGREGATE_OVERRIDE (integer)
PHP 5 specific flag to classkit_import() Only defined when classkit compatibility is enabled.
RUNKIT_VERSION (string)
Defined to the current version of the runkit package.
CLASSKIT_VERSION (string)
Defined to the current version of the runkit package. Only defined when classkit compatibility is enabled.


설치/설정

Table of Contents


요구 조건

Modifying Constants, Functions, Classes, and Methods works with all releases of PHP 4 and PHP 5. No special requirements are necessary.

Custom Superglobals are only available in PHP 4.2.0 or later.

Sandboxing requires PHP 5.1.0 or later, or PHP 5.0.0 with a special TSRM patch applied. Regardless of which version of PHP is in use it must be compiled with the --enable-maintainer-zts option. See the README file in the runkit package for additional information.



설치

» PECL 확장은 PHP 배포판에서 제공하지 않습니다.

PECL 확장 설치에 관한 정보는 매뉴얼의 PECL 확장 설치에 있습니다. 새 릴리즈, 내려받기, 소스파일, 개발자 정보, CHANGELOG 등의 추가 정보는 여기에 있습니다: » http://pecl.php.net/package/runkit.

PECL 확장에 대한 DLL은 현재 사용할 수 없습니다. 윈도우에서 빌드하기 섹션을 참고하십시오.



실행시 설정

이 함수의 작동은 php.ini 설정에 영향을 받습니다.

Runkit Configuration Options
Name Default Changeable Changelog
runkit.superglobal "" PHP_INI_PERDIR  
runkit.internal_override "0" PHP_INI_SYSTEM  

PHP_INI_* 모드에 대한 상세와 정의는 환경 설정을 바꿀 수 있는 곳를 참고하십시오.

위 설정 지시어에 대한 간단한 설명입니다.

runkit.superglobal string
Comma-separated list of variable names to be treated as superglobals. This value should be set in the systemwide php.ini file, but may work in perdir configuration contexts depending on your SAPI.

Example #1 Custom Superglobals with runkit.superglobal=_FOO,_BAR in php.ini

<?php
function show_values() {
  echo 
"Foo is $_FOO\n";
  echo 
"Bar is $_BAR\n";
  echo 
"Baz is $_BAZ\n";
}

$_FOO 'foo';
$_BAR 'bar';
$_BAZ 'baz';

/* Displays foo and bar, but not baz */
show_values();
?>
runkit.internal_override boolean
Enables ability to modify/rename/remove internal functions.



자원형

이 확장은 리소스형을 정의하지 않습니다.




runkit 함수 목록


Runkit_Sandbox

(PECL runkit >= 0.7.0)

Runkit_Sandbox Runkit Sandbox Class -- PHP Virtual Machine

설명

Instantiating the Runkit_Sandbox class creates a new thread with its own scope and program stack. Using a set of options passed to the constructor, this environment may be restricted to a subset of what the primary interpreter can do and provide a safer environment for executing user supplied code.

Note: Sandbox 지원(runkit_linux(), runkit_lint_file(), Runkit_Sandbox 클래스에 필요합니다)은 PHP 5.1이나 특별히 패치된 PHP 5.0에서 쓰레드 안전(therad safety)을 활성화해야 합니다. 자세한 정보는 runkit 패키지에 포함된 README 파일을 참고하십시오.

Constructor

void Runkit_Sandbox::__construct ([ array $options ] )

options is an associative array containing any combination of the special ini options listed below.

safe_mode

If the outer script which is instantiating the Runkit_Sandbox class is configured with safe_mode = off, then safe_mode may be turned on for the sandbox environment. This setting can not be used to disable safe_mode when it's already enabled in the outer script.

safe_mode_gid

If the outer script which is instantiating the Runkit_Sandbox class is configured with safe_mode_gid = on, then safe_mode_gid may be turned off for the sandbox environment. This setting can not be used to enable safe_mode_gid when it's already disabled in the outer script.

safe_mode_include_dir

If the outer script which is instantiating the Runkit_Sandbox class is configured with a safe_mode_include_dir, then a new safe_mode_include_dir may be set for sandbox environments below the currently defined value. safe_mode_include_dir may also be cleared to indicate that the bypass feature is disabled. If safe_mode_include_dir was blank in the outer script, but safe_mode was not enabled, then any arbitrary safe_mode_include_dir may be set while turning safe_mode on.

open_basedir

open_basedir may be set to any path below the current setting of open_basedir. If open_basedir is not set within the global scope, then it is assumed to be the root directory and may be set to any location.

allow_url_fopen

Like safe_mode , this setting can only be made more restrictive, in this case by setting it to FALSE when it is previously set to TRUE

disable_functions

Comma separated list of functions to disable within the sandbox sub-interpreter. This list need not contain the names of the currently disabled functions, they will remain disabled whether listed here or not.

disable_classes

Comma separated list of classes to disable within the sandbox sub-interpreter. This list need not contain the names of the currently disabled classes, they will remain disabled whether listed here or not.

runkit.superglobal

Comma separated list of variables to be treated as superglobals within the sandbox sub-interpreter. These variables will be used in addition to any variables defined internally or through the global runkit.superglobal setting.

runkit.internal_override

Ini option runkit.internal_override may be disabled (but not re-enabled) within sandboxes.

Example #1 Instantiating a restricted sandbox

<?php
$options 
= array(
  
'safe_mode'=>true,
  
'open_basedir'=>'/var/www/users/jdoe/',
  
'allow_url_fopen'=>'false',
  
'disable_functions'=>'exec,shell_exec,passthru,system',
  
'disable_classes'=>'myAppClass');
$sandbox = new Runkit_Sandbox($options);
/* Non-protected ini settings may set normally */
$sandbox->ini_set('html_errors',true);
?>

Accessing Variables

All variables in the global scope of the sandbox environment are accessible as properties of the sandbox object. The first thing to note is that because of the way memory between these two threads is managed, object and resource variables can not currently be exchanged between interpreters. Additionally, all arrays are deep copied and any references will be lost. This also means that references between interpreters are not possible.

Example #2 Working with variables in a sandbox

<?php
$sandbox 
= new Runkit_Sandbox();

$sandbox->foo 'bar';
$sandbox->eval('echo "$foo\n"; $bar = $foo . "baz";');
echo 
"{$sandbox->bar}\n";
if (isset(
$sandbox->foo)) unset($sandbox->foo);
$sandbox->eval('var_dump(isset($foo));');
?>

위 예제의 출력:

bar
barbaz
bool(false)

Calling PHP Functions

Any function defined within the sandbox may be called as a method on the sandbox object. This also includes a few pseudo-function language constructs: eval(), include(), include_once(), require(), require_once(), echo(), print(), die(), and exit().

Example #3 Calling sandbox functions

<?php
$sandbox 
= new Runkit_Sandbox();

echo 
$sandbox->str_replace('a','f','abc');
?>

위 예제의 출력:

fbc

When passing arguments to a sandbox function, the arguments are taken from the outer instance of PHP. If you wish to pass arguments from the sandbox's scope, be sure to access them as properties of the sandbox object as illustrated above.

Example #4 Passing arguments to sandbox functions

<?php
$sandbox 
= new Runkit_Sandbox();

$foo 'bar';
$sandbox->foo 'baz';
echo 
$sandbox->str_replace('a',$foo,'a');
echo 
$sandbox->str_replace('a',$sandbox->foo,'a');
?>

위 예제의 출력:

bar
baz

Changing Sandbox Settings

As of runkit version 0.5, certain Sandbox settings may be modified on the fly using ArrayAccess syntax. Some settings, such as active are read-only and meant to provide status information. Other settings, such as output_handler may be set and read much like a normal array offset. Future settings may be write-only, however no such settings currently exist.

Sandbox Settings / Status Indicators
Setting Type Purpose Default
active Boolean (Read Only) TRUE if the Sandbox is still in a usable state, FALSE if the request is in bailout due to a call to die(), exit(), or because of a fatal error condition. TRUE (Initial)
output_handler Callback When set to a valid callback, all output generated by the Sandbox instance will be processed through the named function. Sandbox output handlers follow the same calling conventions as the system-wide output handler. None
parent_access Boolean May the sandbox use instances of the Runkit_Sandbox_Parent class? Must be enabled for other Runkit_Sandbox_Parent related settings to work. FALSE
parent_read Boolean May the sandbox read variables in its parent's context? FALSE
parent_write Boolean May the sandbox modify variables in its parent's context? FALSE
parent_eval Boolean May the sandbox evaluate arbitrary code in its parent's context? DANGEROUS FALSE
parent_include Boolean May the sandbox include php code files in its parent's context? DANGEROUS FALSE
parent_echo Boolean May the sandbox echo data in its parent's context effectively bypassing its own output_handler? FALSE
parent_call Boolean May the sandbox call functions in its parent's context? FALSE
parent_die Boolean May the sandbox kill its own parent? (And thus itself) FALSE
parent_scope Integer What scope will parental property access look at? 0 == Global scope, 1 == Calling scope, 2 == Scope preceeding calling scope, 3 == The scope before that, etc..., etc... 0 (Global)
parent_scope String When parent_scope is set to a string value, it refers to a named array variable in the global scope. If the named variable does not exist at the time of access it will be created as an empty array. If the variable exists but it not an array, a dummy array will be created containing a reference to the named global variable.  



Runkit_Sandbox_Parent

(PECL runkit >= 0.7.0)

Runkit_Sandbox_Parent Runkit Anti-Sandbox Class

설명

void Runkit_Sandbox_Parent::__construct ( void )

Instantiating the Runkit_Sandbox_Parent class from within a sandbox environment created from the Runkit_Sandbox class provides some (controlled) means for a sandbox child to access its parent.

Note: Sandbox 지원(runkit_linux(), runkit_lint_file(), Runkit_Sandbox 클래스에 필요합니다)은 PHP 5.1이나 특별히 패치된 PHP 5.0에서 쓰레드 안전(therad safety)을 활성화해야 합니다. 자세한 정보는 runkit 패키지에 포함된 README 파일을 참고하십시오.

In order for any of the Runkit_Sandbox_Parent features to function. Support must be enabled on a per-sandbox basis by enabling the parent_access flag from the parent's context.

Example #1 Working with variables in a sandbox

<?php
$sandbox 
= new Runkit_Sandbox();
$sandbox['parent_access'] = true;
?>

Accessing the Parent's Variables

Just as with sandbox variable access, a sandbox parent's variables may be read from and written to as properties of the Runkit_Sandbox_Parent class. Read access to parental variables may be enabled with the parent_read setting (in addition to the base parent_access setting). Write access, in turn, is enabled through the parent_write setting.

Unlike sandbox child variable access, the variable scope is not limited to globals only. By setting the parent_scope setting to an appropriate integer value, other scopes in the active call stack may be inspected instead. A value of 0 (Default) will direct variable access at the global scope. 1 will point variable access at whatever variable scope was active at the time the current block of sandbox code was executed. Higher values progress back through the functions that called the functions that led to the sandbox executing code that tried to access its own parent's variables.

Example #2 Accessing parental variables

<?php
$php 
= new Runkit_Sandbox();
$php['parent_access'] = true;
$php['parent_read'] = true;

$test "Global";

$php->eval('$PARENT = new Runkit_Sandbox_Parent;');

$php['parent_scope'] = 0;
one();

$php['parent_scope'] = 1;
one();

$php['parent_scope'] = 2;
one();

$php['parent_scope'] = 3;
one();

$php['parent_scope'] = 4;
one();

$php['parent_scope'] = 5;
one();

function 
one() {
    
$test "one()";
    
two();
}

function 
two() {
    
$test "two()";
    
three();
}

function 
three() {
    
$test "three()";
    
$GLOBALS['php']->eval('var_dump($PARENT->test);');
}
?>

위 예제의 출력:

string(6) "Global"
string(7) "three()"
string(5) "two()"
string(5) "one()"
string(6) "Global"
string(6) "Global"

Calling the Parent's Functions

Just as with sandbox access, a sandbox may access its parents functions providing that the proper settings have been enabled. Enabling parent_call will allow the sandbox to call all functions available to the parent scope. Language constructs are each controlled by their own setting: print() and echo() are enabled with parent_echo. die() and exit() are enabled with parent_die. eval() is enabled with parent_eval while include(), include_once(), require(), and require_once() are enabled through parent_include.



runkit_class_adopt

(PECL runkit >= 0.7.0)

runkit_class_adopt Convert a base class to an inherited class, add ancestral methods when appropriate

설명

bool runkit_class_adopt ( string $classname , string $parentname )

인수

classname

Name of class to be adopted

parentname

Parent class which child class is extending

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 A runkit_class_adopt() example

<?php
class myParent {
  function 
parentFunc() {
    echo 
"Parent Function Output\n";
  }
}

class 
myChild {
}

runkit_class_adopt('myChild','myParent');
myChild::parentFunc();
?>

위 예제의 출력:

Parent Function Output

참고



runkit_class_emancipate

(PECL runkit >= 0.7.0)

runkit_class_emancipate Convert an inherited class to a base class, removes any method whose scope is ancestral

설명

bool runkit_class_emancipate ( string $classname )

인수

classname

Name of class to emancipate

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 A runkit_class_emancipate() example

<?php
class myParent {
  function 
parentFunc () {
    echo 
"Parent Function Output\n";
  }
}
class 
myChild extends myParent {
}

myChild::parentFunc();
runkit_class_emancipate('myChild');
myChild::parentFunc();
?>

위 예제의 출력:

Parent Function Output
Fatal error: Call to undefined function:  parentFunc() in example.php on line 12

참고

  • runkit_class_adopt() - Convert a base class to an inherited class, add ancestral methods when appropriate



runkit_constant_add

(PECL runkit >= 0.7.0)

runkit_constant_add Similar to define(), but allows defining in class definitions as well

설명

bool runkit_constant_add ( string $constname , mixed $value )

인수

constname

Name of constant to declare. Either a string to indicate a global constant, or classname::constname to indicate a class constant.

value

NULL, Bool, Long, Double, String, or Resource value to store in the new constant.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



runkit_constant_redefine

(PECL runkit >= 0.7.0)

runkit_constant_redefine Redefine an already defined constant

설명

bool runkit_constant_redefine ( string $constname , mixed $newvalue )

인수

constname

Constant to redefine. Either string indicating global constant, or classname::constname indicating class constant.

newvalue

New value to assign to constant.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



runkit_constant_remove

(PECL runkit >= 0.7.0)

runkit_constant_remove Remove/Delete an already defined constant

설명

bool runkit_constant_remove ( string $constname )

인수

constname

Name of constant to remove. Either a string indicating a global constant, or classname::constname indicating a class constant.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



runkit_function_add

(PECL runkit >= 0.7.0)

runkit_function_add Add a new function, similar to create_function()

설명

bool runkit_function_add ( string $funcname , string $arglist , string $code )

인수

funcname

Name of function to be created

arglist

Comma separated argument list

code

Code making up the function

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 A runkit_function_add() example

<?php
runkit_function_add
('testme','$a,$b','echo "The value of a is $a\n"; echo "The value of b is $b\n";');
testme(1,2);
?>

위 예제의 출력:

The value of a is 1
The value of b is 2

참고



runkit_function_copy

(PECL runkit >= 0.7.0)

runkit_function_copy Copy a function to a new function name

설명

bool runkit_function_copy ( string $funcname , string $targetname )

인수

funcname

Name of existing function

targetname

Name of new function to copy definition to

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 A runkit_function_copy() example

<?php
function original() {
  echo 
"In a function\n";
}
runkit_function_copy('original','duplicate');
original();
duplicate();
?>

위 예제의 출력:

In a function
In a function

참고



runkit_function_redefine

(PECL runkit >= 0.7.0)

runkit_function_redefine Replace a function definition with a new implementation

설명

bool runkit_function_redefine ( string $funcname , string $arglist , string $code )

Note: 기본적으로 사용자 함수만 삭제하거나, 이름을 바꾸거나, 변경할 수 있습니다. 내장 함수를 덮어쓰려면 php.ini 파일에서 runkit.internal_override을 활성화하여야 합니다.

인수

funcname

Name of function to redefine

arglist

New list of arguments to be accepted by function

code

New code implementation

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 A runkit_function_redefine() example

<?php
function testme() {
  echo 
"Original Testme Implementation\n";
}
testme();
runkit_function_redefine('testme','','echo "New Testme Implementation\n";');
testme();
?>

위 예제의 출력:

Original Testme Implementation
New Testme Implementation

참고



runkit_function_remove

(PECL runkit >= 0.7.0)

runkit_function_remove Remove a function definition

설명

bool runkit_function_remove ( string $funcname )

Note: 기본적으로 사용자 함수만 삭제하거나, 이름을 바꾸거나, 변경할 수 있습니다. 내장 함수를 덮어쓰려면 php.ini 파일에서 runkit.internal_override을 활성화하여야 합니다.

인수

funcname

Name of function to be deleted

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



runkit_function_rename

(PECL runkit >= 0.7.0)

runkit_function_rename Change a function's name

설명

bool runkit_function_rename ( string $funcname , string $newname )

Note: 기본적으로 사용자 함수만 삭제하거나, 이름을 바꾸거나, 변경할 수 있습니다. 내장 함수를 덮어쓰려면 php.ini 파일에서 runkit.internal_override을 활성화하여야 합니다.

인수

funcname

Current function name

newname

New function name

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



runkit_import

(PECL runkit >= 0.7.0)

runkit_import Process a PHP file importing function and class definitions, overwriting where appropriate

설명

bool runkit_import ( string $filename [, int $flags= RUNKIT_IMPORT_CLASS_METHODS ] )

Similar to include() however any code residing outside of a function or class is simply ignored. Additionally, depending on the value of flags , any functions or classes which already exist in the currently running environment will be automatically overwritten by their new definitions.

인수

filename

Filename to import function and class definitions from

flags

Bitwise OR of the RUNKIT_IMPORT_* family of constants.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.



runkit_lint_file

(PECL runkit >= 0.7.0)

runkit_lint_file Check the PHP syntax of the specified file

설명

bool runkit_lint_file ( string $filename )

The runkit_lint_file() function performs a syntax (lint) check on the specified filename testing for scripting errors. This is similar to using php -l from the commandline.

Note: Sandbox 지원(runkit_linux(), runkit_lint_file(), Runkit_Sandbox 클래스에 필요합니다)은 PHP 5.1이나 특별히 패치된 PHP 5.0에서 쓰레드 안전(therad safety)을 활성화해야 합니다. 자세한 정보는 runkit 패키지에 포함된 README 파일을 참고하십시오.

인수

filename

File containing PHP Code to be lint checked

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



runkit_lint

(PECL runkit >= 0.7.0)

runkit_lint Check the PHP syntax of the specified php code

설명

bool runkit_lint ( string $code )

The runkit_lint() function performs a syntax (lint) check on the specified php code testing for scripting errors. This is similar to using php -l from the command line except runkit_lint() accepts actual code rather than a filename.

Note: Sandbox 지원(runkit_linux(), runkit_lint_file(), Runkit_Sandbox 클래스에 필요합니다)은 PHP 5.1이나 특별히 패치된 PHP 5.0에서 쓰레드 안전(therad safety)을 활성화해야 합니다. 자세한 정보는 runkit 패키지에 포함된 README 파일을 참고하십시오.

인수

code

PHP Code to be lint checked

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



runkit_method_add

(PECL runkit >= 0.7.0)

runkit_method_addDynamically adds a new method to a given class

설명

bool runkit_method_add ( string $classname , string $methodname , string $args , string $code [, int $flags= RUNKIT_ACC_PUBLIC ] )
Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

인수

classname

The class to which this method will be added

methodname

The name of the method to add

args

Comma-delimited list of arguments for the newly-created method

code

The code to be evaluated when methodname is called

flags

The type of method to create, can be RUNKIT_ACC_PUBLIC, RUNKIT_ACC_PROTECTED or RUNKIT_ACC_PRIVATE

Note: This parameter is only used as of PHP 5, because, prior to this, all methods were public.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 runkit_method_add() example

<?php
class Example {
    function 
foo() {
        echo 
"foo!\n";
    }
}

// create an Example object
$e = new Example();

// Add a new public method
runkit_method_add(
    
'Example',
    
'add',
    
'$num1, $num2',
    
'return $num1 + $num2;',
    
RUNKIT_ACC_PUBLIC
);

// add 12 + 4
echo $e->add(124);
?>

위 예제의 출력:

16

참고



runkit_method_copy

(PECL runkit >= 0.7.0)

runkit_method_copyCopies a method from class to another

설명

bool runkit_method_copy ( string $dClass , string $dMethod , string $sClass [, string $sMethod ] )
Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

인수

dClass

Destination class for copied method

dMethod

Destination method name

sClass

Source class of the method to copy

sMethod

Name of the method to copy from the source class. If this parameter is omitted, the value of dMethod is assumed.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 runkit_method_copy() example

<?php
class Foo {
    function 
example() {
        return 
"foo!\n";
    }
}

class 
Bar {
    
// initially, no methods
}

// copy the example() method from the Foo class to the Bar class, as baz()
runkit_method_copy('Bar''baz''Foo''example');

// output copied function
echo Bar::baz();
?>

위 예제의 출력:

foo!

참고



runkit_method_redefine

(PECL runkit >= 0.7.0)

runkit_method_redefineDynamically changes the code of the given method

설명

bool runkit_method_redefine ( string $classname , string $methodname , string $args , string $code [, int $flags= RUNKIT_ACC_PUBLIC ] )

Note: This function cannot be used to manipulate the currently running (or chained) method.

Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

인수

classname

The class in which to redefine the method

methodname

The name of the method to redefine

args

Comma-delimited list of arguments for the redefined method

code

The new code to be evaluated when methodname is called

flags

The redefined method can be RUNKIT_ACC_PUBLIC, RUNKIT_ACC_PROTECTED or RUNKIT_ACC_PRIVATE

Note: This parameter is only used as of PHP 5, because, prior to this, all methods were public.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 runkit_method_redefine() example

<?php
class Example {
    function 
foo() {
        return 
"foo!\n";
    }
}

// create an Example object
$e = new Example();

// output Example::foo() (before redefine)
echo "Before: " $e->foo();

// Redefine the 'foo' method
runkit_method_redefine(
    
'Example',
    
'foo',
    
'',
    
'return "bar!\n";',
    
RUNKIT_ACC_PUBLIC
);

// output Example::foo() (after redefine)
echo "After: " $e->foo();
?>

위 예제의 출력:

Before: foo!
After: bar!

참고



runkit_method_remove

(PECL runkit >= 0.7.0)

runkit_method_removeDynamically removes the given method

설명

bool runkit_method_remove ( string $classname , string $methodname )

Note: This function cannot be used to manipulate the currently running (or chained) method.

Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

인수

classname

The class in which to remove the method

methodname

The name of the method to remove

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 runkit_method_remove() example

<?php
class Example {
    function 
foo() {
        return 
"foo!\n";
    }
    
    function 
bar() {
        return 
"bar!\n";
    }
}

// Remove the 'foo' method
runkit_method_remove(
    
'Example',
    
'foo'
);

echo 
implode(' 'get_class_methods('Example'));

?>

위 예제의 출력:

bar

참고



runkit_method_rename

(PECL runkit >= 0.7.0)

runkit_method_renameDynamically changes the name of the given method

설명

bool runkit_method_rename ( string $classname , string $methodname , string $newname )

Note: This function cannot be used to manipulate the currently running (or chained) method.

Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

인수

classname

The class in which to rename the method

methodname

The name of the method to rename

newname

The new name to give to the renamed method

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 runkit_method_rename() example

<?php
class Example {
    function 
foo() {
        return 
"foo!\n";
    }
}

// Rename the 'foo' method to 'bar'
runkit_method_rename(
    
'Example',
    
'foo',
    
'bar'
);

// output renamed function
echo Example::bar();
?>

위 예제의 출력:

foo!

참고



runkit_return_value_used

(PECL runkit >= 0.8.0)

runkit_return_value_usedDetermines if the current functions return value will be used

설명

bool runkit_return_value_used ( void )

반환값

Returns TRUE if the function's return value is used by the calling scope, otherwise FALSE

예제

Example #1 runkit_return_value_used() example

<?php
function foo() {
  
var_dump(runkit_return_value_used());
}

foo();
$f foo();
?>

위 예제의 출력:

bool(false)
bool(true)



runkit_sandbox_output_handler

(PECL runkit >= 0.7.0)

runkit_sandbox_output_handler Specify a function to capture and/or process output from a runkit sandbox

설명

mixed runkit_sandbox_output_handler ( object $sandbox [, mixed $callback ] )

Ordinarily, anything output (such as with echo() or print()) will be output as though it were printed from the parent's scope. Using runkit_sandbox_output_handler() however, output generated by the sandbox (including errors), can be captured by a function outside of the sandbox.

Note: Sandbox 지원(runkit_linux(), runkit_lint_file(), Runkit_Sandbox 클래스에 필요합니다)은 PHP 5.1이나 특별히 패치된 PHP 5.0에서 쓰레드 안전(therad safety)을 활성화해야 합니다. 자세한 정보는 runkit 패키지에 포함된 README 파일을 참고하십시오.

Note: Deprecated
As of runkit version 0.5, this function is deprecated and is scheduled to be removed from the package prior to a 1.0 release. The output handler for a given Runkit_Sandbox instance may be read/set using the array offset syntax shown on the Runkit_Sandbox class definition page.

인수

sandbox

Object instance of Runkit_Sandbox class on which to set output handling.

callback

Name of a function which expects one parameter. Output generated by sandbox will be passed to this callback. Anything returned by the callback will be displayed normally. If this parameter is not passed then output handling will not be changed. If a non-truth value is passed, output handling will be disabled and will revert to direct display.

반환값

Returns the name of the previously defined output handler callback, or FALSE if no handler was previously defined.

예제

Example #1 Feeding output to a variable

<?php
function capture_output($str) {
  
$GLOBALS['sandbox_output'] .= $str;

  return 
'';
}

$sandbox_output '';

$php = new Runkit_Sandbox();
runkit_sandbox_output_handler($php'capture_output');
$php->echo("Hello\n");
$php->eval('var_dump("Excuse me");');
$php->die("I lost myself.");
unset(
$php);

echo 
"Sandbox Complete\n\n";
echo 
$sandbox_output;
?>

위 예제의 출력:

Sandbox Complete

Hello
string(9) "Excuse me"
I lost myself.



runkit_superglobals

(PECL runkit >= 0.7.0)

runkit_superglobals Return numerically indexed array of registered superglobals

설명

array runkit_superglobals ( void )

반환값

Returns a numerically indexed array of the currently registered superglobals. i.e. _GET, _POST, _REQUEST, _COOKIE, _SESSION, _SERVER, _ENV, _FILES


Table of Contents




Break the silence operator


소개

The scream extension gives the possibility to disable the silencing error control operator so all errors are being reported. This feature is controlled by an ini setting.



설치/설정

Table of Contents


요구 조건

PHP version 5.2.0 or greater.



설치

PECL 확장 설치에 관한 정보는 매뉴얼의 PECL 확장 설치에 있습니다. 새 릴리즈, 내려받기, 소스파일, 개발자 정보, CHANGELOG 등의 추가 정보는 여기에 있습니다: » http://pecl.php.net/package/scream



실행시 설정

이 함수의 작동은 php.ini 설정에 영향을 받습니다.

scream 설정 옵션
이름 기본값 가변성 Changelog
scream.enabled Off PHP_INI_ALL  

PHP_INI_* 모드에 대한 상세와 정의는 환경 설정을 바꿀 수 있는 곳를 참고하십시오.

위 설정 지시어에 대한 간단한 설명입니다.

scream.enabled int

Whether or not to enable scream.



자원형

이 확장은 리소스형을 정의하지 않습니다.




예제

Table of Contents


Example that shows the effect of scream

This example demonstrates how scream affects the behaviour of PHP's error handler.

Example #1 Enabling and disabling scream at runtime

<?php
// Make sure errors will be shown
ini_set('display_errors'true);
error_reporting(E_ALL);

// Disable scream - this is the default and produce an error
ini_set('scream.enabled'false);
echo 
"Opening http://example.com/not-existing-file\n";
@
fopen('http://example.com/not-existing-file''r');

// Now enable scream and try again
ini_set('scream.enabled'true);
echo 
"Opening http://example.com/not-existing-file\n";
@
fopen('http://example.com/another-not-existing-file''r');
?>

위 예제의 출력 예시:

Opening http://example.com/not-existing-file
Opening http://example.com/not-existing-file

Warning: fopen(http://example.com/another-not-existing-file): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in example.php on line 14

Note: Usually one would set this in the php.ini configuration file instead of changing the code.






오디오 형식 조작


ID3 Tags


소개

These functions let you read and manipulate ID3 tags. ID3 tags are used in MP3 files to store title of the song, as well as information about the artist, album, genre, year and track number.

Since version 0.2 it is also possible to extract text frames from ID3 v2.2+ tags.



설치/설정

Table of Contents


요구 조건

이 확장을 빌드할 때 외부 라이브러리가 필요하지 않습니다.



설치

id3 is part of PECL and can be installed using the PEAR installer. To compile PHP with id3 support, download the sourcecode, put it in php-src/ext/id3 and compile PHP using --enable-id3.



실행시 설정

이 확장은 php.ini 설정이 존재하지 않습니다.



자원형

이 확장은 리소스형을 정의하지 않습니다.




Predefined Constants

Most of the id3 functions either let you specify or return a tag version. In order to specify the version please use on of these constants.

ID3_V1_0 (integer)
ID3_V1_0 is used if you are working with ID3 V1.0 tags. These tags may contain the fields title, artist, album, genre, year and comment.
ID3_V1_1 (integer)
ID3_V1_1 is used if you are working with ID3 V1.1 tags. These tags may all information contained in v1.0 tags plus the track number.
ID3_V2_1 (integer)
ID3_V2_1 is used if you are working with ID3 V2.1 tags.
ID3_V2_2 (integer)
ID3_V2_2 is used if you are working with ID3 V2.2 tags.
ID3_V2_3 (integer)
ID3_V2_3 is used if you are working with ID3 V2.3 tags.
ID3_V2_4 (integer)
ID3_V2_4 is used if you are working with ID3 V2.4 tags.
ID3_BEST (integer)
ID3_BEST is used if would like to let the id3 functions determine which tag version should be used.



ID3 함수 목록


id3_get_frame_long_name

(PECL id3 >= 0.2)

id3_get_frame_long_nameGet the long name of an ID3v2 frame

설명

string id3_get_frame_long_name ( string $frameId )

id3_get_frame_long_name() returns the long name for an ID3v2 frame.

인수

frameId

An ID3v2 frame

반환값

Returns the frame long name or FALSE on errors.

예제

Example #1 id3_get_frame_long_name() example

<?php
$longName 
id3_get_frame_long_name("TOLY");
echo 
$longName;
?>

위 예제의 출력:

Original lyricist(s)/text writer(s)

참고



id3_get_frame_short_name

(PECL id3 >= 0.2)

id3_get_frame_short_nameGet the short name of an ID3v2 frame

설명

string id3_get_frame_short_name ( string $frameId )

id3_get_frame_short_name() returns the short name for an ID3v2 frame.

인수

frameId

An ID3v2 frame

반환값

Returns the frame short name or FALSE on errors.

The values returned by id3_get_frame_short_name() are used in the array returned by id3_get_tag().

예제

Example #1 id3_get_frame_short_name() example

<?php
$shortName 
id3_get_frame_short_name("TOLY");
echo 
$shortName;
?>

위 예제의 출력:

originalLyricist

참고



id3_get_genre_id

(PECL id3 >= 0.1)

id3_get_genre_idGet the id for a genre

설명

int id3_get_genre_id ( string $genre )

id3_get_genre_id() returns the id for a genre.

인수

genre

An integer ranging from 0 to 147

반환값

The genre id or FALSE on errors.

예제

Example #1 id3_get_genre_id() example

<?php
$id 
id3_get_genre_id("Alternative");
echo 
$id;
?>

위 예제의 출력:

20

참고



id3_get_genre_list

(PECL id3 >= 0.1)

id3_get_genre_listGet all possible genre values

설명

array id3_get_genre_list ( void )

id3_get_genre_list() returns an array containing all possible genres that may be stored in an ID3 tag. This list has been created by Eric Kemp and later extended by WinAmp.

This function is useful to provide you users a list of genres from which they may choose one. When updating the ID3 tag you will always have to specify the genre as an integer ranging from 0 to 147.

반환값

Returns an array containing all possible genres that may be stored in an ID3 tag.

예제

Example #1 id3_get_genre_list() example

<?php
$genres 
id3_get_genre_list();
print_r($genres);
?>

위 예제의 출력:

Array
(
    [0] => Blues
    [1] => Classic Rock
    [2] => Country
    [3] => Dance
    [4] => Disco
    [5] => Funk
    [6] => Grunge
    [7] => Hip-Hop
    [8] => Jazz
    [9] => Metal
    [10] => New Age
    [11] => Oldies
    [12] => Other
    [13] => Pop
    [14] => R&B
    [15] => Rap
    [16] => Reggae
    [17] => Rock
    [18] => Techno
    [19] => Industrial
    [20] => Alternative
    [21] => Ska
    [22] => Death Metal
    [23] => Pranks
    [24] => Soundtrack
    [25] => Euro-Techno
    [26] => Ambient
    [27] => Trip-Hop
    [28] => Vocal
    [29] => Jazz+Funk
    [30] => Fusion
    [31] => Trance
    [32] => Classical
    [33] => Instrumental
    [34] => Acid
    [35] => House
    [36] => Game
    [37] => Sound Clip
    [38] => Gospel
    [39] => Noise
    [40] => Alternative Rock
    [41] => Bass
    [42] => Soul
    [43] => Punk
    [44] => Space
    [45] => Meditative
    [46] => Instrumental Pop
    [47] => Instrumental Rock
    [48] => Ethnic
    [49] => Gothic
    [50] => Darkwave
    [51] => Techno-Industrial
    [52] => Electronic
    [53] => Pop-Folk
    [54] => Eurodance
    [55] => Dream
    [56] => Southern Rock
    [57] => Comedy
    [58] => Cult
    [59] => Gangsta
    [60] => Top 40
    [61] => Christian Rap
    [62] => Pop/Funk
    [63] => Jungle
    [64] => Native US
    [65] => Cabaret
    [66] => New Wave
    [67] => Psychadelic
    [68] => Rave
    [69] => Showtunes
    [70] => Trailer
    [71] => Lo-Fi
    [72] => Tribal
    [73] => Acid Punk
    [74] => Acid Jazz
    [75] => Polka
    [76] => Retro
    [77] => Musical
    [78] => Rock & Roll
    [79] => Hard Rock
    [80] => Folk
    [81] => Folk-Rock
    [82] => National Folk
    [83] => Swing
    [84] => Fast Fusion
    [85] => Bebob
    [86] => Latin
    [87] => Revival
    [88] => Celtic
    [89] => Bluegrass
    [90] => Avantgarde
    [91] => Gothic Rock
    [92] => Progressive Rock
    [93] => Psychedelic Rock
    [94] => Symphonic Rock
    [95] => Slow Rock
    [96] => Big Band
    [97] => Chorus
    [98] => Easy Listening
    [99] => Acoustic
    [100] => Humour
    [101] => Speech
    [102] => Chanson
    [103] => Opera
    [104] => Chamber Music
    [105] => Sonata
    [106] => Symphony
    [107] => Booty Bass
    [108] => Primus
    [109] => Porn Groove
    [110] => Satire
    [111] => Slow Jam
    [112] => Club
    [113] => Tango
    [114] => Samba
    [115] => Folklore
    [116] => Ballad
    [117] => Power Ballad
    [118] => Rhytmic Soul
    [119] => Freestyle
    [120] => Duet
    [121] => Punk Rock
    [122] => Drum Solo
    [123] => Acapella
    [124] => Euro-House
    [125] => Dance Hall
    [126] => Goa
    [127] => Drum & Bass
    [128] => Club-House
    [129] => Hardcore
    [130] => Terror
    [131] => Indie
    [132] => BritPop
    [133] => Negerpunk
    [134] => Polsk Punk
    [135] => Beat
    [136] => Christian Gangsta
    [137] => Heavy Metal
    [138] => Black Metal
    [139] => Crossover
    [140] => Contemporary C
    [141] => Christian Rock
    [142] => Merengue
    [143] => Salsa
    [144] => Thrash Metal
    [145] => Anime
    [146] => JPop
    [147] => SynthPop
)

참고



id3_get_genre_name

(PECL id3 >= 0.1)

id3_get_genre_nameGet the name for a genre id

설명

string id3_get_genre_name ( int $genre_id )

id3_get_genre_name() returns the name for a genre id.

인수

genre_id

An integer ranging from 0 to 147

반환값

Returns the name as a string.

예제

Example #1 id3_get_genre_name() example

<?php
$genre 
id3_get_genre_name(20);
echo 
$genre;
?>

위 예제의 출력:

Alternative

참고



id3_get_tag

(PECL id3 >= 0.1)

id3_get_tagGet all information stored in an ID3 tag

설명

array id3_get_tag ( string $filename [, int $version= ID3_BEST ] )

id3_get_tag() is used to get all information stored in the id3 tag of the specified file.

인수

filename

The path to the MP3 file

Instead of a filename you may also pass a valid stream resource

version

Allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags

Since version 0.2 id3_get_tag() also supports ID3 tags of version 2.2, 2.3 and 2.4. To extract information from these tags, pass one of the constants ID3_V2_2, ID3_V2_3 or ID3_V2_4 as the second parameter. ID3 v2.x tags can contain a lot more information about the MP3 file than ID3 v1.x tags.

반환값

Returns an associative array with various keys like: title, artist, ..

The key genre will contain an integer between 0 and 147. You may use id3_get_genre_name() to convert it to a human readable string.

예제

Example #1 id3_get_tag() example

<?php
$tag 
id3_get_tag"path/to/example.mp3" );
print_r($tag);
?>

위 예제의 출력 예시:

Array
(
    [title] => DN-38416
    [artist] => Re:\Legion
    [album] => Reflections
    [year] => 2004
    [genre] => 19
)

Example #2 id3_get_tag() example

<?php
$tag 
id3_get_tag"path/to/example2.mp3"ID3_V2_3 );
print_r($tag);
?>

위 예제의 출력 예시:

Array
(
    [copyright] => Dirty Mac
    [originalArtist] => Dirty Mac
    [composer] => Marcus Götze
    [artist] => Dirty Mac
    [title] => Little Big Man
    [album] => Demo-Tape
    [track] => 5/12
    [genre] => (17)Rock
    [year] => 2001
)

참고



id3_get_version

(PECL id3 >= 0.1)

id3_get_versionGet version of an ID3 tag

설명

int id3_get_version ( string $filename )

id3_get_version() retrieves the version(s) of the ID3 tag(s) in the MP3 file.

If a file contains an ID3 v1.1 tag, it always contains a 1.0 tag, as version 1.1 is just an extension of 1.0.

인수

filename

The path to the MP3 file

Instead of a filename you may also pass a valid stream resource

반환값

Returns the version number of the ID3 tag of the file. As a tag can contain ID3 v1.x and v2.x tags, the return value of this function should be bitwise compared with the predefined constants ID3_V1_0, ID3_V1_1 and ID3_V2.

예제

Example #1 id3_get_version() example

<?php
$version 
id3_get_version"path/to/example.mp3" );
if (
$version ID3_V1_0) {
    echo 
"Contains a 1.x tag\n";
}
if (
$version ID3_V1_1) {
    echo 
"Contains a 1.1 tag\n";
}
if (
$version ID3_V2) {
    echo 
"Contains a 2.x tag\n";
}
?>

위 예제의 출력 예시:

Contains a 1.x tag
Contains a 1.1 tag

참고



id3_remove_tag

(PECL id3 >= 0.1)

id3_remove_tagRemove an existing ID3 tag

설명

bool id3_remove_tag ( string $filename [, int $version= ID3_V1_0 ] )

id3_remove_tag() is used to remove the information stored of an ID3 tag.

인수

filename

The path to the MP3 file

Instead of a filename you may also pass a valid stream resource

version

Allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 id3_remove_tag() example

<?php
$result 
id3_remove_tag"path/to/example.mp3"ID3_V1_0 );
if (
$result === true) {
    echo 
"Tag succesfully removed\n";
}
?>

If the file is writable and contained a 1.0 tag, this will output:

Tag succesfully removed

주의

Note: Currently id3_remove_tag() only supports version 1.0 and 1.1. If you choose to remove a 1.0 tag and the file contains a 1.1 tag, this tag will be removed, as v1.1 is only an extension of 1.0.

참고



id3_set_tag

(PECL id3 >= 0.1)

id3_set_tagUpdate information stored in an ID3 tag

설명

bool id3_set_tag ( string $filename , array $tag [, int $version= ID3_V1_0 ] )

id3_set_tag() is used to change the information stored of an ID3 tag. If no tag has been present, it will be added to the file.

인수

filename

The path to the MP3 file

Instead of a filename you may also pass a valid stream resource

tag

An associative array of tag keys and values

The following keys may be used in the associative array:

Keys in the associative array
key possible value available in version
title string with maximum of 30 characters v1.0, v1.1
artist string with maximum of 30 characters v1.0, v1.1
album string with maximum of 30 characters v1.0, v1.1
year 4 digits v1.0, v1.1
genre integer value between 0 and 147 v1.0, v1.1
comment string with maximum of 30 characters (28 in v1.1) v1.0, v1.1
track integer between 0 and 255 v1.1

version

Allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 id3_set_tag() example

<?php
$data 
= array(
              
"title" => "Re:Start",
              
"artist" => "Re:\Legion",
              
"comment" => "A nice track"
             
);
$result id3_set_tag"path/to/example.mp3"$dataID3_V1_0 );
if (
$result === true) {
    echo 
"Tag succesfully updated\n";
}
?>

If the file is writable, this will output:

Tag succesfully updated

주의

Note: Currently id3_remove_tag() only supports version 1.0 and 1.1.

참고


Table of Contents




KTaglib


소개

KTaglib is an object oriented binding to the taglib library from the KDE project used in projects like Amarok to read and write ID3 and Ogg tags. The library also provides access to audio information. The bindings are designed usually follow the underlying C++ API, but were changed whenever there is a more PHP-like way.

Note: At the moment ktaglib is able to read and write ID3v1 and ID3v2 tags.



설치/설정

Table of Contents


요구 조건

If you want to build ktaglib you need at least taglib 1.5 installed. To obtain the taglib see the » taglib project page. Windows DLL's are build static against taglib, therefore there is no need to have taglib installed.



설치

KTaglib support in PHP is not enabled by default. You will need to configure PHP --with-ktaglib[=DIR]

Note: KTaglib is part of PECL.




예약 상수

이 확장은 다음의 상수들을 정의합니다. 이 확장을 PHP에 내장했거나, 실행시에 동적으로 읽어들일 경우에만 사용할 수 있습니다.

KTaglib uses class constants. Most of the constants are mappings to the according Taglib enums and constants.

KTaglib_MPEG_Header::Version1 (integer)
ID3 version is 1.0
KTaglib_MPEG_Header::Version2 (integer)
ID3 version is 2.0
KTaglib_MPEG_Header::Version2_5 (integer)
ID3 version is 2.5
KTaglib_ID3v2_AttachedPictureFrame::Other (integer)
Picture type Other
KTaglib_ID3v2_AttachedPictureFrame::FileIcon (integer)
Picture type FileIcon
KTaglib_ID3v2_AttachedPictureFrame::OtherFileIcon (integer)
Picture type OtherFileIcon
KTaglib_ID3v2_AttachedPictureFrame::FrontCover (integer)
Picture type FrontCover
KTaglib_ID3v2_AttachedPictureFrame::BackCover (integer)
Picture type BackCover
KTaglib_ID3v2_AttachedPictureFrame::LeafletPage (integer)
Picture type LeafletPage
KTaglib_ID3v2_AttachedPictureFrame::Media (integer)
Picture type Media
KTaglib_ID3v2_AttachedPictureFrame::LeadArtist (integer)
Picture type LeadArtist
KTaglib_ID3v2_AttachedPictureFrame::Artist (integer)
Picture type Artist
KTaglib_ID3v2_AttachedPictureFrame::Conductor (integer)
Picture type Condutor
KTaglib_ID3v2_AttachedPictureFrame::Band (integer)
Picture type Band
KTaglib_ID3v2_AttachedPictureFrame::Composer (integer)
Picture type Composer
KTaglib_ID3v2_AttachedPictureFrame::Lyricist (integer)
Picture type Lyricist
KTaglib_ID3v2_AttachedPictureFrame::RecordingLocation (integer)
Picture type RecordingLocation
KTaglib_ID3v2_AttachedPictureFrame::DuringRecording (integer)
Picture type DuringRecording
KTaglib_ID3v2_AttachedPictureFrame::DuringPerformance (integer)
Picture type DuringPerformance
KTaglib_ID3v2_AttachedPictureFrame::MovieScreenCapture (integer)
Picture type MovieScreenCapture
KTaglib_ID3v2_AttachedPictureFrame::ColouredFish (integer)
Picture type ColouredFish
KTaglib_ID3v2_AttachedPictureFrame::Illustration (integer)
Picture type Illustration
KTaglib_ID3v2_AttachedPictureFrame::BandLogo (integer)
Picture type BandLogo


The KTagLib_MPEG_File class

소개

Represents an MPEG file. MPEG files can have ID3v1, ID3v2 tags and audio properties.

Class synopsis

KTagLib_MPEG_File
KTagLib_MPEG_File {
}

KTaglib_MPEG_File::__construct

(0.0.1)

KTaglib_MPEG_File::__constructOpens a new file

설명

KTaglib_MPEG_File::__construct ( string $filename )

Opens a new MPEG file.

인수

filename

The file to read

예제

Example #1 Opens a new MP3 file and read the title

<?php
$mpeg 
= new KTaglib_MPEG_File('example.mp3');
echo 
$mpeg->getID3v1Tag()->getTitle();
?>



KTaglib_MPEG_File::getAudioProperties

(0.0.1)

KTaglib_MPEG_File::getAudioPropertiesReturns an object that provides access to the audio properties

설명

public KTaglib_MPEG_File: KTaglib_MPEG_File::getAudioProperties ( void )

Returns an object that provides access to the audio properties of the mpeg file.

반환값

Returns an KTaglib_MPEG_AudioProperties object or false.



KTaglib_MPEG_File::getID3v1Tag

(0.0.1)

KTaglib_MPEG_File::getID3v1TagReturns an object representing an ID3v1 tag

설명

public KTaglib_ID3v1_Tag KTaglib_MPEG_File::getID3v1Tag ([ bool $create= false ] )

Returns an object that represents an ID3v1 tag, which can be used to get information about the ID3v1 tag.

반환값

Returns an KTaglib_MPEG_ID3v1Tag object or false if there is no ID3v1 tag.



KTaglib_MPEG_File::getID3v2Tag

(0.0.1)

KTaglib_MPEG_File::getID3v2TagReturns a ID3v2 object

설명

public KTaglib_ID3v2_Tag KTaglib_MPEG_File::getID3v2Tag ([ bool $create= false ] )

Returns a ID3v2 object for the mpeg file. If no ID3v2 Tag is present, an KTaglib_TagNotFoundException is thrown.

반환값

Returns the KTaglib_ID3v2_Tag object of the MPEG file or false if there is no ID3v2 tag


Table of Contents



The KTaglib_MPEG_AudioProperties class

소개

Represents the audio properties of a MPEG file, like length, bitrate or samplerate.

Class synopsis

KTaglib_MPEG_Audioproperties
KTaglib_MPEG_AudioProperties {
}

KTaglib_MPEG_AudioProperties::getBitrate

(0.0.1)

KTaglib_MPEG_AudioProperties::getBitrateReturns the bitrate of the MPEG file

설명

public int KTaglib_MPEG_AudioProperties::getBitrate ( void )

Returns the bitrate of the MPEG file

반환값

Returns the bitrate as an integer



KTaglib_MPEG_AudioProperties::getChannels

(0.0.1)

KTaglib_MPEG_AudioProperties::getChannelsReturns the amount of channels of a MPEG file

설명

public int KTaglib_MPEG_AudioProperties::getChannels ( void )

Returns the amount of channels of the MPEG file

반환값

Returns the channel count as an integer



KTaglib_MPEG_AudioProperties::getLayer

(0.0.1)

KTaglib_MPEG_AudioProperties::getLayerReturns the layer of a MPEG file

설명

public int KTaglib_MPEG_AudioProperties::getLayer ( void )

Returns the layer of the MPEG file (usually 3 for MP3).

반환값

Returns the layer as an integer



KTaglib_MPEG_AudioProperties::getLength

(0.0.1)

KTaglib_MPEG_AudioProperties::getLengthReturns the length of a MPEG file

설명

public int KTaglib_MPEG_AudioProperties::getLength ( void )

Returns the length of the MPEG file

반환값

Returns the length as an integer



KTaglib_MPEG_AudioProperties::getSampleBitrate

(0.0.1)

KTaglib_MPEG_AudioProperties::getSampleBitrateReturns the sample bitrate of a MPEG file

설명

public int KTaglib_MPEG_AudioProperties::getSampleBitrate ( void )

Returns the sample bitrate of the MPEG file

반환값

Returns the sample bitrate as an integer



KTaglib_MPEG_AudioProperties::getVersion

(0.0.1)

KTaglib_MPEG_AudioProperties::getVersionReturns the version of a MPEG file

설명

public int KTaglib_MPEG_AudioProperties::getVersion ( void )

Returns the version of the MPEG file header. The possible versions are defined in Tag_MPEG_Header (Version1, Version2, Version2.5).

반환값

Returns the version



KTaglib_MPEG_AudioProperties::isCopyrighted

(0.0.1)

KTaglib_MPEG_AudioProperties::isCopyrightedReturns the length of a MPEG file

설명

public bool KTaglib_MPEG_AudioProperties::isCopyrighted ( void )

Returns true if the MPEG file is copyrighted

반환값

Returns true if the MPEG file is copyrighted



KTaglib_MPEG_AudioProperties::isOriginal

(0.0.1)

KTaglib_MPEG_AudioProperties::isOriginalReturns the length of a MPEG file

설명

public bool KTaglib_MPEG_AudioProperties::isOriginal ( void )

Returns true if the file is marked as the original file

반환값

Returns true if the file is marked as the original file



KTaglib_MPEG_AudioProperties::isProtectionEnabled

(0.0.1)

KTaglib_MPEG_AudioProperties::isProtectionEnabledReturns the length of a MPEG file

설명

public bool KTaglib_MPEG_AudioProperties::isProtectionEnabled ( void )

Returns true if protection mechanism (like DRM) are enabled for this file

반환값

Returns true if protection mechanism (like DRM) are enabled for this file


Table of Contents



The KTaglib_Tag class

소개

Base class for ID3v1 or ID3v2 tags

Class synopsis

KTaglib_Tag
KTaglib_Tag {
}

KTaglib_Tag::getAlbum

(0.0.1)

KTaglib_Tag::getAlbumReturns the title string from a ID3 tag

설명

public string KTaglib_Tag::getAlbum ( void )

Returns the album string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

반환값

Returns the album string



KTaglib_Tag::getArtist

(0.0.1)

KTaglib_Tag::getArtistReturns the artist string from a ID3 tag

설명

public string KTaglib_Tag::getArtist ( void )

Returns the artist string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

반환값

Returns the artist string



KTaglib_Tag::getComment

(0.0.1)

KTaglib_Tag::getCommentReturns the comment from a ID3 tag

설명

public string KTaglib_Tag::getComment ( void )

Returns the comment of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

반환값

Returns the comment string



KTaglib_Tag::getGenre

(0.0.1)

KTaglib_Tag::getGenreReturns the genre from a ID3 tag

설명

public string KTaglib_Tag::getGenre ( void )

Returns the genre of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

반환값

Returns the genre string



KTaglib_Tag::getTitle

(0.0.1)

KTaglib_Tag::getTitleReturns the title string from a ID3 tag

설명

public string KTaglib_Tag::getTitle ( void )

Returns the title string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

반환값

Returns the title string



KTaglib_Tag::getTrack

(0.0.1)

KTaglib_Tag::getTrackReturns the track number from a ID3 tag

설명

public int KTaglib_Tag::getTrack ( void )

Returns the track number of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

반환값

Returns the track number as an integer



KTaglib_Tag::getYear

(0.0.1)

KTaglib_Tag::getYearReturns the year from a ID3 tag

설명

public int KTaglib_Tag::getYear ( void )

Returns the year of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

반환값

Returns the year as an integer



KTaglib_Tag::isEmpty

(0.0.1)

KTaglib_Tag::isEmptyReturns true if the tag is empty

설명

public bool KTaglib_Tag::isEmpty ( void )

Returns true if the tag exists, but is empty. This method is implemented in ID3v1 and ID3v2 tags.

반환값

Returns true if the tag is empty, otherwise false.


Table of Contents



The KTagLib_ID3v2_Tag class

소개

Represents and ID3v2 tag. It provides a list of ID3v2 frames and can be used to add and remove additional frames.

Class synopsis

KTagLib_ID3v2_Tag
extends KTagLib_Tag {
}

KTaglib_ID3v2_Tag::addFrame

(0.0.1)

KTaglib_ID3v2_Tag::addFrameAdd a frame to the ID3v2 tag

설명

public bool KTaglib_ID3v2_Tag::addFrame ( KTagLib_ID3v2_Frame $frame )

Adds a frame to the ID3v2 tag. The frame must be a valid KTagLib_ID3v2_Frame object. To save the tag, the save function needs to be invoked.

반환값

Returns true on success, otherwise false.



KTaglib_ID3v2_Tag::getFrameList

(0.0.1)

KTaglib_ID3v2_Tag::getFrameListReturns an array of ID3v2 frames, associated with the ID3v2 tag

설명

public array KTaglib_ID3v2_Tag::getFrameList ( void )

Returns an array of ID3v2 frames, associated with the ID3v2 tag.

반환값

Return an array of KTaglib_ID3v2_Frame objects


Table of Contents



The KTagLib_ID3v2_Frame class

소개

The base class for ID3v2 frames. ID3v2 tags are separated in various specialized frames. Some frames can exists multiple times.

Class synopsis

KTagLib_ID3v2_Frame
extends KTagLib_Tag {
}

KTaglib_ID3v2_Frame::getSize

(0.0.1)

KTaglib_ID3v2_Frame::getSizeReturns the size of the frame in bytes

설명

public int KTaglib_ID3v2_Frame::getSize ( void )

Returns the size of the frame in bytes. Please refer to id3.org to see what ID3v2 frames are and how they are defined.

반환값

Returns the size of the frame in bytes



KTaglib_ID3v2_Frame::__toString

(0.0.1)

KTaglib_ID3v2_Frame::__toStringReturns a string representation of the frame

설명

public string KTaglib_ID3v2_Frame::__toString ( void )

Returns a string representation of the frame. This might be just the frame id, but might contain more information. Please see the ktaglib documentation for more information

반환값

Returns a string representation of the frame.


Table of Contents



The KTaglib_ID3v2_AttachedPictureFrame class

소개

Represents an ID3v2 frame that can hold a picture.

Class synopsis

KTaglib_ID3v2_AttachedPictureFrame
extends KTagLib_ID3v2_Frame {
}

KTaglib_ID3v2_AttachedPictureFrame::getDescription

(0.0.1)

KTaglib_ID3v2_AttachedPictureFrame::getDescriptionReturns a description for the picture in a picture frame

설명

public string KTaglib_ID3v2_AttachedPictureFrame::getDescription ( void )

Returns the attached description for a picture frame in an ID3v2.x frame.

반환값

Returns a description for the picture in a picture frame



KTaglib_ID3v2_AttachedPictureFrame::getMimeType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::getMimeTypeReturns the mime type of the picture

설명

public string KTaglib_ID3v2_AttachedPictureFrame::getMimeType ( void )

Returns the mime type of the image represented by the attached picture frame.

Please notice that this method might return different types. While ID3v2.2 have a mime type that doesn't start with "image/", ID3v2.3 and v2.4 usually start with "image/". Therefore the method might return "image/png" for IDv2.3 frames and just "PNG" for ID3v2.2 frames.

Notice that even the frame is an attached picture, the mime type might not be set and therefore an empty string might be returned.

반환값

Returns the mime type of the image represented by the attached picture frame.



KTaglib_ID3v2_AttachedPictureFrame::getType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::getTypeReturns the type of the image

설명

public int KTaglib_ID3v2_AttachedPictureFrame::getType ( void )

Returns the type of the image.

The ID3v2 specification allows an AttachedPictureFrame to set the type of an image. This can be e.g. FrontCover or FileIcon. Please refer to the KTagLib_ID3v2_AttachedPictureFrame class description for a list of available types.

반환값

Returns the integer representation of the type.



KTaglib_ID3v2_AttachedPictureFrame::savePicture

(0.0.1)

KTaglib_ID3v2_AttachedPictureFrame::savePictureSaves the picture to a file

설명

public bool KTaglib_ID3v2_AttachedPictureFrame::savePicture ( string $filename )

Saves the attached picture to the given filename.

반환값

Returns true on success, otherwise false



KTaglib_ID3v2_AttachedPictureFrame::setMimeType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::setMimeTypeSet's the mime type of the picture

설명

public string KTaglib_ID3v2_AttachedPictureFrame::getMimeType ( string $type )

Sets the mime type of the image. This should in most cases be "image/png" or "image/jpeg".



KTaglib_ID3v2_AttachedPictureFrame::setPicture

(0.0.1)

KTaglib_ID3v2_AttachedPictureFrame::setPictureSets the frame picture to the given image

설명

public void KTaglib_ID3v2_AttachedPictureFrame::setPicture ( string $filename )

Sets the picture to the give image. The image is loaded from the given filename. Please note that the picture is not saved unless you call the save method of the corresponding file object.

반환값

Returns true on success, otherwise false



KTaglib_ID3v2_AttachedPictureFrame::setType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::setTypeSet the type of the image

설명

public void KTaglib_ID3v2_AttachedPictureFrame::setType ( int $type )

Sets the type of the image. This can be e.g. FrontCover or FileIcon. Please refer to the KTaglib_ID3v2_AttachedPictureFrame class description for a list of available types and their constant mappings.


Table of Contents




OGG/Vorbis


소개

The OGG/Vorbis file format, as defined by » http://www.vorbis.com/, is a scheme for compressing audio streams by multiple factors with a minimum of quality loss. This extension adds Ogg Vorbis support to PHP's URL Wrappers. When used in read mode, compressed OGG/Vorbis data is expanded to raw PCM audio in one of six PCM encoding formats listed below.



설치/설정

Table of Contents


요구 조건

This extension requires PHP >= 4.3.0, » libogg >= 1.0, and » libvorbis >= 1.0.



설치

PECL 확장 설치에 관한 정보는 매뉴얼의 PECL 확장 설치에 있습니다. 새 릴리즈, 내려받기, 소스파일, 개발자 정보, CHANGELOG 등의 추가 정보는 여기에 있습니다: » http://pecl.php.net/package/oggvorbis



실행시 설정

이 확장은 php.ini 설정이 존재하지 않습니다.



자원형

이 확장은 리소스형을 정의하지 않습니다.




예약 상수

이 확장은 다음의 상수들을 정의합니다. 이 확장을 PHP에 내장했거나, 실행시에 동적으로 읽어들일 경우에만 사용할 수 있습니다.

OGG/Vorbis supports PCM encodings in the following formats
Constant Definition
OGGVORBIS_PCM_U8 Unsigned 8-bit PCM.
OGGVORBIS_PCM_S8 Signed 8-bit PCM.
OGGVORBIS_PCM_U16_LE Unsigned 16-bit PCM. Little Endian byte order.
OGGVORBIS_PCM_U16_BE Unsigned 16-bit PCM. Big Endian byte order.
OGGVORBIS_PCM_S16_LE Signed 16-bit PCM. Little Endian byte order.
OGGVORBIS_PCM_S16_BE Signed 16-bit PCM. Big Endian byte order.


Context options

OGG/Vorbis tuning options
Option Definition Relevance Default
pcm_mode PCM byte encoding used. See constants below. Read / Write OGGVORBIS_PCM_S16_LE
rate PCM Sampling rate. Measured in Hz. Write only 44100
bitrate Vorbis Average Bitrate Encoding / Variable Bitrate Encoding. Measured in bps (ABR) or Quality level (VBR: 0.0 to 1.0). 128000 ABR is rough equal to 0.4 VBR. Write only 128000
channels Number of PCM channels. 1 == Mono, 2 == Stereo. Write only 2
serialno Serial Number of stream within file. Must be unique within file. Because of the potential to select a duplicate serial number within a chained file, make efforts to manually assign unique numbers when encoding. Write only Random
comments Associative array of file comments. Will be translated to strtoupper($name) . "=$value". Note: This context option is not available in oggvorbis-0.1 Write only array('ENCODER' => 'PHP/OggVorbis, http://pear.php.net/oggvorbis')


예제

Table of Contents


Examples on using the ogg:// wrapper.

Example #1 Reading an OGG/Vorbis file

<?php
dl
("oggvorbis.so");

/* By default, ogg:// will decode to Signed 16-bit Little Endian */
$fp fopen('ogg://myaudio.ogg''r');

/* Collect some information about the file. */
$metadata stream_get_meta_data($fp);

/* Inspect the first song (usually the only song, 
   but OGG/Vorbis files may be chained) */
$songdata $metadata['wrapper_data'][0];

echo 
"OGG/Vorbis file encoded by: {$songdata['vendor']}\n.";
echo 
"  {$songdata['channels']} channels of {$songdata['rate']}Hz sampling encoded at {$songdata['bitrate_nominal']}bps.\n";
foreach(
$songdata['comments'] as $comment) {
    echo 
"  $comment\n";
}

while (
$audio_data fread($fp8192)) {
  
/* Do something with the PCM audio we're extracting from the OGG.
     Copying to /dev/dsp is a good target on linux systems, 
     just remember to setup the device for your sampling mode first. */
}

fclose($fp);

?>

Example #2 Encode an audio file to OGG/Vorbis

<?php
dl
('oggvorbis.so');

$context stream_context_create(array('ogg'=>array(
             
'pcm_mode' => OGGVORBIS_PCM_S8,  /* Signed 8bit audio */
             
'rate' => 44100,                 /* 44kHz CD quality */
             
'bitrate' => 0.5,                /* Midquality VBR */
             
'channels' => 1,                 /* Mono */
             
'serialno' => 12345)));          /* Unique within our stream */

/* Open file for appending.  This will "chain" a second OGG stream at the end of the first. */
$ogg fopen('ogg://mysong.ogg''a'false$context);

$pcm fopen('mysample.pcm''r');

/* Compress the raw PCM audio from mysample.pcm into mysong.ogg */
stream_copy_to_stream($pcm$ogg);

fclose($pcm);
fclose($ogg);
?>





OpenAL Audio Bindings


소개

Platform independent audio bindings. Requires the » OpenAL library.



설치/설정

Table of Contents


요구 조건

이 확장을 빌드할 때 외부 라이브러리가 필요하지 않습니다.



설치

» PECL 확장은 PHP 배포판에서 제공하지 않습니다.

PECL 확장 설치에 관한 정보는 매뉴얼의 PECL 확장 설치에 있습니다. 새 릴리즈, 내려받기, 소스파일, 개발자 정보, CHANGELOG 등의 추가 정보는 여기에 있습니다: » http://pecl.php.net/package/openal.

PECL 확장에 대한 DLL은 현재 사용할 수 없습니다. 윈도우에서 빌드하기 섹션을 참고하십시오.



실행시 설정

이 확장은 php.ini 설정이 존재하지 않습니다.



자원형

This extension defines four resource types: Open AL(Device) - Returned by openal_device_open(), Open AL(Context) - Returned by openal_context_create(), Open AL(Buffer) - Returned by openal_buffer_create(), and Open AL(Source) - Returned by openal_source_create().




예약 상수

이 확장은 다음의 상수들을 정의합니다. 이 확장을 PHP에 내장했거나, 실행시에 동적으로 읽어들일 경우에만 사용할 수 있습니다.

ALC_FREQUENCY (integer)
Context Attribute
ALC_REFRESH (integer)
Context Attribute
ALC_SYNC (integer)
Context Attribute
AL_FREQUENCY (integer)
Buffer Setting
AL_BITS (integer)
Buffer Setting
AL_CHANNELS (integer)
Buffer Setting
AL_SIZE (integer)
Buffer Setting
AL_BUFFER (integer)
Source/Listener Setting (Integer)
AL_SOURCE_RELATIVE (integer)
Source/Listener Setting (Integer)
AL_SOURCE_STATE (integer)
Source/Listener Setting (Integer)
AL_PITCH (integer)
Source/Listener Setting (Float)
AL_GAIN (integer)
Source/Listener Setting (Float)
AL_MIN_GAIN (integer)
Source/Listener Setting (Float)
AL_MAX_GAIN (integer)
Source/Listener Setting (Float)
AL_MAX_DISTANCE (integer)
Source/Listener Setting (Float)
AL_ROLLOFF_FACTOR (integer)
Source/Listener Setting (Float)
AL_CONE_OUTER_GAIN (integer)
Source/Listener Setting (Float)
AL_CONE_INNER_ANGLE (integer)
Source/Listener Setting (Float)
AL_CONE_OUTER_ANGLE (integer)
Source/Listener Setting (Float)
AL_REFERENCE_DISTANCE (integer)
Source/Listener Setting (Float)
AL_POSITION (integer)
Source/Listener Setting (Float Vector)
AL_VELOCITY (integer)
Source/Listener Setting (Float Vector)
AL_DIRECTION (integer)
Source/Listener Setting (Float Vector)
AL_ORIENTATION (integer)
Source/Listener Setting (Float Vector)
AL_FORMAT_MONO8 (integer)
PCM Format
AL_FORMAT_MONO16 (integer)
PCM Format
AL_FORMAT_STEREO8 (integer)
PCM Format
AL_FORMAT_STEREO16 (integer)
PCM Format
AL_INITIAL (integer)
Source State
AL_PLAYING (integer)
Source State
AL_PAUSED (integer)
Source State
AL_STOPPED (integer)
Source State
AL_LOOPING (integer)
Source State
AL_TRUE (integer)
Boolean value recognized by OpenAL
AL_FALSE (integer)
Boolean value recognized by OpenAL


OpenAL 함수 목록


openal_buffer_create

(PECL openal >= 0.1.0)

openal_buffer_create Generate OpenAL buffer

설명

resource openal_buffer_create ( void )

반환값

Returns an Open AL(Buffer) resource on success or FALSE on failure.

참고



openal_buffer_data

(PECL openal >= 0.1.0)

openal_buffer_data Load a buffer with data

설명

bool openal_buffer_data ( resource $buffer , int $format , string $data , int $freq )

인수

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

format

Format of data , one of: AL_FORMAT_MONO8, AL_FORMAT_MONO16, AL_FORMAT_STEREO8 그리고 AL_FORMAT_STEREO16

data

Block of binary audio data in the format and freq specified.

freq

Frequency of data given in Hz.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



openal_buffer_destroy

(PECL openal >= 0.1.0)

openal_buffer_destroy Destroys an OpenAL buffer

설명

bool openal_buffer_destroy ( resource $buffer )

인수

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



openal_buffer_get

(PECL openal >= 0.1.0)

openal_buffer_get Retrieve an OpenAL buffer property

설명

int openal_buffer_get ( resource $buffer , int $property )

인수

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

property

Specific property, one of: AL_FREQUENCY, AL_BITS, AL_CHANNELS 그리고 AL_SIZE.

반환값

Returns an integer value appropriate to the property requested or FALSE on failure.

참고



openal_buffer_loadwav

(PECL openal >= 0.1.0)

openal_buffer_loadwav Load a .wav file into a buffer

설명

bool openal_buffer_loadwav ( resource $buffer , string $wavfile )

인수

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

wavfile

Path to .wav file on local file system.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



openal_context_create

(PECL openal >= 0.1.0)

openal_context_create Create an audio processing context

설명

resource openal_context_create ( resource $device )

인수

device

An Open AL(Device) resource (previously created by openal_device_open()).

반환값

Returns an Open AL(Context) resource on success or FALSE on failure.

참고



openal_context_current

(PECL openal >= 0.1.0)

openal_context_current Make the specified context current

설명

bool openal_context_current ( resource $context )

인수

context

An Open AL(Context) resource (previously created by openal_context_create()).

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



openal_context_destroy

(PECL openal >= 0.1.0)

openal_context_destroy Destroys a context

설명

bool openal_context_destroy ( resource $context )

인수

context

An Open AL(Context) resource (previously created by openal_context_create()).

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



openal_context_process

(PECL openal >= 0.1.0)

openal_context_process Process the specified context

설명

bool openal_context_process ( resource $context )

인수

context

An Open AL(Context) resource (previously created by openal_context_create()).

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



openal_context_suspend

(PECL openal >= 0.1.0)

openal_context_suspend Suspend the specified context

설명

bool openal_context_suspend ( resource $context )

인수

context

An Open AL(Context) resource (previously created by openal_context_create()).

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



openal_device_close

(PECL openal >= 0.1.0)

openal_device_close Close an OpenAL device

설명

bool openal_device_close ( resource $device )

인수

device

An Open AL(Device) resource (previously created by openal_device_open()) to be closed.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



openal_device_open

(PECL openal >= 0.1.0)

openal_device_open Initialize the OpenAL audio layer

설명

resource openal_device_open ([ string $device_desc ] )

인수

device_desc

Open an audio device optionally specified by device_desc . If device_desc is not specified the first available audio device will be used.

반환값

Returns an Open AL(Device) resource on success or FALSE on failure.

참고



openal_listener_get

(PECL openal >= 0.1.0)

openal_listener_get Retrieve a listener property

설명

mixed openal_listener_get ( int $property )

인수

property

Property to retrieve, one of: AL_GAIN (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)) 그리고 AL_ORIENTATION (array(float,float,float)).

반환값

Returns a float or array of floats (as appropriate), or FALSE on failure.

참고



openal_listener_set

(PECL openal >= 0.1.0)

openal_listener_set Set a listener property

설명

bool openal_listener_set ( int $property , mixed $setting )

인수

property

Property to set, one of: AL_GAIN (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)) 그리고 AL_ORIENTATION (array(float,float,float)).

setting

Value to set, either float, or an array of floats as appropriate.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



openal_source_create

(PECL openal >= 0.1.0)

openal_source_create Generate a source resource

설명

resource openal_source_create ( void )

반환값

Returns an Open AL(Source) resource on success or FALSE on failure.

참고



openal_source_destroy

(PECL openal >= 0.1.0)

openal_source_destroy Destroy a source resource

설명

bool openal_source_destroy ( resource $source )

인수

source

An Open AL(Source) resource (previously created by openal_source_create()).

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



openal_source_get

(PECL openal >= 0.1.0)

openal_source_get Retrieve an OpenAL source property

설명

mixed openal_source_get ( resource $source , int $property )

인수

source

An Open AL(Source) resource (previously created by openal_source_create()).

property

Property to get, one of: AL_SOURCE_RELATIVE (int), AL_SOURCE_STATE (int), AL_PITCH (float), AL_GAIN (float), AL_MIN_GAIN (float), AL_MAX_GAIN (float), AL_MAX_DISTANCE (float), AL_ROLLOFF_FACTOR (float), AL_CONE_OUTER_GAIN (float), AL_CONE_INNER_ANGLE (float), AL_CONE_OUTER_ANGLE (float), AL_REFERENCE_DISTANCE (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)), AL_DIRECTION (array(float,float,float)).

반환값

Returns the type associated with the property being retrieved or FALSE on failure.

참고



openal_source_pause

(PECL openal >= 0.1.0)

openal_source_pause Pause the source

설명

bool openal_source_pause ( resource $source )

인수

source

An Open AL(Source) resource (previously created by openal_source_create()).

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



openal_source_play

(PECL openal >= 0.1.0)

openal_source_play Start playing the source

설명

bool openal_source_play ( resource $source )

인수

source

An Open AL(Source) resource (previously created by openal_source_create()).

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



openal_source_rewind

(PECL openal >= 0.1.0)

openal_source_rewind Rewind the source

설명

bool openal_source_rewind ( resource $source )

인수

source

An Open AL(Source) resource (previously created by openal_source_create()).

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



openal_source_set

(PECL openal >= 0.1.0)

openal_source_set Set source property

설명

bool openal_source_set ( resource $source , int $property , mixed $setting )

인수

source

An Open AL(Source) resource (previously created by openal_source_create()).

property

Property to set, one of: AL_BUFFER (OpenAL(Source)), AL_LOOPING (bool), AL_SOURCE_RELATIVE (int), AL_SOURCE_STATE (int), AL_PITCH (float), AL_GAIN (float), AL_MIN_GAIN (float), AL_MAX_GAIN (float), AL_MAX_DISTANCE (float), AL_ROLLOFF_FACTOR (float), AL_CONE_OUTER_GAIN (float), AL_CONE_INNER_ANGLE (float), AL_CONE_OUTER_ANGLE (float), AL_REFERENCE_DISTANCE (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)), AL_DIRECTION (array(float,float,float)).

setting

Value to assign to specified property . Refer to the description of property for a description of the value(s) expected.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



openal_source_stop

(PECL openal >= 0.1.0)

openal_source_stop Stop playing the source

설명

bool openal_source_stop ( resource $source )

인수

source

An Open AL(Source) resource (previously created by openal_source_create()).

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



openal_stream

(PECL openal >= 0.1.0)

openal_stream Begin streaming on a source

설명

resource openal_stream ( resource $source , int $format , int $rate )

인수

source

An Open AL(Source) resource (previously created by openal_source_create()).

format

Format of data , one of: AL_FORMAT_MONO8, AL_FORMAT_MONO16, AL_FORMAT_STEREO8 그리고 AL_FORMAT_STEREO16

rate

Frequency of data to stream given in Hz.

반환값

Returns a stream resource on success, or FALSE on failure.

참고


Table of Contents





인증 서비스


Kerberos V


소개

These package allows you to access Kerberos V administration servers. You can create, modify, and delete Kerberos V principals and policies.

More information about Kerberos can be found at » http://web.mit.edu/kerberos/www/.

Documentation for Kerberos and KADM5 can be found at » http://web.mit.edu/kerberos/www/krb5-1.2/krb5-1.2.8/doc/admin_toc.html.



설치/설정

Table of Contents


요구 조건

이 확장을 빌드할 때 외부 라이브러리가 필요하지 않습니다.



설치

These functions allow you to access Kerberos administration servers. In order to have these functions available, you must compile PHP with KADM5 support by using the --with-kadm5 configurable option. If you use this option without specifying the path to KADM5, PHP will use the built-in KADM5 client libraries. Users who run other applications that use KADM5 (for example, running PHP 4 and PHP 5 as concurrent apache modules, or auth-kadm5) should always specify the path to KADM5: --with-kadm5=/path/to/kadm5. This will force PHP to use the client libraries installed by KADM5, avoiding any conflicts.



실행시 설정

이 확장은 php.ini 설정이 존재하지 않습니다.



자원형

This extension defines a KADM5 handle returned by kadm5_init_with_password().




예약 상수

Table of Contents

이 확장은 다음의 상수들을 정의합니다. 이 확장을 PHP에 내장했거나, 실행시에 동적으로 읽어들일 경우에만 사용할 수 있습니다.


Constants for Attribute Flags

The functions kadm5_create_principal(), kadm5_modify_principal(), and kadm5_modify_principal() allow to specify special attributes using a bitfield. The symbols are defined below:

Attributes for use by the KDC
constant
KRB5_KDB_DISALLOW_POSTDATED
KRB5_KDB_DISALLOW_FORWARDABLE
KRB5_KDB_DISALLOW_TGT_BASED
KRB5_KDB_DISALLOW_RENEWABLE
KRB5_KDB_DISALLOW_PROXIABLE
KRB5_KDB_DISALLOW_DUP_SKEY
KRB5_KDB_DISALLOW_ALL_TIX
KRB5_KDB_REQUIRES_PRE_AUTH
KRB5_KDB_REQUIRES_HW_AUTH
KRB5_KDB_REQUIRES_PWCHANGE
KRB5_KDB_DISALLOW_SVR
KRB5_KDB_PWCHANGE_SERVER
KRB5_KDB_SUPPORT_DESMD5
KRB5_KDB_NEW_PRINC



Constants for Options

The functions kadm5_create_principal(), kadm5_modify_principal(), and kadm5_get_principal() allow to specify or return principal's options as an associative array. The keys for the associative array are defined as string constants below:

Options for creating/modifying/retrieving principals
constant funcdef description
KADM5_PRINCIPAL long The expire time of the princial as a Kerberos timestamp.
KADM5_PRINC_EXPIRE_TIME long The expire time of the princial as a Kerberos timestamp.
KADM5_LAST_PW_CHANGE long The time this principal's password was last changed.
KADM5_PW_EXPIRATION long The expire time of the principal's current password, as a Kerberos timestamp.
KADM5_MAX_LIFE long The maximum lifetime of any Kerberos ticket issued to this principal.
KADM5_MAX_RLIFE long The maximum renewable lifetime of any Kerberos ticket issued to or for this principal.
KADM5_MOD_NAME string The name of the Kerberos principal that most recently modified this principal.
KADM5_MOD_TIME long The time this principal was last modified, as a Kerberos timestamp.
KADM5_KVNO long The version of the principal's current key.
KADM5_POLICY string The name of the policy controlling this principal.
KADM5_CLEARPOLICY long Standard procedure is to assign the 'default' policy to new principals. KADM5_CLEARPOLICY suppresses this behaviour.
KADM5_LAST_SUCCESS long The KDC time of the last successfull AS_REQ.
KADM5_LAST_FAILED long The KDC time of the last failed AS_REQ.
KADM5_FAIL_AUTH_COUNT long The number of consecutive failed AS_REQs.
KADM5_RANDKEY long Generates a random password for the principal. The parameter password will be ignored.
KADM5_ATTRIBUTES long A bitfield of attributes for use by the KDC.




예제

Table of Contents


This simple example shows how to connect, query, print resulting principals and disconnect from a KADM5 database.

Example #1 KADM5 extension overview example

<?php

  $handle 
kadm5_init_with_password("afs-1""GONICUS.LOCAL""admin/admin""password");

  print 
"<h1>get_principals</h1>\n";
  
$principals kadm5_get_principals($handle);
  for( 
$i=0$i<count($principals); $i++)
      print 
"$principals[$i]<br>\n";

  print 
"<h1>get_policies</h1>\n";
  
$policies kadm5_get_policies($handle);
  for( 
$i=0$i<count($policies); $i++)
      print 
"$policies[$i]<br>\n";

  print 
"<h1>get_principal burbach@GONICUS.LOCAL</h1>\n";

  
$options kadm5_get_principal($handle"burbach@GONICUS.LOCAL" );
  
$keys array_keys($options);
  for( 
$i=0$i<count($keys); $i++) {
    
$value $options[$keys[$i]];
    print 
"$keys[$i]$value<br>\n";
  }

  
$options = array(KADM5_PRINC_EXPIRE_TIME => 0);
  
kadm5_modify_principal($handle"burbach@GONICUS.LOCAL"$options);

  
kadm5_destroy($handle);
?>




KADM5 함수 목록


kadm5_chpass_principal

(PECL kadm5 >= 0.2.3)

kadm5_chpass_principalChanges the principal's password

설명

bool kadm5_chpass_principal ( resource $handle , string $principal , string $password )

kadm5_chpass_principal() sets the new password password for the principal .

인수

handle

A KADM5 handle.

principal

The principal.

password

The new password.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 Example of changing principal's password

<?php

$handle 
kadm5_init_with_password("afs-1""GONICUS.LOCAL""admin/admin""password");

kadm5_chpass_principal($handle"burbach@GONICUS.LOCAL""newpassword");

kadm5_destroy($handle);
?>



kadm5_create_principal

(PECL kadm5 >= 0.2.3)

kadm5_create_principalCreates a kerberos principal with the given parameters

설명

bool kadm5_create_principal ( resource $handle , string $principal [, string $password [, array $options ]] )

Creates a principal with the given password .

인수

handle

A KADM5 handle.

principal

The principal.

password

If password is omitted or is NULL, a random key will be generated.

options

It is possible to specify several optional parameters within the array options . Allowed are the following options: KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES, KADM5_MAX_LIFE, KADM5_KVNO, KADM5_POLICY, KADM5_CLEARPOLICY, KADM5_MAX_RLIFE.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 Example of principal's creation

<?php

$handle 
kadm5_init_with_password("afs-1""GONICUS.LOCAL""admin/admin""password");

$attributes KRB5_KDB_REQUIRES_PRE_AUTH KRB5_KDB_DISALLOW_PROXIABLE;
$options = array(KADM5_PRINC_EXPIRE_TIME => 0,
                 
KADM5_POLICY => "default",
                 
KADM5_ATTRIBUTES => $attributes);

kadm5_create_principal($handle"burbach@GONICUS.LOCAL""password"$options);

kadm5_destroy($handle);
?>

참고



kadm5_delete_principal

(PECL kadm5 >= 0.2.3)

kadm5_delete_principalDeletes a kerberos principal

설명

bool kadm5_delete_principal ( resource $handle , string $principal )

Removes the principal from the Kerberos database.

인수

handle

A KADM5 handle.

principal

The removed principal.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 kadm5_delete_principal() example

<?php

$handle 
kadm5_init_with_password("afs-1""GONICUS.LOCAL""admin/admin""password");

kadm5_delete_principal($handle"burbach@GONICUS.LOCAL");

kadm5_destroy($handle);
?>

참고



kadm5_destroy

(PECL kadm5 >= 0.2.3)

kadm5_destroyCloses the connection to the admin server and releases all related resources

설명

bool kadm5_destroy ( resource $handle )

Closes the connection to the admin server and releases all related resources.

인수

handle

A KADM5 handle.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



kadm5_flush

(PECL kadm5 >= 0.2.3)

kadm5_flushFlush all changes to the Kerberos database

설명

bool kadm5_flush ( resource $handle )

Flush all changes to the Kerberos database, leaving the connection to the Kerberos admin server open.

인수

handle

A KADM5 handle.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.



kadm5_get_policies

(PECL kadm5 >= 0.2.3)

kadm5_get_policiesGets all policies from the Kerberos database

설명

array kadm5_get_policies ( resource $handle )

Gets an array containing the policies's names.

인수

handle

A KADM5 handle.

반환값

Returns array of policies on success, or FALSE on failure.

예제

Example #1 kadm5_get_policies() example

<?php
$handle 
kadm5_init_with_password("afs-1""GONICUS.LOCAL""admin/admin""password");

print 
"<h1>get_policies</h1>\n";
foreach (
kadm5_get_policies($handle) as $policy) {
    echo 
"$policy<br />\n";
}

kadm5_destroy($handle);
?>



kadm5_get_principal

(PECL kadm5 >= 0.2.3)

kadm5_get_principalGets the principal's entries from the Kerberos database

설명

array kadm5_get_principal ( resource $handle , string $principal )

Gets the principal's entries from the Kerberos database.

인수

handle

A KADM5 handle.

principal

The principal.

반환값

Returns array of options containing the following keys: KADM5_PRINCIPAL, KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES, KADM5_MAX_LIFE, KADM5_MOD_NAME, KADM5_MOD_TIME, KADM5_KVNO, KADM5_POLICY, KADM5_MAX_RLIFE, KADM5_LAST_SUCCESS, KADM5_LAST_FAILED, KADM5_FAIL_AUTH_COUNT on success, or FALSE on failure.

예제

Example #1 kadm5_get_principal() example

<?php
$handle 
kadm5_init_with_password("afs-1""GONICUS.LOCAL""admin/admin""password");

print 
"<h1>get_principal burbach@GONICUS.LOCAL</h1>\n";

$options kadm5_get_principal($handle"burbach@GONICUS.LOCAL" );

foreach (
$options as $key => $value) {
    echo 
"$key$value<br />\n";
}

kadm5_destroy($handle);
?>

참고



kadm5_get_principals

(PECL kadm5 >= 0.2.3)

kadm5_get_principalsGets all principals from the Kerberos database

설명

array kadm5_get_principals ( resource $handle )

kadm5_get_principals() returns an array containing the principals's names.

인수

handle

A KADM5 handle.

반환값

Returns array of principals on success, or FALSE on failure.

예제

Example #1 kadm5_get_principals() example

<?php
$handle 
kadm5_init_with_password("afs-1""GONICUS.LOCAL""admin/admin""password");

print 
"<h1>get_principals</h1>\n";
foreach (
kadm5_get_principals($handle) as $principal) {
    echo 
"$principal<br />\n";
}

kadm5_destroy($handle);
?>

참고



kadm5_init_with_password

(PECL kadm5 >= 0.2.3)

kadm5_init_with_passwordOpens a connection to the KADM5 library

설명

resource kadm5_init_with_password ( string $admin_server , string $realm , string $principal , string $password )

Opens a connection with the KADM5 library using the principal and the given password to obtain initial credentials from the admin_server .

인수

admin_server

The server.

realm

Defines the authentication domain for the connection.

principal

The principal.

password

If password is omitted or is NULL, a random key will be generated.

반환값

Returns a KADM5 handle on success, or FALSE on failure.

예제

Example #1 KADM5 initialization example

<?php

$handle 
kadm5_init_with_password("afs-1""GONICUS.LOCAL""admin/admin""password");

$attributes KRB5_KDB_REQUIRES_PRE_AUTH KRB5_KDB_DISALLOW_PROXIABLE;
$options = array(KADM5_PRINC_EXPIRE_TIME => 0,
                 
KADM5_POLICY => "default",
                 
KADM5_ATTRIBUTES => $attributes);

kadm5_create_principal($handle"burbach@GONICUS.LOCAL""password"$options);

kadm5_destroy($handle);
?>

주의

Note: Connection should be closed after use with kadm5_destroy().

참고

  • kadm5_destroy() - Closes the connection to the admin server and releases all related resources



kadm5_modify_principal

(PECL kadm5 >= 0.2.3)

kadm5_modify_principalModifies a kerberos principal with the given parameters

설명

bool kadm5_modify_principal ( resource $handle , string $principal , array $options )

Modifies a principal according to the given options .

인수

handle

A KADM5 handle.

principal

The principal.

options

It is possible to specify several optional parameters within the array options . Allowed are the following options: KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES, KADM5_MAX_LIFE, KADM5_KVNO, KADM5_POLICY, KADM5_CLEARPOLICY, KADM5_MAX_RLIFE. KADM5_FAIL_AUTH_COUNT.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 Example of modifying principal

<?php

$handle 
kadm5_init_with_password("afs-1""GONICUS.LOCAL""admin/admin""password");

$attributes KRB5_KDB_REQUIRES_PRE_AUTH;
$options = array(KADM5_PRINC_EXPIRE_TIME => 3451234,
                 
KADM5_POLICY => "gonicus",
                 
KADM5_ATTRIBUTES => $attributes);

kadm5_modify_principal($handle"burbach@GONICUS.LOCAL"$options);

kadm5_destroy($handle);
?>

참고


Table of Contents




Radius


소개

This package is based on the libradius (Remote Authentication Dial In User Service) of FreeBSD. It allows clients to perform authentication and accounting by means of network requests to remote servers.

This PECL extension adds full support for Radius Authentication (» RFC 2865) and Radius Accounting (» RFC 2866). This package is available for Unix (tested on FreeBSD and Linux) and for Windows.

Note: An exact description for libradius can be found » here. A detailed description of the configuration file can be found » here.



설치/설정

Table of Contents


요구 조건

이 확장을 빌드할 때 외부 라이브러리가 필요하지 않습니다.



설치

Howto install the package?

  • untar the package (usually into php4/ext)
  • rename radius-x.x to radius
  • run ./buildconf in php4
  • run ./configure --enable-radius
  • make; make install

or if you would like to have it as .so:

  • untar the package
  • run phpize in the radius-x.x directory
  • run ./configure in the radius-x.x directory
  • make; make install

For Windows I recommend to use the php_radius.dll from » http://snaps.php.net/. 이 PECL 확장에 대한 DLL은 현재 사용할 수 없습니다. 윈도우에서 빌드하기 섹션을 참고하십시오.



실행시 설정

이 확장은 php.ini 설정이 존재하지 않습니다.



자원형

이 확장은 리소스형을 정의하지 않습니다.




예약 상수

이 확장은 다음의 상수들을 정의합니다. 이 확장을 PHP에 내장했거나, 실행시에 동적으로 읽어들일 경우에만 사용할 수 있습니다.

RADIUS_ACCESS_REQUEST ()
Authentication Request
RADIUS_ACCESS_ACCEPT ()
Access accepted
RADIUS_ACCESS_REJECT ()
Access rejected
RADIUS_ACCOUNTING_REQUEST ()
Accounting request
RADIUS_ACCOUNTING_RESPONSE ()
Accounting response
RADIUS_ACCESS_CHALLENGE ()
Accsess challenge
RADIUS_USER_NAME (string)
Username
RADIUS_USER_PASSWORD (string)
Password
RADIUS_CHAP_PASSWORD (string)
Chap Password: chappass = md5(ident + plaintextpass + challenge)
RADIUS_NAS_IP_ADDRESS (string)
NAS IP-Adress
RADIUS_NAS_PORT (int)
NAS Port
RADIUS_SERVICE_TYPE (int)

Type of Service, one of:

  • RADIUS_LOGIN
  • RADIUS_FRAMED
  • RADIUS_CALLBACK_LOGIN
  • RADIUS_CALLBACK_FRAMED
  • RADIUS_OUTBOUND
  • RADIUS_ADMINISTRATIVE
  • RADIUS_NAS_PROMPT
  • RADIUS_AUTHENTICATE_ONLY
  • RADIUS_CALLBACK_NAS_PROMPT

RADIUS_FRAMED_PROTOCOL (int)

Framed Protocol, one of:

  • RADIUS_PPP
  • RADIUS_SLIP
  • RADIUS_ARAP
  • RADIUS_GANDALF
  • RADIUS_XYLOGICS

RADIUS_FRAMED_IP_ADDRESS (string)
IP-Address
RADIUS_FRAMED_IP_NETMASK (string)
Netmask
RADIUS_FRAMED_ROUTING (int)
Routing
RADIUS_FILTER_ID (string)
Filter ID
RADIUS_FRAMED_MTU (int)
MTU
RADIUS_FRAMED_COMPRESSION (int)

Compression, one of:

  • RADIUS_COMP_NONE
  • RADIUS_COMP_VJ
  • RADIUS_COMP_IPXHDR

RADIUS_LOGIN_IP_HOST (string)
Login IP Host
RADIUS_LOGIN_SERVICE (int)
Login Service
RADIUS_LOGIN_TCP_PORT (int)
Login TCP Port
RADIUS_REPLY_MESSAGE (string)
Reply Message
RADIUS_CALLBACK_NUMBER (string)
Callback Number
RADIUS_CALLBACK_ID (string)
Callback ID
RADIUS_FRAMED_ROUTE (string)
Framed Route
RADIUS_FRAMED_IPX_NETWORK (string)
Framed IPX Network
RADIUS_STATE (string)
State
RADIUS_CLASS (int)
Class
RADIUS_VENDOR_SPECIFIC (int)
Vendor specific attribute
RADIUS_SESSION_TIMEOUT (int)
Session timeout
RADIUS_IDLE_TIMEOUT (int)
Idle timeout
RADIUS_TERMINATION_ACTION (int)
Termination action
RADIUS_CALLED_STATION_ID (int)
Called Station Id
RADIUS_CALLING_STATION_ID (string)
Calling Station Id
RADIUS_NAS_IDENTIFIER (int)
NAS ID
RADIUS_PROXY_STATE (int)
Proxy State
RADIUS_LOGIN_LAT_SERVICE (int)
Login LAT Service
RADIUS_LOGIN_LAT_NODE (int)
Login LAT Node
RADIUS_LOGIN_LAT_GROUP (int)
Login LAT Group
RADIUS_FRAMED_APPLETALK_LINK (int)
Framed Appletalk Link
RADIUS_FRAMED_APPLETALK_NETWORK (int)
Framed Appletalk Network
RADIUS_FRAMED_APPLETALK_ZONE (int)
Framed Appletalk Zone
RADIUS_CHAP_CHALLENGE (string)
Challenge
RADIUS_NAS_PORT_TYPE (int)

NAS port type, one of:

  • RADIUS_ASYNC
  • RADIUS_SYNC
  • RADIUS_ISDN_SYNC
  • RADIUS_ISDN_ASYNC_V120
  • RADIUS_ISDN_ASYNC_V110
  • RADIUS_VIRTUAL
  • RADIUS_PIAFS
  • RADIUS_HDLC_CLEAR_CHANNEL
  • RADIUS_X_25
  • RADIUS_X_75
  • RADIUS_G_3_FAX
  • RADIUS_SDSL
  • RADIUS_ADSL_CAP
  • RADIUS_ADSL_DMT
  • RADIUS_IDSL
  • RADIUS_ETHERNET
  • RADIUS_XDSL
  • RADIUS_CABLE
  • RADIUS_WIRELESS_OTHER
  • RADIUS_WIRELESS_IEEE_802_11

RADIUS_PORT_LIMIT (int)
Port Limit
RADIUS_LOGIN_LAT_PORT (int)
Login LAT Port
RADIUS_CONNECT_INFO (string)
Connect info
RADIUS_ACCT_STATUS_TYPE (int)

Accounting status type, one of:

  • RADIUS_START
  • RADIUS_STOP
  • RADIUS_ACCOUNTING_ON
  • RADIUS_ACCOUNTING_OFF

RADIUS_ACCT_DELAY_TIME (int)
Accounting delay time
RADIUS_ACCT_INPUT_OCTETS (int)
Accounting input bytes
RADIUS_ACCT_OUTPUT_OCTETS (int)
Accounting output bytes
RADIUS_ACCT_SESSION_ID (int)
Accounting session ID
RADIUS_ACCT_AUTHENTIC (int)

Accounting authentic, one of:

  • RADIUS_AUTH_RADIUS
  • RADIUS_AUTH_LOCAL
  • RADIUS_AUTH_REMOTE

RADIUS_ACCT_SESSION_TIME (int)
Accounting session time
RADIUS_ACCT_INPUT_PACKETS (int)
Accounting input packets
RADIUS_ACCT_OUTPUT_PACKETS (int)
Accounting output packets
RADIUS_ACCT_TERMINATE_CAUSE (int)

Accounting terminate cause, one of:

  • RADIUS_TERM_USER_REQUEST
  • RADIUS_TERM_LOST_CARRIER
  • RADIUS_TERM_LOST_SERVICE
  • RADIUS_TERM_IDLE_TIMEOUT
  • RADIUS_TERM_SESSION_TIMEOUT
  • RADIUS_TERM_ADMIN_RESET
  • RADIUS_TERM_ADMIN_REBOOT
  • RADIUS_TERM_PORT_ERROR
  • RADIUS_TERM_NAS_ERROR
  • RADIUS_TERM_NAS_REQUEST
  • RADIUS_TERM_NAS_REBOOT
  • RADIUS_TERM_PORT_UNNEEDED
  • RADIUS_TERM_PORT_PREEMPTED
  • RADIUS_TERM_PORT_SUSPENDED
  • RADIUS_TERM_SERVICE_UNAVAILABLE
  • RADIUS_TERM_CALLBACK
  • RADIUS_TERM_USER_ERROR
  • RADIUS_TERM_HOST_REQUEST

RADIUS_ACCT_MULTI_SESSION_ID (string)
Accounting multi session ID
RADIUS_ACCT_LINK_COUNT (int)
Accounting link count
RADIUS_VENDOR_MICROSOFT (int)

Microsoft specific vendor attributes (» RFC 2548), one of:

  • RADIUS_MICROSOFT_MS_CHAP_RESPONSE
  • RADIUS_MICROSOFT_MS_CHAP_ERROR
  • RADIUS_MICROSOFT_MS_CHAP_PW_1
  • RADIUS_MICROSOFT_MS_CHAP_PW_2
  • RADIUS_MICROSOFT_MS_CHAP_LM_ENC_PW
  • RADIUS_MICROSOFT_MS_CHAP_NT_ENC_PW
  • RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_POLICY
  • RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_TYPES
  • RADIUS_MICROSOFT_MS_RAS_VENDOR
  • RADIUS_MICROSOFT_MS_CHAP_DOMAIN
  • RADIUS_MICROSOFT_MS_CHAP_CHALLENGE
  • RADIUS_MICROSOFT_MS_CHAP_MPPE_KEYS
  • RADIUS_MICROSOFT_MS_BAP_USAGE
  • RADIUS_MICROSOFT_MS_LINK_UTILIZATION_THRESHOLD
  • RADIUS_MICROSOFT_MS_LINK_DROP_TIME_LIMIT
  • RADIUS_MICROSOFT_MS_MPPE_SEND_KEY
  • RADIUS_MICROSOFT_MS_MPPE_RECV_KEY
  • RADIUS_MICROSOFT_MS_RAS_VERSION
  • RADIUS_MICROSOFT_MS_OLD_ARAP_PASSWORD
  • RADIUS_MICROSOFT_MS_NEW_ARAP_PASSWORD
  • RADIUS_MICROSOFT_MS_ARAP_PASSWORD_CHANGE_REASON
  • RADIUS_MICROSOFT_MS_FILTER
  • RADIUS_MICROSOFT_MS_ACCT_AUTH_TYPE
  • RADIUS_MICROSOFT_MS_ACCT_EAP_TYPE
  • RADIUS_MICROSOFT_MS_CHAP2_RESPONSE
  • RADIUS_MICROSOFT_MS_CHAP2_SUCCESS
  • RADIUS_MICROSOFT_MS_CHAP2_PW
  • RADIUS_MICROSOFT_MS_PRIMARY_DNS_SERVER
  • RADIUS_MICROSOFT_MS_SECONDARY_DNS_SERVER
  • RADIUS_MICROSOFT_MS_PRIMARY_NBNS_SERVER
  • RADIUS_MICROSOFT_MS_SECONDARY_NBNS_SERVER
  • RADIUS_MICROSOFT_MS_ARAP_CHALLENGE



예제

Howto start?

  • get a radius resource
  • configure the library
  • create the request
  • put attributes
  • send the request
  • receive attributes
  • close the radius resource (optional)

Take also a look at the examples in this package.

The package contains an example php script. This script demonstrates howto authenticate with radius using PAP or CHAP (md5). If you authenticate with Microsoft Radius servers then its not possible to use CHAP (md5). If you would like to authenticate with Microsoft Servers you have to use MS-CHAPv1 or MS-CHAPv2, but its more complicated, because you need md4, sha1 and des to generate the right data. The enclosed examples demonstrate all authentication-methods, including MS-CHAPv1 and MS-CHAPv2. To get the MS-CHAP to work you need the mcrypt and the mhash extension, starting with version 1.2 of the package, the mcrypt extension is no longer needed.



Radius 함수 목록

Contact Information

If you have comments, bugfixes, enhancements or want to help to develop this you can send me a mail at » mbretter@php.net.


radius_acct_open

(PECL radius >= 1.1.0)

radius_acct_openCreates a Radius handle for accounting

설명

resource radius_acct_open ( void )

반환값

Returns a handle on success, FALSE on error. This function only fails if insufficient memory is available.

예제

Example #1 radius_acct_open() example

<?php
$res 
radius_acct_open ()
    or die (
"Could not create handle");
print(
"Handle successfully created");
?>



radius_add_server

(PECL radius >= 1.1.0)

radius_add_serverAdds a server

설명

bool radius_add_server ( resource $radius_handle , string $hostname , int $port , string $secret , int $timeout , int $max_tries )

radius_add_server() may be called multiple times, and it may be used together with radius_config(). At most 10 servers may be specified. When multiple servers are given, they are tried in round-robin fashion until a valid response is received, or until each server's max_tries limit has been reached.

인수

radius_handle

hostname

The hostname parameter specifies the server host, either as a fully qualified domain name or as a dotted-quad IP address in text form.

port

The port specifies the UDP port to contact on the server. If port is given as 0, the library looks up the radius/udp or radacct/udp service in the network services database, and uses the port found there. If no entry is found, the library uses the standard Radius ports, 1812 for authentication and 1813 for accounting.

secret

The shared secret for the server host is passed to the secret parameter. The Radius protocol ignores all but the leading 128 bytes of the shared secret.

timeout

The timeout for receiving replies from the server is passed to the timeout parameter, in units of seconds.

max_tries

The maximum number of repeated requests to make before giving up is passed into the max_tries .

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 radius_add_server() example

<?php
if (!radius_add_server($res'radius.example.com'1812'testing123'33)) {
    echo 
'RadiusError:' radius_strerror($res). "\n<br>";
    exit;
}
?>

참고

  • radius_config() - Causes the library to read the given configuration file



radius_auth_open

(PECL radius >= 1.1.0)

radius_auth_openCreates a Radius handle for authentication

설명

resource radius_auth_open ( void )

반환값

Returns a handle on success, FALSE on error. This function only fails if insufficient memory is available.

예제

Example #1 radius_auth_open() example

<?php
$radh 
radius_auth_open()
    or die (
"Could not create handle");
echo 
"Handle successfully created";
?>



radius_close

(PECL radius >= 1.1.0)

radius_closeFrees all ressources

설명

bool radius_close ( resource $radius_handle )

It is not needed to call this function because php frees all resources at the end of each request.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.



radius_config

(PECL radius >= 1.1.0)

radius_configCauses the library to read the given configuration file

설명

bool radius_config ( resource $radius_handle , string $file )

Before issuing any Radius requests, the library must be made aware of the servers it can contact. The easiest way to configure the library is to call radius_config(). radius_config() causes the library to read a configuration file whose format is described in » radius.conf.

인수

radius_handle

file

The pathname of the configuration file is passed as the file argument to radius_config(). The library can also be configured programmatically by calls to radius_add_server().

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



radius_create_request

(PECL radius >= 1.1.0)

radius_create_requestCreate accounting or authentication request

설명

bool radius_create_request ( resource $radius_handle , int $type )

A Radius request consists of a code specifying the kind of request, and zero or more attributes which provide additional information. To begin constructing a new request, call radius_create_request().

Note: Attention: You must call this function, before you can put any attribute!

인수

radius_handle

type

Type is RADIUS_ACCESS_REQUEST or RADIUS_ACCOUNTING_REQUEST.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 radius_create_request() example

<?php
if (!radius_create_request($resRADIUS_ACCESS_REQUEST)) {
    echo 
'RadiusError:' radius_strerror($res). "\n<br />";
    exit;
}
?>

참고



radius_cvt_addr

(PECL radius >= 1.1.0)

radius_cvt_addrConverts raw data to IP-Address

설명

string radius_cvt_addr ( string $data )

예제

Example #1 radius_cvt_addr() example

<?php
while ($resa radius_get_attr($res)) {

    if (!
is_array($resa)) {
        
printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    
$attr $resa['attr'];
    
$data $resa['data'];
    
    switch (
$attr) {

    case 
RADIUS_FRAMED_IP_ADDRESS:
        
$ip radius_cvt_addr($data);
        echo 
"IP: $ip<br>\n";
        break;

    case 
RADIUS_FRAMED_IP_NETMASK:
        
$mask radius_cvt_addr($data);
        echo 
"MASK: $mask<br>\n";
        break;
    }
}
?>

참고



radius_cvt_int

(PECL radius >= 1.1.0)

radius_cvt_intConverts raw data to integer

설명

int radius_cvt_int ( string $data )

예제

Example #1 radius_cvt_int() example

<?php
while ($resa radius_get_attr($res)) {

    if (!
is_array($resa)) {
        
printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    
$attr $resa['attr'];
    
$data $resa['data'];
    
    switch (
$attr) {

    case 
RADIUS_FRAMED_MTU:
        
$mtu radius_cvt_int($data);
        echo 
"MTU: $mtu<br>\n";
        break;
    }
}
?>

참고



radius_cvt_string

(PECL radius >= 1.1.0)

radius_cvt_stringConverts raw data to string

설명

string radius_cvt_string ( string $data )

예제

Example #1 radius_cvt_string() example

<?php
while ($resa radius_get_attr($res)) {

    if (!
is_array($resa)) {
        
printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    
$attr $resa['attr'];
    
$data $resa['data'];
    
    switch (
$attr) {

    case 
RADIUS_FILTER_ID:
        
$id radius_cvt_string($data);
        echo 
"Filter ID: $id<br>\n";
        break;
    }
}
?>

참고



radius_demangle_mppe_key

(PECL radius >= 1.2.0)

radius_demangle_mppe_keyDerives mppe-keys from mangled data

설명

string radius_demangle_mppe_key ( resource $radius_handle , string $mangled )

When using MPPE with MS-CHAPv2, the send- and recv-keys are mangled (see » RFC 2548), however this function is useless, because I don't think that there is or will be a PPTP-MPPE implementation in PHP.

반환값

Returns the demangled string, or FALSE on error.



radius_demangle

(PECL radius >= 1.2.0)

radius_demangleDemangles data

설명

string radius_demangle ( resource $radius_handle , string $mangled )

Some data (Passwords, MS-CHAPv1 MPPE-Keys) is mangled for security reasons, and must be demangled before you can use them.

반환값

Returns the demangled string, or FALSE on error.



radius_get_attr

(PECL radius >= 1.1.0)

radius_get_attrExtracts an attribute

설명

mixed radius_get_attr ( resource $radius_handle )

Like Radius requests, each response may contain zero or more attributes. After a response has been received successfully by radius_send_request(), its attributes can be extracted one by one using radius_get_attr(). Each time radius_get_attr() is called, it gets the next attribute from the current response.

반환값

Returns an associative array containing the attribute-type and the data, or error number <= 0.

예제

Example #1 radius_get_attr() example

<?php
while ($resa radius_get_attr($res)) {

    if (!
is_array($resa)) {
        
printf("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    
$attr $resa['attr'];
    
$data $resa['data'];
    
printf("Got Attr:%d %d Bytes %s\n"$attrstrlen($data), bin2hex($data));
}
?>

참고



radius_get_vendor_attr

(PECL radius >= 1.1.0)

radius_get_vendor_attrExtracts a vendor specific attribute

설명

array radius_get_vendor_attr ( string $data )

If radius_get_attr() returns RADIUS_VENDOR_SPECIFIC, radius_get_vendor_attr() may be called to determine the vendor.

반환값

Returns an associative array containing the attribute-type, vendor and the data, or FALSE on error.

예제

Example #1 radius_get_vendor_attr() example

<?php
while ($resa radius_get_attr($res)) {

    if (!
is_array($resa)) {
        
printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    
$attr $resa['attr'];
    
$data $resa['data'];
    
printf("Got Attr:%d %d Bytes %s\n"$attrstrlen($data), bin2hex($data));
    if (
$attr == RADIUS_VENDOR_SPECIFIC) {

        
$resv radius_get_vendor_attr($data);
        if (
is_array($resv)) {
            
$vendor $resv['vendor'];
            
$attrv $resv['attr'];
            
$datav $resv['data'];    
            
printf("Got Vendor Attr:%d %d Bytes %s\n"$attrvstrlen($datav), bin2hex($datav));
        }
        
    }
}
?>

참고



radius_put_addr

(PECL radius >= 1.1.0)

radius_put_addrAttaches an IP-Address attribute

설명

bool radius_put_addr ( resource $radius_handle , int $type , string $addr )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.



radius_put_attr

(PECL radius >= 1.1.0)

radius_put_attrAttaches a binary attribute

설명

bool radius_put_attr ( resource $radius_handle , int $type , string $value )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 radius_put_attr() example

<?php
mt_srand
(time());
$chall mt_rand();
$chapval md5(pack('Ca*','sepp' $chall));
$pass pack('CH*'1$chapval);
if (!
radius_put_attr($resRADIUS_CHAP_PASSWORD$pass)) {
    echo 
'RadiusError:' radius_strerror($res). "\n<br />";
    exit;
}
?>

참고



radius_put_int

(PECL radius >= 1.1.0)

radius_put_intAttaches an integer attribute

설명

bool radius_put_int ( resource $radius_handle , int $type , int $value )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 radius_put_int() example

<?php
if (!radius_put_int($resRAD_FRAMED_PROTOCOLRAD_PPP)) {
   echo 
'RadiusError:' radius_strerror($res). "\n<br />";
   exit;
}
?>

참고



radius_put_string

(PECL radius >= 1.1.0)

radius_put_stringAttaches a string attribute

설명

bool radius_put_string ( resource $radius_handle , int $type , string $value )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 radius_put_string() example

<?php
if (!radius_put_string($resRADIUS_USER_NAME'billy')) {
    echo 
'RadiusError:' radius_strerror($res). "\n<br />";
    exit;
}
?>

참고



radius_put_vendor_addr

(PECL radius >= 1.1.0)

radius_put_vendor_addrAttaches a vendor specific IP-Address attribute

설명

bool radius_put_vendor_addr ( resource $radius_handle , int $vendor , int $type , string $addr )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.



radius_put_vendor_attr

(PECL radius >= 1.1.0)

radius_put_vendor_attrAttaches a vendor specific binary attribute

설명

bool radius_put_vendor_attr ( resource $radius_handle , int $vendor , int $type , string $value )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

예제

Example #1 radius_put_vendor_attr() example

<?php
if (!radius_put_vendor_attr($resRADIUS_VENDOR_MICROSOFTRAD_MICROSOFT_MS_CHAP_CHALLENGE$challenge)) {
    echo 
'RadiusError:' radius_strerror($res). "\n<br />";
    exit;
}
?>

참고



radius_put_vendor_int

(PECL radius >= 1.1.0)

radius_put_vendor_intAttaches a vendor specific integer attribute

설명

bool radius_put_vendor_int ( resource $radius_handle , int $vendor , int $type , int $value )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



radius_put_vendor_string

(PECL radius >= 1.1.0)

radius_put_vendor_stringAttaches a vendor specific string attribute

설명

bool radius_put_vendor_string ( resource $radius_handle , int $vendor , int $type , string $value )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

반환값

성공할 경우 TRUE를, 실패할 경우 FALSE를 반환합니다.

참고



radius_request_authenticator

(PECL radius >= 1.1.0)

radius_request_authenticatorReturns the request authenticator

설명

string radius_request_authenticator ( resource $radius_handle )

The request authenticator is needed for demangling mangled data like passwords and encryption-keys.

반환값

Returns the request authenticator as string, or FALSE on error.

참고



radius_send_request

(PECL radius >= 1.1.0)

radius_send_requestSends the request and waites for a reply

설명

int radius_send_request ( resource $radius_handle )

After the Radius request has been constructed, it is sent by radius_send_request().

The radius_send_request() function sends the request and waits for a valid reply, retrying the defined servers in round-robin fashion as necessary.

반환값

If a valid response is received, radius_send_request() returns the Radius code which specifies the type of the response. This will typically be RADIUS_ACCESS_ACCEPT, RADIUS_ACCESS_REJECT, or RADIUS_ACCESS_CHALLENGE. If no valid response is received, radius_send_request() returns FALSE.

참고



radius_server_secret

(PECL radius >= 1.1.0)

radius_server_secretReturns the shared secret

설명

string radius_server_secret ( resource $radius_handle )

The shared secret is needed as salt for demangling mangled data like passwords and encryption-keys.

반환값

Returns the server's shared secret as string, or FALSE on error.



radius_strerror

(PECL radius >= 1.1.0)

radius_strerrorReturns an error message

설명

string radius_strerror ( resource $radius_handle )

If Radius-functions fail then they record an error message. This error message can be retrieved with this function.

반환값

Returns error messages as string from failed radius functions.


Table of Contents





Calendar and Event Related Extensions


Calendar


소개

The calendar extension presents a series of functions to simplify converting between different calendar formats. The intermediary or standard it is based on is the Julian Day Count. The Julian Day Count is a count of days starting from January 1st, 4713 B.C. To convert between calendar systems, you must first convert to Julian Day Count, then to the calendar system of your choice. Julian Day Count is very different from the Julian Calendar! For more information on Julian Day Count, visit » http://www.hermetic.ch/cal_stud/jdn.htm. For more information on calendar systems visit » http://www.fourmilab.ch/documents/calendar/. Excerpts from this page are included in these instructions, and are in quotes.



설치/설정

Table of Contents


요구 조건

이 확장을 빌드할 때 외부 라이브러리가 필요하지 않습니다.



설치

이 함수들를 작동시키기 위해서는, PHP를 컴파일할때 --enable-calendar 옵션을 써야 한다.

PHP 윈도우 버전에서는 이 확장에 대한 지원이 포함되어 있습니다. 이 함수들을 이용하기 위해서 추가로 확장을 읽어들일 필요가 없습니다.



실행시 설정

이 확장은 php.ini 설정이 존재하지 않습니다.



자원형

이 확장은 리소스형을 정의하지 않습니다.




예약 상수

이 확장은 다음의 상수들을 정의합니다. 이 확장을 PHP에 내장했거나, 실행시에 동적으로 읽어들일 경우에만 사용할 수 있습니다.

CAL_GREGORIAN (integer)
CAL_JULIAN (integer)
CAL_JEWISH (integer)
CAL_FRENCH (integer)
CAL_NUM_CALS (integer)
CAL_DOW_DAYNO (integer)
CAL_DOW_SHORT (integer)
CAL_DOW_LONG (integer)
CAL_MONTH_GREGORIAN_SHORT (integer)
CAL_MONTH_GREGORIAN_LONG (integer)
CAL_MONTH_JULIAN_SHORT (integer)
CAL_MONTH_JULIAN_LONG (integer)
CAL_MONTH_JEWISH (integer)
CAL_MONTH_FRENCH (integer)

The following constants are available since PHP 4.3.0 :

CAL_EASTER_DEFAULT (integer)
CAL_EASTER_ROMAN (integer)
CAL_EASTER_ALWAYS_GREGORIAN (integer)
CAL_EASTER_ALWAYS_JULIAN (integer)

The following constants are available since PHP 5.0.0 :

CAL_JEWISH_ADD_ALAFIM_GERESH (integer)
CAL_JEWISH_ADD_ALAFIM (integer)
CAL_JEWISH_ADD_GERESHAYIM (integer)


Calendar 함수 목록


cal_days_in_month

(PHP 4 >= 4.1.0, PHP 5)

cal_days_in_monthReturn the number of days in a month for a given year and calendar

설명

int cal_days_in_month ( int $calendar , int $month , int $year )

This function will return the number of days in the month of year for the specified calendar .

인수

calendar

Calendar to use for calculation

month

Month in the selected calendar

year

Year in the selected calendar

반환값

The length in days of the selected month in the given calendar

예제

Example #1 cal_days_in_month() example

<?php
$num 
cal_days_in_month(CAL_GREGORIAN82003); // 31
echo "There was $num days in August 2003";
?>



cal_from_jd

(PHP 4 >= 4.1.0, PHP 5)

cal_from_jdConverts from Julian Day Count to a supported calendar

설명

array cal_from_jd ( int $jd , int $calendar )

cal_from_jd() converts the Julian day given in jd into a date of the specified calendar . Supported calendar values are CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH.

인수

jd

Julian day as integer

calendar

Calendar to convert to

반환값

Returns an array containing calendar information like month, day, year, day of week, abbreviated and full names of weekday and month and the date in string form "month/day/year".

예제

Example #1 cal_from_jd() example

<?php
$today 
unixtojd(mktime(0008162003));
print_r(cal_from_jd($todayCAL_GREGORIAN));
?>

위 예제의 출력:

Array
(
    [date] => 8/16/2003
    [month] => 8
    [day] => 16
    [year] => 2003
    [dow] => 6
    [abbrevdayname] => Sat
    [dayname] => Saturday
    [abbrevmonth] => Aug
    [monthname] => August
)

참고

  • cal_to_jd() - Converts from a supported calendar to Julian Day Count
  • jdtofrench() - Converts a Julian Day Count to the French Republican Calendar
  • jdtogregorian() - Converts Julian Day Count to Gregorian date
  • jdtojewish() - Converts a Julian day count to a Jewish calendar date
  • jdtojulian() - Converts a Julian Day Count to a Julian Calendar Date
  • jdtounix() - Convert Julian Day to Unix timestamp



cal_info

(PHP 4 >= 4.1.0, PHP 5)

cal_infoReturns information about a particular calendar

설명

array cal_info ([ int $calendar= -1 ] )

cal_info() returns information on the specified calendar .

Calendar information is returned as an array containing the elements calname, calsymbol, month, abbrevmonth and maxdaysinmonth. The names of the different calendars which can be used as calendar are as follows:

  • 0 or CAL_GREGORIAN - Gregorian Calendar
  • 1 or CAL_JULIAN - Julian Calendar
  • 2 or CAL_JEWISH - Jewish Calendar
  • 3 or CAL_FRENCH - French Revolutionary Calendar

If no calendar is specified information on all supported calendars is returned as an array.

인수

calendar

Calendar to return information for. If no calendar is specified information about all calendars is returned.

반환값

변경점

버전 설명
Since 5.0 The calendar parameter becomes optional and defaults to "all calendars" if omitted.

예제

Example #1 cal_info() example

<?php
$info 
cal_info(0);
print_r($info);
?>

위 예제의 출력:

Array
(
    [months] => Array
        (
            [1] => January
            [2] => February
            [3] => March
            [4] => April
            [5] => May
            [6] => June
            [7] => July
            [8] => August
            [9] => September
            [10] => October
            [11] => November
            [12] => December
        )

    [abbrevmonths] => Array
        (
            [1] => Jan
            [2] => Feb
            [3] => Mar
            [4] => Apr
            [5] => May
            [6] => Jun
            [7] => Jul
            [8] => Aug
            [9] => Sep
            [10] => Oct
            [11] => Nov
            [12] => Dec
        )

    [maxdaysinmonth] => 31
    [calname] => Gregorian
    [calsymbol] => CAL_GREGORIAN
)



cal_to_jd

(PHP 4 >= 4.1.0, PHP 5)

cal_to_jdConverts from a supported calendar to Julian Day Count

설명

int cal_to_jd ( int $calendar , int $month , int $day , int $year )

cal_to_jd() calculates the Julian day count for a date in the specified calendar . Supported calendar s are CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH.

인수

calendar

Calendar to convert from, one of CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH or CAL_FRENCH.

month

The month as a number, the valid range depends on the calendar

day

The day as a number, the valid range depends on the calendar

year

The year as a number, the valid range depends on the calendar

반환값

A Julian Day number.

참고

  • cal_from_jd() - Converts from Julian Day Count to a supported calendar
  • frenchtojd() - Converts a date from the French Republican Calendar to a Julian Day Count
  • gregoriantojd() - Converts a Gregorian date to Julian Day Count
  • jewishtojd() - Converts a date in the Jewish Calendar to Julian Day Count
  • juliantojd() - Converts a Julian Calendar date to Julian Day Count
  • unixtojd() - Convert Unix timestamp to Julian Day



easter_date

(PHP 4, PHP 5)

easter_dateGet Unix timestamp for midnight on Easter of a given year

설명

int easter_date ([ int $year ] )

Returns the Unix timestamp corresponding to midnight on Easter of the given year.

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).

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 at ely.anglican dot org>)

인수

year

The year as a number between 1970 an 2037

반환값

The easter date as a unix timestamp.

변경점

버전 설명
Since 4.3.0 The year parameter is optional and defaults to the current year according to the local time if omitted.

예제

Example #1 easter_date() example

<?php

echo date("M-d-Y"easter_date(1999));        // Apr-04-1999
echo date("M-d-Y"easter_date(2000));        // Apr-23-2000
echo date("M-d-Y"easter_date(2001));        // Apr-15-2001

?>

참고

  • easter_days() - Get number of days after March 21 on which Easter falls for a given year for calculating Easter before 1970 or after 2037



easter_days

(PHP 4, PHP 5)

easter_daysGet number of days after March 21 on which Easter falls for a given year

설명

int easter_days ([ int $year [, int $method= CAL_EASTER_DEFAULT ]] )

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).

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 at ely.anglican dot org>)

인수

year

The year as a positive number

method

Allows to calculate easter dates based on the Gregorian calendar during the years 1582 - 1752 when set to CAL_EASTER_ROMAN. See the calendar constants for more valid constants.

반환값

The number of days after March 21st that the Easter Sunday is in the given year .

변경점

버전 설명
Since 4.3.0 The year parameter is optional and defaults to the current year according to the local time if omitted.
Since 4.3.0 The method parameter was introduced.

예제

Example #1 easter_days() example

<?php

echo easter_days(1999);        // 14, i.e. April 4
echo easter_days(1492);        // 32, i.e. April 22
echo easter_days(1913);        //  2, i.e. March 23

?>

참고

  • easter_date() - Get Unix timestamp for midnight on Easter of a given year



FrenchToJD

(PHP 4, PHP 5)

FrenchToJDConverts a date from the French Republican Calendar to a 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.

인수

month

The month as a number from 1 (for Vendémiaire) to 13 (for the period of 5-6 days at the end of each year)

day

The day as a number from 1 to 30

year

The year as a number between 1 and 14

반환값

The julian day for the given french revolution date as an integer.

참고

  • jdtofrench() - Converts a Julian Day Count to the French Republican Calendar
  • cal_to_jd() - Converts from a supported calendar to Julian Day Count



GregorianToJD

(PHP 4, PHP 5)

GregorianToJDConverts a Gregorian date to 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 function 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.

인수

month

The month as a number from 1 (for January) to 12 (for December)

day

The day as a number from 1 to 31

year

The year as a number between -4714 and 9999

반환값

The julian day for the given gregorian date as an integer.

예제

Example #1 Calendar functions

<?php
$jd 
GregorianToJD(10111970);
echo 
"$jd\n";
$gregorian JDToGregorian($jd);
echo 
"$gregorian\n";
?>

참고

  • jdtogregorian() - Converts Julian Day Count to Gregorian date
  • cal_to_jd() - Converts from a supported calendar to Julian Day Count



JDDayOfWeek

(PHP 4, PHP 5)

JDDayOfWeekReturns the day of the week

설명

mixed jddayofweek ( int $julianday [, int $mode= CAL_DOW_DAYNO ] )

Returns the day of the week. Can return a string or an integer depending on the mode.

인수

julianday

A julian day number as integer

mode
Calendar week modes
Mode Meaning
0 (Default) Return the day number as an int (0=Sunday, 1=Monday, etc)
1 Returns string containing the day of week (English-Gregorian)
2 Return a string containing the abbreviated day of week (English-Gregorian)

반환값

The gregorian weekday as either an integer or string.



JDMonthName

(PHP 4, PHP 5)

JDMonthNameReturns a month name

설명

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.

Calendar modes
Mode Meaning Values
0 Gregorian - abbreviated Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
1 Gregorian January, February, March, April, May, June, July, August, September, October, November, December
2 Julian - abbreviated Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
3 Julian January, February, March, April, May, June, July, August, September, October, November, December
4 Jewish Tishri, Heshvan, Kislev, Tevet, Shevat, AdarI, AdarII, Nisan, Iyyar, Sivan, Tammuz, Av, Elul
5 French Republican Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra

인수

jday

The Julian Day to operate on

calendar

The calendar to take the month name from

반환값

The month name for the given Julian Day and calendar .



JDToFrench

(PHP 4, PHP 5)

JDToFrenchConverts a Julian Day Count to the French Republican Calendar

설명

string jdtofrench ( int $juliandaycount )

Converts a Julian Day Count to the French Republican Calendar.

인수

julianday

A julian day number as integer

반환값

The french revolution date as a string in the form "month/day/year"

참고

  • frenchtojd() - Converts a date from the French Republican Calendar to a Julian Day Count
  • cal_from_jd() - Converts from Julian Day Count to a supported calendar



JDToGregorian

(PHP 4, PHP 5)

JDToGregorianConverts Julian Day Count to Gregorian date

설명

string jdtogregorian ( int $julianday )

Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year".

인수

julianday

A julian day number as integer

반환값

The gregorian date as a string in the form "month/day/year"

참고



jdtojewish

(PHP 4, PHP 5)

jdtojewishConverts a Julian day count to a Jewish calendar date

설명

string jdtojewish ( int $juliandaycount [, bool $hebrew= false [, int $fl= 0 ]] )

Converts a Julian Day Count to the Jewish Calendar.

인수

julianday

A julian day number as integer

hebrew

If the hebrew parameter is set to TRUE, the fl parameter is used for Hebrew, string based, output format.

fl

The available formats are: CAL_JEWISH_ADD_ALAFIM_GERESH, CAL_JEWISH_ADD_ALAFIM, CAL_JEWISH_ADD_GERESHAYIM.

반환값

The jewish date as a string in the form "month/day/year"

변경점

버전 설명
5.0.0 The fl parameter was added.
4.3.0 The hebrew parameter was added.

예제

Example #1 jdtojewish() Example

<?php
echo jdtojewish(gregoriantojd(1082002), true,
       
CAL_JEWISH_ADD_GERESHAYIM CAL_JEWISH_ADD_ALAFIM CAL_JEWISH_ADD_ALAFIM_GERESH); 
?>

참고

  • jewishtojd() - Converts a date in the Jewish Calendar to Julian Day Count
  • cal_from_jd() - Converts from Julian Day Count to a supported calendar



JDToJulian

(PHP 4, PHP 5)

JDToJulianConverts a Julian Day Count to a 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".

인수

julianday

A julian day number as integer

반환값

The julian date as a string in the form "month/day/year"

참고

  • juliantojd() - Converts a Julian Calendar date to Julian Day Count
  • cal_from_jd() - Converts from Julian Day Count to a supported calendar



jdtounix

(PHP 4, PHP 5)

jdtounixConvert Julian Day to Unix timestamp

설명

int jdtounix ( int $jday )

This function will return a Unix timestamp corresponding to the Julian Day given in jday or FALSE if jday is not inside the Unix epoch (Gregorian years between 1970 and 2037 or 2440588 <= jday <= 2465342 ). The time returned is localtime (and not GMT).

인수

jday

A julian day number between 2440588 and 2465342.

반환값

The unix timestamp for the start of the given julian day.

참고

  • unixtojd() - Convert Unix timestamp to Julian Day



JewishToJD

(PHP 4, PHP 5)

JewishToJDConverts a date in the Jewish Calendar to Julian Day Count

설명

int jewishtojd ( int $month , int $day , int $year )

Although this function 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.

인수

month

The month as a number from 1 to 13

day

The day as a number from 1 to 30

year

The year as a number between 1 and 9999

반환값

The julian day for the given jewish date as an integer.

참고

  • jdtojewish() - Converts a Julian day count to a Jewish calendar date
  • cal_to_jd() - Converts from a supported calendar to Julian Day Count



JulianToJD

(PHP 4, PHP 5)

JulianToJDConverts a Julian Calendar date to 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 function 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.

Caution

Remember, the current calendar system being used worldwide is the Gregorian calendar. gregoriantojd() can be used to convert such dates to their Julian Day count.

인수

month

The month as a number from 1 (for January) to 12 (for December)

day

The day as a number from 1 to 31

year

The year as a number between -4713 and 9999

반환값

The julian day for the given julian date as an integer.

참고

  • jdtojulian() - Converts a Julian Day Count to a Julian Calendar Date
  • cal_to_jd() - Converts from a supported calendar to Julian Day Count



unixtojd

(PHP 4, PHP 5)

unixtojdConvert Unix timestamp to Julian Day

설명

int unixtojd ([ int $timestamp= time() ] )

Return the Julian Day for a Unix timestamp (seconds since 1.1.1970), or for the current day if no timestamp is given.

인수

timestamp

A unix timestamp to convert.

반환값

A julian day number as integer.

참고

  • jdtounix() - Convert Julian Day to Unix timestamp


Table of Contents

  • cal_days_in_month — Return the number of days in a month for a given year and calendar
  • cal_from_jd — Converts from Julian Day Count to a supported calendar
  • cal_info — Returns information about a particular calendar
  • cal_to_jd — Converts from a supported calendar to Julian Day Count
  • easter_date — Get Unix timestamp for midnight on Easter of a given year
  • easter_days — Get number of days after March 21 on which Easter falls for a given year
  • FrenchToJD — Converts a date from the French Republican Calendar to a Julian Day Count
  • GregorianToJD — Converts a Gregorian date to Julian Day Count
  • JDDayOfWeek — Returns the day of the week
  • JDMonthName — Returns a month name
  • JDToFrench — Converts a Julian Day Count to the French Republican Calendar
  • JDToGregorian — Converts Julian Day Count to Gregorian date
  • jdtojewish — Converts a Julian day count to a Jewish calendar date
  • JDToJulian — Converts a Julian Day Count to a Julian Calendar Date
  • jdtounix — Convert Julian Day to Unix timestamp
  • JewishToJD — Converts a date in the Jewish Calendar to Julian Day Count
  • JulianToJD — Converts a Julian Calendar date to Julian Day Count
  • unixtojd — Convert Unix timestamp to Julian Day



Date and Time


소개

These functions allow you to get the date and time from the server where your PHP scripts are running. You can use these functions to format the date and time in many different ways.

Note: Please keep in mind that these functions are dependent on the locale settings of your server. Make sure to take daylight saving time (use e.g. $date = strtotime('+7 days', $date) and not $date += 7*24*60*60) and leap years into consideration when working with these functions.

Note: The timezones referenced in this section can be found in the 지원하는 시간대 목록.



설치/설정

Table of Contents


요구 조건

이 확장을 빌드할 때 외부 라이브러리가 필요하지 않습니다.



설치

이 함수들은 설치하지 않아도 사용할 수 있습니다; PHP 코어의 일부입니다.

Note: Getting the latest timezone database
The latest version of the timezone database can be installed via PECL's » timezonedb.

Note: Experimental DateTime support in PHP 5.1.x
Although the DateTime class (and related functions) are enabled by default since PHP 5.2.0, it is possible to add experimental support into PHP 5.1.x by using the following flag before configure/compile: CFLAGS=-DEXPERIMENTAL_DATE_SUPPORT=1



실행시 설정

이 함수의 작동은 php.ini 설정에 영향을 받습니다.

Date/Time Configuration Options
Name Default Changeable Changelog
date.default_latitude "31.7667" PHP_INI_ALL Available since PHP 5.0.0.
date.default_longitude "35.2333" PHP_INI_ALL Available since PHP 5.0.0.
date.sunrise_zenith "90.583333" PHP_INI_ALL Available since PHP 5.0.0.
date.sunset_zenith "90.583333" PHP_INI_ALL Available since PHP 5.0.0.
date.timezone "" PHP_INI_ALL Available since PHP 5.1.0.

PHP_INI_* 모드에 대한 상세와 정의는 환경 설정을 바꿀 수 있는 곳를 참고하십시오.

위 설정 지시어에 대한 간단한 설명입니다.

date.default_latitude float

The default latitude.

date.default_longitude float

The default longitude.

date.sunrise_zenith float

The default sunrise zenith.

date.sunset_zenith float

The default sunset zenith.

date.timezone string

The default timezone used by all date/time functions if the TZ environment variable isn't set. The precedence order is described in the date_default_timezone_get() page. See 지원하는 시간대 목록 for a list of supported timezones.

Note: The first four configuration options are currently only used by date_sunrise() and date_sunset().



자원형

이 확장은 리소스형을 정의하지 않습니다.




예약 상수

The DATE_ constants are defined since PHP 5.1.1 and they offer standard date representations, which can be used along with the date format functions (like date()).

Following constants exists since PHP 5.1.2 and specify a format returned by functions date_sunrise() and date_sunset().

SUNFUNCS_RET_TIMESTAMP (integer)
Timestamp
SUNFUNCS_RET_STRING (integer)
Hours:minutes (example: 08:02)
SUNFUNCS_RET_DOUBLE (integer)
Hours as floating point number (example 8.75)


지원하는 시간대 목록

Table of Contents

여기에서 PHP에서 지원하는 모든 시간대 목록을 확인할 수 있습니다. 이는 date_default_timezone_set() 등에서 사용합니다.

Note: 최신 버전의 시간대 데이터베이스는 PECL의 » timezonedb를 통해 설치할 수 있습니다.

Note: This list is based upon Version 2009.10 of the timezonedb.


Africa

Africa
Africa/Abidjan Africa/Accra Africa/Addis_Ababa Africa/Algiers Africa/Asmara
Africa/Asmera Africa/Bamako Africa/Bangui Africa/Banjul Africa/Bissau
Africa/Blantyre Africa/Brazzaville Africa/Bujumbura Africa/Cairo Africa/Casablanca
Africa/Ceuta Africa/Conakry Africa/Dakar Africa/Dar_es_Salaam Africa/Djibouti
Africa/Douala Africa/El_Aaiun Africa/Freetown Africa/Gaborone Africa/Harare
Africa/Johannesburg Africa/Kampala Africa/Khartoum Africa/Kigali Africa/Kinshasa
Africa/Lagos Africa/Libreville Africa/Lome Africa/Luanda Africa/Lubumbashi
Africa/Lusaka Africa/Malabo Africa/Maputo Africa/Maseru Africa/Mbabane
Africa/Mogadishu Africa/Monrovia Africa/Nairobi Africa/Ndjamena Africa/Niamey
Africa/Nouakchott Africa/Ouagadougou Africa/Porto-Novo Africa/Sao_Tome Africa/Timbuktu
Africa/Tripoli Africa/Tunis Africa/Windhoek    


America

America
America/Adak America/Anchorage America/Anguilla America/Antigua America/Araguaina
America/Argentina/Buenos_Aires America/Argentina/Catamarca America/Argentina/ComodRivadavia America/Argentina/Cordoba America/Argentina/Jujuy
America/Argentina/La_Rioja America/Argentina/Mendoza America/Argentina/Rio_Gallegos America/Argentina/Salta America/Argentina/San_Juan
America/Argentina/San_Luis America/Argentina/Tucuman America/Argentina/Ushuaia America/Aruba America/Asuncion
America/Atikokan America/Atka America/Bahia America/Barbados America/Belem
America/Belize America/Blanc-Sablon America/Boa_Vista America/Bogota America/Boise
America/Buenos_Aires America/Cambridge_Bay America/Campo_Grande America/Cancun America/Caracas
America/Catamarca America/Cayenne America/Cayman America/Chicago America/Chihuahua
America/Coral_Harbour America/Cordoba America/Costa_Rica America/Cuiaba America/Curacao
America/Danmarkshavn America/Dawson America/Dawson_Creek America/Denver America/Detroit
America/Dominica America/Edmonton America/Eirunepe America/El_Salvador America/Ensenada
America/Fort_Wayne America/Fortaleza America/Glace_Bay America/Godthab America/Goose_Bay
America/Grand_Turk America/Grenada America/Guadeloupe America/Guatemala America/Guayaquil
America/Guyana America/Halifax America/Havana America/Hermosillo America/Indiana/Indianapolis
America/Indiana/Knox America/Indiana/Marengo America/Indiana/Petersburg America/Indiana/Tell_City America/Indiana/Vevay
America/Indiana/Vincennes America/Indiana/Winamac America/Indianapolis America/Inuvik America/Iqaluit
America/Jamaica America/Jujuy America/Juneau America/Kentucky/Louisville America/Kentucky/Monticello
America/Knox_IN America/La_Paz America/Lima America/Los_Angeles America/Louisville
America/Maceio America/Managua America/Manaus America/Marigot America/Martinique
America/Mazatlan America/Mendoza America/Menominee America/Merida America/Mexico_City
America/Miquelon America/Moncton America/Monterrey America/Montevideo America/Montreal
America/Montserrat America/Nassau America/New_York America/Nipigon America/Nome
America/Noronha America/North_Dakota/Center America/North_Dakota/New_Salem America/Panama America/Pangnirtung
America/Paramaribo America/Phoenix America/Port-au-Prince America/Port_of_Spain America/Porto_Acre
America/Porto_Velho America/Puerto_Rico America/Rainy_River America/Rankin_Inlet America/Recife
America/Regina America/Resolute America/Rio_Branco America/Rosario America/Santarem
America/Santiago America/Santo_Domingo America/Sao_Paulo America/Scoresbysund America/Shiprock
America/St_Barthelemy America/St_Johns America/St_Kitts America/St_Lucia America/St_Thomas
America/St_Vincent America/Swift_Current America/Tegucigalpa America/Thule America/Thunder_Bay
America/Tijuana America/Toronto America/Tortola America/Vancouver America/Virgin
America/Whitehorse America/Winnipeg America/Yakutat America/Yellowknife  


Antarctica

Antarctica
Antarctica/Casey Antarctica/Davis Antarctica/DumontDUrville Antarctica/Mawson Antarctica/McMurdo
Antarctica/Palmer Antarctica/Rothera Antarctica/South_Pole Antarctica/Syowa Antarctica/Vostok


Arctic

Arctic
Arctic/Longyearbyen


Asia

Asia
Asia/Aden Asia/Almaty Asia/Amman Asia/Anadyr Asia/Aqtau
Asia/Aqtobe Asia/Ashgabat Asia/Ashkhabad Asia/Baghdad Asia/Bahrain
Asia/Baku Asia/Bangkok Asia/Beirut Asia/Bishkek Asia/Brunei
Asia/Calcutta Asia/Choibalsan Asia/Chongqing Asia/Chungking Asia/Colombo
Asia/Dacca Asia/Damascus Asia/Dhaka Asia/Dili Asia/Dubai
Asia/Dushanbe Asia/Gaza Asia/Harbin Asia/Ho_Chi_Minh Asia/Hong_Kong
Asia/Hovd Asia/Irkutsk Asia/Istanbul Asia/Jakarta Asia/Jayapura
Asia/Jerusalem Asia/Kabul Asia/Kamchatka Asia/Karachi Asia/Kashgar
Asia/Kathmandu Asia/Katmandu Asia/Kolkata Asia/Krasnoyarsk Asia/Kuala_Lumpur
Asia/Kuching Asia/Kuwait Asia/Macao Asia/Macau Asia/Magadan
Asia/Makassar Asia/Manila Asia/Muscat Asia/Nicosia Asia/Novosibirsk
Asia/Omsk Asia/Oral Asia/Phnom_Penh Asia/Pontianak Asia/Pyongyang
Asia/Qatar Asia/Qyzylorda Asia/Rangoon Asia/Riyadh Asia/Saigon
Asia/Sakhalin Asia/Samarkand Asia/Seoul Asia/Shanghai Asia/Singapore
Asia/Taipei Asia/Tashkent Asia/Tbilisi Asia/Tehran Asia/Tel_Aviv
Asia/Thimbu Asia/Thimphu Asia/Tokyo Asia/Ujung_Pandang Asia/Ulaanbaatar
Asia/Ulan_Bator Asia/Urumqi Asia/Vientiane Asia/Vladivostok Asia/Yakutsk
Asia/Yekaterinburg Asia/Yerevan      


Atlantic

Atlantic
Atlantic/Azores Atlantic/Bermuda Atlantic/Canary Atlantic/Cape_Verde Atlantic/Faeroe
Atlantic/Faroe Atlantic/Jan_Mayen Atlantic/Madeira Atlantic/Reykjavik Atlantic/South_Georgia
Atlantic/St_Helena Atlantic/Stanley      


Australia

Australia
Australia/ACT Australia/Adelaide Australia/Brisbane Australia/Broken_Hill Australia/Canberra
Australia/Currie Australia/Darwin Australia/Eucla Australia/Hobart Australia/LHI
Australia/Lindeman Australia/Lord_Howe Australia/Melbourne Australia/North Australia/NSW
Australia/Perth Australia/Queensland Australia/South Australia/Sydney Australia/Tasmania
Australia/Victoria Australia/West Australia/Yancowinna    


Europe

Europe
Europe/Amsterdam Europe/Andorra Europe/Athens Europe/Belfast Europe/Belgrade
Europe/Berlin Europe/Bratislava Europe/Brussels Europe/Bucharest Europe/Budapest
Europe/Chisinau Europe/Copenhagen Europe/Dublin Europe/Gibraltar Europe/Guernsey
Europe/Helsinki Europe/Isle_of_Man Europe/Istanbul Europe/Jersey Europe/Kaliningrad
Europe/Kiev Europe/Lisbon Europe/Ljubljana Europe/London Europe/Luxembourg
Europe/Madrid Europe/Malta Europe/Mariehamn Europe/Minsk Europe/Monaco
Europe/Moscow Europe/Nicosia Europe/Oslo Europe/Paris Europe/Podgorica
Europe/Prague Europe/Riga Europe/Rome Europe/Samara Europe/San_Marino
Europe/Sarajevo Europe/Simferopol Europe/Skopje Europe/Sofia Europe/Stockholm
Europe/Tallinn Europe/Tirane Europe/Tiraspol Europe/Uzhgorod Europe/Vaduz
Europe/Vatican Europe/Vienna Europe/Vilnius Europe/Volgograd Europe/Warsaw
Europe/Zagreb Europe/Zaporozhye Europe/Zurich    


Indian

Indian
Indian/Antananarivo Indian/Chagos Indian/Christmas Indian/Cocos Indian/Comoro
Indian/Kerguelen Indian/Mahe Indian/Maldives Indian/Mauritius Indian/Mayotte
Indian/Reunion        


Pacific

Pacific
Pacific/Apia Pacific/Auckland Pacific/Chatham Pacific/Easter Pacific/Efate
Pacific/Enderbury Pacific/Fakaofo Pacific/Fiji Pacific/Funafuti Pacific/Galapagos
Pacific/Gambier Pacific/Guadalcanal Pacific/Guam Pacific/Honolulu Pacific/Johnston
Pacific/Kiritimati Pacific/Kosrae Pacific/Kwajalein Pacific/Majuro Pacific/Marquesas
Pacific/Midway Pacific/Nauru Pacific/Niue Pacific/Norfolk Pacific/Noumea
Pacific/Pago_Pago Pacific/Palau Pacific/Pitcairn Pacific/Ponape Pacific/Port_Moresby
Pacific/Rarotonga Pacific/Saipan Pacific/Samoa Pacific/Tahiti Pacific/Tarawa
Pacific/Tongatapu Pacific/Truk Pacific/Wake Pacific/Wallis Pacific/Yap


Others

Others
Brazil/Acre Brazil/DeNoronha Brazil/East Brazil/West Canada/Atlantic
Canada/Central Canada/East-Saskatchewan Canada/Eastern Canada/Mountain Canada/Newfoundland
Canada/Pacific Canada/Saskatchewan Canada/Yukon CET Chile/Continental
Chile/EasterIsland CST6CDT Cuba EET Egypt
Eire EST EST5EDT Etc/GMT Etc/GMT+0
Etc/GMT+1 Etc/GMT+10 Etc/GMT+11 Etc/GMT+12 Etc/GMT+2
Etc/GMT+3 Etc/GMT+4 Etc/GMT+5 Etc/GMT+6 Etc/GMT+7
Etc/GMT+8 Etc/GMT+9 Etc/GMT-0 Etc/GMT-1 Etc/GMT-10
Etc/GMT-11 Etc/GMT-12 Etc/GMT-13 Etc/GMT-14 Etc/GMT-2
Etc/GMT-3 Etc/GMT-4 Etc/GMT-5 Etc/GMT-6 Etc/GMT-7
Etc/GMT-8 Etc/GMT-9 Etc/GMT0 Etc/Greenwich Etc/UCT
Etc/Universal Etc/UTC Etc/Zulu Factory GB
GB-Eire GMT GMT+0 GMT-0 GMT0
Greenwich Hongkong HST Iceland Iran
Israel Jamaica Japan Kwajalein Libya
MET Mexico/BajaNorte Mexico/BajaSur Mexico/General MST
MST7MDT Navajo NZ NZ-CHAT Poland
Portugal PRC PST8PDT ROC ROK
Singapore Turkey UCT Universal US/Alaska
US/Aleutian US/Arizona US/Central US/East-Indiana US/Eastern
US/Hawaii US/Indiana-Starke US/Michigan US/Mountain US/Pacific
US/Pacific-New US/Samoa UTC W-SU WET
Zulu        
Warning

여기에 있는 시간대 목록을 사용하지 마십시오(UTC 제외). 하위 호환을 위해서 남겨져 있을 뿐입니다.




The DateTime class

소개

Representation of date and time.

클래스 개요

DateTime
DateTime {
/* Constants */
const string DateTime::ATOM = Y-m-d\TH:i:sP ;
const string DateTime::COOKIE = l, d-M-y H:i:s T ;
const string DateTime::ISO8601 = Y-m-d\TH:i:sO ;
const string DateTime::RFC822 = D, d M y H:i:s O ;
const string DateTime::RFC850 = l, d-M-y H:i:s T ;
const string DateTime::RFC1036 = D, d M y H:i:s O ;
const string DateTime::RFC1123 = D, d M Y H:i:s O ;
const string DateTime::RFC2822 = D, d M Y H:i:s O ;
const string DateTime::RFC3339 = Y-m-d\TH:i:sP ;
const string DateTime::RSS = D, d M Y H:i:s O ;
const string DateTime::W3C = Y-m-d\TH:i:sP ;
/* Methods */
public DateTime add ( string $interval )
__construct ([ string $time= "now" [, DateTimeZone $timezone= NULL ]] )
public static DateTime createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )
public DateInterval diff ( DateTime $datetime [, bool $absolute ] )
public string format ( string $format )
public static array getLastErrors ( void )
public int getOffset ( void )
public int getTimestamp ( void )
public DateTimeZone getTimezone ( void )
public DateTime modify ( string $modify )
public static DateTime __set_state ( array $array )
public DateTime setDate ( int $year , int $month , int $day )
public DateTime setISODate ( int $year , int $week [, int $day ] )
public DateTime setTime ( int $hour , int $minute [, int $second ] )
public DateTime setTimestamp ( int $unixtimestamp )
public DateTime setTimezone ( DateTimeZone $timezone )
public DateTime sub ( DateInterval $interval )
public DateTime __wakeup ( void )
}

예약 상수

DateTime Node Types

DateTime::ATOM
DATE_ATOM
Atom (example: 2005-08-15T15:52:01+00:00)
DateTime::COOKIE
DATE_COOKIE
HTTP Cookies (example: Monday, 15-Aug-05 15:52:01 UTC)
DateTime::ISO8601
DATE_ISO8601
ISO-8601 (example: 2005-08-15T15:52:01+0000)
DateTime::RFC822
DATE_RFC822
RFC 822 (example: Mon, 15 Aug 05 15:52:01 +0000)
DateTime::RFC850
DATE_RFC850
RFC 850 (example: Monday, 15-Aug-05 15:52:01 UTC)
DateTime::RFC1036
DATE_RFC1036
RFC 1036 (example: Mon, 15 Aug 05 15:52:01 +0000)
DateTime::RFC1123
DATE_RFC1123
RFC 1123 (example: Mon, 15 Aug 2005 15:52:01 +0000)
DateTime::RFC2822
DATE_RFC2822
RFC 2822 (Mon, 15 Aug 2005 15:52:01 +0000)
DateTime::RFC3339
DATE_RFC3339
Same as DATE_ATOM (since PHP 5.1.3)
DateTime::RSS
DATE_RSS
RSS (Mon, 15 Aug 2005 15:52:01 +0000)
DateTime::W3C
DATE_W3C
World Wide Web Consortium (example: 2005-08-15T15:52:01+00:00)

DateTime::add

(PHP 5 >= 5.3.0)

DateTime::add Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object

설명

public DateTime DateTime::add ( string $interval )
DateTime date_add ( DateTime $object , DateInterval $interval )

Adds the specified DateInterval object to the specified DateTime object.

인수

object

절차식 전용: date_create()가 반환하는 DateTime 객체.

interval

The amount to be added. For the date use "P3D", "P3M", "P3Y" or a combination of the three e.g. "P2M5D" (Y = Years, M = Months, D = Days.) MUST BE YEAR MONTH DAY FORMAT "P5Y", "P5M2D", "P5Y4D". For the time use "T3H", "T3M", "T3S" or a combination of the three e.g. "T5H20M" (H = Hours, M = Minutes, S = Seconds). For dateTime use "P5Y2M4DT5H20M". The digit before the letter (NOT P or T) can be any amount.

반환값

Returns the modified DateTime.

예제

Example #1 date_add() example

<?php

$date 
= new DateTime("18-July-2008 16:30:30");
echo 
$date->format("d-m-Y H:i:s").'<br />';

date_add($date, new DateInterval("P5D"));
echo 
'<br />'.$date->format("d-m-Y").' : 5 Days';

date_add($date, new DateInterval("P5M"));
echo 
'<br />'.$date->format("d-m-Y").' : 5 Months';

date_add($date, new DateInterval("P5Y"));
echo 
'<br />'.$date->format("d-m-Y").' : 5 Years';

date_add($date, new DateInterval("P5Y5M5D"));
echo 
'<br />'.$date->format("d-m-Y").' : 5 Days, 5 Months, 5 Years';

date_add($date, new DateInterval("P5YT5H"));
echo 
'<br />'.$date->format("d-m-Y H:i:s").' : 5 Years, 5 Hours';

?>

주의

Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

참고

  • DateTime::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
  • DateTime::diff() - Returns the difference between two DateTime objects



DateTime::__construct

(PHP 5 >= 5.2.0)

DateTime::__constructReturns new DateTime object

설명

DateTime::__construct ([ string $time= "now" [, DateTimeZone $timezone= NULL ]] )

Returns new DateTime object.

인수

time

String in a format accepted by strtotime(), defaults to "now".

timezone

Time zone of the time.

오류/예외

Emits Exception in case of an error.

예제

Example #1 DateTime::__construct() example

<?php
date_default_timezone_set
('Europe/London');

$datetime = new DateTime('2008-08-03 14:52:10');
echo 
$datetime->format(DATE_ATOM);
?>



DateTime::createFromFormat

(PHP 5 >= 5.3.0)

DateTime::createFromFormatReturns new DateTime object formatted according to the specified format

설명

public static DateTime DateTime::createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )

Returns new DateTime object formatted according to the specified format.

인수

format

Format accepted by date().

time

String representing the time.

timezone

Time zone.

반환값

Returns new DateTime instance.



DateTime::diff

(PHP 5 >= 5.3.0)

DateTime::diffReturns the difference between two DateTime objects

설명

public DateInterval DateTime::diff ( DateTime $datetime [, bool $absolute ] )

Returns the difference between two DateTime objects.

인수

datetime

The date to compare to.

absolute

Whether to return absolute difference. Defaults to FALSE.

반환값

The difference between two dates.



DateTime::format

(PHP 5 >= 5.2.0)

DateTime::formatReturns date formatted according to given format

설명

public string DateTime::format ( string $format )
string date_format ( DateTime $object , string $format )

인수

object

절차식 전용: date_create()가 반환하는 DateTime 객체.

format

Format accepted by date().

반환값

Returns formatted date on success or FALSE on failure.

예제

Example #1 Displaying the date and time using the procedural form

<?php
date_default_timezone_set
('Europe/London');

$datetime date_create('2008-08-03 14:52:10');
echo 
date_format($datetime'jS, F Y') . "\n";
echo 
date_format($datetimeDATE_ATOM);
?>

Example #2 Displaying the date and time using the object oriented form

<?php
date_default_timezone_set
('Europe/London');

$datetime = new DateTime('2008-08-03 14:52:10');
echo 
$datetime->format('jS, F Y') . "\n";
echo 
$datetime->format(DATE_ATOM);
?>
?>

위 예제의 출력:

3rd, August 2008
2008-08-03T14:52:10+01:00

참고

  • date() - 로컬 날짜/시간을 형식화합니다



DateTime::getLastErrors

(PHP 5 >= 5.3.0)

DateTime::getLastErrorsReturns the warnings and errors

설명

public static array DateTime::getLastErrors ( void )

Returns the warnings and errors found while parsing a date/time string.

인수

이 함수는 인수가 없습니다.

반환값

Returns array containing info about warnings and errors.

예제

Example #1 DateTime::getLastErrors() example

<?php
$date 
date_create('asdfasdf');
print_r(DateTime::getLastErrors());
?>

위 예제의 출력:

Array
(
    [warning_count] => 1
    [warnings] => Array
        (
            [6] => Double timezone specification
        )

    [error_count] => 1
    [errors] => Array
        (
            [0] => The timezone could not be found in the database
        )

)



DateTime::getOffset

(PHP 5 >= 5.2.0)

DateTime::getOffsetReturns the daylight saving time offset

설명

public int DateTime::getOffset ( void )
int date_offset_get ( DateTime $object )

인수

object

절차식 전용: date_create()가 반환하는 DateTime 객체.

반환값

Returns DST offset in seconds on success or FALSE on failure.

예제

Example #1 Comparing offsets between Summer and Winter

<?php
date_default_timezone_set
('Europe/London');

$winter = new DateTime('2008-12-25 14:25:41');
$summer = new DateTime('2008-07-14 14:25:41');

echo 
$winter->getOffset(); // Winter offset: 0
echo $summer->getOffset(); // Summer offset: 3600 = 1 hour
?>



DateTime::getTimestamp

(PHP 5 >= 5.3.0)

DateTime::getTimestampGets the Unix timestamp

설명

public int DateTime::getTimestamp ( void )

Gets the Unix timestamp.

인수

이 함수는 인수가 없습니다.

반환값

Returns Unix timestamp representing the date.

참고



DateTime::getTimezone

(PHP 5 >= 5.2.0)

DateTime::getTimezoneReturn time zone relative to given DateTime

설명

public DateTimeZone DateTime::getTimezone ( void )

인수

object

절차식 전용: date_create()가 반환하는 DateTime 객체.

반환값

Returns DateTimeZone object on success or FALSE on failure.

예제

Example #1 Setting and getting DateTimeZone objects

<?php
date_default_timezone_set
('Europe/London');

$datetime = new DateTime('2008-08-03 12:35:23');
echo 
$datetime->getTimezone()->getName() . "\n";

$datetime = new DateTime('2008-08-03 12:35:23');
$la_time = new DateTimeZone('America/Los_Angeles');
$datetime->setTimezone($la_time);
echo 
$datetime->getTimezone()->getName();
?>

위 예제의 출력:

Europe/London
America/Los_Angeles

참고



DateTime::modify

(PHP 5 >= 5.2.0)

DateTime::modifyAlters the timestamp

설명

public DateTime DateTime::modify ( string $modify )
DateTime date_modify ( DateTime $object , string $modify )

Alter the timestamp of a DateTime object by incrementing or decrementing in a format accepted by strtotime().

인수

object

절차식 전용: date_create()가 반환하는 DateTime 객체.

modify

String in a relative format accepted by strtotime().

반환값

Returns the modified DateTime.

변경점

버전 설명
5.3.0반환값을 NULL에서 DateTime으로 변경.

예제

Example #1 A date_modify() example

<?php
$date 
= new DateTime("2006-12-12");
$date->modify("+1 day");
echo 
$date->format("Y-m-d");
?>

위 예제의 출력:

2006-12-13

참고

  • strtotime() - Parse about any English textual datetime description into a Unix timestamp



DateTime::__set_state

(PHP 5 >= 5.2.0)

DateTime::__set_stateThe __set_state handler

설명

public static DateTime DateTime::__set_state ( array $array )

The __set_state handler.

인수

array

Initialization array.

반환값

Returns a new instance of a DateTime object.



DateTime::setDate

(PHP 5 >= 5.2.0)

DateTime::setDateSets the date

설명

public DateTime DateTime::setDate ( int $year , int $month , int $day )
DateTime date_date_set ( DateTime $object , int $year , int $month , int $day )

Resets the current date of the DateTime object to a different date.

인수

object

절차식 전용: date_create()가 반환하는 DateTime 객체.

year

Year of the date.

month

Month of the date.

day

Day of the date.

반환값

Returns the modified DateTime.

변경점

버전 설명
5.3.0반환값을 NULL에서 DateTime으로 변경.

예제

Example #1 Object oriented example usage

<?php
date_default_timezone_set
('Europe/London');

$datetime = new DateTime('2008-08-03 14:52:10');
$datetime->setDate(20081012);

echo 
$datetime->format(DATE_RFC2822);
?>

Example #2 Procedural example usage

<?php
date_default_timezone_set
('Europe/London');

$datetime date_create('2008-08-03 14:52:10');
date_date_set($datetime20081012);

echo 
date_format($datetimeDATE_RFC2822);
?>

위 예제의 출력:

Sun, 12 Oct 2008 14:52:10 +0100

참고



DateTime::setISODate

(PHP 5 >= 5.2.0)

DateTime::setISODateSets the ISO date

설명

public DateTime DateTime::setISODate ( int $year , int $week [, int $day ] )
DateTime date_isodate_set ( DateTime $object , int $year , int $week [, int $day ] )

Set a date according to the ISO 8601 standard - using weeks and day offsets rather than specific dates.

인수

object

절차식 전용: date_create()가 반환하는 DateTime 객체.

year

Year of the date.

week

Week of the date.

day

Offset from the first day of the week.

반환값

Returns the modified DateTime.

변경점

버전 설명
5.3.0반환값을 NULL에서 DateTime으로 변경.

예제

Example #1 Finding the date from a week number and day offset

<?php
date_default_timezone_set
('Europe/London');

$datetime = new DateTime();

// Offset from start of week 2 (7) = 5
$datetime->setISODate(200825); // Day 5 of week 2 of 2008 is the 11th of January. 

// Offset from start of week 2 (7) = 10
$datetime->setISODate(2008210); // Day 10 of week 2 of 2008 is the 16th of January.
?>

Example #2 Finding the month a week is in

<?php
date_default_timezone_set
('Europe/London');

$datetime date_create();
date_isodate_set($datetime20086); // Week 6 of 2008 is in February.
?>

참고



DateTime::setTime

(PHP 5 >= 5.2.0)

DateTime::setTimeSets the time

설명

public DateTime DateTime::setTime ( int $hour , int $minute [, int $second ] )
DateTime date_time_set ( DateTime $object , int $hour , int $minute [, int $second ] )

Resets the current time of the DateTime object to a different time.

인수

object

절차식 전용: date_create()가 반환하는 DateTime 객체.

hour

Hour of the time.

minute

Minute of the time.

second

Second of the time.

반환값

Returns the modified DateTime.

변경점

버전 설명
5.3.0반환값을 NULL에서 DateTime으로 변경.

예제

Example #1 Changing the time of a DateTime object

<?php
date_default_timezone_set
('Europe/London');

$datetime = new DateTime('2008-08-03 12:35:23');
echo 
$datetime->format('Y-m-d H:i:s') . "\n";

$datetime->setTime(145524);
echo 
$datetime->format('Y-m-d H:i:s') . "\n";

// Warning: Does not increment the hour!
// This is because the hour has been set (14) - see date_modify()
$datetime->setTime($datetime->format('H'), $datetime->format('n') + 6);
echo 
$datetime->format('Y-m-d H:i:s') . "\n";

// *Does* increment the day, because the day has not been set
$datetime->setTime($datetime->format('H') + 12$datetime->format('n'));
echo 
$datetime->format('Y-m-d H:i:s') . "\n";
?>

위 예제의 출력:

2008-08-03 12:35:23
2008-08-03 14:55:24
2008-08-03 14:14:00
2008-08-04 02:08:00

참고



DateTime::setTimestamp

(PHP 5 >= 5.3.0)

DateTime::setTimestampSets the date and time based on an Unix timestamp

설명

public DateTime DateTime::setTimestamp ( int $unixtimestamp )

Sets the date and time based on an Unix timestamp.

인수

unixtimestamp

Unix timestamp representing the date.

반환값

Returns the modified DateTime.

참고



DateTime::setTimezone

(PHP 5 >= 5.2.0)

DateTime::setTimezoneSets the time zone for the DateTime object

설명

public DateTime DateTime::setTimezone ( DateTimeZone $timezone )

인수

object

절차식 전용: date_create()가 반환하는 DateTime 객체.

timezone

Desired time zone.

반환값

Returns the modified DateTime.

변경점

버전 설명
5.3.0 Changed the return value from NULL to DateTime.

예제

Example #1 Setting and getting DateTimeZone objects

<?php
date_default_timezone_set
('Europe/London');

$datetime = new DateTime('2008-08-03 12:35:23');
echo 
$datetime->getTimezone()->getName() . "\n";

$datetime = new DateTime('2008-08-03 12:35:23');
$la_time = new DateTimeZone('America/Los_Angeles');
$datetime->setTimezone($la_time);
echo 
$datetime->getTimezone()->getName();
?>

위 예제의 출력:

Europe/London
America/Los_Angeles

참고



DateTime::sub

(PHP 5 >= 5.3.0)

DateTime::sub Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

설명

public DateTime DateTime::sub ( DateInterval $interval )
DateTime date_sub ( DateTime $object , DateInterval $interval )

Subtracts the specified DateInterval object from the specified DateTime object.

인수

object

절차식 전용: date_create()가 반환하는 DateTime 객체.

interval

The amount to be subtracted. For the date use "P3D", "P3M", "P3Y" or a combination of the three e.g. "P2M5D" (Y = Years, M = Months, D = Days.) MUST BE YEAR MONTH DAY FORMAT "P5Y", "P5M2D", "P5Y4D". For the time use "T3H", "T3M", "T3S" or a combination of the three e.g. "T5H20M" (H = Hours, M = Minutes, S = Seconds). For dateTime use "P5Y2M4DT5H20M". The digit before the letter (NOT P or T) can be any amount.

반환값

Returns the modified DateTime.

예제

Example #1 date_sub() example

<?php

$date 
= new DateTime("18-July-2008 16:30:30");
echo 
$date->format("d-m-Y H:i:s").'<br />';

date_sub($date, new DateInterval("P5D"));
echo 
'<br />'.$date->format("d-m-Y").' : 5 Days';

date_sub($date, new DateInterval("P5M"));
echo 
'<br />'.$date->format("d-m-Y").' : 5 Months';

date_sub($date, new DateInterval("P5Y"));
echo 
'<br />'.$date->format("d-m-Y").' : 5 Years';

date_sub($date, new DateInterval("P5Y5M5D"));
echo 
'<br />'.$date->format("d-m-Y").' : 5 Days, 5 Months, 5 Years';

date_sub($date, new DateInterval("P5YT5H"));
echo 
'<br />'.$date->format("d-m-Y H:i:s").' : 5 Years, 5 Hours';

?>

주의

Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

참고

  • DateTime::add() - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
  • DateTime::diff() - Returns the difference between two DateTime objects



DateTime::__wakeup

(PHP 5 >= 5.2.0)

DateTime::__wakeupThe __wakeup handler

설명

public DateTime DateTime::__wakeup ( void )

The __wakeup handler.

인수

이 함수는 인수가 없습니다.

반환값

Initializes a DateTime object.


Table of Contents



The DateTimeZone class

소개

Representation of time zone.

클래스 개요

DateTimeZone
DateTimeZone {
/* Constants */
const integer DateTimeZone::AFRICA = 1 ;
const integer DateTimeZone::AMERICA = 2 ;
const integer DateTimeZone::ANTARCTICA = 4 ;
const integer DateTimeZone::ARCTIC = 8 ;
const integer DateTimeZone::ASIA = 16 ;
const integer DateTimeZone::ATLANTIC = 32 ;
const integer DateTimeZone::AUSTRALIA = 64 ;
const integer DateTimeZone::EUROPE = 128 ;
const integer DateTimeZone::INDIAN = 256 ;
const integer DateTimeZone::PACIFIC = 512 ;
const integer DateTimeZone::UTC = 1024 ;
const integer DateTimeZone::ALL = 2047 ;
const integer DateTimeZone::ALL_WITH_BC = 4095 ;
const integer DateTimeZone::PER_COUNTRY = 4096 ;
/* Methods */
__construct ( string $timezone )
public array getLocation ( void )
public string getName ( void )
int getOffset ( DateTime $datetime )
array getTransitions ([ int $timestamp_begin [, int $timestamp_end ]] )
staticarray listAbbreviations ( void )
staticarray listIdentifiers ([ int $what= DateTime::ALL [, string $country= NULL ]] )
}

예약 상수

DateTimeZone Node Types

DateTimeZone::AFRICA

Africa time zones.

DateTimeZone::AMERICA

America time zones.

DateTimeZone::ANTARCTICA

Antarctica time zones.

DateTimeZone::ARCTIC

Artic time zones.

DateTimeZone::ASIA

Asia time zones.

DateTimeZone::ATLANTIC

Atlantic time zones.

DateTimeZone::AUSTRALIA

Australia time zones.

DateTimeZone::EUROPE

Europe time zones.

DateTimeZone::INDIAN

Indian time zones.

DateTimeZone::PACIFIC

Pacific time zones.

DateTimeZone::UTC

UTC time zones.

DateTimeZone::ALL

All time zones.

DateTimeZone::ALL_WITH_BC

All time zones including backwards compatible.

DateTimeZone::PER_COUNTRY

Time zones per country.


DateTimeZone::__construct

(PHP 5 >= 5.2.0)

DateTimeZone::__constructCreates new DateTimeZone object

설명

DateTimeZone::__construct ( string $timezone )

Creates new DateTimeZone object.

인수

timezone

One of timezones.

반환값

Returns DateTimeZone on success.

오류/예외

This method throws Exception if the timezone supplied is not recognised as a valid timezone.

예제

Example #1 Catching errors when instantiating DateTimeZone

<?php
// Error handling by catching exceptions
$timezones = array('Europe/London''Mars/Phobos''Jupiter/Europa');

foreach (
$timezones as $tz) {
    try {
        
$mars = new DateTimeZone($tz);
    } catch(
Exception $e) {
        echo 
$e->getMessage() . '<br />';
    }
}
?>

위 예제의 출력:

DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Mars/Phobos)
DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Jupiter/Europa)



DateTimeZone::getLocation

(PHP 5 >= 5.3.0)

DateTimeZone::getLocationReturns location information for a timezone

설명

public array DateTimeZone::getLocation ( void )

Returns location information for a timezone, including country code, latitude/longitude and comments.

인수

이 함수는 인수가 없습니다.

반환값

Array containing location information about timezone.

예제

Example #1 DateTimeZone::getLocation() example

<?php
$tz 
= new DateTimeZone("Europe/Prague");
print_r($tz->getLocation());
?>

위 예제의 출력:

Array
(
    [country_code] => CZ
    [latitude] => 50.08333
    [longitude] => 14.43333
    [comments] => 
)



DateTimeZone::getName

(PHP 5 >= 5.2.0)

DateTimeZone::getNameReturns the name of the timezone

설명

public string DateTimeZone::getName ( void )

Returns the name of the timezone.

인수

이 함수는 인수가 없습니다.

반환값

One of timezones.



DateTimeZone::getOffset

(PHP 5 >= 5.2.0)

DateTimeZone::getOffsetReturns the timezone offset from GMT

설명

int DateTimeZone::getOffset ( DateTime $datetime )
int timezone_offset_get ( DateTimeZone $object , DateTime $datetime )

This function returns the offset to GMT for the date/time specified in the datetime parameter. The GMT offset is calculated with the timezone information contained in the DateTimeZone object being used.

인수

obejct

절차식 전용: timezone_open()이 반환하는 DateTimeZone 객체.

datetime

DateTime that contains the date/time to compute the offset from.

반환값

Returns time zone offset in seconds on success or FALSE on failure.

예제

Example #1 DateTimeZone::getOffset() examples

<?php
// Create two timezone objects, one for Taipei (Taiwan) and one for
// Tokyo (Japan)
$dateTimeZoneTaipei = new DateTimeZone("Asia/Taipei");
$dateTimeZoneJapan = new DateTimeZone("Asia/Tokyo");

// Create two DateTime objects that will contain the same Unix timestamp, but
// have different timezones attached to them.
$dateTimeTaipei = new DateTime("now"$dateTimeZoneTaipei);
$dateTimeJapan = new DateTime("now"$dateTimeZoneJapan);

// Calculate the GMT offset for the date/time contained in the $dateTimeTaipei
// object, but using the timezone rules as defined for Tokyo
// ($dateTimeZoneJapan).
$timeOffset $dateTimeZoneJapan->getOffset($dateTimeTaipei);

// Should show int(32400) (for dates after Sat Sep 8 01:00:00 1951 JST).
var_dump($timeOffset);
?>



DateTimeZone::getTransitions

(PHP 5 >= 5.2.0)

DateTimeZone::getTransitionsReturns all transitions for the timezone

설명

array DateTimeZone::getTransitions ([ int $timestamp_begin [, int $timestamp_end ]] )
array timezone_transitions_get ( DateTimeZone $object [, int $timestamp_begin [, int $timestamp_end ]] )

인수

obejct

절차식 전용: timezone_open()이 반환하는 DateTimeZone 객체.

timestamp_begin

Begin timestamp.

timestamp_end

End timestamp.

반환값

Returns numerically indexed array containing associative array with all transitions on success or FALSE on failure.

변경점

버전 설명
5.3.0 The optional timestamp_begin and timestamp_end were added.

예제

Example #1 A timezone_transitions_get() example

<?php
$timezone 
= new DateTimeZone("CET");
print_r(reset($timezone->getTransitions()));
?>

위 예제의 출력 예시:

Array
(
    [ts] => -1693706400
    [time] => 1916-04-30T22:00:00+0000
    [offset] => 7200
    [isdst] => 1
    [abbr] => CEST
)



DateTimeZone::listAbbreviations

(PHP 5 >= 5.2.0)

DateTimeZone::listAbbreviationsReturns associative array containing dst, offset and the timezone name

설명

staticarray DateTimeZone::listAbbreviations ( void )

반환값

Returns array on success or FALSE on failure.

예제

Example #1 A timezone_abbreviations_list() example

<?php
$timezone_abbreviations 
DateTimeZone::listAbbreviations();
print_r($timezone_abbreviations["acst"]);
?>

위 예제의 출력 예시:

Array
(
    [0] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => America/Porto_Acre
        )

    [1] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => America/Eirunepe
        )

    [2] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => America/Rio_Branco
        )

    [3] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => Brazil/Acre
        )

)

참고



DateTimeZone::listIdentifiers

(PHP 5 >= 5.2.0)

DateTimeZone::listIdentifiersReturns numerically index array with all timezone identifiers

설명

staticarray DateTimeZone::listIdentifiers ([ int $what= DateTime::ALL [, string $country= NULL ]] )
array timezone_identifiers_list ([ int $what= DateTime::ALL [, string $country= NULL ]] )

인수

object

절차식 전용: date_create()가 반환하는 DateTime 객체.

what

One of DateTimeZone class constants, defaults to DateTimeZone::ALL.

country

A two-letter ISO 3166-1 compatible country code.

Note: This option is only used when what is set to DateTimeZone::PER_COUNTRY.

반환값

Returns array on success or FALSE on failure.

변경점

버전 설명
5.3.0 Added the optional what and country parameters.

예제

Example #1 A timezone_identifiers_list() example

<?php
$timezone_identifiers 
DateTimeZone::listIdentifiers();
for (
$i=0$i 5$i++) {
    echo 
"$timezone_identifiers[$i]\n";
}
?>

위 예제의 출력 예시:

Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmera

참고


Table of Contents



The DateInterval class

소개

Representation of date interval.

클래스 개요

DateInterval
DateInterval {
/* Methods */
__construct ( string $interval_spec )
public static DateInterval createFromDateString ( string $time )
public string format ( string $format )
}

DateInterval::__construct

(PHP 5 >= 5.3.0)

DateInterval::__constructCreates new DateInterval object

설명

DateInterval::__construct ( string $interval_spec )

Creates new DateInterval object.

인수

interval_spec

Interval specification.



DateInterval::createFromDateString

(PHP 5 >= 5.3.0)

DateInterval::createFromDateStringSets up a DateInterval from the relative parts of the string

설명

public static DateInterval DateInterval::createFromDateString ( string $time )

Uses the normal date parsers and sets up a DateInterval from the relative parts of the parsed string.

인수

time

Date with relative parts.

반환값

Returns new DateInterval instance if success.



DateInterval::format

(PHP 5 >= 5.3.0)

DateInterval::formatFormats the interval

설명

public string DateInterval::format ( string $format )

Formats the interval.

인수

format

The following characters are recognized in the format parameter string.
format character Description Example values
Y Years, numeric, at least 2 digits with leading 0 01, 03
y Years, numeric 1, 3
M Months, numeric, at least 2 digits with leading 0 01, 03, 12
m Months, numeric 01, 03, 12
D Days, numeric, at least 2 digits with leading 0 01, 03, 31
d Days, numeric 1, 3, 31
a Total amount of days 4, 18, 8123
H Hours, numeric, at least 2 digits with leading 0 01, 03, 23
h Hours, numeric 1, 3, 23
I Minutes, numeric, at least 2 digits with leading 0 01, 03, 59
i Minutes, numeric 1, 3, 59
S Seconds, numeric, at least 2 digits with leading 0 01, 03, 57
s Seconds, numeric 1, 3, 57
R Sign "-" when negative, "+" when positive -, +
r Sign "-" when negative, empty when positive -,
% Literal % %

Note: The prefix % is required in order for the format specifiers to work correctly.

반환값

Returns the formatted interval.


Table of Contents



The DatePeriod class

소개

Representation of date period.

클래스 개요

DatePeriod
DatePeriod implements Traversable {
/* Constants */
const integer DatePeriod::EXCLUDE_START_DATE = 1 ;
/* Methods */
__construct ( DateTime $start , DateInterval $interval , int $recurrences [, int $options ] )
}

예약 상수

DatePeriod Node Types

DatePeriod::EXCLUDE_START_DATE

Exclude start date, used in DatePeriod::__construct().


DatePeriod::__construct

(PHP 5 >= 5.3.0)

DatePeriod::__constructCreates new DatePeriod object

설명

DatePeriod::__construct ( DateTime $start , DateInterval $interval , int $recurrences [, int $options ] )
DatePeriod::__construct ( DateTime $start , DateInterval $interval , DateTime $end [, int $options ] )
DatePeriod::__construct ( string $isostr [, int $options ] )

Creates new DatePeriod object.

인수

start

Start date.

interval

Interval.

recurrences

Number of recurrences.

end

End date.

isostr

String containing the ISO interval.

options

Can be set to DateTime::EXCLUDE_START_DATE.


Table of Contents



Date/Time 함수 목록


checkdate

(PHP 4, PHP 5)

checkdate그레고리력 날짜를 확인합니다

설명

bool checkdate ( int $month , int $day , int $year )

인수로 구성되는 날짜의 유효성을 확인합니다. 날짜는 각 인수가 적합하게 정의되어 있으면 유효한 것으로 간주됩니다.

인수

month

1에서 12까지 월.

day

주어진 month 에서 허용된 일 수. 윤년도 고려됩니다.

year

1에서 32767까지 년도.

반환값

주어진 날짜가 유효하면 TRUE를, 유효하지 않으면 FALSE를 반환합니다.

예제

Example #1 checkdate() 예제

<?php
var_dump
(checkdate(12312000));
var_dump(checkdate(2292001));
?>

위 예제의 출력:

bool(true);
bool(false);

참고

  • mktime() - Get Unix timestamp for a date
  • strtotime() - Parse about any English textual datetime description into a Unix timestamp



date_add

(PHP 5 >= 5.3.0)

date_add별칭: DateTime::add

설명

이 함수는 다음 함수의 별칭입니다: DateTime::add



date_create_from_format

(PHP 5 >= 5.3.0)

date_create_from_format별칭: DateTime::createFromFormat

설명

이 함수는 다음 함수의 별칭입니다: DateTime::createFromFormat



date_create

(PHP 5 >= 5.2.0)

date_createReturns new DateTime object

설명

DateTime date_create ([ string $time= "now" [, DateTimeZone $timezone= NULL ]] )

인수

time

String in a format accepted by strtotime(), defaults to "now".

timezone

Time zone of the time.

반환값

Returns DateTime object on success or FALSE on failure.

예제

Example #1 date_create() example

<?php
date_default_timezone_set
('Europe/London');

$datetime date_create('2008-08-03 14:52:10');
echo 
date_format($datetimeDATE_ATOM);
?>

위 예제의 출력:

2008-08-03T14:52:10+01:00



date_date_set

(PHP 5 >= 5.2.0)

date_date_set별칭: DateTime::setDate

설명

이 함수는 다음 함수의 별칭입니다: DateTime::setDate



date_default_timezone_get

(PHP 5 >= 5.1.0)

date_default_timezone_get Gets the default timezone used by all date/time functions in a script

설명

string date_default_timezone_get ( void )

In order of preference, this function returns the default timezone by:

  • Reading the timezone set using the date_default_timezone_set() function (if any)

  • Reading the TZ environment variable (if non empty)

  • Reading the value of the date.timezone ini option (if set)

  • Querying the host operating system (if supported and allowed by the OS)

If none of the above succeed, date_default_timezone_get will return a default timezone of UTC.

반환값

Returns a string.

예제

Example #1 Getting the default timezone

<?php
date_default_timezone_set
('Europe/London');

if (
date_default_timezone_get()) {
    echo 
'date_default_timezone_set: ' date_default_timezone_get() . '<br />';
}

if (
ini_get('date.timezone')) {
    echo 
'date.timezone: ' ini_get('date.timezone');
}

?>

위 예제의 출력 예시:

date_default_timezone_set: Europe/London
date.timezone: Europe/London

Example #2 Getting the abbreviation of a timezone

<?php
date_default_timezone_set
('America/Los_Angeles');
echo 
date_default_timezone_get() . ' => ' date('e') . ' => ' date('T');
?>

위 예제의 출력:

America/Los_Angeles => America/Los_Angeles => PST

참고



date_default_timezone_set

(PHP 5 >= 5.1.0)

date_default_timezone_set Sets the default timezone used by all date/time functions in a script

설명

bool date_default_timezone_set ( string $timezone_identifier )

date_default_timezone_set() sets the default timezone used by all date/time functions.

Note: Since PHP 5.1.0 (when the date/time functions were rewritten), every call to a date/time function will generate a E_NOTICE if the timezone isn't valid, and/or a E_WARNING message if using the system settings or the TZ environment variable.

Instead of using this function to set the default timezone in your script, you can also use the INI setting date.timezone to set the default timezone.

인수

timezone_identifier

The timezone identifier, like UTC or Europe/Lisbon. The list of valid identifiers is available in the 지원하는 시간대 목록.

반환값

This function returns FALSE if the timezone_identifier isn't valid, or TRUE otherwise.

예제

Example #1 Getting the default timezone

<?php
date_default_timezone_set
('America/Los_Angeles');

$script_tz date_default_timezone_get();

if (
strcmp($script_tzini_get('date.timezone'))){
    echo 
'Script timezone differs from ini-set timezone.';
} else {
    echo 
'Script timezone and ini-set timezone match.';
}
?>

변경점

버전 설명
5.3.0 Now throws E_WARNING rather then E_STRICT.
5.1.2 The function started to validate the timezone_identifier parameter.

참고



date_diff

(PHP 5 >= 5.3.0)

date_diff별칭: DateTime::diff

설명

이 함수는 다음 함수의 별칭입니다: DateTime::diff



date_format

(PHP 5 >= 5.2.0)

date_format별칭: DateTime::format

설명

이 함수는 다음 함수의 별칭입니다: DateTime::format



date_get_last_errors

(PHP 5 >= 5.3.0)

date_get_last_errors별칭: DateTime::getLastErrors

설명

이 함수는 다음 함수의 별칭입니다: DateTime::getLastErrors



date_interval_create_from_date_string

(PHP 5 >= 5.3.0)

date_interval_create_from_date_string별칭: DateInterval::createFromDateString

설명

이 함수는 다음 함수의 별칭입니다: DateInterval::createFromDateString



date_interval_format

(PHP 5 >= 5.3.0)

date_interval_format별칭: DateInterval::format

설명

이 함수는 다음 함수의 별칭입니다: DateInterval::format



date_isodate_set

(PHP 5 >= 5.2.0)

date_isodate_set별칭: DateTime::setISODate

설명

이 함수는 다음 함수의 별칭입니다: DateTime::setISODate



date_modify

(PHP 5 >= 5.2.0)

date_modify별칭: DateTime::modify

설명

이 함수는 다음 함수의 별칭입니다: DateTime::modify



date_offset_get

(PHP 5 >= 5.2.0)

date_offset_get별칭: DateTime::getOffset

설명

이 함수는 다음 함수의 별칭입니다: DateTime::getOffset



date_parse_from_format

(PHP 5 >= 5.3.0)

date_parse_from_formatGet info about given date

설명

array date_parse_from_format ( string $format , string $date )

Returns associative array with detailed info about given date.

인수

format

Format accepted by date() with some extras.

date

String representing the date.

반환값

Returns associative array with detailed info about given date.

예제

Example #1 date_parse_from_format() example

<?php
$date 
"6.1.2009 13:00+01:00";
print_r(date_parse_from_format("j.n.Y H:iP"$date));
?>

위 예제의 출력:

Array
(
    [year] => 2009
    [month] => 1
    [day] => 6
    [hour] => 13
    [minute] => 0
    [second] => 0
    [fraction] => 
    [warning_count] => 0
    [warnings] => Array
        (
        )

    [error_count] => 0
    [errors] => Array
        (
        )

    [is_localtime] => 1
    [zone_type] => 1
    [zone] => -60
    [is_dst] => 
)



date_parse

(PHP 5 >= 5.2.0)

date_parseReturns associative array with detailed info about given date

설명

array date_parse ( string $date )

인수

date

Date in format accepted by strtotime().

반환값

Returns array with information about the parsed date on success, or FALSE on failure.

오류/예외

In case the date format has an error, the element 'errors' will contains the error messages.

예제

Example #1 A date_parse() example

<?php
print_r
(date_parse("2006-12-12 10:00:00.5"));
?>

위 예제의 출력:

Array
(
    [year] => 2006
    [month] => 12
    [day] => 12
    [hour] => 10
    [minute] => 0
    [second] => 0
    [fraction] => 0.5
    [warning_count] => 0
    [warnings] => Array()
    [error_count] => 0
    [errors] => Array()
    [is_localtime] => 
)

참고

  • getdate() - 날짜/시간 정보를 가져온다



date_sub

(PHP 5 >= 5.3.0)

date_sub별칭: DateTime::sub

설명

이 함수는 다음 함수의 별칭입니다: DateTime::sub



date_sun_info

(PHP 5 >= 5.1.2)

date_sun_infoReturns an array with information about sunset/sunrise and twilight begin/end

설명

array date_sun_info ( int $time , float $latitude , float $longitude )

인수

time

Timestamp.

latitude

Latitude in degrees.

longitude

Longitude in degrees.

반환값

Returns array on success or FALSE on failure.

예제

Example #1 A date_sun_info() example

<?php
$sun_info 
date_sun_info(strtotime("2006-12-12"), 31.766735.2333);
foreach (
$sun_info as $key => $val) {
    echo 
"$key: " date("H:i:s"$val) . "\n";
}
?>

위 예제의 출력:

sunrise: 05:52:11
sunset: 15:41:21
transit: 10:46:46
civil_twilight_begin: 05:24:08
civil_twilight_end: 16:09:24
nautical_twilight_begin: 04:52:25
nautical_twilight_end: 16:41:06
astronomical_twilight_begin: 04:21:32
astronomical_twilight_end: 17:12:00

참고

  • date_sunrise() - Returns time of sunrise for a given day and location
  • date_sunset() - Returns time of sunset for a given day and location



date_sunrise

(PHP 5)

date_sunriseReturns time of sunrise for a given day and location

설명

mixed date_sunrise ( int $timestamp [, int $format= SUNFUNCS_RET_STRING [, float $latitude= ini_get("date.default_latitude") [, float $longitude= ini_get("date.default_longitude") [, float $zenith= ini_get("date.sunrise_zenith") [, float $gmt_offset= 0 ]]]]] )

date_sunrise() returns the sunrise time for a given day (specified as a timestamp ) and location.

인수

timestamp

The timestamp of the day from which the sunrise time is taken.

format

format constants
constant description example
SUNFUNCS_RET_STRING returns the result as string 16:46
SUNFUNCS_RET_DOUBLE returns the result as float 16.78243132
SUNFUNCS_RET_TIMESTAMP returns the result as integer (timestamp) 1095034606

latitude

Defaults to North, pass in a negative value for South. See also: date.default_latitude

longitude

Defaults to East, pass in a negative value for West. See also: date.default_longitude

zenith

Default: date.sunrise_zenith

gmtoffset

Specified in hours.

반환값

Returns the sunrise time in a specified format on success, or FALSE on failure.

오류/예외

모든 날짜/시간 함수 호출은 시간대가 유효하지 않을 때 E_NOTICE를, 시스템 설정이나 TZ 환경 변수를 사용할 때 E_STRICT를 생성합니다. date_default_timezone_set()을 참고하십시오.

변경점

버전 설명
5.1.0

시간대 오류시 E_STRICTE_NOTICE가 발생합니다.

예제

Example #1 date_sunrise() example

<?php

/* calculate the sunrise time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/

echo date("D M d Y"). ', sunrise time : ' .date_sunrise(time(), SUNFUNCS_RET_STRING38.4, -9901);

?>

위 예제의 출력 예시:

Mon Dec 20 2004, sunrise time : 08:54

참고

  • date_sunset() - Returns time of sunset for a given day and location



date_sunset

(PHP 5)

date_sunset Returns time of sunset for a given day and location

설명

mixed date_sunset ( int $timestamp [, int $format= SUNFUNCS_RET_STRING [, float $latitude= ini_get("date.default_latitude") [, float $longitude= ini_get("date.default_longitude") [, float $zenith= ini_get("date.sunset_zenith") [, float $gmt_offset= 0 ]]]]] )

date_sunset() returns the sunset time for a given day (specified as a timestamp ) and location.

인수

timestamp

The timestamp of the day from which the sunset time is taken.

format

format constants
constant description example
SUNFUNCS_RET_STRING returns the result as string 16:46
SUNFUNCS_RET_DOUBLE returns the result as float 16.78243132
SUNFUNCS_RET_TIMESTAMP returns the result as integer (timestamp) 1095034606

latitude

Defaults to North, pass in a negative value for South. See also: date.default_latitude

longitude

Defaults to East, pass in a negative value for West. See also: date.default_longitude

zenith

Default: date.sunset_zenith

gmtoffset

Specified in hours.

오류/예외

모든 날짜/시간 함수 호출은 시간대가 유효하지 않을 때 E_NOTICE를, 시스템 설정이나 TZ 환경 변수를 사용할 때 E_STRICT를 생성합니다. date_default_timezone_set()을 참고하십시오.

변경점

버전 설명
5.1.0

시간대 오류시 E_STRICTE_NOTICE가 발생합니다.

반환값

Returns the sunset time in a specified format on success, or FALSE on failure.

예제

Example #1 date_sunset() example

<?php

/* calculate the sunset time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/

echo date("D M d Y"). ', sunset time : ' .date_sunset(time(), SUNFUNCS_RET_STRING38.4, -9901);

?>

위 예제의 출력 예시:

Mon Dec 20 2004, sunset time : 18:13

참고

  • date_sunrise() - Returns time of sunrise for a given day and location



date_time_set

(PHP 5 >= 5.2.0)

date_time_set별칭: DateTime::setTime

설명

이 함수는 다음 함수의 별칭입니다: DateTime::setTime



date_timestamp_get

(PHP 5 >= 5.3.0)

date_timestamp_get별칭: DateTime::getTimestamp

설명

이 함수는 다음 함수의 별칭입니다: DateTime::getTimestamp



date_timestamp_set

(PHP 5 >= 5.3.0)

date_timestamp_set별칭: DateTime::setTimestamp

설명

이 함수는 다음 함수의 별칭입니다: DateTime::setTimestamp



date_timezone_get

(PHP 5 >= 5.2.0)

date_timezone_get별칭: DateTime::getTimezone

설명

이 함수는 다음 함수의 별칭입니다: DateTime::getTimezone



date_timezone_set

(PHP 5 >= 5.2.0)

date_timezone_set별칭: DateTime::setTimezone

설명

이 함수는 다음 함수의 별칭입니다: DateTime::setTimezone



date

(PHP 4, PHP 5)

date로컬 날짜/시간을 형식화합니다

설명

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

정수형으로 주어지는 timestamp 나, timestamp가 주어지지 않았을 경우에는 현재 로컬 시간을 사용하여, 주어진 포맷 문자열에 따라 형식화한 문자열을 반환합니다. 즉 timestamp 는 선택적이고, 기본값은 time()의 값입니다.

인수

formant

출력하는 날짜 string의 형식. 아래 형식화 옵션을 참고하십시오.

다음 문자들을 format 인수 문자열로 인식합니다.
format 문자 설명 반환값 예시
--- ---
d 일, 앞에 0이 붙는 2 숫자 01에서 31
D 요일 글자 표현, 3 문자 Mon에서 Sun
j 앞에 0이 붙지 않는 일 1에서 31
l (소문자 'L') 요일의 완전한 글자 표현 Sunday에서 Saturday
N 요일의 ISO-8601 숫자 표현 (PHP 5.1.0에서 추가) 1(월요일)에서 7(일요일)
S 일 영어 접미사, 2 문자 st, nd, rd, th. j와 잘 맞습니다.
w 요일 숫자 표현 0(일요일)에서 6(토요일)
z 해당 연도 일차 (0에서 시작) 0에서 365
--- ---
W ISO-8601 주차, 주는 월요일에 시작 (PHP 4.1.0에서 추가) 예시: 42 (그 해의 42번째 주)
--- ---
F January나 March 같은 월의 완전한 글자 표현 January에서 December
m 0이 붙는 월 숫자 표현 01에서 12
M 월의 축약 글자 표현, 3 문자 Jan에서 Dec
n 0이 붙지 않는 월 숫자 표현 1에서 12
t 주어진 월의 일 수 28에서 31
--- ---
L 윤년 여부 윤년엔 1, 그 외엔 0
o ISO-8601 연도. Y와 같지만, ISO 주차(W)가 전해나 다음해에 해당하면, 그 연도를 사용합니다. (PHP 5.1.0에서 추가) 예시: 19992003
Y 연도의 완전한 숫자 표현, 4 숫자 예시: 19992003
y 연도의 두 숫자 표현 예시: 9903
시간 --- ---
a 오전과 오후의 소문자 am 또는 pm
A 오전과 오후의 대문자 AM 또는 PM
B 스와치 인터넷 시간 000에서 999
g 0이 붙지 않는 12시간 형식 시 1에서 12
G 0이 붙지 않는 24시간 형식 시 0에서 23
h 0이 붙는 12시간 형식 시 01에서 12
H 0이 붙는 24시간 형식 시 00에서 23
i 0이 붙는 분 00에서 59
s 초, 0이 붙음 00에서 59
u 마이크로초 (PHP 5.2.2에서 추가) 예시: 54321
시간대 --- ---
e 시간대 식별자 (PHP 5.1.0에서 추가) 예시: UTC, GMT, Atlantic/Azores
I (대문자 i) 일광 절약 시간 여부 일광 절약 시간이면 1, 아니면 0
O 그리니치 시간(GMT)과 시차 예시: +0200
P 시와 분 사이에 콜론이 들어가는 그리니치 시간(GMT)과 차이 예시: +02:00
T 시간대 축약어 예시: EST, MDT ...
Z 시간대 오프셋 초. UTC 서쪽은 항상 음수, UTC 동쪽은 항상 양수 -43200에서 50400
날짜/시간 표현 --- ---
c ISO 8601 날짜 (PHP 5에서 추가) 2004-02-12T15:19:21+00:00
r » RFC 2822 형식 날짜 예시: Thu, 21 Dec 2000 16:01:07 +0200
U 유닉스 에포치(January 1 1970 00:00:00 GMT)부터 초수 time() 참조

format 문자열로 인식되지 않는 문자는 그대로 출력합니다. Z 형식은 gmdate()를 이용할 때는 항상 0을 반환합니다.

Note: 이 함수는 integer 타임스탬프만 받아들이므로, u 형식 문자는 date_create()로 만들어진 사용자 기반 타임스탬프를 date_format() 함수에 이용할 때만 유용합니다.

timestamp

선택적인 timestamp 인수는 timestamp 가 주어지지 않았을 경우, 현재 로컬 시간을 기본값으로 가지는 integer 유닉스 타임스탬프입니다. 즉, 기본값은 time() 값입니다.

반환값

형식화된 날짜 문자열을 반환합니다. timestamp 에 숫자가 아닌 값을 사용하면, FALSE를 반환하고 E_WARNING 등급 오류가 발생합니다.

오류/예외

모든 날짜/시간 함수 호출은 시간대가 유효하지 않을 때 E_NOTICE를, 시스템 설정이나 TZ 환경 변수를 사용할 때 E_STRICT를 생성합니다. date_default_timezone_set()을 참고하십시오.

변경점

버전 설명
5.1.0 유효한 타임스탬프 범위는 보통 Fri, 13 Dec 1901 20:45:54 GMT 에서 Tue, 19 Jan 2038 03:14:07 GMT 입니다. (이 날짜들은 32비트 부호 있는 정수의 최소값과 최대값에 해당합니다) 그러나, PHP 5.1.0 이전에는 몇몇 시스템에서 이 범위가 01-01-1970에서 19-01-2038로 제한되었습니다. (윈도우 등)
5.1.0

시간대 오류시 E_STRICTE_NOTICE가 발생합니다.

5.1.1 format 인수 지정에 사용할 수 있는 유용한 표준 날짜/시간 상수가 있습니다.

예제

Example #1 date() 예제코드

<?php
// 기본 시간대를 설정. PHP 5.1 부터 가능.
date_default_timezone_set('UTC');


// 출력 예시: Monday
echo date("l");

// 출력 예시: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');

// 출력: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " date("l"mktime(000712000));

/* 형식 인수로 상수 사용하기 */
// 출력 예시: Mon, 15 Aug 2005 15:12:46 UTC
echo date(DATE_RFC822);

// 출력 예시: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOMmktime(000712000));
?>

format 문자열로 인식하는 문자 바로 앞에 백슬래시를 붙여서 이스케이프를 함으로써, 인식하는 것 막을 수 있습니다. 백슬래시가 붙는 문자가 이미 특별한 의미를 가지고 있다면, 백슬래시를 이스케이프해야 합니다.

Example #2 date()의 회피 문자

<?php
// 다음의 출력: Wednesday the 15th
echo date("l \\t\h\e jS");
?>

date()mktime()을 함께 사용함으로써 미래나 과거의 시간을 얻을 수 있습니다.

Example #3 date()mktime() 예제

<?php
$tomorrow  
mktime (0,0,0,date("m")  , date("d")+1date("Y"));
$lastmonth mktime (0,0,0,date("m")-1date("d"),   date("Y"));
$nextyear  mktime (0,0,0,date("m"),   date("d"),   date("Y")+1);
?>

Note: 이는 일광 절약 시간을 고려하기 때문에, 단순히 timestamp에 하루나 한달에 해당하는 초를 더하는 것보다 신뢰할 수 있습니다.

date() 형식화의 몇몇 예제. 모든 다른 문자들도 이스케이프 해야함에 주의하십시오. 현재 특별한 의미를 가진 어떤 것이 바람직하지 못한 결과를 가져올 수 있고, 앞으로의 PHP 버전에서는 다른 문자들도 지정될 수가 있습니다. 이스케이프 할 때는, \n이 줄바꿈으로 인식 되는 것과 같은 예을 피하기 위해서는 작은 따옴표를 사용해야만 합니다.

Example #4 date() 형식화

<?php
// Assuming today is: March 10th, 2001, 5:16:18 pm

$today date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today date("m.d.y");                         // 03.10.01
$today date("j, n, Y");                       // 10, 3, 2001
$today date("Ymd");                           // 20010310
$today date('h-i-s, j-m-y, it is w Day');     // 05-16-17, 10-03-01, 1631 1618 6 Fripm01
$today date('\i\t \i\s \t\h\e jS \d\a\y.');   // It is the 10th day.
$today date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
$today date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:16:18 m is month
$today date("H:i:s");                         // 17:16:18
?>

다른 언어로 날짜를 형식화 하기 위해서는, date() 대신에 setlocale()strftime() 함수를 사용해야 합니다.

주의

Note: 날짜의 문자 표현에서 타임스탬프를 만드려면, strtotime()을 사용할 수 있습니다. 추가적으로, 몇몇 데이터베이스는 날짜 형식에서 타임스탬프로 바꾸는 함수를 가지고 있습니다. (MySQL의 » UNIX_TIMESTAMP 등)

Tip

PHP 5.1부터 요청의 시작 타임스탬프가 $_SERVER['REQUEST_TIME']에 존재합니다.

참고

  • getlastmod() - 페이지를 수정한 최종 시간을 얻습니다
  • gmdate() - Format a GMT/UTC date/time
  • mktime() - Get Unix timestamp for a date
  • strftime() - Format a local time/date according to locale settings
  • time() - Return current Unix timestamp



getdate

(PHP 4, PHP 5)

getdate날짜/시간 정보를 가져온다

설명

array getdate ([ int $timestamp= time() ] )

timestamp 의 날짜 정보를 포함하는 연관 배열이나, timestamp 가 주어지지 않는다면 현재 로컬 시간를 반환합니다.

인수

timestamp

선택적인 timestamp 인수는 timestamp 가 주어지지 않았을 경우, 현재 로컬 시간을 기본값으로 가지는 integer 유닉스 타임스탬프입니다. 즉, 기본값은 time() 값입니다.

반환값

timestamp 에 관련된 정보를 가진 연관 array를 반환합니다. 반환되는 연관 배열 원소는 다음과 같습니다:

반환되는 연관 배열의 키 원소들
설명 Example returned values
"seconds" 초의 숫자 표현 0 부터 59
"minutes" 분의 숫자 표현 0 부터 59
"hours" 시간의 숫자 표현 0 부터 23
"mday" 일의 숫자 표현 1 부터 31
"wday" 요일의 숫자 표현 0 (일요일) 부터 6 (토요일)
"mon" 월의 숫자 표현 1 부터 12
"year" 연도의 숫자표현, 4 자리 예시: 1999 또는 2003
"yday" 연도의 일차 0 부터 365
"weekday" 요일, 완전한 문자 Sunday 부터 Saturday
"month" 월, 완전한 문자, January 나 March January 부터 December
0 유닉스 Epoch (January 1 1970 00:00:00 GMT)로부터의 초, time()에 의해 반환되는 값과 유사하고, date()에 의해서 사용됩니다. 시스템에 의존합니다, 일반적으로 -2147483648 부터 2147483647.

예제

Example #1 getdate() 예제

<?php
$today 
getdate(); 
print_r($today);
?>

위 예제의 출력 예시:

Array
(
    [seconds] => 40
    [minutes] => 58
    [hours]   => 21
    [mday]    => 17
    [wday]    => 2
    [mon]     => 6
    [year]    => 2003
    [yday]    => 167
    [weekday] => Tuesday
    [month]   => June
    [0]       => 1055901520
)

참고

  • date() - 로컬 날짜/시간을 형식화합니다
  • time() - Return current Unix timestamp
  • setlocale() - Set locale information



gettimeofday

(PHP 4, PHP 5)

gettimeofdayGet current time

설명

mixed gettimeofday ([ bool $return_float ] )

This is an interface to gettimeofday(2). It returns an associative array containing the data returned from the system call.

인수

return_float

When set to TRUE, a float instead of an array is returned.

반환값

By default an array is returned. If return_float is set, then a float is returned.

Array keys:

  • "sec" - seconds since the Unix Epoch
  • "usec" - microseconds
  • "minuteswest" - minutes west of Greenwich
  • "dsttime" - type of dst correction

변경점

버전 설명
5.1.0 The return_float parameter was added.

예제

Example #1 gettimeofday() example

<?php
print_r
(gettimeofday());

echo 
gettimeofday(true);
?>

위 예제의 출력 예시:

Array
(
    [sec] => 1073504408
    [usec] => 238215
    [minuteswest] => 0
    [dsttime] => 1
)

1073504408.23910



gmdate

(PHP 4, PHP 5)

gmdateFormat a GMT/UTC date/time

설명

string gmdate ( string $format [, int $timestamp ] )

Identical to the date() function except that the time returned is Greenwich Mean Time (GMT).

인수

format

The format of the outputted date string. See the formatting options for the date() function.

timestamp

선택적인 timestamp 인수는 timestamp 가 주어지지 않았을 경우, 현재 로컬 시간을 기본값으로 가지는 integer 유닉스 타임스탬프입니다. 즉, 기본값은 time() 값입니다.

반환값

Returns a formatted date string. If a non-numeric value is used for timestamp , FALSE is returned and an E_WARNING level error is emitted.

변경점

버전 설명
5.1.0 The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer). However, before PHP 5.1.0 this range was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows).
5.1.1 There are useful constants of standard date/time formats that can be used to specify the format parameter.

예제

Example #1 gmdate() 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".

<?php
echo date("M d Y H:i:s"mktime(000111998));
echo 
gmdate("M d Y H:i:s"mktime(000111998));
?>

참고

  • date() - 로컬 날짜/시간을 형식화합니다
  • mktime() - Get Unix timestamp for a date
  • gmmktime() - Get Unix timestamp for a GMT date
  • strftime() - Format a local time/date according to locale settings



gmmktime

(PHP 4, PHP 5)

gmmktimeGet Unix timestamp for a GMT date

설명

int gmmktime ([ int $hour= gmdate("H") [, int $minute= gmdate("i") [, int $second= gmdate("s") [, int $month= gmdate("n") [, int $day= gmdate("j") [, int $year= gmdate("Y") [, int $is_dst= -1 ]]]]]]] )

Identical to mktime() except the passed parameters represents a GMT date. gmmktime() internally uses mktime() so only times valid in derived local time can be used.

Like mktime(), arguments may be left out in order from right to left, with any omitted arguments being set to the current corresponding GMT value.

인수

hour

The hour

minute

The minute

second

The second

month

The month

day

The day

year

The year

is_dst

Parameters always represent a GMT date so is_dst doesn't influence the result.

반환값

Returns a integer Unix timestamp.

변경점

버전 설명
5.1.0 As of PHP 5.1.0, the is_dst parameter became deprecated. As a result, the new timezone handling features should be used instead.

예제

Example #1 gmmktime() on Windows boundary

<?php
gmmktime
(000111970); // valid in GMT and west, invalid in east
?>

참고

  • mktime() - Get Unix timestamp for a date
  • date() - 로컬 날짜/시간을 형식화합니다
  • time() - Return current Unix timestamp



gmstrftime

(PHP 4, PHP 5)

gmstrftimeFormat a GMT/UTC time/date according to locale settings

설명

string gmstrftime ( string $format [, int $timestamp= time() ] )

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".

인수

format

See description in strftime().

timestamp

선택적인 timestamp 인수는 timestamp 가 주어지지 않았을 경우, 현재 로컬 시간을 기본값으로 가지는 integer 유닉스 타임스탬프입니다. 즉, 기본값은 time() 값입니다.

반환값

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().

예제

Example #1 gmstrftime() example

<?php
setlocale
(LC_TIME'en_US');
echo 
strftime("%b %d %Y %H:%M:%S"mktime(2000123198)) . "\n";
echo 
gmstrftime("%b %d %Y %H:%M:%S"mktime(2000123198)) . "\n";
?>

참고

  • strftime() - Format a local time/date according to locale settings



idate

(PHP 5)

idateFormat a local time/date as integer

설명

int idate ( string $format [, int $timestamp= time() ] )

Returns a number formatted according to the given format string using the given integer timestamp or the current local time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().

Unlike the function date(), idate() accepts just one char in the format parameter.

인수

format

The following characters are recognized in the format parameter string
format character Description
B Swatch Beat/Internet Time
d Day of the month
h Hour (12 hour format)
H Hour (24 hour format)
i Minutes
I (uppercase i) returns 1 if DST is activated, 0 otherwise
L (uppercase l) returns 1 for leap year, 0 otherwise
m Month number
s Seconds
t Days in current month
U Seconds since the Unix Epoch - January 1 1970 00:00:00 UTC - this is the same as time()
w Day of the week (0 on Sunday)
W ISO-8601 week number of year, weeks starting on Monday
y Year (1 or 2 digits - check note below)
Y Year (4 digits)
z Day of the year
Z Timezone offset in seconds

timestamp

선택적인 timestamp 인수는 timestamp 가 주어지지 않았을 경우, 현재 로컬 시간을 기본값으로 가지는 integer 유닉스 타임스탬프입니다. 즉, 기본값은 time() 값입니다.

반환값

Returns an integer.

As idate() always returns an integer and as they can't start with a "0", idate() may return fewer digits than you would expect. See the example below.

오류/예외

모든 날짜/시간 함수 호출은 시간대가 유효하지 않을 때 E_NOTICE를, 시스템 설정이나 TZ 환경 변수를 사용할 때 E_STRICT를 생성합니다. date_default_timezone_set()을 참고하십시오.

변경점

버전 설명
5.1.0

시간대 오류시 E_STRICTE_NOTICE가 발생합니다.

예제

Example #1 idate() example

<?php
$timestamp 
strtotime('1st January 2004'); //1072915200

// this prints the year in a two digit format
// however, as this would start with a "0", it
// only prints "4"
echo idate('y'$timestamp);
?>

참고

  • date() - 로컬 날짜/시간을 형식화합니다
  • time() - Return current Unix timestamp



localtime

(PHP 4, PHP 5)

localtimeGet the local time

설명

array localtime ([ int $timestamp= time() [, bool $is_associative= false ]] )

The localtime() function returns an array identical to that of the structure returned by the C function call.

인수

timestamp

선택적인 timestamp 인수는 timestamp 가 주어지지 않았을 경우, 현재 로컬 시간을 기본값으로 가지는 integer 유닉스 타임스탬프입니다. 즉, 기본값은 time() 값입니다.

is_associative

If set to FALSE or not supplied then the array is returned as a regular, numerically indexed array. If the argument is set to TRUE then localtime() returns 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 Months are from 0 (Jan) to 11 (Dec) and days of the week are from 0 (Sun) to 6 (Sat).
  • "tm_mon" - month of the year, starting with 0 for January
  • "tm_year" - Years since 1900
  • "tm_wday" - Day of the week
  • "tm_yday" - Day of the year
  • "tm_isdst" - Is daylight savings time in effect

오류/예외

모든 날짜/시간 함수 호출은 시간대가 유효하지 않을 때 E_NOTICE를, 시스템 설정이나 TZ 환경 변수를 사용할 때 E_STRICT를 생성합니다. date_default_timezone_set()을 참고하십시오.

변경점

버전 설명
5.1.0

시간대 오류시 E_STRICTE_NOTICE가 발생합니다.

예제

Example #1 localtime() example

<?php
$localtime 
localtime();
$localtime_assoc localtime(time(), true);
print_r($localtime);
print_r($localtime_assoc);
?>

위 예제의 출력 예시:

Array
(
    [0] => 24
    [1] => 3
    [2] => 19
    [3] => 3
    [4] => 3
    [5] => 105
    [6] => 0
    [7] => 92
    [8] => 1
)

Array
(
    [tm_sec] => 24
    [tm_min] => 3
    [tm_hour] => 19
    [tm_mday] => 3
    [tm_mon] => 3
    [tm_year] => 105
    [tm_wday] => 0
    [tm_yday] => 92
    [tm_isdst] => 1
)



microtime

(PHP 4, PHP 5)

microtimeReturn current Unix timestamp with microseconds

설명

mixed microtime ([ bool $get_as_float ] )

microtime() returns the current Unix timestamp with microseconds. This function is only available on operating systems that support the gettimeofday() system call.

인수

get_as_float

When called without the optional argument, this function 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. Both portions of the string are returned in units of seconds.

If the optional get_as_float is set to TRUE then a float (in seconds) is returned.

변경점

버전 설명
5.0.0 The get_as_float parameter was added.

예제

Example #1 Timing script execution with microtime()

<?php
/**
 * Simple function to replicate PHP 5 behaviour
 */
function microtime_float()
{
    list(
$usec$sec) = explode(" "microtime());
    return ((float)
$usec + (float)$sec);
}

$time_start microtime_float();

// Sleep for a while
usleep(100);

$time_end microtime_float();
$time $time_end $time_start;

echo 
"Did nothing in $time seconds\n";
?>

Example #2 Timing script execution in PHP 5

<?php
$time_start 
microtime(true);

// Sleep for a while
usleep(100);

$time_end microtime(true);
$time $time_end $time_start;

echo 
"Did nothing in $time seconds\n";
?>

참고

  • time() - Return current Unix timestamp



mktime

(PHP 4, PHP 5)

mktimeGet Unix timestamp for a date

설명

int mktime ([ int $hour= date("H") [, int $minute= date("i") [, int $second= date("s") [, int $month= date("n") [, int $day= date("j") [, int $year= date("Y") [, int $is_dst= -1 ]]]]]]] )

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 00:00:00 GMT) 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.

인수

hour

The number of the hour.

minute

The number of the minute.

second

The number of seconds past the minute.

month

The number of the month.

day

The number of the day.

year

The number of the year, may be a two or four digit value, with values between 0-69 mapping to 2000-2069 and 70-100 to 1970-2000. On systems where time_t is a 32bit signed integer, as most common today, the valid range for year is somewhere between 1901 and 2038. However, before PHP 5.1.0 this range was limited from 1970 to 2038 on some systems (e.g. Windows).

is_dst

This parameter can be set to 1 if the time is during daylight savings time (DST), 0 if it is not, or -1 (the default) if it is unknown whether the time is within daylight savings time or not. If it's unknown, PHP tries to figure it out itself. This can cause unexpected (but not incorrect) results. Some times are invalid if DST is enabled on the system PHP is running on or is_dst is set to 1. If DST is enabled in e.g. 2:00, all times between 2:00 and 3:00 are invalid and mktime() returns an undefined (usually negative) value. Some systems (e.g. Solaris 8) enable DST at midnight so time 0:30 of the day when DST is enabled is evaluated as 23:30 of the previous day.

Note: As of PHP 5.1.0, this parameter became deprecated. As a result, the new timezone handling features should be used instead.

반환값

mktime() returns the Unix timestamp of the arguments given. If the arguments are invalid, the function returns FALSE (before PHP 5.1 it returned -1).

오류/예외

모든 날짜/시간 함수 호출은 시간대가 유효하지 않을 때 E_NOTICE를, 시스템 설정이나 TZ 환경 변수를 사용할 때 E_STRICT를 생성합니다. date_default_timezone_set()을 참고하십시오.

변경점

버전 설명
5.3.0 mktime() now throws E_DEPRECATED notice if the is_dst parameter is used.
5.1.0 The is_dst parameter became deprecated. Made the function return FALSE on error, instead of -1. Fixed the function to accept the year, month and day to be all passed as zero.
5.1.0

시간대 오류시 E_STRICTE_NOTICE가 발생합니다.

예제

Example #1 mktime() basic example

<?php
// Set the default timezone to use. Available as of PHP 5.1
date_default_timezone_set('UTC');

// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " date("l"mktime(000712000));

// Prints something like: 2006-04-05T01:02:03+00:00
echo date('c'mktime(123452006));
?>

Example #2 mktime() example

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".

<?php
echo date("M-d-Y"mktime(00012321997));
echo 
date("M-d-Y"mktime(0001311997));
echo 
date("M-d-Y"mktime(000111998));
echo 
date("M-d-Y"mktime(0001198));
?>

Example #3 Last day of next month

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".

<?php
$lastday 
mktime(000302000);
echo 
strftime("Last day in Feb 2000 is: %d"$lastday);
$lastday mktime(0004, -312000);
echo 
strftime("Last day in Feb 2000 is: %d"$lastday);
?>

주의

Caution

Before PHP 5.1.0, negative timestamps were not supported under any known version of Windows and some other systems as well. Therefore the range of valid years was limited to 1970 through 2038.

참고

  • gmmktime() - Get Unix timestamp for a GMT date
  • date() - 로컬 날짜/시간을 형식화합니다
  • time() - Return current Unix timestamp



strftime

(PHP 4, PHP 5)

strftimeFormat a local time/date according to locale settings

설명

string strftime ( string $format [, int $timestamp= time() ] )

Format the time and/or date according to locale settings. Month and weekday names and other language-dependent strings respect the current locale set with setlocale().

Not all conversion specifiers may be supported by your C library, in which case they will not be supported by PHP's strftime(). Additionally, not all platforms support negative timestamps, so your date range may be limited to no earlier than the Unix epoch. This means that %e, %T, %R and, %D (and possibly others) - as well as dates prior to Jan 1, 1970 - will not work on Windows, some Linux distributions, and a few other operating systems. For Windows systems, a complete overview of supported conversion specifiers can be found at » MSDN.

인수

format

The following characters are recognized in the format parameter string
format Description Example returned values
Day --- ---
%a An abbreviated textual representation of the day Sun through Sat
%A A full textual representation of the day Sunday through Saturday
%d Two-digit day of the month (with leading zeros) 01 to 31
%e Day of the month, with a space preceding single digits 1 to 31
%j Day of the year, 3 digits with leading zeros 001 to 366
%u ISO-8601 numeric representation of the day of the week 1 (for Monday) though 7 (for Sunday)
%w Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
Week --- ---
%U Week number of the given year, starting with the the first Sunday as the first week 13 (for the 13th full week of the year)
%V ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week 01 through 53 (where 53 accounts for an overlapping week)
%W A numeric representation of the week of the year, starting with the first Monday as the first week 46 (for the 46th week of the year beginning with a Monday)
Month --- ---
%b Abbreviated month name, based on the locale Jan through Dec
%B Full month name, based on the locale January through December
%h Abbreviated month name, based on the locale (an alias of %b) Jan through Dec
%m Two digit representation of the month 01 (for January) through 12 (for December)
Year --- ---
%C Two digit representation of the century (year divided by 100, truncated to an integer) 19 for the 20th Century
%g Two digit representation of the year going by ISO-8601:1988 standards (see %V) Example: 09 for the week of January 6, 2009
%G The full four-digit version of %g Example: 2008 for the week of January 3, 2009
%y Two digit representation of the year Example: 09 for 2009, 79 for 1979
%Y Four digit representation for the year Example: 2038
Time --- ---
%H Two digit representation of the hour in 24-hour format 00 through 23
%I Two digit representation of the hour in 12-hour format 01 through 12
%l (lower-case 'L') Hour in 12-hour format, with a space preceeding single digits 1 through 12
%M Two digit representation of the minute 00 through 59
%p UPPER-CASE 'AM' or 'PM' based on the given time Example: AM for 00:31, PM for 22:23
%P lower-case 'am' or 'pm' based on the given time Example: am for 00:31, pm for 22:23
%r Same as "%I:%M:%S %p" Example: 09:34:17 PM for 21:34:17
%R Same as "%H:%M" Example: 00:35 for 12:35 AM, 16:44 for 4:44 PM
%S Two digit representation of the second 00 through 59
%T Same as "%H:%M:%S" Example: 21:34:17 for 09:34:17 PM
%X Preferred time representation based on locale, without the date Example: 03:59:16 or 15:59:16
%z Either the time zone offset from UTC or the abbreviation (depends on operating system) Example: -0500 or EST for Eastern Time
%Z The time zone offset/abbreviation option NOT given by %z (depends on operating system) Example: -0500 or EST for Eastern Time
Time and Date Stamps --- ---
%c Preferred date and time stamp based on local Example: Tue Feb 5 00:45:10 2009 for February 4, 2009 at 12:45:10 AM
%D Same as "%m/%d/%y" Example: 02/05/09 for February 5, 2009
%F Same as "%Y-%m-%d" (commonly used in database datestamps) Example: 2009-02-05 for February 5, 2009
%s Unix Epoch Time timestamp (same as the time() function) Example: 305815200 for September 10, 1979 08:40:00 AM
%x Preferred date representation based on locale, without the time Example: 02/05/09 for February 5, 2009
Miscellaneous --- ---
%n A newline character ("\n") ---
%t A Tab character ("\t") ---
%% A literal percentage character ("%") ---

Maximum length of this parameter is 1023 characters.

Warning

Contrary to ISO-9889:1999, Sun Solaris starts with Sunday as 1. As a result, %u may not function as described in this manual.

timestamp

선택적인 timestamp 인수는 timestamp 가 주어지지 않았을 경우, 현재 로컬 시간을 기본값으로 가지는 integer 유닉스 타임스탬프입니다. 즉, 기본값은 time() 값입니다.

반환값

Returns a string formatted according format 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().

오류/예외

모든 날짜/시간 함수 호출은 시간대가 유효하지 않을 때 E_NOTICE를, 시스템 설정이나 TZ 환경 변수를 사용할 때 E_STRICT를 생성합니다. date_default_timezone_set()을 참고하십시오.

변경점

버전 설명
5.1.0

시간대 오류시 E_STRICTE_NOTICE가 발생합니다.

예제

This example will work if you have the respective locales installed in your system.

Example #1 strftime() locale examples

<?php
setlocale
(LC_TIME"C");
echo 
strftime("%A");
setlocale(LC_TIME"fi_FI");
echo 
strftime(" in Finnish is %A,");
setlocale(LC_TIME"fr_FR");
echo 
strftime(" in French %A and");
setlocale(LC_TIME"de_DE");
echo 
strftime(" in German %A.\n");
?>

Example #2 ISO 8601:1988 week number example

<?php
/*     December 2002 / January 2003
ISOWk  M   Tu  W   Thu F   Sa  Su
----- ----------------------------
51     16  17  18  19  20  21  22
52     23  24  25  26  27  28  29
1      30  31   1   2   3   4   5
2       6   7   8   9  10  11  12
3      13  14  15  16  17  18  19   */

// Outputs: 12/28/2002 - %V,%G,%Y = 52,2002,2002
echo "12/28/2002 - %V,%G,%Y = " strftime("%V,%G,%Y"strtotime("12/28/2002")) . "\n";

// Outputs: 12/30/2002 - %V,%G,%Y = 1,2003,2002
echo "12/30/2002 - %V,%G,%Y = " strftime("%V,%G,%Y"strtotime("12/30/2002")) . "\n";

// Outputs: 1/3/2003 - %V,%G,%Y = 1,2003,2003
echo "1/3/2003 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("1/3/2003")) . "\n";

// Outputs: 1/10/2003 - %V,%G,%Y = 2,2003,2003
echo "1/10/2003 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("1/10/2003")) . "\n";



/*     December 2004 / January 2005
ISOWk  M   Tu  W   Thu F   Sa  Su
----- ----------------------------
51     13  14  15  16  17  18  19
52     20  21  22  23  24  25  26
53     27  28  29  30  31   1   2
1       3   4   5   6   7   8   9
2      10  11  12  13  14  15  16   */

// Outputs: 12/23/2004 - %V,%G,%Y = 52,2004,2004
echo "12/23/2004 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("12/23/2004")) . "\n";

// Outputs: 12/31/2004 - %V,%G,%Y = 53,2004,2004
echo "12/31/2004 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("12/31/2004")) . "\n";

// Outputs: 1/2/2005 - %V,%G,%Y = 53,2004,2005
echo "1/2/2005 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("1/2/2005")) . "\n";

// Outputs: 1/3/2005 - %V,%G,%Y = 1,2005,2005
echo "1/3/2005 - %V,%G,%Y = " strftime("%V,%G,%Y",strtotime("1/3/2005")) . "\n";

?>

주의

Note: %G and %V, which are based on ISO 8601:1988 week numbers can give unexpected (albeit correct) results if the numbering system is not thoroughly understood. See %V examples in this manual page.

참고



strptime

(PHP 5 >= 5.1.0)

strptime Parse a time/date generated with strftime()

설명

array strptime ( string $date , string $format )

strptime() returns an array with the date parsed, or FALSE on error.

Month and weekday names and other language dependent strings respect the current locale set with setlocale() (LC_TIME).

인수

date (string)

The string to parse (e.g. returned from strftime())

format (string)

The format used in date (e.g. the same as used in strftime()).

For more information about the format options, read the strftime() page.

반환값

Returns an array, or FALSE on failure.

The following parameters are returned in the array
parameters Description
"tm_sec" Seconds after the minute (0-61)
"tm_min" Minutes after the hour (0-59)
"tm_hour" Hour since midnight (0-23)
"tm_mday" Day of the month (1-31)
"tm_mon" Months since January (0-11)
"tm_year" Years since 1900
"tm_wday" Days since Sunday (0-6)
"tm_yday" Days since January 1 (0-365)
"unparsed" the date part which was not recognized using the specified format

예제

Example #1 strptime() example

<?php
$format 
'%d/%m/%Y %H:%M:%S';
$strf strftime($format);

echo 
"$strf\n";

print_r(strptime($strf$format));
?>

위 예제의 출력 예시:

03/10/2004 15:54:19

Array
(
    [tm_sec] => 19
    [tm_min] => 54
    [tm_hour] => 15
    [tm_mday] => 3
    [tm_mon] => 9
    [tm_year] => 104
    [tm_wday] => 0
    [tm_yday] => 276
    [unparsed] =>
)

주의

Note: 이 함수는 윈도우 플랫폼에서는 작동하지 않습니다.

참고

  • strftime() - Format a local time/date according to locale settings



strtotime

(PHP 4, PHP 5)

strtotimeParse about any English textual datetime description into a Unix timestamp

설명

int strtotime ( string $time [, int $now ] )

The function expects to be given a string containing a US English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now , or the current time if now is not supplied.

This function will use the TZ environment variable (if available) to calculate the timestamp. Since PHP 5.1.0 there are easier ways to define the timezone that is used across all date/time functions. That process is explained in the date_default_timezone_get() function page.

Note: If the number of the year is specified in a two digit format, the values between 00-69 are mapped to 2000-2069 and 70-99 to 1970-1999. See the notes below for possible differences on 32bit systems (possible dates might end on 2038-01-19 03:14:07).

인수

time

The string to parse. Before PHP 5.0.0, microseconds weren't allowed in the time, since PHP 5.0.0 they are allowed but ignored.

now

The timestamp which is used as a base for the calculation of relative dates.

반환값

Returns a timestamp on success, FALSE otherwise. Previous to PHP 5.1.0, this function would return -1 on failure.

오류/예외

모든 날짜/시간 함수 호출은 시간대가 유효하지 않을 때 E_NOTICE를, 시스템 설정이나 TZ 환경 변수를 사용할 때 E_STRICT를 생성합니다. date_default_timezone_set()을 참고하십시오.

변경점

버전 설명
5.1.0 It now returns FALSE on failure, instead of -1.
5.1.0

시간대 오류시 E_STRICTE_NOTICE가 발생합니다.

예제

Example #1 A strtotime() example

<?php
echo strtotime("now"), "\n";
echo 
strtotime("10 September 2000"), "\n";
echo 
strtotime("+1 day"), "\n";
echo 
strtotime("+1 week"), "\n";
echo 
strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo 
strtotime("next Thursday"), "\n";
echo 
strtotime("last Monday"), "\n";
?>

Example #2 Checking for failure

<?php
$str 
'Not Good';

// previous to PHP 5.1.0 you would compare with -1, instead of false
if (($timestamp strtotime($str)) === false) {
    echo 
"The string ($str) is bogus";
} else {
    echo 
"$str == " date('l dS \o\f F Y h:i:s A'$timestamp);
}
?>

주의

Warning

In PHP 5 up to 5.0.2, "now" and other relative times are wrongly computed from today's midnight. It differs from other versions where it is correctly computed from current time.

Warning

In PHP versions prior to 4.4.0, "next" is incorrectly computed as +2. A typical solution to this is to use "+1".

Note: The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.) Additionally, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch. This means that e.g. dates prior to Jan 1, 1970 will not work on Windows, some Linux distributions, and a few other operating systems. PHP 5.1.0 and newer versions overcome this limitation though.

참고

  • strptime() - Parse a time/date generated with strftime



time

(PHP 4, PHP 5)

timeReturn current Unix timestamp

설명

int time ( void )

Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

예제

Example #1 time() example

<?php
$nextWeek 
time() + (24 60 60);
                   
// 7 days; 24 hours; 60 mins; 60secs
echo 'Now:       'date('Y-m-d') ."\n";
echo 
'Next Week: 'date('Y-m-d'$nextWeek) ."\n";
// or using strtotime():
echo 'Next Week: 'date('Y-m-d'strtotime('+1 week')) ."\n";
?>

위 예제의 출력 예시:

Now:       2005-03-30
Next Week: 2005-04-06
Next Week: 2005-04-06

주의

Tip

Timestamp of the start of the request is available in $_SERVER['REQUEST_TIME'] since PHP 5.1.

참고

  • date() - 로컬 날짜/시간을 형식화합니다
  • microtime() - Return current Unix timestamp with microseconds



timezone_abbreviations_list

(PHP 5 >= 5.1.0)

timezone_abbreviations_list별칭: DateTimeZone::listAbbreviations

설명

이 함수는 다음 함수의 별칭입니다: DateTimeZone::listAbbreviations



timezone_identifiers_list

(PHP 5 >= 5.1.0)

timezone_identifiers_list별칭: DateTimeZone::listIdentifiers

설명

이 함수는 다음 함수의 별칭입니다: DateTimeZone::listIdentifiers



timezone_location_get

(PHP 5 >= 5.3.0)

timezone_location_get별칭: DateTimeZone::getLocation

설명

이 함수는 다음 함수의 별칭입니다: DateTimeZone::getLocation



timezone_name_from_abbr

(PHP 5 >= 5.1.3)

timezone_name_from_abbrReturns the timezone name from abbreviation

설명

string timezone_name_from_abbr ( string $abbr [, int $gmtOffset= -1 [, int $isdst= -1 ]] )

인수

abbr

Time zone abbreviation.

gmtOffset

Offset from GMT in seconds. Defaults to -1 which means that first found time zone corresponding to abbr is returned. Otherwise exact offset is searched and only if not found then the first time zone with any offset is returned.

isdst

Daylight saving time indicator. If abbr doesn't exist then the time zone is searched solely by offset and isdst .

반환값

Returns time zone name on success or FALSE on failure.

예제

Example #1 A timezone_name_from_abbr() example

<?php
echo timezone_name_from_abbr("CET") . "\n";
echo 
timezone_name_from_abbr(""36000) . "\n";
?>

위 예제의 출력 예시:

Europe/Berlin
Europe/Paris

참고



timezone_name_get

(PHP 5 >= 5.1.0)

timezone_name_get별칭: DateTimeZone::getName

설명

이 함수는 다음 함수의 별칭입니다: DateTimeZone::getName



timezone_offset_get

(PHP 5 >= 5.1.0)

timezone_offset_get별칭: DateTimeZone::getOffset

설명

이 함수는 다음 함수의 별칭입니다: DateTimeZone::getOffset



timezone_open

(PHP 5 >= 5.1.0)

timezone_openReturns new DateTimeZone object

설명

DateTimeZone timezone_open ( string $timezone )

인수

timezone

Time zone identifier as full name (e.g. Europe/Prague) or abbreviation (e.g. CET).

반환값

Returns DateTimeZone object on success or FALSE on failure.



timezone_transitions_get

(PHP 5 >= 5.2.0)

timezone_transitions_get별칭: DateTimeZone::getTransitions

설명

이 함수는 다음 함수의 별칭입니다: DateTimeZone::getTransitions



timezone_version_get

(PHP 5 >= 5.3.0)

timezone_version_get Gets the version of the timezonedb

설명

string timezone_version_get ( void )

Returns the current version of the timezonedb.

반환값

Returns a string.

예제

Example #1 Getting the timezonedb version

<?php
echo timezone_version_get();
?>

위 예제의 출력 예시:

2009.7


Table of Contents





Command Line Specific Extensions


Newt


소개

This is a PHP language extension for RedHat Newt library, a terminal-based window and widget library for writing applications with user friendly interface. Once this extension is enabled in PHP it will provide the use of Newt widgets, such as windows, buttons, checkboxes, radiobuttons, labels, editboxes, scrolls, textareas, scales, etc. Use of this extension if very similar to the original Newt API of C programming language.



설치/설정

Table of Contents


요구 조건

This module uses the functions of the RedHat Newt library. You need libnewt version >= 0.51.0.



설치

» PECL 확장은 PHP 배포판에서 제공하지 않습니다. PECL 확장 설치에 관한 정보는 매뉴얼의 PECL 확장 설치에 있습니다. 새 릴리즈, 내려받기, 소스파일, 개발자 정보, CHANGELOG 등의 추가 정보는 여기에 있습니다: » http://pecl.php.net/package/newt.

PHP 4에서 이 PECL 확장의 소스는 PHP 소스의 ext/ 디렉토리 안이나, 위의 PECL 링크에서 찾을 수 있습니다. In order to use these functions you must compile CGI or CLI PHP with newt support by using the --with-newt[=DIR] configure option.

Note: This extension is not available for Windows platform.
You may need also curses and slang libraries, in order to compile this extension. To specify locations of these libraries, use the following configuration options: --with-curses-dir=/path/to/libcurses --with-slang-dir=/path/to/libslang



실행시 설정

이 확장은 php.ini 설정이 존재하지 않습니다.



자원형

This extension uses two resource types: "newt component" and "newt grid".

Resource type "newt component" is returned by functions, which create common newt widgets (for example: newt_button())

Resource type "newt grid" is a special link identifier for components, returned by newt grid factory functions (for example: newt_create_grid())




예약 상수

Table of Contents

이 확장은 다음의 상수들을 정의합니다. 이 확장을 PHP에 내장했거나, 실행시에 동적으로 읽어들일 경우에만 사용할 수 있습니다.


Newt form exit reasons

Newt form exit reasons
constant meaning
NEWT_EXIT_HOTKEY hotkey defined by newt_form_add_hot_key() was pressed
NEWT_EXIT_COMPONENT some component has caused form to exit
NEWT_EXIT_FDREADY file descriptor specified in newt_form_watch_fd() is ready to be read or written to
NEWT_EXIT_TIMER time specified in newt_form_set_timer() has elapsed


Newt colorsets

Newt colorsets
constant meaning
NEWT_COLORSET_ROOT  
NEWT_COLORSET_BORDER  
NEWT_COLORSET_WINDOW  
NEWT_COLORSET_SHADOW  
NEWT_COLORSET_TITLE  
NEWT_COLORSET_BUTTON  
NEWT_COLORSET_ACTBUTTON  
NEWT_COLORSET_CHECKBOX  
NEWT_COLORSET_ACTCHECKBOX  
NEWT_COLORSET_ENTRY  
NEWT_COLORSET_LABEL  
NEWT_COLORSET_LISTBOX  
NEWT_COLORSET_ACTLISTBOX  
NEWT_COLORSET_TEXTBOX  
NEWT_COLORSET_ACTTEXTBOX  
NEWT_COLORSET_HELPLINE  
NEWT_COLORSET_ROOTTEXT  
NEWT_COLORSET_ROOTTEXT  
NEWT_COLORSET_EMPTYSCALE  
NEWT_COLORSET_FULLSCALE  
NEWT_COLORSET_DISENTRY  
NEWT_COLORSET_COMPACTBUTTON  
NEWT_COLORSET_ACTSELLISTBOX  
NEWT_COLORSET_SELLISTBOX  


Newt argument flags

Newt argument flags
constant meaning
NEWT_ARG_LAST  
NEWT_ARG_APPEND  


Newt Flags Sense

Newt Flags Sense
constant meaning
NEWT_FLAGS_SET  
NEWT_FLAGS_RESET  
NEWT_FLAGS_TOGGLE  


Newt Components Flags

Newt Components Flags
constant meaning
NEWT_FLAG_RETURNEXIT Exit form, when component is activated
NEWT_FLAG_HIDDEN Component is hidden
NEWT_FLAG_SCROLL Component is scrollable
NEWT_FLAG_DISABLED Component is disabled
NEWT_FLAG_BORDER  
NEWT_FLAG_WRAP Wrap text
NEWT_FLAG_NOF12 Don't exit form on pressing F12
NEWT_FLAG_MULTIPLE  
NEWT_FLAG_SELECTED Component is selected
NEWT_FLAG_CHECKBOX Component is checkbox
NEWT_FLAG_PASSWORD Entry component is password entry
NEWT_FLAG_SHOWCURSOR Show cursor


File Descriptor Flags

File Descriptor Flags
constant meaning
NEWT_FD_READ  
NEWT_FD_WRITE  
NEWT_FD_EXCEPT  


Checkbox Tree Flags

Checkbox Tree Flags
constant meaning
NEWT_CHECKBOXTREE_UNSELECTABLE  
NEWT_CHECKBOXTREE_HIDE_BOX  
NEWT_CHECKBOXTREE_COLLAPSED  
NEWT_CHECKBOXTREE_EXPANDED  
NEWT_CHECKBOXTREE_UNSELECTED  
NEWT_CHECKBOXTREE_SELECTED  


Entry Flags

Entry Flags
constant meaning
NEWT_ENTRY_SCROLL  
NEWT_ENTRY_HIDDEN  
NEWT_ENTRY_RETURNEXIT  
NEWT_ENTRY_DISABLED  


Listbox Flags

Listbox Flags
constant meaning
NEWT_LISTBOX_RETURNEXIT  


Textbox Flags

Textbox Flags
constant meaning
NEWT_TEXTBOX_WRAP Wrap text in the textbox
NEWT_TEXTBOX_SCROLL Scroll text in the textbox


Form Flags

Form Flags
constant meaning
NEWT_FORM_NOF12 Don't exit form on F12 press


Newt Keys

Newt Keys
constant meaning
NEWT_KEY_TAB  
NEWT_KEY_ENTER  
NEWT_KEY_SUSPEND  
NEWT_KEY_ESCAPE  
NEWT_KEY_RETURN  
NEWT_KEY_EXTRA_BASE  
NEWT_KEY_UP  
NEWT_KEY_DOWN  
NEWT_KEY_LEFT  
NEWT_KEY_RIGHT  
NEWT_KEY_BKSPC  
NEWT_KEY_DELETE  
NEWT_KEY_HOME  
NEWT_KEY_END  
NEWT_KEY_UNTAB  
NEWT_KEY_PGUP  
NEWT_KEY_PGDN  
NEWT_KEY_INSERT  
NEWT_KEY_F1  
NEWT_KEY_F2  
NEWT_KEY_F3  
NEWT_KEY_F4  
NEWT_KEY_F5  
NEWT_KEY_F6  
NEWT_KEY_F7  
NEWT_KEY_F8  
NEWT_KEY_F9  
NEWT_KEY_F10  
NEWT_KEY_F11  
NEWT_KEY_F12  
NEWT_KEY_RESIZE  


Newt Anchors

Newt Anchors
constant meaning
NEWT_ANCHOR_LEFT  
NEWT_ANCHOR_RIGHT  
NEWT_ANCHOR_TOP  
NEWT_ANCHOR_BOTTOM  


Grid Flags

Grid Flags
constant meaning
NEWT_GRID_FLAG_GROWX  
NEWT_GRID_FLAG_GROWY  
NEWT_GRID_EMPTY  
NEWT_GRID_COMPONENT  
NEWT_GRID_SUBGRID  



예제

Table of Contents


Basic usage

This example is a PHP port of RedHat 'setup' utility dialog, executed in text mode.

Example #1 Newt Usage Example

<?php
newt_init 
();
newt_cls ();

newt_draw_root_text (00"Test Mode Setup Utility 1.12");
newt_push_help_line (null);
newt_draw_root_text (-300"(c) 1999-2002 RedHat, Inc");

newt_get_screen_size ($rows$cols);

newt_open_window ($rows/2-17$cols/2-103417"Choose a Tool");

$form newt_form ();

$list newt_listbox (3210);

foreach (array (
    
"Authentication configuration",
    
"Firewall configuration",
    
"Mouse configuration",
    
"Network configuration",
    
"Printer configuration",
    
"System services") as $l_item)
{
    
newt_listbox_add_entry ($list$l_item$l_item);
}

$b1 newt_button (512"Run Tool");
$b2 newt_button (2112"Quit");

newt_form_add_component ($form$list);
newt_form_add_components ($form, array($b1$b2));

newt_refresh ();
newt_run_form ($form);

newt_pop_window ();
newt_pop_help_line ();
newt_finished ();
newt_form_destroy ($form);
?>



Newt 함수 목록


newt_bell

(PECL newt >= 0.1)

newt_bellSend a beep to the terminal

설명

void newt_bell ( void )

This function sends a beep to the terminal.

Note: Depending on the terminal's settings, this beep may or may not be audible.

반환값

값을 반환하지 않습니다.



newt_button_bar

(PECL newt >= 0.1)

newt_button_barThis function returns a grid containing the buttons created.

설명

resource newt_button_bar ( array &$buttons )

This function returns a grid containing the buttons created.

인수

buttons

반환값

Returns grid containing the buttons created.



newt_button

(PECL newt >= 0.1)

newt_buttonCreate a new button

설명

resource newt_button ( int $left , int $top , string $text )

Creates a new button.

인수

left

X-coordinate of the button.

top

Y-coordinate of the button.

text

The text which should be displayed in the button.

반환값

Returns a resource link to the created button component, or FALSE on error.

예제

Example #1 A newt_button() example

<?php

$form 
newt_form();

$ok_button newt_button(512"Run Tool");
    
newt_form_add_component($form$ok_button);

?>

참고



newt_centered_window

(PECL newt >= 0.1)

newt_centered_windowOpen a centered window of the specified size

설명

int newt_centered_window ( int $width , int $height [, string $title ] )

Open a centered window of the specified size.

인수

width

Window width

height

Window height

title

Window title

반환값

Undefined value.

참고



newt_checkbox_get_value

(PECL newt >= 0.1)

newt_checkbox_get_valueRetreives value of checkox resource

설명

string newt_checkbox_get_value ( resource $checkbox )

This function returns the character in the sequence which indicates the current value of the checkbox.

인수

checkbox

반환값

Returns character indicating the value of the checkbox.



newt_checkbox_set_flags

(PECL newt >= 0.1)

newt_checkbox_set_flagsConfigures checkbox resource

설명

void newt_checkbox_set_flags ( resource $checkbox , int $flags , int $sense )

This function allows to set various flags on checkbox resource.

인수

checkbox

flags

sense

반환값

값을 반환하지 않습니다.



newt_checkbox_set_value

(PECL newt >= 0.1)

newt_checkbox_set_valueSets the value of the checkbox

설명

void newt_checkbox_set_value ( resource $checkbox , string $value )

This function allows to set the current value of the checkbox resource.

인수

checkbox

value

반환값

값을 반환하지 않습니다.



newt_checkbox_tree_add_item

(PECL newt >= 0.1)

newt_checkbox_tree_add_itemAdds new item to the checkbox tree

설명

void newt_checkbox_tree_add_item ( resource $checkboxtree , string $text , mixed $data , int $flags , int $index [, int $... ] )

This function allows to add new item to the checkbox tree.

인수

checkboxtree

text

data

flags

index

반환값

값을 반환하지 않습니다.



newt_checkbox_tree_find_item

(PECL newt >= 0.1)

newt_checkbox_tree_find_itemFinds an item in the checkbox tree

설명

array newt_checkbox_tree_find_item ( resource $checkboxtree , mixed $data )

Finds an item in the checkbox tree by item's data.

인수

checkboxtree

data

반환값

Returns checkbox tree item resource, or NULL if it wasn't found.



newt_checkbox_tree_get_current

(PECL newt >= 0.1)

newt_checkbox_tree_get_currentReturns checkbox tree selected item

설명

mixed newt_checkbox_tree_get_current ( resource $checkboxtree )

This method returns checkbox tree selected tem.

인수

checkboxtree

반환값

Returns current (selected) checkbox tree item.



newt_checkbox_tree_get_entry_value

(PECL newt >= 0.1)

newt_checkbox_tree_get_entry_value

설명

string newt_checkbox_tree_get_entry_value ( resource $checkboxtree , mixed $data )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

checkboxtree

data

반환값



newt_checkbox_tree_get_multi_selection

(PECL newt >= 0.1)

newt_checkbox_tree_get_multi_selection

설명

array newt_checkbox_tree_get_multi_selection ( resource $checkboxtree , string $seqnum )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

checkboxtree

seqnum

반환값



newt_checkbox_tree_get_selection

(PECL newt >= 0.1)

newt_checkbox_tree_get_selection

설명

array newt_checkbox_tree_get_selection ( resource $checkboxtree )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

checkboxtree

반환값



newt_checkbox_tree_multi

(PECL newt >= 0.1)

newt_checkbox_tree_multi

설명

resource newt_checkbox_tree_multi ( int $left , int $top , int $height , string $seq [, int $flags ] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

left

top

height

seq

flags

반환값



newt_checkbox_tree_set_current

(PECL newt >= 0.1)

newt_checkbox_tree_set_current

설명

void newt_checkbox_tree_set_current ( resource $checkboxtree , mixed $data )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

checkboxtree

data

반환값

값을 반환하지 않습니다.



newt_checkbox_tree_set_entry_value

(PECL newt >= 0.1)

newt_checkbox_tree_set_entry_value

설명

void newt_checkbox_tree_set_entry_value ( resource $checkboxtree , mixed $data , string $value )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

checkboxtree

data

value

반환값

값을 반환하지 않습니다.



newt_checkbox_tree_set_entry

(PECL newt >= 0.1)

newt_checkbox_tree_set_entry

설명

void newt_checkbox_tree_set_entry ( resource $checkboxtree , mixed $data , string $text )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

checkboxtree

data

text

반환값

값을 반환하지 않습니다.



newt_checkbox_tree_set_width

(PECL newt >= 0.1)

newt_checkbox_tree_set_width

설명

void newt_checkbox_tree_set_width ( resource $checkbox_tree , int $width )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

checkbox_tree

width

반환값

값을 반환하지 않습니다.



newt_checkbox_tree

(PECL newt >= 0.1)

newt_checkbox_tree

설명

resource newt_checkbox_tree ( int $left , int $top , int $height [, int $flags ] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

left

top

height

flags

반환값



newt_checkbox

(PECL newt >= 0.1)

newt_checkbox

설명

resource newt_checkbox ( int $left , int $top , string $text , string $def_value [, string $seq ] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

left

top

text

def_value

seq

반환값



newt_clear_key_buffer

(PECL newt >= 0.1)

newt_clear_key_bufferDiscards the contents of the terminal's input buffer without waiting for additional input

설명

void newt_clear_key_buffer ( void )

Discards the contents of the terminal's input buffer without waiting for additional input.

반환값

값을 반환하지 않습니다.

참고



newt_cls

(PECL newt >= 0.1)

newt_cls

설명

void newt_cls ( void )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

반환값

값을 반환하지 않습니다.



newt_compact_button

(PECL newt >= 0.1)

newt_compact_button

설명

resource newt_compact_button ( int $left , int $top , string $text )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

left

top

text

반환값



newt_component_add_callback

(PECL newt >= 0.1)

newt_component_add_callback

설명

void newt_component_add_callback ( resource $component , mixed $func_name , mixed $data )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

component

func_name

data

반환값

값을 반환하지 않습니다.



newt_component_takes_focus

(PECL newt >= 0.1)

newt_component_takes_focus

설명

void newt_component_takes_focus ( resource $component , bool $takes_focus )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

component

takes_focus

반환값

값을 반환하지 않습니다.



newt_create_grid

(PECL newt >= 0.1)

newt_create_grid

설명

resource newt_create_grid ( int $cols , int $rows )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

cols

rows

반환값



newt_cursor_off

(PECL newt >= 0.1)

newt_cursor_off

설명

void newt_cursor_off ( void )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

반환값

값을 반환하지 않습니다.



newt_cursor_on

(PECL newt >= 0.1)

newt_cursor_on

설명

void newt_cursor_on ( void )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

반환값

값을 반환하지 않습니다.



newt_delay

(PECL newt >= 0.1)

newt_delay

설명

void newt_delay ( int $microseconds )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

microseconds

반환값

값을 반환하지 않습니다.



newt_draw_form

(PECL newt >= 0.1)

newt_draw_form

설명

void newt_draw_form ( resource $form )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

form

반환값

값을 반환하지 않습니다.



newt_draw_root_text

(PECL newt >= 0.1)

newt_draw_root_textDisplays the string text at the position indicated

설명

void newt_draw_root_text ( int $left , int $top , string $text )

Displays the string text at the position indicated.

인수

left

Column number

Note: If left is negative, the position is measured from the opposite side of the screen.

top

Line number

Note: If top is negative, the position is measured from the opposite side of the screen.

text

Text to display.

반환값

값을 반환하지 않습니다.

예제

Example #1 A newt_draw_root_text() example

This code demonstrates drawing of titles in the both corners of the screen.

<?php
 newt_init
();
 
newt_cls();

 
newt_draw_root_text (20"Some root text");
 
newt_refresh();
 
sleep(1);

 
newt_draw_root_text (-300"Root text in the other corner");
 
newt_refresh();
 
sleep(1);

 
newt_finished();
?>

참고



newt_entry_get_value

(PECL newt >= 0.1)

newt_entry_get_value

설명

string newt_entry_get_value ( resource $entry )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

entry

반환값



newt_entry_set_filter

(PECL newt >= 0.1)

newt_entry_set_filter

설명

void newt_entry_set_filter ( resource $entry , callback $filter , mixed $data )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

entry

filter

data

반환값

값을 반환하지 않습니다.



newt_entry_set_flags

(PECL newt >= 0.1)

newt_entry_set_flags

설명

void newt_entry_set_flags ( resource $entry , int $flags , int $sense )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

entry

flags

sense

반환값

값을 반환하지 않습니다.



newt_entry_set

(PECL newt >= 0.1)

newt_entry_set

설명

void newt_entry_set ( resource $entry , string $value [, bool $cursor_at_end ] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

entry

value

cursor_at_end

반환값

값을 반환하지 않습니다.



newt_entry

(PECL newt >= 0.1)

newt_entry

설명

resource newt_entry ( int $left , int $top , int $width [, string $init_value [, int $flags ]] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

left

top

width

init_value

flags

반환값



newt_finished

(PECL newt >= 0.1)

newt_finishedUninitializes newt interface

설명

int newt_finished ( void )

Uninitializes newt interface. This function be called, when program is ready to exit.

반환값

Returns 1 on success, 0 on failure.

참고



newt_form_add_component

(PECL newt >= 0.1)

newt_form_add_componentAdds a single component to the form

설명

void newt_form_add_component ( resource $form , resource $component )

Adds a single component to the form .

인수

form

Form to which component will be added

component

Component to add to the form

반환값

값을 반환하지 않습니다.

예제

Example #1 A newt_form_add_component() example

<?php
$form 
newt_form();

$options = array("Authentication configuration""Firewall configuration",
"Mouse configuration""Network configuration""Printer configuration",
"System services");

$list newt_listbox(3210);

foreach (
$options as $l_item) {
    
newt_listbox_add_entry($list$l_item$l_item);
}

newt_form_add_component($form$list);
?>

참고



newt_form_add_components

(PECL newt >= 0.1)

newt_form_add_componentsAdd several components to the form

설명

void newt_form_add_components ( resource $form , array $components )

Adds several components to the form .

인수

form

Form to which components will be added

components

Array of components to add to the form

반환값

값을 반환하지 않습니다.

예제

Example #1 A newt_form_add_components() example

<?php
$form 
newt_form();

$b1 newt_button(512"Run Tool");
$b2 newt_button(2112"Quit");

newt_form_add_components($form, array($b1$b2));
?>

참고



newt_form_add_hot_key

(PECL newt >= 0.1)

newt_form_add_hot_key

설명

void newt_form_add_hot_key ( resource $form , int $key )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

form

key

반환값

값을 반환하지 않습니다.



newt_form_destroy

(PECL newt >= 0.1)

newt_form_destroyDestroys a form

설명

void newt_form_destroy ( resource $form )

This function frees the memory resources used by the form and all of the components which have been added to the form (including those components which are on subforms). Once a form has been destroyed, none of the form's components can be used.

인수

form

Form component, which is going to be destroyed

반환값

값을 반환하지 않습니다.

참고



newt_form_get_current

(PECL newt >= 0.1)

newt_form_get_current

설명

resource newt_form_get_current ( resource $form )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

form

반환값



newt_form_run

(PECL newt >= 0.1)

newt_form_runRuns a form

설명

void newt_form_run ( resource $form , array &$exit_struct )

This function runs the form passed to it.

인수

form

Form component

exit_struct

Array, used for returning information after running the form component. Keys and values are described in the following table:

Form Exit Structure
Index Key Value Type Description
reason integer The reason, why the form has been exited. Possible values are defined here.
watch resource Resource link, specified in newt_form_watch_fd()
key integer Hotkey
component resource Component, which caused the form to exit

반환값

값을 반환하지 않습니다.

참고



newt_form_set_background

(PECL newt >= 0.1)

newt_form_set_background

설명

void newt_form_set_background ( resource $from , int $background )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

from

background

반환값

값을 반환하지 않습니다.



newt_form_set_height

(PECL newt >= 0.1)

newt_form_set_height

설명

void newt_form_set_height ( resource $form , int $height )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

form

height

반환값

값을 반환하지 않습니다.



newt_form_set_size

(PECL newt >= 0.1)

newt_form_set_size

설명

void newt_form_set_size ( resource $form )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

form

반환값

값을 반환하지 않습니다.



newt_form_set_timer

(PECL newt >= 0.1)

newt_form_set_timer

설명

void newt_form_set_timer ( resource $form , int $milliseconds )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

form

milliseconds

반환값

값을 반환하지 않습니다.



newt_form_set_width

(PECL newt >= 0.1)

newt_form_set_width

설명

void newt_form_set_width ( resource $form , int $width )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

form

width

반환값

값을 반환하지 않습니다.



newt_form_watch_fd

(PECL newt >= 0.1)

newt_form_watch_fd

설명

void newt_form_watch_fd ( resource $form , resource $stream [, int $flags ] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

form

stream

flags

반환값

값을 반환하지 않습니다.



newt_form

(PECL newt >= 0.1)

newt_formCreate a form

설명

resource newt_form ([ resource $vert_bar [, string $help [, int $flags ]]] )

Create a new form.

인수

vert_bar

Vertical scrollbar which should be associated with the form

help

Help text string

flags

Various flags

반환값

Returns a resource link to the created form component, or FALSE on error.

예제

Example #1 A newt_form() example

Displays a single button "Quit", which closes the application once it's pressed.

<?php
newt_init
();
newt_cls();

$myform newt_form();
$button newt_button (512"Quit");

newt_form_add_component ($myform$button);
newt_refresh ();
newt_run_form ($myform);

newt_finished ();
newt_form_destroy ($myform);
?>

참고



newt_get_screen_size

(PECL newt >= 0.1)

newt_get_screen_sizeFills in the passed references with the current size of the terminal

설명

void newt_get_screen_size ( int &$cols , int &$rows )

Fills in the passed references with the current size of the terminal.

인수

cols

Number of columns in the terminal

rows

Number of rows in the terminal

반환값

값을 반환하지 않습니다.

예제

Example #1 A newt_get_screen_size() example

This code prints out the screen size of your terminal.

<?php
 newt_init
();
 
newt_get_screen_size (&$cols, &$rows);
 
newt_finished();

 print 
"Your terminal size is: {$cols}x{$rows}\n";
?>

위 예제의 출력:

Your terminal size is: 138x47



newt_grid_add_components_to_form

(PECL newt >= 0.1)

newt_grid_add_components_to_form

설명

void newt_grid_add_components_to_form ( resource $grid , resource $form , bool $recurse )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

grid

form

recurse

반환값

값을 반환하지 않습니다.



newt_grid_basic_window

(PECL newt >= 0.1)

newt_grid_basic_window

설명

resource newt_grid_basic_window ( resource $text , resource $middle , resource $buttons )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

text

middle

buttons

반환값



newt_grid_free

(PECL newt >= 0.1)

newt_grid_free

설명

void newt_grid_free ( resource $grid , bool $recurse )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

grid

recurse

반환값

값을 반환하지 않습니다.



newt_grid_get_size

(PECL newt >= 0.1)

newt_grid_get_size

설명

void newt_grid_get_size ( resouce $grid , int &$width , int &$height )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

grid

width

height

반환값

값을 반환하지 않습니다.



newt_grid_h_close_stacked

(PECL newt >= 0.1)

newt_grid_h_close_stacked

설명

resource newt_grid_h_close_stacked ( int $element1_type , resource $element1 [, int $... [, resource $... ]] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

element1_type

element1

반환값



newt_grid_h_stacked

(PECL newt >= 0.1)

newt_grid_h_stacked

설명

resource newt_grid_h_stacked ( int $element1_type , resource $element1 [, int $... [, resource $... ]] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

element1_type

element1

반환값



newt_grid_place

(PECL newt >= 0.1)

newt_grid_place

설명

void newt_grid_place ( resource $grid , int $left , int $top )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

grid

left

top

반환값

값을 반환하지 않습니다.



newt_grid_set_field

(PECL newt >= 0.1)

newt_grid_set_field

설명

void newt_grid_set_field ( resource $grid , int $col , int $row , int $type , resource $val , int $pad_left , int $pad_top , int $pad_right , int $pad_bottom , int $anchor [, int $flags ] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

grid

col

row

type

val

pad_left

pad_top

pad_right

pad_bottom

anchor

flags

반환값

값을 반환하지 않습니다.



newt_grid_simple_window

(PECL newt >= 0.1)

newt_grid_simple_window

설명

resource newt_grid_simple_window ( resource $text , resource $middle , resource $buttons )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

text

middle

buttons

반환값



newt_grid_v_close_stacked

(PECL newt >= 0.1)

newt_grid_v_close_stacked

설명

resource newt_grid_v_close_stacked ( int $element1_type , resource $element1 [, int $... [, resource $... ]] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

element1_type

element1

반환값



newt_grid_v_stacked

(PECL newt >= 0.1)

newt_grid_v_stacked

설명

resource newt_grid_v_stacked ( int $element1_type , resource $element1 [, int $... [, resource $... ]] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

element1_type

element1

반환값



newt_grid_wrapped_window_at

(PECL newt >= 0.1)

newt_grid_wrapped_window_at

설명

void newt_grid_wrapped_window_at ( resource $grid , string $title , int $left , int $top )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

grid

title

left

top

반환값

값을 반환하지 않습니다.



newt_grid_wrapped_window

(PECL newt >= 0.1)

newt_grid_wrapped_window

설명

void newt_grid_wrapped_window ( resource $grid , string $title )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

grid

title

반환값

값을 반환하지 않습니다.



newt_init

(PECL newt >= 0.1)

newt_initInitialize newt

설명

int newt_init ( void )

Initializes the newt interface. This function must be called before any other newt function.

반환값

Returns 1 on success, 0 on failure.

참고



newt_label_set_text

(PECL newt >= 0.1)

newt_label_set_text

설명

void newt_label_set_text ( resource $label , string $text )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

label

text

반환값

값을 반환하지 않습니다.



newt_label

(PECL newt >= 0.1)

newt_label

설명

resource newt_label ( int $left , int $top , string $text )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

left

top

text

반환값



newt_listbox_append_entry

(PECL newt >= 0.1)

newt_listbox_append_entry

설명

void newt_listbox_append_entry ( resource $listbox , string $text , mixed $data )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

listbox

text

data

반환값

값을 반환하지 않습니다.



newt_listbox_clear_selection

(PECL newt >= 0.1)

newt_listbox_clear_selection

설명

void newt_listbox_clear_selection ( resource $listbox )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

listbox

반환값

값을 반환하지 않습니다.



newt_listbox_clear

(PECL newt >= 0.1)

newt_listbox_clear

설명

void newt_listbox_clear ( resource $listobx )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

listobx

반환값

값을 반환하지 않습니다.



newt_listbox_delete_entry

(PECL newt >= 0.1)

newt_listbox_delete_entry

설명

void newt_listbox_delete_entry ( resource $listbox , mixed $key )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

listbox

key

반환값

값을 반환하지 않습니다.



newt_listbox_get_current

(PECL newt >= 0.1)

newt_listbox_get_current

설명

string newt_listbox_get_current ( resource $listbox )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

listbox

반환값



newt_listbox_get_selection

(PECL newt >= 0.1)

newt_listbox_get_selection

설명

array newt_listbox_get_selection ( resource $listbox )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

listbox

반환값



newt_listbox_insert_entry

(PECL newt >= 0.1)

newt_listbox_insert_entry

설명

void newt_listbox_insert_entry ( resource $listbox , string $text , mixed $data , mixed $key )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

listbox

text

data

key

반환값

값을 반환하지 않습니다.



newt_listbox_item_count

(PECL newt >= 0.1)

newt_listbox_item_count

설명

int newt_listbox_item_count ( resource $listbox )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

listbox

반환값



newt_listbox_select_item

(PECL newt >= 0.1)

newt_listbox_select_item

설명

void newt_listbox_select_item ( resource $listbox , mixed $key , int $sense )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

listbox

key

sense

반환값

값을 반환하지 않습니다.



newt_listbox_set_current_by_key

(PECL newt >= 0.1)

newt_listbox_set_current_by_key

설명

void newt_listbox_set_current_by_key ( resource $listbox , mixed $key )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

listbox

key

반환값

값을 반환하지 않습니다.



newt_listbox_set_current

(PECL newt >= 0.1)

newt_listbox_set_current

설명

void newt_listbox_set_current ( resource $listbox , int $num )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

listbox

num

반환값

값을 반환하지 않습니다.



newt_listbox_set_data

(PECL newt >= 0.1)

newt_listbox_set_data

설명

void newt_listbox_set_data ( resource $listbox , int $num , mixed $data )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

listbox

num

data

반환값

값을 반환하지 않습니다.



newt_listbox_set_entry

(PECL newt >= 0.1)

newt_listbox_set_entry

설명

void newt_listbox_set_entry ( resource $listbox , int $num , string $text )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

listbox

num

text

반환값

값을 반환하지 않습니다.



newt_listbox_set_width

(PECL newt >= 0.1)

newt_listbox_set_width

설명

void newt_listbox_set_width ( resource $listbox , int $width )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

listbox

width

반환값

값을 반환하지 않습니다.



newt_listbox

(PECL newt >= 0.1)

newt_listbox

설명

resource newt_listbox ( int $left , int $top , int $height [, int $flags ] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

left

top

height

flags

반환값



newt_listitem_get_data

(PECL newt >= 0.1)

newt_listitem_get_data

설명

mixed newt_listitem_get_data ( resource $item )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

item

반환값



newt_listitem_set

(PECL newt >= 0.1)

newt_listitem_set

설명

void newt_listitem_set ( resource $item , string $text )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

item

text

반환값

값을 반환하지 않습니다.



newt_listitem

(PECL newt >= 0.1)

newt_listitem

설명

resource newt_listitem ( int $left , int $top , string $text , bool $is_default , resouce $prev_item , mixed $data [, int $flags ] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

left

top

text

is_default

prev_item

data

flags

반환값



newt_open_window

(PECL newt >= 0.1)

newt_open_windowOpen a window of the specified size and position

설명

int newt_open_window ( int $left , int $top , int $width , int $height [, string $title ] )

Open a window of the specified size and position.

인수

left

Location of the upper left-hand corner of the window (column number)

top

Location of the upper left-hand corner of the window (row number)

width

Window width

height

Window height

title

Window title

반환값

Returns 1 on success, 0 on failure.

참고



newt_pop_help_line

(PECL newt >= 0.1)

newt_pop_help_lineReplaces the current help line with the one from the stack

설명

void newt_pop_help_line ( void )

Replaces the current help line with the one from the stack.

Note: It's important not to call to newt_pop_help_line() more than newt_push_help_line().

반환값

값을 반환하지 않습니다.

참고



newt_pop_window

(PECL newt >= 0.1)

newt_pop_windowRemoves the top window from the display

설명

void newt_pop_window ( void )

Removes the top window from the display, and redraws the display areas which the window overwrote.

반환값

값을 반환하지 않습니다.

참고



newt_push_help_line

(PECL newt >= 0.1)

newt_push_help_lineSaves the current help line on a stack, and displays the new line

설명

void newt_push_help_line ([ string $text ] )

Saves the current help line on a stack, and displays the new line.

인수

text

New help text message

Note: If not specified, the help line is cleared.

반환값

값을 반환하지 않습니다.

참고



newt_radio_get_current

(PECL newt >= 0.1)

newt_radio_get_current

설명

resource newt_radio_get_current ( resource $set_member )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

set_member

반환값



newt_radiobutton

(PECL newt >= 0.1)

newt_radiobutton

설명

resource newt_radiobutton ( int $left , int $top , string $text , bool $is_default [, resource $prev_button ] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

left

top

text

is_default

prev_button

반환값



newt_redraw_help_line

(PECL newt >= 0.1)

newt_redraw_help_line

설명

void newt_redraw_help_line ( void )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

반환값

값을 반환하지 않습니다.



newt_reflow_text

(PECL newt >= 0.1)

newt_reflow_text

설명

string newt_reflow_text ( string $text , int $width , int $flex_down , int $flex_up , int &$actual_width , int &$actual_height )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

text

width

flex_down

flex_up

actual_width

actual_height

반환값



newt_refresh

(PECL newt >= 0.1)

newt_refreshUpdates modified portions of the screen

설명

void newt_refresh ( void )

To increase performance, newt only updates the display when it needs to, not when the program tells it to write to the terminal. Applications can force newt to immediately update modified portions of the screen by calling this function.

반환값

값을 반환하지 않습니다.



newt_resize_screen

(PECL newt >= 0.1)

newt_resize_screen

설명

void newt_resize_screen ([ bool $redraw ] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

redraw

반환값

값을 반환하지 않습니다.



newt_resume

(PECL newt >= 0.1)

newt_resumeResume using the newt interface after calling newt_suspend()

설명

void newt_resume ( void )

Resume using the newt interface after calling newt_suspend().

반환값

값을 반환하지 않습니다.

참고

  • newt_suspend() - Tells newt to return the terminal to its initial state



newt_run_form

(PECL newt >= 0.1)

newt_run_formRuns a form

설명

resource newt_run_form ( resource $form )

This function runs the form passed to it.

인수

form

Form component

반환값

The component which caused the form to stop running.

Note: Notice that this function doesn't fit in with newt's normal naming convention. It is an older interface which will not work for all forms. It was left in newt only for legacy applications. It is a simpler interface than the new newt_form_run() though, and is still used quite often as a result. When an application is done with a form, it destroys the form and all of the components the form contains.

참고



newt_scale_set

(PECL newt >= 0.1)

newt_scale_set

설명

void newt_scale_set ( resource $scale , int $amount )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

scale

amount

반환값

값을 반환하지 않습니다.



newt_scale

(PECL newt >= 0.1)

newt_scale

설명

resource newt_scale ( int $left , int $top , int $width , int $full_value )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

left

top

width

full_value

반환값



newt_scrollbar_set

(PECL newt >= 0.1)

newt_scrollbar_set

설명

void newt_scrollbar_set ( resource $scrollbar , int $where , int $total )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

scrollbar

where

total

반환값

값을 반환하지 않습니다.



newt_set_help_callback

(PECL newt >= 0.1)

newt_set_help_callback

설명

void newt_set_help_callback ( mixed $function )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

function

반환값

값을 반환하지 않습니다.



newt_set_suspend_callback

(PECL newt >= 0.1)

newt_set_suspend_callbackSet a callback function which gets invoked when user presses the suspend key

설명

void newt_set_suspend_callback ( callback $function , mixed $data )

Set a callback function which gets invoked when user presses the suspend key (normally ^Z). If no suspend callback is registered, the suspend keystroke is ignored.

인수

function

A callback function, which accepts one argument: data

data

This data is been passed to the callback function

반환값

값을 반환하지 않습니다.

참고

  • newt_suspend() - Tells newt to return the terminal to its initial state
  • newt_resume() - Resume using the newt interface after calling newt_suspend



newt_suspend

(PECL newt >= 0.1)

newt_suspendTells newt to return the terminal to its initial state

설명

void newt_suspend ( void )

Tells newt to return the terminal to its initial state. Once this is done, the application can suspend itself (by sending itself a SIGTSTP, fork a child program, or do whatever else it likes).

반환값

값을 반환하지 않습니다.

참고

  • newt_resume() - Resume using the newt interface after calling newt_suspend



newt_textbox_get_num_lines

(PECL newt >= 0.1)

newt_textbox_get_num_lines

설명

int newt_textbox_get_num_lines ( resource $textbox )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

textbox

반환값



newt_textbox_reflowed

(PECL newt >= 0.1)

newt_textbox_reflowed

설명

resource newt_textbox_reflowed ( int $left , int $top , char $*text , int $width , int $flex_down , int $flex_up [, int $flags ] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

left

top

*text

width

flex_down

flex_up

flags

반환값



newt_textbox_set_height

(PECL newt >= 0.1)

newt_textbox_set_height

설명

void newt_textbox_set_height ( resource $textbox , int $height )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

textbox

height

반환값

값을 반환하지 않습니다.



newt_textbox_set_text

(PECL newt >= 0.1)

newt_textbox_set_text

설명

void newt_textbox_set_text ( resource $textbox , string $text )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

textbox

text

반환값

값을 반환하지 않습니다.



newt_textbox

(PECL newt >= 0.1)

newt_textbox

설명

resource newt_textbox ( int $left , int $top , int $width , int $height [, int $flags ] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

left

top

width

height

flags

반환값



newt_vertical_scrollbar

(PECL newt >= 0.1)

newt_vertical_scrollbar

설명

resource newt_vertical_scrollbar ( int $left , int $top , int $height [, int $normal_colorset [, int $thumb_colorset ]] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

left

top

height

normal_colorset

thumb_colorset

반환값



newt_wait_for_key

(PECL newt >= 0.1)

newt_wait_for_keyDoesn't return until a key has been pressed

설명

void newt_wait_for_key ( void )

This function doesn't return until a key has been pressed. The keystroke is then ignored. If a key is already in the terminal's buffer, this function discards a keystroke and returns immediately.

반환값

값을 반환하지 않습니다.

참고

  • newt_clear_key_buffer() - Discards the contents of the terminal's input buffer without waiting for additional input



newt_win_choice

(PECL newt >= 0.1)

newt_win_choice

설명

int newt_win_choice ( string $title , string $button1_text , string $button2_text , string $format [, mixed $args [, mixed $... ]] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

title

button1_text

button2_text

format

args

반환값



newt_win_entries

(PECL newt >= 0.1)

newt_win_entries

설명

int newt_win_entries ( string $title , string $text , int $suggested_width , int $flex_down , int $flex_up , int $data_width , array &$items , string $button1 [, string $... ] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

title

text

suggested_width

flex_down

flex_up

data_width

items

button1

button2

반환값

예제

Example #1 A newt_win_entries() example

<?php

newt_init
();
newt_cls();

$entries[] = array('text' => 'First name:''value' => &$f_name);
$entries[] = array('text' => 'Last name:',  'value' => &$l_name);

$rc newt_win_entries("User information""Please enter your credentials:"507730$entries"Ok""Back");
newt_finished ();

if (
$rc != 2) {
    echo 
"Your name is: $f_name $l_name\n";
}
?>



newt_win_menu

(PECL newt >= 0.1)

newt_win_menu

설명

int newt_win_menu ( string $title , string $text , int $suggestedWidth , int $flexDown , int $flexUp , int $maxListHeight , array $items , int &$listItem [, string $button1 [, string $... ]] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

title

text

suggestedWidth

flexDown

flexUp

maxListHeight

items

listItem

button1

반환값

값을 반환하지 않습니다.



newt_win_message

(PECL newt >= 0.1)

newt_win_message

설명

void newt_win_message ( string $title , string $button_text , string $format [, mixed $args [, mixed $... ]] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

title

button_text

format

args

반환값

값을 반환하지 않습니다.



newt_win_messagev

(PECL newt >= 0.1)

newt_win_messagev

설명

void newt_win_messagev ( string $title , string $button_text , string $format , array $args )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

title

button_text

format

args

반환값

값을 반환하지 않습니다.



newt_win_ternary

(PECL newt >= 0.1)

newt_win_ternary

설명

int newt_win_ternary ( string $title , string $button1_text , string $button2_text , string $button3_text , string $format [, mixed $args [, mixed $... ]] )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

title

Its description

button1_text

Its description

button2_text

Its description

button3_text

Its description

format

Its description

args

Its description

반환값

What the function returns, first on success, then on failure. See also the &return.success; entity


Table of Contents




Ncurses Terminal Screen Control


소개

ncurses (new curses) is a free software emulation of curses in System V Rel 4.0 (and above). It uses terminfo format, supports pads, colors, multiple highlights, form characters and function key mapping. Because of the interactive nature of this library, it will be of little use for writing Web applications, but may be useful when writing scripts meant using PHP from the command line.

The features available, such as colors, depend on the terminal that you are using. Use functions such as ncurses_has_colors(), ncurses_can_change_color(), and ncurses_has_ic() to check for individual capabilities.

Note: 이 확장은 » PECL 저장소로 옮겨졌으며, 더 이상 PHP로 제공되지 않습니다.5.3.0.

ncurses is available for the following platforms:

  • AIX
  • BeOS
  • BSD variants (FreeBSD, NetBSD, OpenBSD)
  • Cygwin
  • Digital Unix (aka OSF1)
  • GNU/Linux
  • HPUX
  • IRIX64
  • Mac OS X
  • OS/2
  • QNX
  • SCO OpenServer
  • Solaris
  • Tru64



설치/설정

Table of Contents


요구 조건

You need the ncurses libraries and headerfiles. Download the latest version from the » ftp://ftp.gnu.org/pub/gnu/ncurses/ or from an other GNU-Mirror.



설치

To get these functions to work, you have to compile the CGI or CLI version of PHP with --with-ncurses[=DIR].



실행시 설정

이 확장은 php.ini 설정이 존재하지 않습니다.



자원형

This extension defines window, panel and pad resources.




예약 상수

Table of Contents

이 확장은 다음의 상수들을 정의합니다. 이 확장을 PHP에 내장했거나, 실행시에 동적으로 읽어들일 경우에만 사용할 수 있습니다.


Error codes

On error ncurses functions return -1. Some functions return 0 on success. See the relevant pages in the documentation for actual return values.



Colors

ncurses color constants
constant meaning
NCURSES_COLOR_BLACK no color (black)
NCURSES_COLOR_WHITE white
NCURSES_COLOR_RED red - supported when terminal is in color mode
NCURSES_COLOR_GREEN green - supported when terminal is in color mode
NCURSES_COLOR_YELLOW yellow - supported when terminal is in color mode
NCURSES_COLOR_BLUE blue - supported when terminal is in color mode
NCURSES_COLOR_CYAN cyan - supported when terminal is in color mode
NCURSES_COLOR_MAGENTA magenta - supported when terminal is in color mode


Keys

ncurses key constants
constant meaning
NCURSES_KEY_F0 - NCURSES_KEY_F64 function keys F1 - F64
NCURSES_KEY_DOWN down arrow
NCURSES_KEY_UP up arrow
NCURSES_KEY_LEFT left arrow
NCURSES_KEY_RIGHT right arrow
NCURSES_KEY_HOME home key (upward+left arrow)
NCURSES_KEY_BACKSPACE backspace
NCURSES_KEY_DL delete line
NCURSES_KEY_IL insert line
NCURSES_KEY_DC delete character
NCURSES_KEY_IC insert char or enter insert mode
NCURSES_KEY_EIC exit insert char mode
NCURSES_KEY_CLEAR clear screen
NCURSES_KEY_EOS clear to end of screen
NCURSES_KEY_EOL clear to end of line
NCURSES_KEY_SF scroll one line forward
NCURSES_KEY_SR scroll one line backward
NCURSES_KEY_NPAGE next page
NCURSES_KEY_PPAGE previous page
NCURSES_KEY_STAB set tab
NCURSES_KEY_CTAB clear tab
NCURSES_KEY_CATAB clear all tabs
NCURSES_KEY_SRESET soft (partial) reset
NCURSES_KEY_RESET reset or hard reset
NCURSES_KEY_PRINT print
NCURSES_KEY_LL lower left
NCURSES_KEY_A1 upper left of keypad
NCURSES_KEY_A3 upper right of keypad
NCURSES_KEY_B2 center of keypad
NCURSES_KEY_C1 lower left of keypad
NCURSES_KEY_C3 lower right of keypad
NCURSES_KEY_BTAB back tab
NCURSES_KEY_BEG beginning
NCURSES_KEY_CANCEL cancel
NCURSES_KEY_CLOSE close
NCURSES_KEY_COMMAND cmd (command)
NCURSES_KEY_COPY copy
NCURSES_KEY_CREATE create
NCURSES_KEY_END end
NCURSES_KEY_EXIT exit
NCURSES_KEY_FIND find
NCURSES_KEY_HELP help
NCURSES_KEY_MARK mark
NCURSES_KEY_MESSAGE message
NCURSES_KEY_MOVE move
NCURSES_KEY_NEXT next
NCURSES_KEY_OPEN open
NCURSES_KEY_OPTIONS options
NCURSES_KEY_PREVIOUS previous
NCURSES_KEY_REDO redo
NCURSES_KEY_REFERENCE ref (reference)
NCURSES_KEY_REFRESH refresh
NCURSES_KEY_REPLACE replace
NCURSES_KEY_RESTART restart
NCURSES_KEY_RESUME resume
NCURSES_KEY_SAVE save
NCURSES_KEY_SBEG shiftet beg (beginning)
NCURSES_KEY_SCANCEL shifted cancel
NCURSES_KEY_SCOMMAND shifted command
NCURSES_KEY_SCOPY shifted copy
NCURSES_KEY_SCREATE shifted create
NCURSES_KEY_SDC shifted delete char
NCURSES_KEY_SDL shifted delete line
NCURSES_KEY_SELECT select
NCURSES_KEY_SEND shifted end
NCURSES_KEY_SEOL shifted end of line
NCURSES_KEY_SEXIT shifted exit
NCURSES_KEY_SFIND shifted find
NCURSES_KEY_SHELP shifted help
NCURSES_KEY_SHOME shifted home
NCURSES_KEY_SIC shifted input
NCURSES_KEY_SLEFT shifted left arrow
NCURSES_KEY_SMESSAGE shifted message
NCURSES_KEY_SMOVE shifted move
NCURSES_KEY_SNEXT shifted next
NCURSES_KEY_SOPTIONS shifted options
NCURSES_KEY_SPREVIOUS shifted previous
NCURSES_KEY_SPRINT shifted print
NCURSES_KEY_SREDO shifted redo
NCURSES_KEY_SREPLACE shifted replace
NCURSES_KEY_SRIGHT shifted right arrow
NCURSES_KEY_SRSUME shifted resume
NCURSES_KEY_SSAVE shifted save
NCURSES_KEY_SSUSPEND shifted suspend
NCURSES_KEY_UNDO undo
NCURSES_KEY_MOUSE mouse event has occurred
NCURSES_KEY_MAX maximum key value


Mouse

mouse constants
Constant meaning
NCURSES_BUTTON1_RELEASED - NCURSES_BUTTON4_RELEASED button (1-4) released
NCURSES_BUTTON1_PRESSED - NCURSES_BUTTON4_PRESSED button (1-4) pressed
NCURSES_BUTTON1_CLICKED - NCURSES_BUTTON4_CLICKED button (1-4) clicked
NCURSES_BUTTON1_DOUBLE_CLICKED - NCURSES_BUTTON4_DOUBLE_CLICKED button (1-4) double clicked
NCURSES_BUTTON1_TRIPLE_CLICKED - NCURSES_BUTTON4_TRIPLE_CLICKED button (1-4) triple clicked
NCURSES_BUTTON_CTRL ctrl pressed during click
NCURSES_BUTTON_SHIFT shift pressed during click
NCURSES_BUTTON_ALT alt pressed during click
NCURSES_ALL_MOUSE_EVENTS report all mouse events
NCURSES_REPORT_MOUSE_POSITION report mouse position



Ncurses 함수 목록


ncurses_addch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addchAdd character at current position and advance cursor

설명

int ncurses_addch ( int $ch )
Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

ch



ncurses_addchnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addchnstrAdd attributed string with specified length at current position

설명

int ncurses_addchnstr ( string $s , int $n )
Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

s

n



ncurses_addchstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addchstrAdd attributed string at current position

설명

int ncurses_addchstr ( string $s )
Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

s



ncurses_addnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addnstrAdd string with specified length at current position

설명

int ncurses_addnstr ( string $s , int $n )
Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

s

n



ncurses_addstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addstrOutput text at current position

설명

int ncurses_addstr ( string $text )
Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

text



ncurses_assume_default_colors

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_assume_default_colorsDefine default colors for color 0

설명

int ncurses_assume_default_colors ( int $fg , int $bg )
Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

fg

bg



ncurses_attroff

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_attroffTurn off the given attributes

설명

int ncurses_attroff ( int $attributes )
Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

attributes



ncurses_attron

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_attronTurn on the given attributes

설명

int ncurses_attron ( int $attributes )
Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

attributes



ncurses_attrset

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_attrsetSet given attributes

설명

int ncurses_attrset ( int $attributes )
Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

attributes



ncurses_baudrate

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_baudrateReturns baudrate of terminal

설명

int ncurses_baudrate ( void )
Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.



ncurses_beep

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_beepLet the terminal beep

설명

int ncurses_beep ( void )
Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

ncurses_beep() sends an audible alert (bell) and if its not possible flashes the screen.

참고



ncurses_bkgd

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_bkgdSet background property for terminal screen

설명

int ncurses_bkgd ( int $attrchar )
Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

attrchar



ncurses_bkgdset

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_bkgdsetControl screen background

설명

void ncurses_bkgdset ( int $attrchar )
Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

attrchar



ncurses_border

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_borderDraw a border around the screen using attributed characters

설명

int ncurses_border ( int $left , int $right , int $top , int $bottom , int $tl_corner , int $tr_corner , int $bl_corner , int $br_corner )
Warning

이 함수는 실험적입니다. 이 함수의 작동, 함수의 이름, 그리고 관련된 모든 문서는 이후의 PHP 릴리즈에서 예고 없이 변경할 수 있습니다. 이 함수의 사용에 관한 것은 사용자 책임입니다.

Draws the specified lines and corners around the main window.

Use ncurses_wborder() for borders around subwindows!

인수

Every parameter expects 0 to draw a line or 1 to skip it.

left

right

top

bottom

tl_corner

Top left corner

tr_corner

Top right corner

bl_corner

Bottom left corner

br_corner

Bottom right corner

참고



ncurses_bottom_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_bottom_panelMoves a visible panel to the bottom of the stack

설명

int ncurses_bottom_panel ( resource $panel )
Warning

이 함수는 현재 문서화 되어있지 않습니다; 인수 목록만을 제공합니다.

인수

panel



ncurses_can_change_color

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_can_change_colorChecks if terminal color definitions can be changed

설명

bool ncurses_can_change_color ( void )

Checks whether the terminal has color capabilities and whether the programmer can change color definitions using