Podręcznik PHP

Stig Sæther Bakken
Alexander Aulbach
Egon Schmid
Jim Winstead
Lars Torben Wilson
Rasmus Lerdorf
Andrei Zmievski
Jouni Ahto

Redakcja:

Stig Sæther Bakken
Egon Schmid
Leszek Krupiński
Sławomir Pucia
Tomasz Wójtowicz
Paweł Paprota
Adam Major

14-02-2002

Copyright

Prawa autorskie do tego podręcznika © Copyright 1997, 1998, 1999, 2000, 2001, 2002 należą do PHP Documentation Group. Lista członków grupy znajduje się na pierwszej stronie podręcznika.

Podręcznik może być dystrybuowany zgodnie z warunkami licencji GNU General Public License opublikowanej przez Free Software Foundation; Licencja w wersji 2 lub (do wyboru) dowolnej późniejszej.


Spis treści
Przedmowa
I. Na początek
1. Wprowadzenie
2. Instalacja
3. Konfiguracja
4. Security
II. Opis języka
5. Podstawowa składnia
6. Types
7. Zmienne
8. Stałe
9. Wyrażenia
10. Operatory
11. Control Structures
12. Funkcje
13. Klasy i Obiekty
14. References Explained
III. Możliwości
15. Error Handling
16. Tworzenie i manipulacja obrazkami
17. Autoryzacja HTTP w PHP
18. Ciasteczka (cookies)
19. Handling file uploads
20. Korzystanie ze zdalnych plików
21. Obsługa połączeń
22. Stałe połączenia z bazami danych
23. Tryb bezpieczny
IV. Opis funkcji
I. Apache
II. Tablice
III. Aspell [przestarzałe]
IV. BCMath Operacje arytmetyczne na liczbach o dużej precyzji
V. Bzip2 Compression Functions
VI. Calendar functions
VII. CCVS API Functions
VIII. COM support functions for Windows
IX. Class/Object Functions
X. ClibPDF functions
XI. Crack functions
XII. CURL, Client URL Library Functions
XIII. Cybercash payment functions
XIV. Crédit Mutuel CyberMUT functions
XV. Cyrus IMAP administration functions
XVI. Character type functions
XVII. Database (dbm-style) abstraction layer functions
XVIII. Date and Time functions
XIX. dBase functions
XX. DBM Functions
XXI. dbx functions
XXII. DB++ Functions
XXIII. Direct IO functions
XXIV. Directory functions
XXV. DOM XML functions
XXVI. .NET functions
XXVII. Error Handling and Logging Functions
XXVIII. FrontBase Functions
XXIX. filePro functions
XXX. System plików
XXXI. Forms Data Format functions
XXXII. FriBiDi functions
XXXIII. FTP
XXXIV. Function Handling functions
XXXV. Gettext
XXXVI. GMP functions
XXXVII. HTTP
XXXVIII. Hyperwave functions
XXXIX. ICAP Functions [deprecated]
XL. iconv
XLI. Image functions
XLII. IMAP, POP3 and NNTP functions
XLIII. Informix functions
XLIV. InterBase functions
XLV. Ingres II functions
XLVI. IRC Gateway Functions
XLVII. Java
XLVIII. LDAP functions
XLIX. Poczta elektroniczna
L. mailparse functions
LI. Matematyka
LII. Multi-Byte String Functions
LIII. MCAL functions
LIV. Mcrypt Encryption Functions
LV. Mhash Functions
LVI. Microsoft SQL Server functions
LVII. Ming functions for Flash
LVIII. Miscellaneous functions
LIX. mnoGoSearch Functions
LX. mSQL functions
LXI. MySQL
LXII. Mohawk Software session handler functions
LXIII. muscat functions
LXIV. Network Functions
LXV. Ncurses terminal screen control functions
LXVI. Lotus Notes functions
LXVII. Unified ODBC functions
LXVIII. Oracle 8 functions
LXIX. OpenSSL functions
LXX. Oracle functions
LXXI. Ovrimos SQL functions
LXXII. Output Control Functions
LXXIII. Object property and method call overloading
LXXIV. PDF functions
LXXV. Verisign Payflow Pro functions
LXXVI. PHP Options&Information
LXXVII. POSIX functions
LXXVIII. PostgreSQL functions
LXXIX. Process Control Functions
LXXX. Program Execution functions
LXXXI. Printer functions
LXXXII. Pspell Functions
LXXXIII. GNU Readline
LXXXIV. GNU Recode functions
LXXXV. Regular Expression Functions (Perl-Compatible)
LXXXVI. qtdom functions
LXXXVII. Regular Expression Functions (POSIX Extended)
LXXXVIII. Semaphore and Shared Memory Functions
LXXXIX. SESAM database functions
XC. Sesje
XCI. Shared Memory Functions
XCII. Shockwave Flash functions
XCIII. SNMP functions
XCIV. Socket functions
XCV. String functions
XCVI. Sybase functions
XCVII. URL
XCVIII. Variable Functions
XCIX. vpopmail functions
C. W32api functions
CI. WDDX Functions
CII. XML parser functions
CIII. XMLRPC functions
CIV. XSLT functions
CV. YAZ functions
CVI. YP/NIS Functions
CVII. Zip File Functions (Read Only Access)
CVIII. Zlib Compression Functions
V. Extending PHP 4.0
24. Overview
25. Extension Possibilities
26. Source Layout
27. PHP's Automatic Build System
28. Creating Extensions
29. Using Extensions
30. Troubleshooting
31. Source Discussion
32. Accepting Arguments
33. Creating Variables
34. Duplicating Variable Contents: The Copy Constructor
35. Returning Values
36. Printing Information
37. Startup and Shutdown Functions
38. Calling User Functions
39. Initialization File Support
40. Where to Go from Here
41. Reference: Some Configuration Macros
42. API Macros
VI. FAQ: Frequently Asked Questions
43. General Information
44. Mailing lists
45. Obtaining PHP
46. Database issues
47. Installation
48. Build Problems
49. Using PHP
50. PHP and HTML
51. PHP and COM
52. PHP and other languages
53. Migracja z PHP 2 na PHP 3
54. Migracja z PHP 3 na PHP 4
55. Miscellaneous Questions
VII. Dodatki
A. History of PHP and related projects
B. Using PHP from the command line
C. Migrating from PHP 3 to PHP 4
D. Migrating from PHP/FI 2 to PHP 3
E. Debugging PHP
F. Extending PHP 3
G. Lista Aliasów Funkcji
H. Lista Zarezerwowanych Słów
I. List of Resource Types
J. About the manual
K. missing stuff

Przedmowa

PHP, skrót od "PHP: Hypertext Preprocessor", jest zagnieżdżonym w HTML językiem skryptowym tworzonym na zasadach open-source. Większość jego składni pochodzi z języków C, Java i Perl. Ponadto dodano kilka unikalnych cech specyficznych dla PHP. Celem tego języka, jest umożliwienie twórcom serwisów WWW szybkiego pisania dynamicznych stron, jednak PHP potrafi znacznie więcej.

Podręcznik zawiera przede wszystkim dokumentację funkcji, ale również opis samego języka, omówienie jego możliwości i inne dodatkowe informacje.

Możesz ściągnąć ten podręcznik w kilku formatach ze strony http://www.php.net/docs.php. Pliki są aktualizowane po każdej zmianie zawartości podręcznika. Więcej informacji na temat powstawania dokumentacji możesz znaleźć w dodatku 'O podręczniku'.

I. Na początek


Rozdział 1. Wprowadzenie

Czym jest PHP?

PHP (akronim rekursywny "PHP: Hypertext Preprocessor") jest zagnieżdżonym w HTML jezykiem skryptowym działającym po stronie serwera tworzonym na zasadach open-source.

Prosta odpowiedź, ale co to znaczy? Przykład:

Przykład 1-1. Wprowadzający przykład

<html>
    <head>
        <title>Przykład</title>
    </head>
    <body>
        <?php echo "Cześć! Jestem skryptem PHP!"; ?>
    </body>
</html>

Zauważ jak bardzo różni się to od skryptów pisanych w innych językach, takich jak C czy Perl -- zamiast pisać program, zawierający mnóstwo komend tylko do wypisania HTML, piszesz kod HTML zawierający troche zagnieżdżonego kodu, który robi coś konkretnego (w powyższym przypadku wypisuje jakiś tekst). Kod PHP jest zawarty pomiędzy specjalnymi znacznikami otwierającymi i zamykającymi które pozwalają na wchodzenie do i wychodzenie z "trybu PHP".

PHP różni się od skryptów wykonywanych po stronie klienta takich jak np. JavaScript tym, że cały kod PHP wykonywany jest na serwerze. Jeśli masz na serwerze skrypt podobny do przedstawionego wyżej, klient dostanie tylko rezultat wykonania skryptu, bez możliwości stwierdzenia jak wygląda generujący go kod. Możesz nawet skonfigurować serwer WWW, tak aby wszystkie pliki HTML były przetwarzane przez PHP. A wtedy nie ma sposobu, aby użytkownik mógł stwierdzić jakie asy trzymasz w rękawie.

Najlepszą rzeczą w używaniu PHP jest to, że jest bardzo łatwy w opanowaniu dla początkującego, ale oferuje także wiele zaawansowanych właściwości zaawansowanym programistom. Nie bój się przeglądając długą listę możliwości PHP. PHP można się szybko nauczyć i już po kilku godzinach pisać proste skrypty.

Pomimo że PHP jest rozwijane pod kątem skryptowania server-side, może on znacznie więcej. Przeczytaj rozdział Co potrafi PHP aby uzyskać więcej informacji.


Co potrafi PHP?

Wszystko. PHP jest rozwijane pod kątem pisania skryptów server-side, więc możesz zrobić wszystko co potrafią inne programy CGI, jak na przykład odbierać dane z formularzy, generować dynamicznie zawartość strony, lub odbierać i wysyłać ciasteczka. Ale PHP może o wiele więcej.

Istnieją trzy główne pola użytkowania skryptów PHP.

  • Pisanie skryptów server-side. Jest to najbardziej tradycyjne i główne pole działania PHP. Potrzebujesz 3 rzeczy aby to robić: parser PHP (plik wykonywalny CGI lub moduł serwera), serwer WWW i przeglądarka. Musisz uruchomić serwer WWW połączony z PHP. Dane wyjściowe programów PHP możesz oglądać kożystając z przeglądarki poprzez serwer. Zobacz rozdział Instalacja aby uzyskać więcej informacji.

  • Pisanie skryptów uruchamianych z linii poleceń. Moższ napisać skrypt PHP i uruchomić go bez serwera i przeglądarki. Potrzebujesz do tego tylko parsera PHP. Ten typ użytkowania jest idealny do uruchamiania skryptów regularnie poprzez crona (lub menedżer zadań na Windowsach), lub przetwarzania tekstu. Zobacz rozdział Użytkowanie PHP z linii poleceń aby uzyskać więcej informacji.

  • Pisanie aplikacji client-side z interfejsem użytkownika. PHP jest prawdopodobnie nienajlepszym językiem do pisania okienkowych aplikacji, ale jeśli bardzo dobrze znasz PHP i chcesz skorzystać z zaawansowanych możliwości PHP w swojej aplikacji client-side, możesz także użyć pakiet PHP-GTK do pisania takich programów. Z PHP-GTK Masz także możliwość pisania aplikacji wieloplatformowych. PHP-GTK jest rozszerzeniem PHP i nie jest dostępne w głównej dystrybucji. Jeśli jesteś zainteresowany PHP-GTK, odwiedź stronę domową projektu.

PHP może być także użyty w większości najważniejszych systemów operacyjnych, takich jak Linux, wiele wariantów systemu Unix (włączając w to HP-UX, Solaris i OpenBSD), Microsoft Windows, Mac OS X, RISC OS i prawdopodobnie wiele innych. PHP w chwili obecnej obsługuje większość serwerów HTTP, włączając w to Apache, Microsoft Internet Information Server, Personal Web Server, serwery Netscape i iPlanet, Oreilly Website Pro, Caudium, Xitami, OmniHTTPd i wiele innych. Dla więszości z nich PHP dostępne jest jako moduły serwera, dla pozostałych jako program CGI. PHP może pracować jako procesor CGI.

A więc z PHP istnieje wolnośc wyboru systemu operacyjnego i serwera WWW. Można także wybrać pomiędzy programowaniem proceduralnym a obiektowym, lub pomieszaniem ich obu. Pomimo że nie wszystkie standardy OOP są obsługiwane w PHP, wiele bibliotek i dużych aplikacji (włączając w to biblioteki PEAR) jest napisanych całkowicie w sposób obiektowy.

W PHP nie ma ograniczenia, że na wyjściu musi być HTML. Możliwości PHP obejmują tworzenie obrazów, plików PDF, a nawet animacji Flash (używając libswf i Ming) generowanych "w locie". Możesz także wyprowadzać na wyjście dowolne dane tekstowe, jak na przykład XHTML czy dowolny inny plik XMLowy. PHP może autogenerować te pliki i zapisywać je w systemie plików zamiast wysyłać je na wyjście, tworząc pamięć podręczną dla twojej dynamicznej zawartości.

Jedną z najmocniejszych i najbardziej znaczących możliwości PHP jest obsługa wielu rodzajów baz danych. Pisanie strony WWW wykorzystującej bazę danych jest niewiarygodnie proste. Obecnie obsługiwane są następujące bazy danych:

Adabas DIngresOracle (OCI7 i OCI8)
dBaseInterBaseOvrimos
EmpressFrontBasePostgreSQL
FilePro (tylko do odczytu)mSQLSolid
HyperwaveDirect MS-SQLSybase
IBM DB2MySQLVelocis
InformixODBCUnix dbm

Istenieje także abstrakcyjne rozszerzenie DBX pozwalające na przezroczyste używanie dowolnej bazy danych obsługiwanych przez to rozszerzenie. Dodatkowo PHP obsługuje standard ODBC (Open Database Connection), przez co możesz połączyć się do dowolnej innej bazy danych obsługującej ten popularny standard.

PHP obsługuje również inne serwisy używające protokołów takich jak IMAP, SNMP, NNTP, POP3, HTTP, COM (pod systemami Windows) i wiele innych. Możesz także otwierać surowe gniazda sieciowe i korzystać z innych protokołów. PHP obsługuje WDDX - kompleksowy model wymiany danych pomiędzy praktycznie wszystkimi sieciowymi językami programowania. PHP obsługuje także obiekty Java i może korzystać z nich przezroczyście - tak jak z obiektów PHP. Możesz także skorzystać z rozszerzenia Corba aby użyskać dostęp do zdalnych obiektów.

PHP mam niezwykle przydatne możliwości do obróbki tekstów, od POSIX'owych i PERL'owych wyrażeń regularnych po parsowanie dokumentów XML. Do parsowania i uzyskiwania dostępu do dokumentów XML wykorzystywane są standardy SAX i XML. Możesz także użyć naszych rozszerzeń XSLT do przetwarzania dokumentów XML.

PHP może być używane w sferze e-commerce, ponieważ obsługuje płatności Cybercash, a także funkcje CyberMUT, Verisign Payflow Pro i CCVS, przydatne przy płatnościach on-line.

Na koniec warto wspomnieć, że w PHP istnieje wiele innych interesujących rozszerzeń, takich jak funkcje przeszykiwawcze mnoGoSearch, funkcje bramki IRC, wiele narzędzi do kompresji (gzip, bz2), konwersji kalendarza, tłumaczeń...

To co widać na tej stronie, to nie jest wszystko co ma do zaoferowanie PHP. Przeczytaj rozdział o instalacji i zobacz przegląd funkcji jeśli chcesz dowiedzieć się więcej o rozszerzeniach tutaj wspomnianych.


Rozdział 2. Instalacja

Ogólnie o instalacji

Przed instalacją musisz wiedzieć do czego potrzebne ci jest PHP. PHP jest używane głównie w trzech polach, tak jak to zostało opisane w rozdziale Co potrafi PHP?:

  • skrypty po stronie serwera

  • skrypty wywoływane z linii poleceń

  • aplikacje po stronie klienta

Dla pierwszej pozycji w najbardziej popularnej postaci potrzebne są trzy rzeczy: samo PHP, serwer WWW i przeglądarka internetowa. Najprawdopodobniej posiadasz już przeglądarkę, i zależnie od systemu operacyjnego także serwer (np. Apache na systemach Linux lub IIS na systemach Windows). Możesz także wynająć przestrzeń na serwerze komercyjnym. Tym sposobem nie musisz niczego własnoręcznie konfigurować, a jedynie pisać skrypty, umieszczać je na serwerze i oglądać wyniki w oknie przeglądarki. Listę firm hostujących możesz znaleźć pod adresem http://hosts.php.net/.

Własnoręcznie konfigurując serwer i PHP masz dwie możliwości połączenia PHP z serwerem. Dla wielu serwerów PHP posiada bezpośredni interfejs modułu (zwany także SAPI). Do tych serwerów należą Apache, Microsoft Internet Information Server, Nestscape i iPlanet. Wiele innych serwerów jest obsługiwane przez ISAPI, interfejs modułów Microsoft (na przykład OmniHTTPd). Jeśli PHP nie ma obsługi modułowej dla twojego serwera, możesz używać go jako procesor CGI. Oznacza to, że możesz skonfigurować twój serwer tak, aby korzystał z pliku wykonywalnego PHP (php.exe na systemach Windows) do przetwarzania wszystkich plików PHP dostępnych na serwerze.

Jeśli jesteś zainteresowany używanie PHP do pisania skryptów wywoływanych z linii poleceń (np. pisania skryptów do automatycznego generowania off-line obrazów dla ciebie lub przetwarzania plików tekstowych zależnie od przekazanych argumentów), potrzebujesz pliku wykonywalnego PHP. Aby uzyskać więcej informacji przeczytaj rozdział Pisanie aplikacji PHP wywoływanych z linii poleceń. W tym przypadku nie potrzebujesz ani serwera ani przeglądarki.

W PHP możesz pisać także aplikacje z interfejsem użytkownika używając rozszerzenia PHP-GTK. Jest to podejście zupełnie inne niż tworzenie stron internetowych, ponieważ nie wysyłasz żadnego wyjścia HTMLowego, ale obsługujesz okienka i obiekty w nich zawarte. Aby uzyskać więcej informacji o PHP-GTK, odwiedź stronę poświęconą temu rozszerzeniu. PHP-GTK nie jest zawarte w oficjalnej dystrybucji PHP.

Od tego miejsca rozdział dotyczy konfiguracji PHP z serwerami WWW pracującymi pod kontrolą systemów Unix i Windows w postaci modułów serwera lub binariów CGI.

Kod źródlowy oraz binarne dystrybucje na niektóre platformy (w tym Windows), można znaleźć na stronie http://www.php.net/. Zalecane jest korzystanie z jednego z mirrorów aby pobierać dane z jak najbliższego serwera.


Instalacja na systemach UNIXowych

Ten rozdział poprowadzi Cię przez konfigurację i instalację PHP na systemach UNIXowych. Przeczytaj wszystkie informacje dotyczące konkretnie twojej platformy zanim zaczniesz proces instalacji.

Wymagana wiedza i oprogramowanie:

  • Podstawowa znajomość UNIXa (znajomość polecenia "make" i kompilatora C)

  • Kompilator ANSI C (jeśli masz zamiar kompilować)

  • flex (do kompilacji)

  • bison (do kompilacji)

  • Serwer WWW

  • Komponenty wymagane przez poszczególne moduły (takie jak biblioteki gd, pdf, itp.)

Jest kilka sposobów instalacji PHP na platformach UNIXowych, włączając w to te z kompilacją i konfiguracją, i te poprzez metody pakietowe. Ta dokumentacja skupia się na procesie kompilacji i konfiguracji PHP.

Początkowy proces konfiguracji jest kontrolowany przez użycie opcji linii poleceń skryptu configure. Ta strona podkreśla sposób użycia najbardziej popularnych opcji, ale jest ich o wiele więcej. Zobacz Kompletną listę opcji konfiguracji. Jest kilka sposobów instalacji PHP:


Instruckcja szybkiej instalacji jako moduł Apache'a

PHP może być skompilowane na wiele sposobów, ale najbardziej popularna jest kompilacja jako moduł serwera Apache. Poniżej znajduje się skrócony opis procesu instalacji PHP can be compiled in a number of different ways, but one of the most popular is as an Apache module. The following is a quick installation overview.

Przykład 2-1. Instrukcja szubkiej instalacji PHP 4 (jako moduł Apache'a)

1.  gunzip apache_1.3.x.tar.gz
2.  tar xvf apache_1.3.x.tar
3.  gunzip php-x.x.x.tar.gz
4.  tar xvf php-x.x.x.tar
5.  cd apache_1.3.x
6.  ./configure --prefix=/www
7.  cd ../php-x.x.x
8.  ./configure --with-mysql --with-apache=../apache_1.3.x --enable-track-vars
9.  make
10. make install
11. cd ../apache_1.3.x
12. ./configure --activate-module=src/modules/php4/libphp4.a
13. make
14. make install
15. cd ../php-x.x.x
16. cp php.ini-dist /usr/local/lib/php.ini
17. Wyedytuj plik httpd.conf lub srm.conf i dodaj: 
      AddType application/x-httpd-php .php

18. Zrestartuj serwer. (Musisz zatrzymać i ponownie uruchomiś serwer, a nie
tylko wymusić przeładowanie serwera przez wysłanie sygnału HUP lub USR1.)

Budowanie

Kiedy PHP jest skonfigurowane, możesz przystąpić do budowania pliku wykonywalnego CGI. Polecenie make powinno się tym zająć. Jeśli wystąpią jakieś błędy, zobacz rozdział Problemy.


Instalacja na systemie Unix/Linux

Ten rozdział zawiera wskazówki dotyczące instalacji PHP na dystrybucjach Linuksowych.


Używanie pakietów

Wiele dystrybucji Linuksa zawiera instalatory pakietowe, takie jak RPM. Może to pomóc przy standardowej instalacji, lecz jeśli potrzebujesz mieć różny zestaw opcji (takich jak bezbieczny serwer lub sterownik do innej bazy danych), możesz potrzebować przebudowania PHP i/lub serwera WWW. Jeśli nie jesteś zaznajomiony z budowaniem i kompilacją własnego oprogramowania, warto jest sprawdzić, czy ktoś inny nie zrobił już pakietu PHP z opcjami których potrzebujesz.


Instalacja na systemie Unix/HP-UX

Ta sekcja zawiera wskazówki dotyczące instalacji PHP na systemach HP-UX.

Przykład 2-2. Instrukcja instalacji dla HP-UX 10

From: paul_mckay@clearwater-it.co.uk
04-Jan-2001 09:49
(Te wskazówki dotyczą PHP 4.0.4 i Apache v1.3.9)

A więc chcesz zainstalować PHP i Apache na HP-UX 10.20?

1. Potrzbujesz gzip'a, pobierz pakiet binarny z
http://hpux.connect.org.uk/ftp/hpux/Gnu/gzip-1.2.4a/gzip-1.2.4a-sd-10.20.depot.Z
zdekompresuj plik i zainstaluj używając swinstall

2. Potrzebujesz gcc, pobierz pakiet binarny z
http://gatekeep.cs.utah.edu/ftp/hpux/Gnu/gcc-2.95.2/gcc-2.95.2-sd-10.20.depot.gz 
zdekompresuj plik i zainstaluj gcc używając swinstall.

3. Potrzbujesz GNU binutils, pobierz pakiet binarny z
http://hpux.connect.org.uk/ftp/hpux/Gnu/binutils-2.9.1/binutils-2.9.1-sd-10.20.depot.gz 
zdekompresuj plik i zainstaluj używając swinstall.

4. Potrzbujesz bison'a, pobierz pakiet binarny z
http://hpux.connect.org.uk/ftp/hpux/Gnu/bison-1.28/bison-1.28-sd-10.20.depot.gz 
zainstaluj jw.

5. Potrzbujesz flex'a, możesz pobrać źródła z jednego z mirrorów
http://www.gnu.org. Znajduje się on w katalogu <filename>non-gnu</filename> na
serwerze ftp. Pobierz plik, zdekompresuj a potem wykonaj na nim polecenie tar
-xvf. Wejdź do nowop utworzonego katalogu flex'a a wykonaj polecenia
./configure, make a na koniec make install.

Jeśli wystąpiły błędy to prawdopodobnie dlatego że gcc lub coś podobnego nie
jest w jednym z katalogów zawartych w zmiennej PATH.

Teraz ta cięższa część.

6. Pobierz źródła PHP i Apache.

7. Zdekompresuj i wykonaj na nich polecenie tar -xzf

Potrzebne jest kilka poprawek w plikach aby poprawnie się skompilowały.

8. Najpierw trzeba poprawić plik configure, ponieważ wydaje się że ten skrypt
gubi informację, że kompilacja przebiega na maszynie hpux. Są lepsze sposoby
na poprawienie tego, ale szybciej i łatwiej jest wstawić 
    lt_target=hpux10.20 
do linii 47286 skryptu confugre.

9. Później poprawić w Apache plik GuessOS. W pliku
apache_1.3.9/src/helpers zmień linię 89 z 
    "echo "hp${HPUXMACH}-hpux${HPUXVER}"; exit 0" 
na: 
    "echo "hp${HPUXMACH}-hp-hpux${HPUXVER}"; exit 0" 
    
10. Na HP-UX nie można zainstalować PHP jako obiekt współdzielony, a więc musi
być wkompilowany statycznie, tak jak to opisano w instrukcji na stronie
Apache.

11. PHP i Apache powinno się bez problemu skompilować, ale Apache się nie
uruchomi. Niezbędne jest stworzenie nowego użytkownika dla Apache'a, np. www
lub apache. Teraz zmień linie 252 i 253 pliku conf/httpd.conf z
    User nobody 
    Group nogroup 
na:
    User www 
    Group sys 

Jest to niezbędne, ponieważ na hp-ux Apache nie może pracować jako użytkownik
nobody. Po tych poprawkach Apache i PHP powinny działać.

Mam nadzieję, że to komuś pomogło,
Paul Mckay.

Instalacja na systemie Unix/Solaris

Ten rozdział zawiera wskazówki dotyczące instalacji PHP na systemach Solaris.


Wymagane oprogramowanie

W systemach Solaris często brakuje kompilatorów C i związanych z nim narzędzi. Wymagane jest następujące oprogramowanie:

  • gcc (zalecane, inne kompilatory C mogą działać)

  • make

  • flex

  • bison

  • m4

  • autoconf

  • automake

  • perl

  • gzip

  • tar

Dodatkowo musisz zainstalować (i prawdopodobnie skompilować) dodatkowe oprogramowanie specyficzne dla twojej konfiguracji, takie jak Oracle lub MySQL.


Używanie pakietów

Możesz uprościć instalację pod systemem Solaris używając pkgadd aby zainstalować większość wymaganych komponentów.


Instalacja na systemie Unix/OpenBSD

Ten rozdział zawiera wskazówki dotyczące instalacji PHP na systemach OpenBSD.


Używanie systemu Port

Jest to zalecany sposób instalacji PHP na systemach OpenBSD, ponieważ tak zainstalowane oprogramowanie będzie zawierało najnowsze łaty i poprawki bezpieczeństwa nałożone przez maintainerów. Aby użyć tej metody, upewnij się że masz najnowsze drzewo portów. Później poprostu wybierz opcje z których chcesz skorzystać ('flavours') i wydaj polecenie make install. Poniżej znajduje się przykład jak to zrobić.

Przykład 2-3. Przykład instalacji OpenBSD Ports

$ cd /usr/ports/www/php4
$ make show VARNAME=FLAVORS
 (choose which flavors you want from the list)
$ env FLAVOR="imap gettext ldap mysql gd" make install
$ /usr/local/sbin/php4-enable

Używanie pakietów

Są to prekompilowane pakiety dostępne dla twojej wersji OpenBSD. Są one zintegrowane z wersją zainstalowanego Apache. Jednakże z powodu dużej liczby opcji (zwanych flavours - smaki), łatwiej jest skompilować PHP ze źródeł używając drzewa portów. Przeczytaj stronę podręcznika systemowego packages(7) aby uzyskać więcej informacji o dostępnych pakietach.


Instalacja na systemie Unix/Mac OS X

Ten rozdział zawiera wskazówki dotyczące instalacji PHP na systemach Mac OS X Server.


Używanie pakietów

Jest kilka wstępnie spakowanych i wstępnie skompilowanych wersji PHP dla Mac OS X. Może to pomóc przy korzystaniu ze standardowej konfiguracji, ale jeśli potrzebujesz niestandardowych opcji (takich jak bezpieczny serwer lub driver do innej bazy danych), możesz potrzebować własnoręcznie przebudować PHP i/lub serwer WWW. Jeśli nie jesteś zaznajomiony z budowaniem i kompilacją własnego oprogramowania, warto jest sprawdzić czy ktoś już nie przygotował pakietu PHP z opcjami których potrzebujesz.


Kompilacja na systemie OS X server

Są dwie nieznacznie różne wersja Mac OS X, client i server. Poniższe instrukcje dotyczą OS X Server.

Przykład 2-4. Instalacja na systemie Mac OS X server

1. Pobierz najnowsze dystrybucje Apache i PHP
2. Zdekompresuje je i uruchom program configure z pakietu Apache, np. tak:
    ./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 

4. Możesz także chcieć dodać linię
    setenv OPTIM=-O2 
    Jeśli chcesz aby kompilator dokonał pewnej optymalizacji kodu.
    
5. Póżniej, wejdź do katalogu ze źródłami PHP 4 i skonfiguruj je.
    ./configure --prefix=/usr \ 
    --sysconfdir=/etc \ 
    --localstatedir=/var \ 
    --mandir=/usr/share/man \ 
    --with-xml \ 
    --with-apache=/src/apache_1.3.12 

    Jeśli masz jakieś dodatki (MySQL, GD itp.), dodaj je tutaj. W linii
    '--with-apache' wstaw ścieżkę do katalogu ze źródłami Apache, na przykład
    "/src/apache_1.3.12". 
6. make
7. make install    
    To doda katalog src/modules/php4 do katalogu ze źródłami Apache.
    
8. Teraz, zrekonfiguruj Apache aby zbudował 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 

    Możesz dostać wiadomość mówiącą, że libmodphp4.a jest za stary. Jeśli tak
    się stanie, wejdź do katalogu src/modules/php4 znajdującego się wewnątrz
    katalogu ze źródłami Apache i wydaj to polecenie:

    ranlib libmodphp4.a 

    Potem wróć do katalogu głównego źródeł Apache'a i spróbuj jeszcze raz
    wydać polecenie configure takie jak wyżej. To uaktualni tablicę linków.

9. make

10. make install

11. skopiuj i zmień nazwę pliku php.ini-dist do katalogu "bin" z katalogu ze
źródłami PHP 4:
    cp php.ini-dist /usr/local/bin/php.ini 

    lub (jeśli nie masz katalogu "local")

    cp php.ini-dist /usr/bin/php.ini

Inne przykłady dla Mac OS X client i Mac OS X server są dostępne na Stepwise.


Kompilacja dla MacOS X client

Te wskazówki zostały przekazane przez Marca Liyanage.

Moduł PHP dla serwera WWW Apache został załączony w Mac OS X. Ta wersja zawiera obsługę baz danych MySQL i PostgreSQL.

UWAGA: Bądź ostrożny robiąc to, ponieważ możesz zepsuć swó serwer Apache.

Aby zainstalować:

  • 1. Otwórz okno terminala

  • 2. Napisz "wget http://www.diax.ch/users/liyanage/software/macosx/libphp4.so.gz", poczekaj aż skończy się pobieranie

  • 3. Napisz "gunzip libphp4.so.gz"

  • 4. Napisz "sudo apxs -i -a -n php4 libphp4.so"

Teraz napisz "sudo open -a TextEdit /etc/httpd/httpd.conf" Otworzy się TextEdit z plikiem konfiguracyjnym serwera WWW. Zlokalizuj linke na końcu pliku: (użyj polecenia Find)
*	#AddType application/x-httpd-php .php 
   *	#AddType application/x-httpd-php-source .phps
Usuń dwa znaki hash (#), a potem sapisz plik i wyjdź z programu TextEdit.

Na koniec, napisz "sudo apachectl graceful" aby zrestartować serwer.

PHP powinno teraz działać. Możesz przetestować je wrzucając plik test.php zawierający linię "<?php phpinfo() ?>" do foldera "Sites".

Teraz otwórz 127.0.0.1/~your_username/test.php w swoje przeglądarce WWW Powinieneś zobaczyć tabelkę informacyjną o module PHP.


Kompletna lista opcji konfiguracji

Notatka: Opcje te są podawane tylko w czasie kompilacji. Jeśli chcesz wpłynąć na konfigurację skompilowanego PHP, przeczytaj rozdział Konfiguracja.

Poniżej znajduje się kompletna lista opcji obsługiwanych przez skrypt configure dostarczany z PHP 3 i PHP 4, użytany przy kompilacji w środowiskach Uniksowych. Niektóre opcje są dostępne w PHP 3, niektóre w PHP 4, niektóre w obu - informacje na ten temat znajdują się w opisach opcji. Istnieje wiele opcji, których nazwy różnią się między PHP 3 a PHP 4, ale dotyczą tej samej rzeczy. Te wpisy zawierają odnośniki do siebie nawzajem, więc jeśli masz problem z funkcjonowaniem opcji konfiguracji przeniesionych z PHP 3, sprawdź czy nazwy się nie zmieniły.


Bazy danych

--with-adabas[=DIR]

PHP 3, PHP 4: Dołącz obsługę Adabas D. DIR jest katalogiem gdzie została zainstalowana baza Adabas, domyślnie /usr/local.

Strona domowa Adabas

--enable-dba=shared

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Buduj DBA jako obiekt współdzielony

--enable-dbx

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę DBX

--enable-dbase

PHP 3: Opcja niedostępna; zamiast tego użyj --with-dbase.

PHP 4: Dołącz wbudowaną bibliotekę dbase. Nie potrzebne są zewnętrzne biblioteki.

--with-dbase

PHP 3: Dołącz wbudowaną bibliotekę dbase. Nie potrzebne są zewnętrzne biblioteki.

PHP 4: Opcja niedostępna; zamiast tego użyj --enable-dbase.

--with-db2[=DIR]

PHP 3, PHP 4: Dołącz obsługę Berkeley DB2

--with-db3[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę Berkeley DB3

--with-dbm[=DIR]

PHP 3, PHP 4: Dołącz obsługę DBM

--with-dbmaker[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę DBMaker. DIR to katalog instalacji DBMakera domyślnie tam, gdzie została zainstalowana najnowsza wersja DBMakera (np /home/dbmaker/3.6).

--with-empress[=DIR]

PHP 3, PHP 4: Dołącz obsługę Empress. DIR to katalog instalacji Empress, domyślnie $EMPRESSPATH

--enable-filepro

PHP 3: Opcja niedostępna; zamiast tego użyj --with-filepro.

PHP 4: Dołącz wbudowaną odbsługę filePro (tylko do odczytu). Nie potrzebne są zewnętrzne biblioteki.

--with-filepro

PHP 3: Włącz wbudowaną obsługę filePro (tylko do odczytu). Nie potrzebne sa zewnętrzne biblioteki.

PHP 4: Opcja niedostępna; zamiast tego użyj --enable-filepro.

--with-fbsql[=DIR]

PHP 3: Opcja niedostępna.

PHP 4: Dołącz obsługę FrontBase SQL. DIR to katalog gdzie został zainstalowany FrontBase. Domyślny katalog zależy od systemu operacyjnego: Solaris: /opt/FrontBase, WinNT: \usr\FrontBase, Linux: /usr/frontbase, Mac OSX: /Library/FrontBase.

--with-gdbm[=DIR]

PHP 3, PHP 4: Dołącz obsługę GDBM

--with-hyperwave

PHP 3, PHP 4: Dołącz obsługę Hyperwave

--with-ibm-db2[=DIR]

PHP 3, PHP 4: Dołącz obsługę IBM DB2. DIR to katalog instalcji DB2, domyślnie /home/db2inst1/sqllib.

Strona domowa IBM DB2

--with-informix[=DIR]

PHP 3, PHP 4: Dołącz obsługę Informix. DIR to katalog gdzie został zainstalowany Informix. Brak wartości domyślnej.

--with-ingres[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę Ingres II. DIR to katalog instalacji Ingresa, domyślnie /II/ingres.

--with-interbase[=DIR]

PHP 3, PHP 4: Dołącz obsługę InterBase. DIR to katalog instalacji InterBase'a, domyślnie /usr/interbase.

Funkcje Interbase

Strona domowa Interbase

--with-ldap[=DIR]

PHP 3: Dołącz obsługę LDAP. DIR to katalog instalacji LDAP. Domyślnie /usr i /usr/local

PHP 4: Dołącz obsługę LDAP. DIR to katalog instalacji LDAP.

Parametr ten dołącza obsługę protokołu LDAP (Lightweight Directory Access Protocol). Parametrem jest katalog instalacji LDAP, domyślnie /usr/local/ldap.

Możesz znaleźć więcej informacji o LDAP w RFC1777 i RFC1778.

--with-msql[=DIR]

PHP 3, PHP 4: Dołącz obsługę mSQL. Parametrem tej opcji jest katalog instalacji mSQL, domyślnie /usr/local/Hughes. Jest to domyślne miejsce instalacji dystrybucji mSQL 2.0. configure automatycznie wykrywa która wersja mSWL jest zainstalowana - PHP wspiera obie wersje, 1.0 i 2.0, ale jeśli skompilujesz PHP z mSQL 1.0, możesz korzystać tylko z baz danych mSQL 1.0 i odwrotnie.

Patrz także dyrektywy Konfiguracji mSQL ustawiane w pliku konfiguracyjnym.

Strona domowa mSQL

--with-mysql[=DIR]

PHP 3: Dołącz obsługę MySQL. DIR to katalog instalacji MySQL. Domyślnie przeszukiwane są popularne miejsca instalacji MySQL.

PHP 4: Dołącz obsługę MySQL. DIR to katalog instalacji MySQL. Jeśli nie zostanie podany, użyte zostaną wbudowane biblioteki MySQL. Ta opcja jest domyślnie włączona.

Patrz także dyrektywy Konfiguracji MySQL ustawiane w pliku konfiguracyjnym.

Strona domowa MySQL

--with-ndbm[=DIR]

PHP 3, PHP 4: Dołącz obsługę NDBM

--with-ovrimos

PHP 3, PHP 4: Dołącz obsługę Ovrimos.

--with-oci8[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę Oracle-oci8. Domyślnie DIR to $ORACLE_HOME.

--with-oracle[=DIR]

PHP 3: Dołącz obsługę bazy danych Oracle. DIR to katalog domowy Oracle, domyślnie $ORACLE_HOME.

PHP 4: Dołącz obsługę bazy danych Oracle-oci7. Domyślnie DIR to $ORACLE_HOME.

Dołącza obsługę Oracle. Zostało ono przetestowane i powinno działać przynajmniej z wersjami Oracle 7.0 do 7.3. Parametrem jest katalog ORACLE_HOME. Nie musisz podawać tego parametru jeśli skonfigurowane zostało środowisko Oracle.

Strona domowa Oracle

--with-pgsql[=DIR]

PHP 3: Dołącz obsługę PostgreSQL. DIR to katalog instalacji PostgreSQL, domyślnie /usr/local/pgsql.

PHP 4: Dołącz obsługę PostgreSQL. DIR to katalog instalacji PostgreSQL, domyślnie /usr/local/pgsql. Ustaw DIR na "shared" aby zbudować jako obiekt dołączany dynamicznie (dl), lub "shared,DIR" aby zbudować jako dl i jednocześnie podać DIR.

Patrz także dyrektywy Konfiguracji PostgreSQL'a ustawiane w pliku konfiguracyjnym.

Strona domowa PostgreSQL

--with-solid[=DIR]

PHP 3, PHP 4: Dołącz obsługę Solid. DIR to katalog instalacji Solid, domyślnie /usr/local/solid

Strona domowa Solid

--with-sybase-ct[=DIR]

PHP 3, PHP 4: Dołącz obsługę Sybase-CT. DIR to katalog domowy Sybase, domyślnie /home/sybase.

Patrz także dyrektywy Konfiguracji Sybase-CT ustawiane w pliku konfiguracyjnym.

--with-sybase[=DIR]

PHP 3, PHP 4: Dołącz obsługę Sybase-DB. DIR to katalog domowy Sybase, domyślnie /home/sybase.

Patrz także dyrektywy Konfiguracji Sybase ustawiane w pliku konfiguracyjnym.

Strona domowa Sybase

--with-openlink[=DIR]

PHP 3, PHP 4: Dołącz obsługę OpenLink ODBC. DIR to katalog instalacji OpenLink, domyślnie /usr/local/openlink. Od wersji 4.0.6 PHP ta opcja konfiguracji nie jest ważna. Jeśli chcesz używać systemu ODBC firmy OpenLink Software, użyj opcji --with-iodbc.

Strona domowa OpenLink Software

--with-iodbc[=DIR]

PHP 3, PHP 4: Dołącz obsługę iODBC. DIR jest to katalog instalacji iODBC, domyślnie /usr/local.

Ta opcja została rozwinięta dla iODBC Driver Manager, darmowo rozpowszechnianego menedżera sterowników ODBC który działa na różnych odmianach Uniksa.

Strona domowa FreeODBC or Strona domowa iODBC

--with-custom-odbc[=DIR]

PHP 3, PHP 4: Dołącza obsługę niestandardowej biblioteki ODBC. Parametrem jest główny katalog biblioteki, domyślnie /usr/local.

Te opcja jest używana tylko jeśli zdefiniowałeś CUSTOM_ODBC_LIBS przy uruchomieniu skryptu configure. Niezbędne jest także wstawienie prawidłowego pliku odbc.h na ścieżkę include. Jeśli nie posiadasz takiego pliku, stwórz go i dołącz stamtąd swój własny nagłówek. Twój nagłówek może także wymagać pewnych definicji, zwłaszcza jeśli jest to biblioteka wieloplatformowa. Zdefiniuj je w CFLAGS.

Na przykład możesz używać Sybase SQL Anywhere na QNX w następujący sposób: CFLAGS=-DODBC_QNX LDFLAGS=-lunix CUSTOM_ODBC_LIBS="-ldblib -lodbc" ./configure --with-custom-odbc=/usr/lib/sqlany50

--disable-unified-odbc

PHP 3: Wyłącz zunifikowane obsługę ODBC. Opcja używana tylko jeśli włączona została obsługa iODBC, Adabas, Solid, Velocis lub niestandardowego interfejsu ODBC.

PHP 4: Opcja niedostępna w PHP 4

Moduł zunifikowanego ODBC jest wspólnym interfejsem do wszystkich baz danych z interfejsami opartymi na ODBC, takich jak Solid, IBM DB2 i Adabas D. Działa on także dla zwykłych bibliotek ODBC. Został przetestowany z iODBC, Solid, Adabas D, IBM DB2 i Sybase SQL Anywhere. Wymaga aby włączone było jedno (i tylko jedno) z tych rozszerzeń lub rozszerzenie Velocis, lub podana była niestandardowa biblioteka ODBC. Ta opcja jest używana tylko jeśli została użyta jedna z poniższych funkcji: --with-iodbc, --with-solid, --with-ibm-db2, --with-adabas, --with-velocis, lub --with-custom-odbc.

Patrz także dyrektywy Konfiguracji zunifikowanego ODBC ustawiane w pliku konfiguracyjnym.

--with-unixODBC[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę unixODBC. DIR to katalog instalacji unixODBC, domyślnie /usr/local.

--with-velocis[=DIR]

PHP 3, PHP 4: Dołącz obsługę Velocis. DIR to katalog instalacji Velocis, domyślnie /usr/local/velocis.

Strona domowa Velocis


E-commerce

--with-ccvs[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę CCVS. DIR to katalog instalacji CCVS.

--with-cybermut[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę Cybermut. DIR to katalog SDK Cybermuta, który zawiera plikilibcm-mac.a i cm-mac.h.

--with-mck[=DIR]

PHP 3: Dołącz obsługę Cybercash MCK. DIR to katalog budowania Cybercash mck, domyślnie /usr/src/mck-3.2.0.3-linux. Aby uzyskać więcej informacji zajrzyj do extra/cyberlib.

PHP 4: Opcja niedostępna; zamiast tego użyj --with-cybercash.

--with-cybercash[=DIR]

PHP 3: Opcja niedostępna; zamiast tego użyj --with-mck.

PHP 4: Dołącz obsługę CyberCash. DIR to katalog instalacji CyberCash MCK.

--with-pfpro[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę Verisign Payflow Pro


Grafika

--enable-freetype-4bit-antialias-hack

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę FreeType2 (eksperymentalne).

--with-gd[=DIR]

PHP 3: Dołącz obsługę GD (DIR to katalog instalacji GD).

PHP 4: Dołącz obsługę GD (DIR to katalog instalacji GD). Ustaw DIR jako "shared" aby zbudować rozszerzenie jako moduł współdzielony, lub "shared,DIR" aby zbudować rozszerzenie jako moduł i jednocześnie podać DIR.

--without-gd

PHP 3, PHP 4: Wyłącz obsługę GD.

--with-imagick[=DIR]

PHP 3: Dołącz obsługę ImageMagick. DIR to katalog instalacji ImageMagicka, domyślnie PHP próbuje znaleźć ten katalog na własną rękę. [eksperymentalne].

PHP 4: Opcja niedostępna w PHP 4

--with-jpeg-dir[=DIR]

PHP 3: Katalog jpeg dla pdflib 2.0

PHP 4: Katalog jpeg dla pdflib 3.x i 4.x

--with-png-dir[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Katalog png dla pdflib 3.x i 4.x

--enable-t1lib

PHP 3: Włącz obsługę t1lib.

PHP 4: Opcja niedostępna; zamiast tego użyj --with-t1lib.

--with-t1lib[=DIR]

PHP 3: Opcja niedostępna; zamiast tego użyj --enable-t1lib.

PHP 4: Dołącz obsługę T1lib.

--with-tiff-dir[=DIR]

PHP 3: Katalog tiff dla pdflib 2.0

PHP 4: Katalog tiff dla pdflib 3.x i 4.x

--with-ttf[=DIR]

PHP 3, PHP 4: Dołącz obsługę FreeType

--with-xpm-dir[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Katalog xpm dla gd-1.8+


Różne

Opcje te są w międzyczasie klasyfikowane.

--with-gmp

PHP 3, PHP 4 : Dołącz obsługę GMP.

--disable-bcmath

PHP 3: Skompiluj bez matematycznych funkcji BC dowolnej dokładności. Funkcje te pozwalają operować na liczbach wykraczających poza zakresy zwykłych liczb stało- i zmiennoprzecinkowych; zobacz see Funkcje Matematyczne Dowolnej Dokładności BCMath aby uzyskać więcej szczegółów.

PHP 4: Opcja niedostępna; bcmath nie jest domyślnie wkompilowywany. Użyj opcji --enable-bcmath aby go wkompilować.

--disable-display-source

PHP 3: Skompiluj bez obsługi pokazywania źródeł

PHP 4: Opcja niedostępna w PHP 4

--disable-libtool-lock

PHP 3: Opcja niedostępna w PHP 3

PHP 4: unikaj blokowania (może uszkodzić równoległe budowanie)

--disable-pear

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Nie instaluj PEAR

--disable-pic

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Wyłącz PIC dla obiektów współdzielonych

--disable-posix

PHP 3: Opcja niedostępna w PHP 3; zamiast tego użyj --without-posix.

PHP 4: Wyłącz funkcje POSIXowe.

--enable-pcntl

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Włącz funkcje kontroli procesów. (fork, waitpid, signal, itp.)

--disable-rpath

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Wyłącz przekazywanie dodatkowych ścieżek poszukiwania bibliotek

--disable-session

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Wyłącz obsługę sesji

--enable-bcmath

PHP 3: Opcja niedostępna w PHP 3; bcmath jest wkompilowywany domyślnie Użyj --disable-bcmath aby wyłączyć tą bibliotekę.

PHP 4: Kompiluj z funkcjami matematycznymi z dokładnością bc. Przeczytaj README-BCMATH aby uzyskać informacje jak zainstlować ten moduł. Te funkcje pozwalają operować na liczbach wykraczających poza zakresy dozwolone przez zwykłe liczby stało- i zmiennoprzecinkowe; przeczytaj Funkcje Matematyczne Dowolnej Dokładności BCMath aby uzyskac więcej informacji.

--enable-c9x-inline

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Włącz semantykę C9x-inline

--enable-calendar

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Włącz obsługę konwersji kalendarza

--enable-debug

PHP 3, PHP 4: Kompiluj z symbolami dla debuggera

--enable-debugger

PHP 3: Kompuluj z funkcjami zdalnego debugowania

PHP 4: Opcja niedostępna w PHP 4

--enable-discard-path

PHP 3, PHP 4: Jeśli ta opcja zostanie włączona, binaria CGI PHP mogą być bezpiecznie umieszczone poza drzewem serwera WWW i użytkownicy nie będą mogli obchodzi zabezpieczeń .htaccess.

--enable-dmalloc

PHP 3, PHP 4: Włącz dmalloc

--enable-exif

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Włącz obsługę exif

--enable-experimental-zts

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Ta opcja najprawdopodobniej przerwie proces budowania

--enable-fast-install[=PKGS]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: optymalizacja dla szybkiej instalacji [domyślnie=tak]

--enable-force-cgi-redirect

PHP 3, PHP 4: Włącz sprawdzanie bezpieczeństwa dla wewnętrznych przekierowań serwera. Powinieneś użyć tej opcji jeśli używasz wersji CGI z serwerem Apache.

--enable-inline-optimization

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Jeśli masz dużo pamięci i używasz gcc możesz spróbować włączyć tą opcję.

--enable-libgcc

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Włącz jawne linkowanie z libgcc

--enable-maintainer-mode

PHP 3, PHP 4: włącz reguły i zależności programu make nie przydatne (i czasem niejasne) dla zwykłego użytkownika

--enable-mbstr-enc-trans

PHP 4: włącz automatyczne wykrywanie wpisywanych znaków przez http i translację dla wielobajtowych kodowań znaków.

Ostrze¿enie

--enable-mbstring

PHP 4: włącz funkcje związane z wielobajtowym kodowaniem znaków.

Ostrze¿enie

Ta opcja dostępna jest w PHP od wersji 4.0.6.

--enable-memory-limit

PHP 3, PHP 4: Kompiluj z obsługą limitowania pamięci. [domyślnie=nie]

--enable-safe-mode

PHP 3, PHP 4: Włącz domyślną pracę w trybie bezpiecznym.

--enable-satellite

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Włącz obsługę CORBA przez Satellite (wymaga ORBit)

--enable-shared[=PKGS]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: buduj biblioteki współdzielone [domyślnie=tak]

--enable-sigchild

PHP 3, PHP 4: Włącz obsługę SIGCHLD przez PHP.

--enable-static[=PKGS]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: buduj statyczne biblioteki [domyślnie=tak]

--enable-sysvsem

PHP 3, PHP 4: Włącz obsługę semaforów System V.

--enable-sysvshm

PHP 3, PHP 4: Włącz obsługę pamięci dzielonej System V.

--enable-trans-sid

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Włącz przezroczyste propagowanie id sesji

--with-cdb[=DIR]

PHP 3, PHP 4: Dołącz obsługę CDB

--with-config-file-path=PATH

PHP 3: Ustawia ścieżkę gdzie powinien się znajdować plik php3.ini. Domyśnie /usr/local/lib

PHP 4: Ustawia ścieżkę gdzie powinien się znajdować plik php.ini. Domyślnie /usr/local/lib

--with-cpdflib[=DIR]

PHP 3: Dołącz obsługę ClibPDF. DIR to katalog instalacji ClibPDF, domyślnie /usr/local.

PHP 4: Dołącz obsługę cpdflib (wymaga cpdflib >= 2). DIR to katalog instalacji cpdflib, domyślnie /usr.

--with-esoob[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę Easysoft OOB. DIR to katalog instalacji OOB, domyślnie /usr/local/easysoft/oob/client.

--with-exec-dir[=DIR]

PHP 3, PHP 4: W trybie bezpiecznym pozwól na uruchamianie plików wykonywalnych tylko w DIR, domyślnie /usr/local/php/bin

--with-fdftk[=DIR]

PHP 3, PHP 4: Dołącz obsługę fdftk. DIR to katalog instalacji fdftk, domyślnie /usr/local.

--with-gnu-ld

PHP 3: Opcja niedostępna w PHP 3

PHP 4: załóż, że kompilator C używa GNU ld [domyślnie=nie]

--with-icap[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę ICAP.

--with-imap[=DIR]

PHP 3, PHP 4: Dołącz obsługę protokołu IMAP. DIR jest to katalog gdzie znajdują się pliki nagłówkowe IMAP i plik c-client.a.

--with-imsp[=DIR]

PHP 3: Dołącz wparcie dla IMSP. DIR to katalog gdzie znajdują się pliki nagłówkowe IMSP i plik libimsp.a.

PHP 4: Opcja niedostępna w PHP 4

--with-java[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę języka Java. DIR to katalog gdzie zainstalowane jest JDK. To rozszerzenie może być zbudowane tylko jako obiekt dynamicznie dołączany (dl).

--with-kerberos[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę Kerberosa w protokole IMAP.

--with-mcal[=DIR]

PHP 3, PHP 4: Dołącz obsługę MCAL.

--with-mcrypt[=DIR]

PHP 3, PHP 4: Dołącz obsługę mcrypt. DIR to katalog instalacji mcrypt.

--with-mhash[=DIR]

PHP 3, PHP 4: Dołącz obsługę mhash. DIR to katalog gdzie zainstalowano mhash.

--with-mm[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę mm do przechowywania sesji.

--with-mod_charset

PHP 3, PHP 4: Włącz transfer tablic dla mod_charset (Rosyjski Apache).

--with-pdflib[=DIR]

PHP 3: Dołącz obsługę pdflib (sprawdzone z 0.6 i 2.0). DIR to katalog instalacji pdflib, domyślnie /usr/local.

PHP 4: Dołącz obsługę pdflib 3.x/4.x. DIR to katalog instalacji pdflib, domyślnie /usr/local.

PHP 4 i PDFlib 3.x/4.x wymagają bibliotek JPEG i TIFF. Kompilując obsługę PDFlib użyj opcji --with-jpeg-dir i --with-tiff-dir. Możesz także użyć opcji --with-png-dir i --with-zlib-dir aby wkompilować obsługę PNG i Zlib do rozszerzenia PDFlib.

--enable-shared-pdflib

PHP 3, PHP 4: Aktywuj pdflib jako bibliotekę współdzieloną.

--with-readline[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę readline. DIR to katalog instalacji readline.

--with-regex=TYPE

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Typ biblioteki regex: system, apache, php

--with-servlet[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę serwletów. DIR to katalog instalacji JSDK. To SAPI wymaga, aby roszerzenie Java było zbudowane jako obiekt dynamicznie dołączany.

--with-ming

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę Flash 4 (Ming)

--with-swf[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę swf

--with-system-regex

PHP 3: Nie używaj wbudowanej biblioteki regex

PHP 4: (niezalecane) Użyj systemową bibliotekę regex.

--with-tsrm-pth[=pth-config]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Użyj GNU Pth.

--with-tsrm-pthreads

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Użyj wątków POSIX (domyślnie)

--with-x

PHP 3: użyj X Window System

PHP 4: Opcje niedostępna w PHP 4

--with-bz2[=DIR]

PHP 4: Dołącz obsługę bzip2. DIR to katalog instalacji bzip2.

--with-zlib-dir[=DIR]

PHP 3: Katalog zlib dla pdflib 2.0 lub dołącz obsługę zlib zlib dir for pdflib 2.0 or include zlib support

PHP 4: Katalog zlib dla pdflib 3.x/4.x lub dołącz obsługę zlib

--with-zlib[=DIR]

PHP 3, PHP 4: Dołącz obsługę zlib (wymaga zlib >= 1.0.9). DIR to katalog instalacji zlib, domyślnie /usr.

--with-zip[=DIR]

PHP 4: Dołącz obsługę zip (wymaga zziplib >= 0.10.6). DIR to katalog instalacji zziplib, domyślnie /usr/local.

Najnowsza wersja zziplib może być znaleziona pod adresem http://zziplib.sourceforge.net/.

--without-pcre-regex

PHP 3: Nie dołączaj obsługi Perl Compatible Regular Expressions (kompatybilne z perlem wyrażenia regularne)

PHP 4: Nie dołączaj obsługi Perl Compatible Regular Expressions. Użyj opcji --with-pcre-regex=DIR aby podać lokalizację plików nagłówkowych i bibliotek jeśli nie chcesz używać wbudowanej biblioteki.

--without-posix

PHP 3: Nie dołączaj funkcji POSIXowych

PHP 4: Opcja niedostępna w PHP 4; zamiast tego użyj --disable-posix.

--enable-overload

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Włącz obsługę przeciążania właściwości i metod obiektów.


Sieć

--with-curl[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę CURL

--enable-ftp

PHP 3: Opcja niedostępna; zamiast tegu użyj--with-ftp.

PHP 4: Włącz obsługę FTP

--with-ftp

PHP 3: Dołącz obsługę FTP.

PHP 4: Opcja niedostępna; zamiast tego użyj --enable-ftp.

--disable-url-fopen-wrapper

PHP 3, PHP 4: Wyłącz wrapper URL'i do polecenia fopen, który pozwala na dostęp do plików przez protokoły HTTP lub FTP.

Ostrze¿enie

Ten przełącznik jest dostępny w PHP w wersji 4.0.3 i starszych. Nowsze wersje zawierają parametr pliku konfiguracyjnego allow_url_fopen który znosi konieczność podejmowania decyzji przy kompilacji.

--with-mod-dav=DIR

PHP 3, PHP 4: Dołącz obsługę DAV poprzez moduł Apache'a mod_dav. DIR to katalog instalacji mod_dav (tylko wersja jako moduł Apache'a).

--with-openssl[=DIR]

PHP 3, PHP 4: Dołącz obsługę OpenSSL w SNMP.

--with-snmp[=DIR]

PHP 3, PHP 4: Dołącz obsługę SNMP. DIR to katalog instalacji SNMP, domyślnie przeszukuje wiele popularnych lokalizacji instalacji snmp. Ustaw DIR na 'shared' aby zbudować jako obiekt dynamicznie dołączany (dl), lub 'shared,DIR' aby zbudować jako dl i jednocześnie podać DIR.

--enable-ucd-snmp-hack

PHP 3, PHP 4: Włącz poprawkę UCD SNMP

--enable-sockets

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Włącz obsługę gniazd

--with-yaz[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę YAZ (ANSI/NISO Z39.50). DIR to katalog instalacji binariów YAZ.

--enable-yp

PHP 3: Opcja niedostępna; zamiast tego użyj --with-yp instead.

PHP 4: Dołącz obsługę YP

--with-yp

PHP 3: Dołącz obsługę YP

PHP 4: Opcja niedostępna; zamiast tego użyj --enable-yp.

--with-mnogosearch

PHP 3, PHP 4: Dołącz obsługę mnoGoSearch.


PHP Behaviour

--enable-magic-quotes

PHP 3, PHP 4: Włącz domyślnie "magic quotes".

--disable-short-tags

PHP 3, PHP 4: Wyłącz możliwość używania krótkiej formy tagów otwierających <?.

--enable-track-vars

PHP 3: Włącz domyślne śledzienie zmiennych GET/POST/Cookie.

PHP 4: Opcja niedostępna w PHP 4; od wersji PHP 4.0.2 opcja track_vars jest zawsze włączona.


Serwer

--with-aolserver-src=DIR

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Określ ścieżkę do źródłowej dystrybucji AOLserver

--with-aolserver=DIR

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Określ ścieżkę do zainstalego AOLserver

--with-apache[=DIR]

PHP 3, PHP 4: Zbuduj moduł Apache. DIR to katalog główny Apache, domyślnie /usr/local/etc/httpd.

--with-apxs[=FILE]

PHP 3, PHP 4: Zbuduj moduł współdzielony Apache. FILE to opcjonalna ścieżka do narzędzia apxs z pakietu Apache; domyślnie apxs.

--enable-versioning

PHP 3: Użyj wersjonowania i scoopingu które obsługuje Solaris 2.x i Linux.

PHP 4: Eksportuj tylko wymagane symbole. Przejrzyj plik INSTALL aby uzyskać więcej informacji.

--with-caudium[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Buduj PHP jako moduł Pike do użycia z serwerem Caudium. DIR to katalog instalacji Caudium, domyślnie $prefix/caudium/server. Prefix jest kontrolowany przez opcję --prefix, domyślnie /usr/local.

--with-fhttpd[=DIR]

PHP 3, PHP 4: Buduj moduł fhttpd. DIR to katalog ze źródłami fhttpd, domyślnie /usr/local/src/fhttpd.

--with-nsapi=DIR

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Określ ścieżkę do zainstalowanego Netscape

--with-phttpd=DIR

PHP 3: Opcja niedostępna w PHP 3

PHP 4:

--with-pi3web=DIR

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Buduj PHP jako moduł do użycia z Pi3Web.

--with-roxen=DIR

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Buduj PHP jako moduł Pike. DIR to katalog instalacji Roxen, zazwyczaj /usr/local/roxen/server.

--enable-roxen-zts

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Buduj moduł Roxen używając Zend Thread Safety ("Bezpieczeństwa Wątków Zend").

--with-thttpd=SRCDIR

PHP 3: Opcja niedostępna w PHP 3

PHP 4:

--with-zeus=DIR

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Buduj PHP jako moduł ISAPI do użycia z Zeus.


Teks i język

--with-aspell[=DIR]

PHP 3, PHP 4: Dołącz obsługę ASPELL.

--with-gettext[=DIR]

PHP 3, PHP 4: Dołącz obsługę GNU gettext. DIR to katalog instalacji gettext, domyślnie /usr/local.

--with-iconv[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę iconv.

--with-pspell[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę PSPELL.

--with-recode[=DIR]

PHP 3: Dołącz obsługę GNU recode.

PHP 4: Dołącz obsługę redcode. DIR to katalog instalacji redcode.

--enable-shmop

PHP 3, PHP 4 : Włącz obsługę shmop.


XML

--with-dom[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę DOM (wymaga libxml >= 2.0). DIR to katalog instalacji libxml, domyślnie /usr

--enable-sablot-errors-descriptive

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Włącz błędy opisowe.

--with-sablot[=DIR]

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Dołącz obsługę Sablotrona

--enable-wddx

PHP 3: Opcja niedostępna w PHP 3

PHP 4: Włącz obsługę WDDX

--disable-xml

PHP 3: Opcja niedostępna w PHP 3; funkcje XML nie są budowane domyśłnie. Użyj --with-xml aby je włączyć.

PHP 4: Wyłącz obsługę wbudowanej biblioteki XML expat

--with-xml

PHP 3: Dołącz obsługę XML

PHP 4: Opcje niedostępna; obsługa XML jest budowane domyślnie. Użyj opcji --disable-xml aby je wyłączyć.


Instalacja na systemach Windows

Ten rozdział dotyczy systemół Windows 95/98/Me i Windows NT/2000/XP. (Proces instalacji nie został sprawdzony na XP). Nie spodziewaj się, że PHP będzie działać na 16-bitowych platformach takich jak Windows 3.1. Czasem odnosimy się do obsługiwanych platform jako Win32

Są dwa główne sposoby instalacji PHP na Windowsach: albo ręcznie lub używając instalatora InstallShield.

Jeśli masz Microsoft Visual Studio, możesz budować PHP z orginalnego kodu źródłowego.

Jak już zainstalujesz PHP na systemie Windows możesz chceć dołączyć różne rozszerzenia aby zwiększyć funkcjonalność.


Windows InstallShield

Instalator PHP pod Windows jest dostępny pod adresem http://www.php.net/. Pakiet ten instaluje PHP i, w przypadku IIS, PWS i Xitami, także konfiguruje serwer WWW. Zauważ także, że pomimo że instalator InstallShield jest łatwym sposobem na zmuszenie PHP do pracy, ma on wiele ograniczeń, np. nie obsługuje automatycznego ustawienia rozszerzeń.

Zainstaluj wybrany serwer HTTP i upewnij się że on działa.

Uruchom instalator i wykonuj polecenia pojawiające się na ekranie. Dostępne są w rodzaje instalacji: standardowa, która ustawia domyślne opcje, i zaawansowana, która zadaje pytania podczas instalacji.

Instalator zbiera informacje niezbędne do ustawienia pliku php.ini i konfiguracji serwera WWW do użycia PHP. Dla serwera IIS a także PWS na NT Workstation, wyświetlana jest lista węzłów na serwerze z ustawieniami mapowania skryptów, z których możesz wybrać węzły do których chcesz dodać mapowania skryptów PHP.

Po procesie instalacji instalator poinformuje cię czy potrzebujesz zrestartować system, zrestartować serwer lub poprostu zacznij używać PHP.

Ostrze¿enie

Wiedz, że taki sposób instalacji PHP nie jest bezpieczny. Jeśli potrzebujesz bezpiecznego sposobu na instalację PHP, zrób to lepiej ręcznie, rozważnie dobierając każdą opcję. Instalator automatyczny daje ci od razu działające PHP, ale nie jest ono przeznaczone do pracy na serwerach produkcyjnych.


Ręczny proces instalacji

Ten przewodnik poprowadzi cię przez ręczną instalację i konfigurację PHP na serwerach WWW pracujących pod systemami Windows. Musisz pobrać pakiet binariów PHP ze strony http://www.php.net/. Orginalna wersja tego przewodnika została napisana przez Bob Silva i znaleźć ją można pod adresem http://www.umesd.k12.or.us/php/win32install.html.

Ten przewodnik opisuje proces ręcznej instalacji dla:

  • Personal Web Server 3 i 4 lub nowszy

  • Internet Information Server 3 i 4 lub nowszy

  • Apache 1.3.x

  • OmniHTTPd 2.0b1 i nowsze

  • Oreilly Website Pro

  • Xitami

  • Netscape Enterprise Server, iPlanet

PHP 4 dla Windows dostępny jest w dwóch postaciach: jako plik wykonywalny CGI (php.exe) lub jako kilka rodzajów modułów SAPI (na przykład php4isapi.dll). Ta druga postać jest nowością wprowadzoną w PHP 4 i wprowadza znacznie poprawioną wydajność i ulepszoną funkcjonalnoś.

Ostrze¿enie

Jednakże moduły SAPI NIE powinny być używane na produkcyjnych serwerach. Ogólnie mówiąc, moduły ISAPI mają poważne problemy z niezawodnością, zwłaszcza na platformach starszych niż W2K - możesz doświadczyc wielu błędów 500 serwera a także niestabilności innych modułów serwera, jak np. ASP. Zostałeś ostrzeżony!

Powodem jest to, że moduły PHP SAPI używają PHP w wersji z bezpiecznymi wątkami, co jest nowością w PHP 4 i nie zostało to na tyle przetestowane aby zostało uznane za stabilne, a do tego znaleziono już kilka błędów. Z drugiej strony, użytkownicy zgłaszali uzyskiwanie bardzo dobrych wyników z modułami SAPI, jednakże nie znamy nikogo używającego ich na produkcyjnym serwerze. Podsumowując: jeśli potrzebujesz absolutnej stabilności, zamień wydajność modułów SAPI na stabilność plików wykonywalnych CGI.

Jeśli wybierzesz jeden z modułów SAPI i używasz Windows 95, musisz uaktualnić DCOM ze stron Microsoft DCOM. Dla modułu ISAPI wymagany jest serwer WWW kompatybilny z ISAPI 4.0 (sprawdzone z IIS 4.0, PWS 4.0 i IIS 5.0). IIS 3.0 NIE jest obsługiwane; jeśli potrzebujesz natywnej obsługi PHP powinieneś zainstalować Windows NT 4.0 Option Pack z IIS 4.0.

Poniższe kroki powinny być wykonane przed intrukcjami dla konkretnego serwera.

  • Zdekompresuj plik dystrybucyjny do dowolnego katalogu, np. c:\php\.

  • Musisz się upewnić, że wszystkie DLLe których używa PHP mogą być przez niego znalezione. To, które DLLe są potrzebe zależy od tego, których rozszerzeń PHP używasz a także czy PHP jest skompilowane jako CGI czy jako moduł serwera. php4ts.dll jest używany zawsze. Jeśli używasz PHP w postaci modułu serwera (np. ISAPI lub Apache), to niezbędne są DLLe z katalogu sapi. Jeśli używasz DLLi rozszerzających PHP, one także będą potrzebne. Aby upewnić się że DLLe zostaną znalezione, przekopiuj je do katalogu systemowego (np. winnt/system32 lub windows/system) lub upewnij się że są w tym samym katalogu co główny plik wykonywalny PHP lub DLL twojego serwera WWW (np. php.exe, php4apache.dll).

    Binaria PHP, moduły SAPI i niektóre rozszerzenia opierają się na zewnętrznych bibliotekach DLL. Upewnij się, że dystrybucyjne DLLe znajdują się w jednym z katalogów przeszukiwanych przez Windows. Najlepiej jest przekopiować poniższe pliki do katalogu systemowego, którym jest zazwyczaj:

    c:\windows\system dla Windows 9x/Me
    c:\winnt\system32 dla Windows NT/2000

    Pliki dp przekopiowania to:

    'php4ts.dll', jeśli taki plik już istnieje, nadpisz go
    Pliki z katalogu 'dlls'. Jeśli te pliki są już zainstalowane w twoim systemie, nadpisz je tylko jeśli coś działa nie tak (przed napisaniem ich dobrze jest zrobić kopię zapasową, lub przenieść je do innego folderu - na wszelki wypadek).

    Pobierz najnowszą wersje Microsoft Data Access Components (MDAC) dla twojej platformy, zwłaszcza jeśli używasz Microsoft Windows 9x/NT4. MDAC jest dostępny pod adresem http://www.microsoft.com/data/ .

  • Skopiuj wybrany plik ini (zobacz niżej) do swojego katalogu '%WINDOWS%' na Windows 95/98 lub do katalogu '%SYSTEMROOT%' na Windows NT/2000/XP mień jego nazwę na php.ini. Twój katalog '%WINDOWS%' lub '%SYSTEMROOT%' to zazwyczaj:

    c:\windows na Windows 9x/Me
    c:\winnt lub c:\winnt40 na NT/2000/XP

    Plik dystrybucyjny zawiera dwa pliki ini, php.init-dist i php.ini-optimized. Zalecamy użycie pliku php.ini-optimized, ponieważ opcje zawarte w tym pliku są zoptymalizowane pod względem wydajności i bezpieczeństwa. Najlepiej jest przeczywać rozdział o opcjach inicjalizacyjnych i ustawić każdą opcję własnoręcznie. Jest to dobry sposób jeśli chcesz osiągnąć maksimum bezpieczeństwa, jednakże PHP działa dobrze z domyślnymi plikami ini.

  • Wyedytuj swój nowy plik 'php.ini':

    • Musisz zmienić parametr 'extension_dir' aby wskazywał na twój katalog instalacji PHP, lub tam gdzie umieściłeś pliki 'php_*.dll', np. c:\php\extensions

    • Jeśli używasz OmniHTTPd, nie wykonuj tego kroku. Ustaw 'doc_root' aby wskazywało na katalog dokumentów serwera, np. c:\apache\htdocs lub c:\webroot

    • Wybierz które rozszerzenia chciałbyś ładować kiedy PHP się uruchamia. Zobacz rozdział o Rozszerzeniach Windows , gdzie możesz znaleźć informacje jak włączyć te rozszerzenia i co jest już wbudowane w PHP. Dobrze jest zmusić do działania i przetestować nowo zainstalowane PHP jeszcze przed włączeniem rozszerzeń.

    • Na PWS i IIS możesz ustawić browscap.ini aby wskazywało na 'c:\windows\system\inetsrv\browscap.ini' na Windows 9x/Me lub 'c:\winnt\system32\inetsrv\browscap.ini' na NT/2000/XP.

    • Katalog mibs dostarczany z pakietem dystrybucyjnym dla systemu Windows zawiera pliki z obsługą SMTP. Katalog powinien być przeniesiony do NAPĘD:\usr\mibs (NAPĘD to napęd na którym zainstalowane jest PHP).


Budowanie ze źródeł

Przed rozpoczęciem warto jest odpowiedzieć sobie na pytanie: "Dlaczego budowanie pod Windowsem jest takie trudne?" Do głowy przechodzą dwie odpowiedzi:

  1. Nie ma dużej społeczności programistów lubiących Windows którzy chętnie dzielą się swoimi kodami źródłowymi. Bezpośrednim efektem jest to, że nie poniesione zostały niezbędne inwestycje w infrastrukturę wymaganą do rozwoju oprogramowania. Zasadniczo to co teraz jest dostępne, to niezbędne narzędzia przeniesione z systemu UNIX. Nie zdziw się, jeśli od czasu do czasu pokażą się takie dziedzictwo.

  2. Większosc poniższych instrukcji są w stylu "ustaw i zapomnij". A więc usiądź wygodnie i wykonuj polecenia tak dokładnie jak tylko możesz.


Przygotowania

Zanim zaczniesz, masz dużo rzeczy do pobrania...

  • Dla początkujących, pobierz zestaw Cygwin z najbliższego mirrora cygwin . Zestaw ten zawiera większość popularnych narzędzi GNU używanych w procesie budowania.

  • Pobierz resztę narzędzi niezbędnych do budowania z http://www.php.net/extra/win32build.zip.

  • Pobierz kod źródłowy reseolvera nazw DNS używanego przrz PHP z http://www.php.net/extra/bindlib_w32.zip. Jest to zamiennik biblioteki resolv.lib zawartej w win32build.zip.

  • Jeśli nie masz narzędzia unzip, musisz je pobrać. If you don't already have an unzip utility, you will need one. Darmowa wersja dostępna jest na InfoZip.

Na koniec, potrzebujesz źródeł samego PHP 4. Możesz pobrać najnowsze źródła korzystając z anonimowego serwera CVS. Jeśli pobierzesz plik typu tarball ze snapshotem lub źródłami, nie tylko będziesz musiał odpakować go tar'em i gzip'em, ale tekże skonwertować znaki końca linii w plikach *.dsp i *.dsw zanim Microsoft Visual C++ będzie w stanie cokolwiek z nimi zrobić.

Notatka: Umieść katalogi Zend i TSRM directories wewnątrz katalogu php4 aby w procesie budowania były znalezione przez projekty.


Składanie wszystkiego razem

  • Wykonaj poniższe instrukcje aby zainstalować narzędzie Cygwin.

  • Uruchom setup.exe i wykonuj polecenia instalatora. Jeśli wybierzesz ścieżkę instalacji inną niź c:\cygnus, poinformuj o tym proces budowania przez ustawienie zmiennej środowiskowej Cygwin. Pod systemem Windows 95/98 zmienne środowiskowe ustawia się przez dodawanie odpowiedniej linii do pliku autoexec.bat. Pod systemem Windows NT wejdź w Mój Komputer => Panel Sterowania => System i wybierz zakładkę Środowisko.

    Ostrze¿enie

    Stwórz tymczasowy katalog do użytku Cygwin. Bez niego wiele poleceń (zwłaszcza bison) nie będzie działać. Na Windows 95/98, mkdir C:\TMP. Na Windows NT, mkdir %SystemDrive%\tmp.

  • Stwórz katalog i odzipuj win32build.zip do niego.

  • Uruchom Microsoft Visual C++ i z menu wybierz Tools => Options. W oknie dialogowym wybierz zakładkę 'Directories'. Kolejno zmień listę rozwijaną na Executables, Includes, i Library files, aby się upewnić się, że cygwin\bin, win32build\include, i win32build\lib są na każdej liście. (Aby dodać wpis, wybierz pustą linię z końca listy i zacznij pisać). Zazwyczaj wpisy wyglądają tak:

    • c:\cygnus\bin

    • c:\php-win32build\include

    • c:\php-win32build\lib

    Wciśnij OK i wyjdź z Visual C++.

  • Stwórz kolejny katalog i odzipuj do niego bindlib_w32.zip . Zdecyduj się czy potrzebujesz symbole do debugowania (bindlib - Win32 Debug) czy nie (bindlib - Win32 Release). Zbuduj odpowiednią konfigurację:

    • Dla użytkowników GUI, uruchom VC++ a potem wybierz File => Open Workspace i wybierz bindlib. Potem wybierz Build=>Set Active Configuration i wybierz pożądaną konfigurację. Na koniec wybierz Build=>Rebuild All.

    • Dla użytkowników linii poleceń, upewnij się że zarejestrowałeś zmienne środowiskowe C++ lub uruchomiłeś vcvars.bat, a później wykonaj jedno z poniższych poleceń:

      • msdev bindlib.dsp /MAKE "bindlib - Win32 Debug"

      • msdev bindlib.dsp /MAKE "bindlib - Win32 Release"

    • W tym momencie powinieneś mieć gotowy do użytku resolv.lib w katalogu Debug lub Release. Skopiuj ten plik do katalogu win32build\lib nadpisując plik o tej samej nazwie który już tam istnieje.


Kompilacja

Najlepszy sposób na początek to zbudowanie wersji samodzielnej/CGI.

  • Dla użytkowników GUI, uruchom VC++, wybierz File => Open Workspace i wybierz php4ts. Później wybierz Build=>Set Active Configuration i wybierz pożądaną konfigurację. Na koniec wybierz Build=>Rebuild All.

  • Dla użytkowników linii poleceń, upewnij się że zarejestrowałeś zmienne środowiskowe C++ lub uruchomiłeś vcvars.bat, a później wykonaj jedno z poniższych poleceń:

    • msdev php4ts.dsp /MAKE "php4ts - Win32 Debug_TS"

    • msdev php4ts.dsp /MAKE "php4ts - Win32 Release_TS"

    • W tym momencie powinieneś mieć gotowy do użytku php.exe w katalogu Debug_TS lub Release_TS.

Powtórz powyższe kroki z plikiem php4isapi.dsp (który może być znaleziony w katalogu sapi\isapi) aby zbudować kod niezbędny dla Microsoft IIS.


Instalacja rozszerzeń dla Windows

Po zainstalowaniu PHP i serwera WWW na systemie Windows prawdobopodobnie będziesz chciał zainstalować różne rozszerzenia aby zwiększyć funkcjonalność PHP. Poniższa tabela opisuje niektóre dostępne rozszerzenia. Możesz wybrać które rozszerzenia chcesz załadować kiedy PHP jest uruchamiane poprzez odkomentowanie linii 'extension=php_*.dll' w pliku php.ini. Moduły możesz także dołączać dynamicznie w swoim skrypcie kożystając z funkcji dl().

Nazwy DLLi z rozszerzeniami PHP 4 zaczynają się od 'php_' ('php3_' w przypadku PHP 3). Zapobiega to pomieszaniu rozszerzeń PHP i wspierających je bibliotek.

Notatka: W PHP 4.0.6 obsługa BCMath, Calendar, COM, FTP, MySQL, ODBC, PCRE, Sesji, WDDX i XML jest wbudowana. Nie potrzbujesz ładować żadnych dodatkowych rozszerzeń aby korzystać z tych funkcji. Przeczytaj zawartość pliku README.txt lub install.txt aby uzyskać listę wbudowanych modułów.

Notatka: Niektóre z tych rozszerzeń potrzebują do pracy dodatkowych DLLi. Kilka z nich można znaleźć w pakiecie dystrybucyjnym, w katalogu 'dlls', ale dla niektórych, takich jak Oracle (php_oci8.dll), wymagane DLLe nie są dołączone do pakietu dystrybucyjnego.

Skopuj dołączone DLLe z katalogi 'dlls' do katalogu który przeszukije Windows. Dobrymi miejscami są:

c:\windows\system dla Windows 9x/Me
c:\winnt\system32 dla Windows NT/2000/XP

Jeśłi któreś z nich są już zainstalowane na twoim systemie, nadpisz je tylko jeśli coś nie działa w porządku (przed nadpisaniem ich dobrze jest zrobić kopię zapasową, lub przenieść je do innego folderu - na wszelki wypadek).

Tabela 2-1. Rozszerzenia PHP

RozszerzeniaOpisUwagi
php_bz2.dllbzip2 - funkcje kompresjiBrak
php_calendar.dllCalendar - funkcje konwersji kalendarzaWbudowane od PHP 4.0.3
php_cpdf.dllfunkcje ClibPDFBrak
php3_crypt.dllfunkcje CryptBrak
php_ctype.dllrodzina funcjictypeBrak
php_curl.dllCURL, Client URLWymaga: libeay32.dll, ssleay32.dll (dołączone do dystrybucji)
php_cybercash.dllfunkcje opłat CybercashBrak
php_db.dllfunkcje DBMNiezalecane. Zamiast tego użyj DBA (php_dba.dll)
php_dba.dllfunkcje DBA: DataBase (dbm-style) Abstraction LayerBrak
php_dbase.dllfunkcje dBaseBrak
php3_dbm.dllbiblioteka Berkeley DB2Brak
php_domxml.dllfunkcje DOM XMLWymaga: libxml2.dll (dołączony do dystrybucji)
php_dotnet.dllfunkcje .NETBrak
php_exif.dllnagłówki Read EXIF z JPEGBrak
php_fbsql.dllfunkcje FrontBaseBrak
php_fdf.dllfunkcje FDF: Forms Data FormatWymaga: fdftk.dll (dołączony do dystrybucji)
php_filepro.dllfunkcje fileProDostęp tylko do odczytu
php_ftp.dllfunkcje FTPWbudowane od PHP 4.0.3
php_gd.dllBiblioteka obróbki obrazów GDBrak
php_gettext.dllfunkcje GettextWymaga: gnu_gettext.dll (dołączony do dystrybucji)
php_hyperwave.dllfunkcje HyperWaveBrak
php_iconv.dllkonwersja tablicy znaków ICONVWymaga: iconv-1.3.dll (dołączony do dystrybucji)
php_ifx.dllfunkcje InformixWymaga: bibliotek Informix
php_iisfunc.dllfunkcje zarządzania IISBrak
php_imap.dllfunkcje IMAP, POP3 i NNTPPHP 3: php3_imap4r1.dll
php_ingres.dllfunkcje Ingres IIWymaga: bibliotek Ingres II
php_interbase.dllfunkcje InterBaseWymaga: gds32.dll (dołączony do dystrybucji)
php_java.dllrozszerzenie JavaWymaga: jvm.dll (dołączony do dystrybucji)
php_ldap.dllfunkcje LDAPWymaga: libsasl.dll (dołączony do dystrybucji)
php_mhash.dllfunkcje MhashBrak
php_ming.dllfunkcje Ming dla FlashaBrak
php_msql.dllfunkcje mSQLWymaga: msql.dll (dołączony do dystrybucji)
php3_msql1.dllklient mSQL 1Brak
php3_msql2.dllklient mSQL 2Brak
php_mssql.dllfunkcje MSSQLWymaga: ntwdblib.dll (dołączony do dystrybucji)
php3_mysql.dllfunkcje MySQLWbudowany w PHP 4
php3_nsmail.dllfunkcje poczty NetscapeBrak
php3_oci73.dllfunkcje OracleBrak
php_oci8.dllfunkcje Oracle 8Wymaga: biblioteki klienta Oracle 8
php_openssl.dllfunkcje OpenSSLWymaga: libeay32.dll (dołączony do dystrybucji)
php_oracle.dllfunkcje OracleWymaga: biblioteki klienta Oracle 7
php_pdf.dllfunkcje PDFBrak
php_pgsql.dllfunkcje PostgreSQLBrak
php_printer.dllfunkcje Drukarkibrak
php_sablot.dllfunkcje XSLTWymaga: sablot.dll (dołączony do dystrybucji)
php_snmp.dllfunkcje SNMPtylko NT!
php_sybase_ct.dllfunkcje SybaseWymaga: biblioteki klienta Sybase
php_yaz.dllfunkcje YAZBrak
php_zlib.dllfunkcje kompresji ZLibBrak


Serwery-Apache

Ten rozdział zawiera wskazówki dotyczące instalacji PHP z serwerem Apache, zarówno na systemach Unix i Windows.


Szczegóły instalacji PHP z Apache na systemach Unix.

Możesz wybrać parametry do dodania do configure w linii 8 z Kompletnej listy opcji konfiguracji.

Przykład 2-5. Instrukcja instalacji (wersja jako moduł Apache)

1.  gunzip apache_1.3.x.tar.gz
2.  tar xvf apache_1.3.x.tar
3.  gunzip php-x.x.x.tar.gz
4.  tar xvf php-x.x.x.tar
5.  cd apache_1.3.x
6.  ./configure --prefix=/www
7.  cd ../php-x.x.x
8.  ./configure --with-mysql --with-apache=../apache_1.3.x --enable-track-vars
9.  make
10. make install
11. cd ../apache_1.3.x
12. dla PHP 3: ./configure --activate-module=src/modules/php3/libphp3.a
    dla PHP 4: ./configure --activate-module=src/modules/php4/libphp4.a
13. make
14. make install

  Zamiast tego kroku możesz poprostu skopiować plik binarny httpd przebijając
  istniejący plik. Przedtem upewnij się, że serwer jest zastopowany.

15. cd ../php-x.x.x
16. dla PHP 3: cp php3.ini-dist /usr/local/lib/php3.ini
    dla PHP 4: cp php.ini-dist /usr/local/lib/php.ini

  Możesz wyedytować swój plik .ini aby ustawić opcje PHP. Jeśli
  chcesz użyć innej lokalizacji, użyj
  --with-config-file-path=/path w punkcie 8.

17. Wyedytuj swój plik httpd.conf lub srm.conf i dodaj:
      
     Dla PHP 3:   AddType application/x-httpd-php3 .php3
     Dla PHP 4:   AddType application/x-httpd-php .php
 
  W tym miejscu możesz wybrać dowolne rozszerzenie. .php jest tym sugerowanym.
  Możesz nawet użyć rozszerzenie .html .

18. Użyj zwykłej procedury dla uruchomienia serwera Apache. (Musisz zatrzymać
i ponownie uruchomić serwer, nie tylko spowodować przeładowanie serwera
używając sygnał HUP lub USR1.)

Zależnie od wersji Apache i rodzaju Uniksa, jest wiele możliwości aby zatrzymać i ponownie uruchomić serwer. Poniżej znajdują się typowe polecenia służące do reinstalacji serwera dla różnych wariantów Apache/Uniksa. Powinieneś zamienić /path/to/ na ścieżkę do właściwych aplikacji na swoich systemach.

1. Kilka wariantów Linuksa i SysV:
/etc/rc.d/init.d/httpd restart

2. Używając skrypty apachectl:
/path/to/apachectl stop
/path/to/apachectl start

3. httpdctl i httpsdctl (Używając OpenSSL), podobnie do apachectl:
/path/to/httpsdctl stop
/path/to/httpsdctl start

4. Używając mod_ssl, lub innego serwera SSL, możesz ręcznie zatrzymać i
uruchomnić serwer:
/path/to/apachectl stop
/path/to/apachectl startssl

Lokalizacje binariów apachectl i http(s)dctl mogą się różnić. Jeśli twój system ma polecenia locate lub whereis albo which, mogą one pomóc w szukaniu programów contrl serwera.

Różne przykłady kompilacji PHP dla Apache:

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

Stworzony zostanie współdzielona biblioteka libphp4.so które jest ładowana przez Apache używając linii LoadModule w pliku httpd.conf. W pliku libphp4.so zostanie zawarte wsparcie dla biblioteki PostgreSQL.

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

Tu także zostanie stworzona biblioteka współdzielona libphp4.so, ale zostanie stworzona także współdzielona biblioteka pgsql.so która może być załadowana do PHP używając dyrektywy 'extension' w pliku php.ini lub poprzez użycie w skrypcie funkcji dl().

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

Stworzona zostanie biblioteka libmodphp4.a, plik mod_php4.c i kilka dodatkowych plików, które zostaną skopiowane do katalogu src/modules/php4 który znajduje się w drzewie źródeł Apache. Potem skompiluj Apache używając --activate-module=src/modules/php4/libphp4.a a system budowania Apache stworzy libphp4.a który zostanie dołączony statycznie do pliku binarnego httpd. Obsługa PostgreSQLa zostanie włączona bezpośrednio do pliku binarnego httpd, a więc wynikiem będzie pojedyńczy plik binarny httpd który zawiera całe Apache i całe PHP.

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

To samo co powyżej, ale zamiast dołączania obsługi PostgreSQLL bezpośrednio do ostatecznego pliku httpd dostaniesz współdzieloną bibliotekę pgsql.so którą możesz załadować do PHP kożystając z pliku php.ini lub bezpośrednio używając dl().

Wybierając sposób budowania PHP powinieneś rozważyć wszystkie wady i zalety każdej metody. Budowanie jako obiekt współdzielony oznacza, że możesz kompilować osobno Apache i nie musisz rekompilować wszystkiego jeśli chcesz dodać lub zmienić PHP. Wbudowywanie PHP w Apache (metoda statyczna) oznacza, że PHP będzie się ładowało i uruchamiało szybciej. Aby uzyskać więcej informacji, zobacz stronę Apache na stronie wsparcia DSO.


Instalacja PHP na systemie Windows z Apache 1.3.x

Istnieją 2 sposoby aby skonfigurować PHP do pracy z Apache 1.3.x na systemie Windows. Pierwszy to wykorzystanie binariów CGI (php.exe), a drugi to użycie DLLa modułu Apache. W obu przypadkach musisz zatrzymać serwer Apache i wyedytować plik srm.conf lub httpd.conf aby przygotować Apache do pracy z PHP.

Pomimo że istnieje kilka sposobów konfiguracji PHP w Apache, te poniższe powinny wystarczyć każdemu początkującemu. Aby uzyskać więcej informacji o dyrektywach konfiguracyjnych przejrzyj dokumentację Apache'a.

Jeśłi odzipowałeś pakiet PHP do C:\php\ tak jak zostało to opisane w rozdziale Ręczny proces instalacji , musisz dodać do pliku konfiguracyjnego Apache te linie aby ustawić binaria CGI:

  • ScriptAlias /php/ "c:/php/"

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

  • Action application/x-httpd-php "/php/php.exe"

Druga z powyższych linii może znajdować się w aktualnych wersjach httpd.conf, ale jest wykomentowana. Po zmianie pliku konfiguracyjnego trzeba zrestartować serwer, na przykład NET STOP APACHE a potem NET START APACHE, jeśli uruchamiasz Apache jako Usługę Windows, lub użyj normalnych skrótów.

Jeśli chcesz używać PHP w postaci modułu Apache, upewnij się że plik php4ts.dll znajduje się w katalogu windws/system (dla Windows 9x/Me) lub winnt/system32 (dla Windows NT/2000/XP), nadpisując jakiekolwiek starsze pliki. Potem powinieneś dodać poniższe 2 linie do pliku konfiguracyjnego Apache:

  • LoadModule php4_module c:/php/sapi/php4apache.dll

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

Notatka: W Apache 1.3.22 dla Windows, domyślny plik konfiguracyjny (httpd.conf-dist-win) ma domyślnie dołączoną dyrektywę ClearModuleList. Jeśli ta dyrektywa znajduje się w pliku konfiguracyjnym, musisz dodać AddModule mod_php4.c do listy AddModule. W przeciwnym razie PHP nie będzie zarejestrowane jako moduł Apache.

Aby użyć opcji podświetlania kodu, po prostu stwórz skrypt PHP i wstaw do niego: <?php show_source ("original_php_script.php"); ?> . Zamień original_php_script.php na nazwę pliku którego źródło chcesz pokazać. (Jest to jedyny sposób na zrobienie tego, ponieważ pod systemem Windows nie ma opcji .phps).

Notatka: Na Win-Apache wszystkie znaki backslash ('\') w ścieżkach, jak na przykład "c:\directory\file.ext", muszą być zamienione na znaki slash ('/'), czyli "c:/directory/file.ext".


Serwery-CGI/Linia poleceń

Domyślnie PHP jest budowane jako program CGI. Jest to interpreter z linią poleceń, który może być użyty do przetwarzania CGI, lub skryptowania nie związanego z WWW. Jeśli twój serwer jest obsługiwany przez PHP w postaci modułu, powinieneś wybrać to rozwiązanie ze względu na wydajność. Jednakże wersja CGI umożliwia użytkownikom serwera Apache uruchamiać strony używające PHP z poziomu różnych użytkowników. Przeczytaj rozdział Bezpieczeństwo jeśli zamierzasz uruchomić PHP jako CGI.


Testowanie

Jeśli zbudowałeś PHP jako program CGI, możesz przetestować swoją wersję używając polecenia make test. Przetestowanie skompilowanej przez siebie wersji jest zasadniczo dobrym pomysłem. Test umożliwia wczesne wykrycie problemów z PHP, które mogłyby ujawnić się później.


Benchmarking

Jeśli zbudowałeś PHP 3 jako program CGI, możesz sprawdzić jego wydajność wydając polecenie make bench. Zauważ, że jeśli PHP działa domyślnie w Trybie Bezpiecznym, benchmark może się nie skończyć jeśli trwa więcej niż dozwolone 30 sekund. Dzieje się tak dlatego, że w trybie bezpiecznym nie można użyć funkcji set_time_limit(). Użyj opcji konfiguracji max_execution_time aby ustawić maksymalny czas wykonywania dla twoich skryptów. make bench ignoruje plik konfiguracyjny.

Notatka: make bench jest dostępne tylko dla PHP 3.


Serwery-fhttpd

Aby zbudować PHP jako moduł fhttpd, odpowiedz "yes" na pytanie "Build as an fhttpd module?" (opcja konfiguracji --with-fhttpd=DIR) i określ katalog z fhttpd. Domyślnym katalogiem jest /usr/local/src/fhttpd. Jeśli korzystasz z fhttpd, zbudowanie PHP jako moduł zwiększy wydajność, kontrolę i umożliwi zdalne uruchamianie.


Serwery-Caudium

PHP 4 może być zbudowane jako moduł Pike dla serwera Caudium. Zauważ, że ta opcja nie jest możliwa w PHP 3. Wypełnij poniższe instrukcje aby zainstalować PHP 4 dla Caudium.

Przykład 2-6. Instrukcje Instalacji dla Caudium

1.  Upewnij się, że Caudium zostało zainstalowane przed rozpoczęciem
    instalacji PHP 4. Aby PHP 4 działało prawidłowo, potrzebny jest Pike
    7.0.268 lub nowszy. Dla przykładu załóżmy, że Caudium jest zainstalowany w
    katalogu /opt/caudium/server/.
2.  Zmień katalog na php-x.y.z (gdzie x.y.z to numer wersji).
3.  ./configure --with-caudium=/opt/caudium/server
4.  make
5.  make install
6.  Zrestartuj Caudium jeśli aktualnie jest uruchomiony..
7.  Zaloguj się fo graficznego interfejsu konfiguracyjnego i przejdź do
    serwerów wirtualnych do których chcesz dodać obsługę PHP 4.
8.  Wybierz Add Module i znajdź i dodaj moduł PHP 4 Script Support.
9.  Jeśli w dokumentacji napisane jest 'PHP 4 interpreter isn't available',
    upewnij się, że zrestartowałeś serwer. Jeśli tak, sprawdź
    /opt/caudium/logs/debug/default.1 pod kątem błędów związanych z
    <filename>PHP4.so</filename>. Sprawdź także czy plik
    <filename>caudium/server/lib/[wersja-pike]/PHP4.so</filename> istnieje.
10. Skonfiguruj moduł PHP Script Support jeśli to konieczne.

Możesz oczywiście skompilować moduł Caudium z obsługą dla różnych rozszerzeń dostępnych w PHP 4. Zobacz kompletną listę opcji konfiguracji .

Notatka: Kompilując PHP 4 z obsługą MySQL musisz się upewnić, że użyty został normalny kod klienta MySQL. W przeciwnym przypadku mogą wystąpić konflikty jeśli Pike ma już obsługę MySQL'a. Robi się to przez opreślając katalog instalacji MySQL przy ustawianiu opcji --with-mysql .


Serwery-IIS/PWS

Ten rozdział zawiera wskazówki dotyczące specyficznej dla IIS IIS (Microsoft Internet Information Server) instalacji PHP na PWS/IIS 3, PWS 4 lub nowszym i IIS 4 lub nowszym.


Windows i PWS/IIS 3

Zalecaną metodą konfiguracji tych serweró jest użycie plików rejestru dołączonych do dystrybucji PHP 4 (pws-php4cgi.reg). Możesz chcieć wyedytować ten plik aby się upewnić, że rozszerzenia i katalogi instalacji PHP pasują do twojej konfiguracji. Możesz także wykonać poniższe kroki aby przeprowadzić instalację ręcznie.

Ostrze¿enie

Poniższe kroki prowadzą do bezpośredniej pracy na rejestrze Windows. Jeden błąd może pozostawić system w stanie niestabilnym. Wysoce zalecane jest zrobienie kopii zapasowej rejestru. Zespół PHP nie będzie odpowiedzialny w wypadku uszkodzenia rejestru.

  • Uruchom Regedit.

  • Przejdź do: HKEY_LOCAL_MACHINE /System /CurrentControlSet /Services /W3Svc /Parameters /ScriptMap.

  • W menu Edycja wybierz: Nowy->Wartość ciągu.

  • Wpisz rozszerzenia, które chcesz aby były przypisane do PHP, np. .php

  • Podwójnie kliknij na nowej wartości ciągu i wpisz ścieżkę do php.exe w wartości pola, np. c:\php\php.exe.

  • Ponów te kroki dla każdego rozszerzenia, które chcesz przypisać do skryptów PHP.

Poniższe kroki nie wpływają na serwer WWW i stosuje się je tylko jeśli chcesz aby istniała możliwość uruchamiania twoich skryptów PHP z linii poleceń (np. uruchamiając c:\myscripts\test.php) lub przez podwójne kliknięcie na nich w okienku katalogu. Możesz pominąć te kroki jeśli chcesz, żeby podwójne kliknięcie na skrypcie wywoływało edytor.

  • Teraz przejdź do: HKEY_CLASSES_ROOT

  • Z menu Edycja wybierz: Nowy->Klucz.

  • Nazwij klucz rozszerzeniem które ustawiłeś w poprzednim punkcie, np. .php

  • Zaznacz nowy klucz i w prawym panelu podwójnie kliknij na "wartość domyśłna" i wpisz phpfile.

  • Powtórz ostatni krok dla każdego rozszerzenia które ustawiłeś w poprzednich punktach.

  • Teraz stwórz kolejny Nowy->Klucz pod HKEY_CLASSES_ROOT i nazwij go phpfile.

  • Zaznacz nowy klucz phpfile i w prawym panelu podwójnie kliknij na "wartość domyślna" i wpisz PHP Script.

  • Kliknij prawym przyciskiem na kluczu phpfile i wybierz Nowy->Klucz, nazwij go Shell.

  • Kliknij prawym przyciskiem na kluczu Shell i wybierze Nowy->Klucz, nazwij go open.

  • Kliknij prawym przyciskiem na kluczu open i wybierz Nowy->Klucz, nazwij to command.

  • Zaznacz nowy klucz command, w prawym panelu podwójnie kliknij na "wartość domyślna" i wpisz ścieżkę do php.exe, np. c:\php\php.exe -q %1 . Nie zapomnij o %1.

  • Wyjdź z progamu Regedit.

  • Jeśli używasz PWS na systemie windows, uruchom system ponownie aby przeładować rejestr.

Użytkownicy serwerów PWS i IIS 3 mają teraz w pełni funkcjonalny system. Użytkownicy IIS 4 mogą skorzystać ze sprytnego narzędzia autorstwa Stevena Genusa aby skonfigurować swoje mapowania skryptów.


Windows i PWS 4 lub nowszy

Instalując PHP na systemie Windows z PWS 4 lub nowszym, masz do wyboru 2 możliwości. Albo zainstalować PHP jako binaria CGI, lub jako moduł dll ISAPI.

Jeśli wybierzesz binaria CGI, wykonaj poniższą instrukcję. If you choose the CGI binary, do the following:

  • Wyedytuj załączony plik pws-php4cgi.reg (zajrzyj do katalogu sapi) aby ustalić położenie twojego pliku php.exe. Znaki slash ('\') powinny zostać zamienione na sekwencje escape, na przykład: [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\w3svc\parameters\Script Map] ".php"="c:\\php\\php.exe"

  • W PWS Manager, kliknij prawym przyciskiem na katalogu, do którego chcesz dodać obsługę PHP, i wybierz Properties. Zaznacz pole 'Execute' i potwierdź.

Jeśłi wybierzesz moduł ISAPI, wykonaj poniższą instrukcję:

  • Wyedytuj załącziony plik pws-php4isapi.reg (zajrzyj do katalogu sapi) aby ustalić położenie twojego pliku php4isapi.dll. Znaki slash ('\') powinny być zamienione na sekwencje escape, na przykład: [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\w3svc\parameters\Script Map] ".php"="c:\\php\\sapi\\php4isapi.dll"

  • W PWS Manager, kliknij prawym przyciskiem na katalogu, do którego chcesz dodać obsługę PHP, i wybierz Properties. Zaznacz pole 'Execute' i potwierdź.


Windows NT/2000/XP i IIS 4 lub nowszy

Aby zainstalować PHP na systemie NT/2000/XP Server z serwerm WWW IIS 4 lub nowszym, wypełnij poniższe instrukcje. Masz dwie możliwości korzystania z PHP: używając binariów CGI (php.exe) lub modułu ISAPI.

W obu przypadkach, musisz uruchomić Microsoft Management Console (może istnieć jako 'Internet Services Manager', w Windows NT 4.0 Option Pack lub w Control Panel=>Administrative Tools w Windows 2000/XP). Potem kliknij prawym przyciskiem na węźle twojego serwera WWW (najprawdopodobniej będzie to 'Default Web Server'), i wybierz 'Properties'.

Jeśli chcesz używać binariów CGI, wykonaj poniższe kroki:

  • W 'Home Directory', 'Virtual Directory', lub 'Directory', kliknij na 'Configuration', a później wybierz zakładkę App Mappings.

  • Wybierz Add, a w polu Executable, wpisz: c:\php\php.exe (zakładając, że odzipowałeś PHP do c:\php\).

  • W polu Extension wpisz rozszerzenia nazw plików, które chcesz skojarzyć ze skryptami PHP. Pozostaw 'Method exclusions' niewypełnione i zaznacz pole 'Script engine'. Możesz także chcieć zaznaczyć pole 'Check that file exists' - za cenę małego zmniejszenia wydajności IIS (lub PWS) będzie sprawdzał czy skrypt istnieje i ustawi autoryzację przed uruchamianiem PHP. Oznacza to, że dosteniesz standardowy komunikat błędu 404 zamiast błędów CGI informujących, że PHP nie wysłało żadnych danych.

    Musisz wykonać powyższy krok dla każdego rozszerzenia, które chcesz skojarzyć ze skryptami PHP. Najczęściej spotykane są rozszerzenia .php and .phtml, jednakże dla wstecznej kompatybilności dobrze jest dodać także rozszerzenie .php3.

  • Skonfiguruj odpowiednio kwerstie bezpieczeństwa (robi się to korzystając z programu Internet Service Manager) i jeśli twój NT Server używa system plików NTFS, dodaj prawa wykonywania dla I_USR_ do katalogu, który zawiera php.exe.

Aby użyć moduł ISAPI, wykonaj poniższe polecenia:

  • Jeśli nie chcesz Autentyfikacji HTTP używając PHP, możesz (i powinieneś) pominąć ten krok. W ISAPI Filters, dodaj nowy filtr ISAPI. Użyj PHP jako nazwę filtra, i dopisz ścieżkę do pliku php4isapi.dll

  • W 'Home Directory', kliknij na 'Configuration'. Dodaj nowy wpis do Application Mappings. Użyj ścieżkę do php4isapi.dll jako Executable, dopisz .php jako rozszerzenie, zostaw pole 'Method exclusions' puste, zaznacz pole 'Script engine'.

  • Całkowicie zatrzymaj IIS (NET STOP iisadmin)

  • Uruchom ponownie IIS (NET START w3svc)


Serwery-Netscape i iPlanet

Rozdział ten zawiera wskazówki dotyczące instalacji PHP na serwerach Netscape and iPlanet na systemach Sun Solaris i Windows.

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


Instalacja PHP z Netscape na Sun Solaris

Aby zbudować PHP z serwerami NES lub iPlanet, wejdź do katalogu, który podałbyś jako parametr opcji --with-nsapi = KATALOG. Zazwyczaj jest to /opt/netscape/suitespot/. Przeczytaj także /php-xxx-version/sapi/nsapi/nsapi-readme.txt.

Przykład 2-7. Przykład instalacji dla Netscape Enterprise na Solaris

Instrukcje dla Sun Solaris 2.6 z Netscape Enterprise Server 3.6
Od: bhager@invacare.com

1. Zainstaluj poniższe pakiety z www.sunfreeware.com lub innego serwisu:

    flex-2_5_4a-sol26-sparc-local 
    gcc-2_95_2-sol26-sparc-local 
    gzip-1.2.4-sol26-sparc-local 
    perl-5_005_03-sol26-sparc-local 
    bison-1_25-sol26-sparc-local 
    make-3_76_1-sol26-sparc-local 
    m4-1_4-sol26-sparc-local 
    autoconf-2.13 
    automake-1.4 
    mysql-3.23.24-beta (jeśli potrzebujesz wsparcie dla MySQL) 
    tar-1.13 (GNU tar) 

2. Upewnij się, że zmienna PATH zawiera właściwe katalogi
    PATH=.:/usr/local/bin:/usr/sbin:/usr/bin:/usr/ccs/bin 
    export PATH 

3. gunzip php-x.x.x.tar.gz (jeśli masz plik .gz, jeśli nie przejdź do
   punktu 4)
4. tar xvf php-x.x.x.tar 
5. cd ../php-x.x.x 

6. Dla poniższego kroku upewnij się, że serwer Netscape jest zainstalowany w
   /opt/netscape/suitespot/. W przeciwnym wypadku zmień ścieżkę na właściwą:
   ./configure --with-mysql=/usr/local/mysql --with-nsapi=/opt/netscape/suitespot/ --enable-track-vars --enable-libgcc 
7. make 
8. make install
Po wykonaniu podstawowej instalacji i przeczytaniu właściwego pliku readme, niezbędne może się okazać wykanie dodatkowych kroków konfiguracyjnych.

Najprawdopodobniej niezbędne może się okazać dodanie ścieżek do zmiennej środowiskowej aby Netscape mógł znaleźć biblioteki współdzielone. Najlepiej, żeby było to robione w skryptach startowych serwera Netscape. Użytkownicy Windowsów prawdopodobnie mogą pominąć ten krok. Skrypt startowy zazwyczaj znajduje się w: /ścieżka/do/serwera/https-servername/start

Może się także okazać potrzebna edycja plików konfiguracyjnych, które znajdują się w: /ścieżka/do/serwera/https-servername/config/.

Przykład 2-8. Przykład konfiguracji dla Netscape Enterprise

Instrukcje konfiguracji Netscape Enterprise Server
Od: bhager@invacare.com

1. Dodaj poniższą linię do mime.types:
    type=magnus-internal/x-httpd-php exts=php

2. Dodaj poniższe linie do obj.conf. shlib może się różnić zależnie od systemu
   operacyjnego; dla systemu Unix będzie to coś w stylu
    /opt/netscape/suitespot/bin/libphp4.so.

    Powinieneś umieścić poniższe linie po inicjalizacji typów mime.
    Init fn="load-modules" funcs="php4_init,php4_close,php4_execute,php4_auth_trans" shlib="/php4/nsapiPHP4.dll"
    Init fn=php4_init errorString="Failed to initialize PHP!"

    <object name="default">
    . 
    . 
    . 
    .#UWAGA następna linia powinna się znajdować po wszystkich liniach 
    .#'ObjectType i przed wszystkimi 'AddLog'
    Service fn="php4_execute" type="magnus-internal/x-httpd-php" 
    . 
    . 
    </Object>


    <Object name="x-httpd-php"> 
    ObjectType fn="force-type" type="magnus-internal/x-httpd-php" 
    Service fn=php4_execute 
    </Object> 


    Konfiguracja autoryzacji 

    Autentyfikacja PHP nie może być użyta z żadną inną autoryzacją.
    CAŁA AUTORYZACJA JEST PRZEKAZYWANA DO SKRYPTU PHP. Aby skonfigurować
    autoryzację PHP dla całego serwera, dodaj poniższą linię:

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

    Aby włączyć autoryzację PHP w pojedyńczym katalogu, dodaj poniższą
    linię:

    <Object ppath="d:\ścieżka\do\autoryzowanego\katalogu\*"> 
    AuthTrans fn=php4_auth_trans 
    </Object>

Jeśli używasz Netscape Enterprise 4.x powinieneś użyć poniższą konfigurację:

Przykład 2-9. Przykład konfiguracji dla Netscape Enterprise 4.x

Umieść poniższe ponie po inicjalizacji typów mime, a wszystko inne jest
takie same jak w przykładzie powyżej.
Od: Graeme Hoose (GraemeHoose@BrightStation.com)

Init fn="load-modules" shlib="/path/to/server4/bin/libphp4.so" funcs="php4_init,php4_close,php4_execute,php4_auth_trans"
Init fn="php4_init" LateInit="yes"

Instajacja PHP dla Netscape na Windows

Aby zainstalować PHP jako CGI (dla Netscape Enterprise Server, iPlanet, być może Fastrack), wykonaj poniższe czynności:

  • Skopiuj php4ts.dll do twojego katalogu systemowego (katalog w którym zainstalowałeś Windows)

  • Stwórz powiązanie plików z linii poleceń. Napisz poniższe dwie linie:
    assoc .php=PHPScript
    ftype PHPScript=c:\php\php.exe %1 %*

  • W Netscape Enterprise Administration Server stwórz atrapę katalogu shellcgi i usuń go po chwili (ten krok dodaje 5 ważnych linii do pliku obj.conf i pozwala serwerowi na obsługę skryptów shellcgi).

  • W Netscape Enterprise Administration Server stwórz nowy typ mime (Category: type, Content-Type: magnus-internal/shellcgi, File Suffix:php).

  • Zrób to dla każdej instancji serwera na której chcesz uruchomić PHP.

Więcej szczegółów o ustawianiu PHP jako plik wykonywalny CGI można znaleźć pod adresem: http://benoit.noss.free.fr/php/install-php.html

Aby zainstalować PHP jako NSAPI (dla Netscape Enterprise Server, iPlanet, być może Fastrack), wykonaj poniższe kroki:

  • Skopiuj php4ts.dll do swojego katalogu systemowego (katalog w którym zainstalowany jest Windows)

  • Stwórz skojarzenia plików z linii poleceń. Wykonaj dwa poniższe polecenia:
    assoc .php=PHPScript
    ftype PHPScript=c:\php\php.exe %1 %*

  • W Netscape Enterprise Administration Server stwórz nowy typ mime (Category: type, Content-Type: magnus-internal/x-httpd-php, File Suffix:php).

  • Zatrzymaj usługi WWW i wyedytuj obj.conf. Na końcu sekcji Ini, umieść te dwie linie (konicznie po inicjalizacji typów mime!):
    Init fn="load-modules" funcs="php4_init,php4_close,php4_execute,php4_auth_trans" shlib="c:/php/sapi/php4nsapi.dll"
    Init fn="php4_init" errorString="Failed to initialise PHP!"

  • W sekcji < Object name="default" >, umieść poniższą linię po wszystkich liniach 'ObjectType' i przed wszystkimi liniami 'AddLog':
    Service fn="php4_execute" type="magnus-internal/x-httpd-php"

  • Na końcu pliku stwórz nowy obiekt o nazwie x-httpd-php dodając poniższe linie:
    <Object name="x-httpd-php">
    ObjectType fn="force-type" type="magnus-internal/x-httpd-php"
    Service fn=php4_execute
    </Object>

  • Zrestartuj usługi WWW i nanieś zmiany

  • Zrób to dla każdej instancji serwera WWW na których chcesz uruchomić PHP

Więcej informacji o ustawianiu PHP jako filtr NSAPI możesz znaleźć pod adresem: http://benoit.noss.free.fr/php/install-php4.html


Serwery-OmniHTTPd Server

Ten rozdział zawiera wskazówki dotyczące instalacji PHP z serwerem OmniHTTPd.


OmniHTTPd 2.0b1 i wyższe dla Windows

Aby zmusić PHP do działania z OmniHTTPd musisz wykonać poniższe kroki. Jest to ustawienie z PHP w postaci pliku wykonywalnego CGI. OmniHTTPd obsługuje SAPI, ale testy wykazały, że połączenie modułu PHP ISAPI z OmniHTTPd jest niestabilne.

  • Step 1: Zainstaluj serwer OmniHTTPd.

  • Step 2: Kliknij prawym przyciskiem na niebieskiej ikonie OmniHTTPd znajdującej się przy zegarku i wybierz Properties

  • Step 3: Kliknij na Web Server Global Settings

  • Step 4: W zakładce 'External' wpisz: virtual = .php | actual = c:\path-to-php-dir\php.exe, i kliknij na przycisk Add.

  • Step 5: W zakładce Mime wpisz: virtual = wwwserver/stdcgi | actual = .php, i kliknij na przycisk Add.

  • Step 6: Kliknij na OK

Powtarzaj kroki 2 - 6 dla każdego rozszerzenia które chcesz przypisać do PHP.

Notatka: Niektóre pakiety OmniHTTPd mogą być dostarczane z wbudowaną obsługą PHP. Przy instalacji możesz wybrać 'custom setup' (tryb instalacji, gdzie wiele parametrów może być ustalane przez użytkownika) i odznaczyć komponent PHP. Zalecamy użycie najnowszych binariów PHP. Niektóre serwery OmniHTTPd są dostarczane z wersją beta PHP 4, więc nie powinieneś wybierać wbudowanej obsługi, ale zainstalować swoją własną. Jeśli serwer jest już zainstalowany, użyj przycisku Replace w kroku 4 i 5 aby ustalić nowe, poprawne informacje.


Serwery-Oreilly Website Pro

This section contains notes and hints specific to Oreilly Website Pro.


Oreilly Website Pro 2.5 i nowsze dla Windows

Ta lista opisuje jak skonfigurować PHP w postaci binariów CGI lub modułu ISAPI do pracy z serwerem Oreilly Website Pro na systemie Windows.

  • Wyedytuj Server Properties i wybierz zakładke "Mapping".

  • Z listy wybierz "Associations" i wpisz wybrane rozszerzenie (.php) i ścieżkę do pliku exe (np. c:\php\php.exe) lub pliku DLL ISAPI (np. c:\php\sapi\php4isapi.dll).

  • Wynierz "Content Types", dodaj to samo rozszerzenie (.php) i wpisz typ zawartości. Jeśli używasz pliku wykonywalnego CGI, wpisz 'wwwserver/shellcgi', jeśli wybrałeś moduł ISAPI, wpisz 'wwwserver/isapi' (bez apostrofów).


Serwery-Xitami

Ten rozdział zawiera wskazówki specyficzne dla Xitami.


Xitami dla Windows

Ta lista opisuje jak skonfigurować PHP w postaci binariów CGI do pracy z Xitami pod Windows.

  • Upewnij się, że serwer pracuje, i wejdź przeglądarką WWW na konsolę administracyjną Xitami (zazwyczaj http://127.0.0.1/admin ), i kliknij na 'Configuration'.

  • Przejdź do 'Filters' i dodaj rozszerzenie, które powinno być przetwarzane przez PHP (np. .php) do pola 'File extensions'.

  • W 'Filter command or script dopisz ścieżkę i nazwę twojego pliku wykonywalnego PHP, np. c:\php\php.exe.

  • Kliknij na ikonę 'Save'.


Serwery-Inne serwery WWW

PHP może być skonfigurowane do pracy z wielona serwerami WWW. Przejrzyj Opcje związane z serwerami, gdzie możesz znaleźć pełną listę parametrów dla 'configure' związanych z serwerami. PHP w postaci binariów CGI jest kompatybilne z prawie wszystkimi serwerami WWW obsługującymi interfejs CGI.


Problemy?

Przeczytaj FAQ

Niektóre problemy są bardziej popularne niż inne. Tej najczęściej spotykane są wypisane w FAQ PHP, częsci tego podręcznika.


Inne problemy

Jeśli w dalszym ciągu nie wiesz co zrobić, być może ktoś z listy dyskusyjnej poświęconej instalacji PHP będzie mógł ci pomóc. Powinienej sprawdzić najpierw archiwum, bo być może ktoś już odpowiedział na twoje pytanie. Archiwa znajdują się w dziale 'Support' na stronie http://www.php.net/. Aby zapisać się na listę dyskusyjną dotyczącą instalacji PHP, wyślij pusty list na adres php-install-subscribe@lists.php.net. Adresem jesty dyskusyjnej jest php-install@lists.php.net.

Jeśli chcesz uzyskać pomoc na liście dyskusyjnej, postaraj się być precyzyjny i podaj niezbędne szczegóły dotyczące twojego środowiska (system operacyjny, wersja PHP, serwer WWW, czy PHP działa jako CGI czy jako moduł, itp.), i kod, aby inni mogli odtworzyć i sprawdzić twój problem.


Raporty o błędach

Jeśli uważasz, że znalazłeś błąd w PHP, zgłoś go. Programiści PHP prawdopodobnie nie wiedzą i nim, więc jeśli go nie zgłosisz, to najprawdopodobniej nie będzie usunięty. Możesz zgłaszać błędy korzystając z systemu zgłaszania błędów znajdującego się pod adresem http://bugs.php.net/. Nie wysyłaj raportów o błędach na listy dyskusyjne lub bezpośrednio do developerów. System śledzenia błędów ma także opcję zgłaszania pomysłów na nowe możliwości.

Przeczytaj dokument Jak wysyłać raporty o błędach przed wysłaniem jakiegokolwiek raportu o błędzie!


Rozdział 3. Konfiguracja

Plik konfiguracyjny

Plik konfiguracyjny (nazywający się php3.ini w PHP 3.0, i po prostu php.ini od PHP 4.0) jest czytany w momencie startu PHP. W przypadku PHP w wersji modułu serwera, dzieje się tylko tylko raz, przy starcie serwera. Dla wersji CGI dzieje się to dla każdego uruchomienia.

Przykład 3-1. Przykład php.ini

; dowolny tekst w linii zaczynającej się od średnika (;) jest ignorowana
[php] ; znaczniki sekcji (tekst wewnątrz nawiasów kwadratowych) także jest
      ; ignorowany
; Wartości logiczne mogą być albo:
;    true, on, yes
; lub false, off, no, none
register_globals = off
magic_quotes_gpc = yes

; Stringi mogą być obejmowane w cudzysłowy
include_path = ".:/usr/local/lib/php"

; Znaki backslash (\) są traktowane tak jak każdy inny znak
include_path = ".;c:\php\lib"

Używając PHP jako moduł Apache, możesz zmieniać opcje konfiguracyjne także w plikach konfiguracyjnych Apache i .htaccess.

Korzystając z PHP 3.0 dyrektywy Apache odpowiadają ustawieniom konfiguracyjnym z pliku php3.ini poprzedzonym przez "php3_".

W PHP 4.0 istnieje kilka dyrektyw Apache, które pozwalają na zmianę konfiguracji PHP z plików konfiguracyjnych Apache.

php_value nazwa wartość

Ustawia wartość podanej zmiennej.

php_flag nazwa on|off

Ta opcja jest używana do opcji konfiguracji tak/nie.

php_admin_value nazwa wartość

Ta opcja ustawia wartość podanej zmiennej. Opcje konfiguracji "admin" mogą być ustawiane tylko z głównych plików konfiguracyjnych Apache, nie z plików .htaccess.

php_admin_flag nazwa on|off

Ta opcja jest używana do opcji konfiguracji typu tak/nie.

Przykład 3-2. Przykład konfiguracji Apache

<IfModule mod_php4.c>
  php_value include_path ".:/usr/local/lib/php"
  php_flag safe_mode on
</IfModule>
<IfModule mod_php3.c>
  php3_include_path ".:/usr/local/lib/php"
  php3_safe_mode on
</IfModule>

Możesz przeglądać ustawienia opcji konfiguracyjnych w wyjściu funkcji phpinfo(). Do tych opcji możesz się także dostać używając funkcji get_cfg_var().


Ogólne dyrektywy konfiguracji

allow_url_fopen boolean

Ta opcja włącza interfejsy do funkcji fopen rozpoznające URLe pozwalające na dostęp do obiektów URL jak do plików. Domyślne interfejsy pozwalają na dostęp do zdalnych plików korzystając z protokołów ftp lub http. Niektóre rozszerzenia, takie jak zlib, mogą rejestrować dodatkowe interfejsy.

Notatka: Dyrektywa ta została wprowadzona zaraz po wyjściu wersji 4.0.3. Dla wersji 4.0.3 i wyższych możesz wyłączyć tą opcję w czasie kompilacji używając przełącznika --disable-url-fopen-wrapper.

asp_tags boolean

Włącza możliwość użycia tagów takich jak w ASP - <% %> - razem z normalnymi tagami <?php ?>. Dotyczy to także skrótowego wyświetlania wartości zmiennych typu <%= $value %>. Aby uzyskać więcej informacji przeczytaj rozdział more information, see Wyskakiwanie z HTMLa.

Notatka: Obsługa ASPowych tagów została dodana w wersji 3.0.4.

auto_append_file string

Określa nazwę pliku, który jest automatycznie przetwarzany po głównym pliku. Plik jest dołączany tak, jakby została wywołana funkcja include(), a więc używana jest opcja include_path.

Specjalna wartość none wyłącza auto-dołączanie.

Notatka: Jeśli skrypt zostanie zakończony przez exit(), nie dojdzie do auto-dołączenia.

auto_prepend_file string

Określa nazwę pliku, który będzie automatycznie przetwarzany przed głównym plikiem. Plik jest dołączany tak, jakby wywołana była funkcja include(), a więc używana jest opcja include_path.

Specjalna wartość none wyłącza automatyczne poprzedzanie pliku.

cgi_ext string

display_errors boolean

Określa, czy błędy powinny być wyświetlane jako część wyjścia HTML czy nie.

doc_root string

Katalog "katalogu głównego" PHP na serwerze. Używane tylko, jeśli jest to ciąg niepusty. Jeśli PHP jest skonfigurowane do pracy w trybie bezpiecznym, pliki spoza tego katalogu nie będą serwowane.

engine boolean

Ta dyrektywa jest przydatna tylko przy pracy z PHP w postaci modułu Apache. Jest ona używana na hostach, na których chce się włączać i wyłączać parsowanie PHP na podstawie katalogu lub na podstawie wirtualnego serwera. Umieszczając engine off we właściwych miejscach pliku httpd.conf PHP może być aktywne lub nieaktywne.

error_log string

Nazwa pliku, gdzie logowane mają być błędy. Jeśli użyta jest specjalna wartość syslog, błędy wysyłane są do systemowej aplikacji logowania. Na systemach oznacza to syslog(3) a na Windows NT - log zdarzeń. Systemowa aplikacja logowania nie jest obsługiwana przez Windows 95.

error_reporting integer

Ustaw poziom zgłaszania błędów. Parametrem jest liczba całkowita reprezentująca zestaw bitów. Dodaj wartości poziomów zgałaszania błędów które chcesz.

Tabela 3-1. Poziomy zgłaszania błędów

wartość bitowazgłaszany błąd
1normalne błędy
2normalne ostrzerzenia
4błędy parsera
8niekrytyczne ostrzerzenia związane ze stylem
Domyślną wartością dla tej dyrektywy jest 7 (wyświetlane są normalne błędy, normalne ostrzeżenia i błędy parsera).

html_errors boolean

Wyłącz tagi HTMLowe w informacjach o błędach.

open_basedir string

Ogranicz pliki które mogą być otwarte przez PHP do podanego drzewa katalogów.

Jeśli skrypt próbuje otworzyć plik, np. przez funkcje fopen lub gzopen, sprawdzane jest położenie pliku. Kiedy plik jest poza podanym drzewem katalogów, PHP odmawia otwarcia takiego pliku. Wszystkie dowiązania symboliczne są rozwiązywane, więc nie jest możliwe uniknąć tego ograniecznia przez symlinki.

Wartość specjalna . wskazuje, że katalog w którym znajduje się skrypt będzie uznawany jako katalog bazowy dla tej dyrektywy.

Pod systemem Windows, oddzielaj katalogi średnikami. Na wszystkich innych systemach, oddzielaj katalogi dwukropkami. Pracując jako moduł Apache, ścieżki open_basedir katalogów nadrzędnych są automatycznie dziedziczone.

Notatka: Obsługa dla wielu katalogów została dodana w 3.0.7.

Domyślnie PHP pozwala na otwieranie wszystkich plików.

gpc_order string

Ustaw kolejność parsowania zmiennych GET/POST/COOKIE. Domyślne ustawienie do "GPC". Ustawienie tej dyrektywy np. na "GP" spowoduje, że PHP będzie całkowicie ignorował ciasteczka i przebijał wszystkie zmienne otrzymane metodą GET zmiennymi o tej samej nazwie otrzymanymi metodą POST.

Zauważ, że ta opcja nie jest dostępna w PHP 4. Użyj opcji variables_order.

variables_order string

Ustawia porządek przetwarzania zmiennych EGPCS (Environment, GET, Post, Cookie, Server). Domyślne ustawienie tej dyrektywy to "EGPCS".Ustawienie tej dyrektywy np. na "GP" spowoduje, że PHP będzie całkowicie ignorował ciasteczka i przebijał wszystkie zmienne otrzymane metodą GET zmiennymi o tej samej nazwie otrzymanymi metodą POST.

Patrz także register_globals.

ignore_user_abort string

Domyślnie włączona. Jeśli zostanie zmieniona na Off, skrypty będą przerywane jak tylkol będą próbowały wysłać coś do klienta, który przerwał połączenie. ignore_user_abort().

include_path string

Określa listę katalogów, gdzie funkcje require(), include() i fopen_with_path() będą szukały plików. Format jest podobny do zmiennej środowiskowej PATH: lista katalogów oddzielona dwukropkiem na systemach UNIX lub średnikiem na systemach Windows.

Przykład 3-3. include_path na systemach UNIX

include_path=.:/home/httpd/php-lib

Przykład 3-4. include_path na systemach Windows

include_path=".;c:\www\phplib"
Domyślną wartością tej dyrektywy jest . (tylko bieżący katalog).

isapi_ext string

log_errors boolean

Ustawia czy komunikaty o błędach skryptu mają być logowane do logu błędów serwera. W związku z tym ta opcja jest specyficzna dla poszczególnych serwerów.

magic_quotes_gpc boolean

Ustawia stan magic_quotes dla operacji GPC (Get/Post/Cookie). Jeśli magic_quotes są włączone, wszystkie znaki ' (apostrof), " (cudzysłów), \ (backslash) i znaki NULL są zamieniane na sekwencje escape przez dodanie przed te znaki znaku backslash. Jeśli włączona jest także dyrektywa magic_quotes_sybase, wszystkie apostrofy są zamieniane na sekwencej escape przez dodanie apostrofu zamiast znaku backslash.

magic_quotes_runtime boolean

Jeśli włączona jest dyrektywa magic_quotes_runtime, większośc funkcji, które zwracają dane z dowolnych zewnętrznych źródeł, włączając w to bazy danych i pliki tekstowe, będzie zwracała dane z apostrofami i cudzysłowami zamienionymi na sekwencje escape przy pomocy znaku backslash. Jeśli włączona jest także opcja magic_quotes_sybase, apostrof będzę zamieniany na sekwencję escape przy pomocy apostrofu zamiast znaku backslash.

magic_quotes_sybase boolean

Jeśli włączona jest opcja magic_quotes_sybase, apostrof będzie zamieniany na sekwencję escape używając apostrofu zamiast znaku backslash, jeśli włączona jest opcja magic_quotes_gpc i/lub magic_quotes_runtime.

max_execution_time integer

Dyrektywa to określa maksymalny czas w sekundach wykonywania skryptu, zanim zostanie przerwany przez parser. Pomaga to w zapobieganiu blokowania serwera przez kiepsko napisane skrypty. Domyślne ustawienie to 30.

Na dyrektywę max_execution_time nie wpływają wywołania systemowe, funkcja sleep() itp. Zobacz opis funkcji set_time_limit() aby uzyskać więcej szczegółów.

memory_limit integer

Dyrektywa ta ustawia maksymalną wielkość pamięci w bajtach, którą skrypt może zaalokować. Pomaga to w zapobieganiu zjadania całej dostępnej pamięci serwera przez kiepsko napisane skrypty.

nsapi_ext string

register_globals boolean

Ustala, czy rejestrować zmienne EGPCS (Environment, GET, POST, Cookie, Server) jako zmienne globalne. Możesz wyłączyć tę opcję jeśli nie chcesz zaśmiecić globalnych zasięgów swoich skryptów przez dane użytkownika. Ma to największy sens jeśli użwane jest w połączeniu z track_vars - w takim przypadku do zmiennych EGCPS możliwy jest przez zmienne globalne $HTTP_ENV_VARS, $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS, i $HTTP_SERVER_VARS.

Zauważ, że nie musisz ustawiać AllowOverride All w bloku Directory pliku konfiguracyjnego serwera Apache aby to działało.

short_open_tag boolean

Ustala, czy dozwolona jest skrócona forma tagu otwierającego PHP (<? ?>). Jeśli chcesz używać PHP w połączeniu z XMLem, powinieneś wyłączyć tą opcję. Jeśli ta opcja jest wyłączona, musisz używać długiej postaci tagu otwierającego. (<?php ?>).

sql.safe_mode boolean

track_errors boolean

Jeśli dyrektywa ta jest włączona, ostatnia informacja o błędzie będzie dostępna jako zmienna globalna $php_errormsg.

track_vars boolean

Jeśli ta dyrektywa jest włączona, zmienne EGCS (Environment, GET, POST, Cookie, Server) będą dostępne w globalnych tablicach asocjacyjnych $HTTP_ENV_VARS, $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_COOKIE_VARS, i $HTTP_SERVER_VARS.

Zauważ, ze od PHP 4.0.3 dyrektywa track_vars jest zawsze włączona.

upload_tmp_dir string

Katalog tymczasowy używany do przechowywania plików podczas obsługiwania uploadu plików. Musi być to katalog z prawem zapisu dla użytkownika, jako który pracuje PHP.

upload_max_filesize integer

Maksymalny rozmiar uploadowanego pliku. Wartość podawana jest w bajtach.

user_dir string

Podstawowa nazwa katalogu używanego jako katalog domowy użytkownika dla plików PHP, na przykład public_html.

warn_plus_overloading boolean

Jeśli dyrektywa ta jest włączona, PHP będzie wyświetlał ostrzeżenie jeśli operator plus (+) został użyty do stringów. Dzięki temu łatwiej jest znaleźć skrypty, które wymagają użycia operatora sklejania stringów (.).


Dyrektywy konfiguracji trybu bezpiecznego

safe_mode boolean

Określa, czy PHP ma pracować w trybie bezpiecznym. Przeczytaj rozdziały Bezpieczeństwo i Safe Mode aby uzyskać więcej informacji.

safe_mode_exec_dir string

Jeśli PHP pracuje w trybie bezpiecznym, funkcje system() i inne wywołujące inne programy, odmówią wykonania programów z katalogów innych niż ten.


Dyrektywy konfiguracji debuggera

debugger.host string

Nazwa lub adres IP hosta używanego przez debugger.

debugger.port string

Numer portu używany przez debugger.

debugger.enabled boolean

Określa, czy debugger jest włączony.


Dyrektywy ładowania rozszerzeń

enable_dl boolean

Ta dyrektywa jest jedynie przydatna przy pracy PHP jako moduł Apache. Możesz włączać i wyłączać możliwość dynamicznego ładowania rozszerzeń PHP przez funkcję dl() zależnie od katalogu lub wirtualnego serwera.

Głównym powodem wyłączania dynamicznego ładowania rozszerzeń jest kwestia bezpieczeństwa. Używając dynamicznych rozszerzeń możliwe jest ominięcie praktycznie wszystkich ograniczeń safe_mode i open_basedir.

Domyślnie zezwalane jest dynamiczne ładowanie, z wyjątkiem pracy w trybie bezpiecznym. W trybie bezpiecznym korzystanie z funkcji dl() jest zawsze zabronione.

extension_dir string

Katalog, w którym PHP powinno szukać dynamicznie dołączanych rozszerzeń.

extension string

Które dynamicznie ładowane rozszerzenia ładować przy starcie PHP.


Dyrektywy konfiguracji MySQL

mysql.allow_persistent boolean

Czy pozwalać na stałe połączenia MySQL ('persistent connections').

mysql.default_host string

Domyślny host serwera, który będzie używany przy łączeniu się z serwerem baz danych jeśli nie zostanie podany żaden inny host.

mysql.default_user string

Domyślna nazwa użytkownika, która będzie używana przy łączeniu się z serwerm baz danych jeśli nie zostanie podana żadna inna nazwa.

mysql.default_password string

Domyślne hasło, które będzie użyte przy łączeniu się z serwerem baz danych jeśli nie zostanie podane żadne inne hasło.

mysql.default_port string

Domyślny numer portu TCP, który będzie użyty przy łączeniu się z serwerm baz danych jeśli nie zostanie podany żaden inny port. Jeśli nie będzie podany port domyślny, będzie on pobrany ze zmiennej środowiskowej MYSQL_TCP_PORT, wpisu mysql-tcp w pliku /etc/services lub stałej czasu kompilacji MYSQL_PORT, w tym właśnie porządku. Pod Win32 użyta będzie tylko stała MYSQL_PORT.

mysql.default_socket string

Domyślna nazwa gniazda, które będzie użyta to łączenia się z lokalnym serwerem baz danych jeśli nie zostanie podana żadna inna nazwa gniazda.

mysql.max_persistent integer

Maksymalna liczba stałych połączeń MySQL na każdy proces.

mysql.max_links integer

Maksymalna liczba połączeń MySQL na proces, włączając w to połączenia stałe.


Dyrektywy konfiguracji mSQL

msql.allow_persistent boolean

Czy pozwalać na stałe połączenia mSQL.

msql.max_persistent integer

Maksymalna liczba trwałych połączeń mSQL na każdy proces.

msql.max_links integer

Maksymalna liczna połączeń mSQL na każdy proces, włączając w to połączenia stałe.


Dyrektywy konfiguracji PostgreSQL

pgsql.allow_persistent boolean

Czy pozwalać na stałe połączenia PostgreSQL.

pgsql.max_persistent integer

Maksymalna liczba stałych połączeń PostgreSQL na każdy proces.

pgsql.max_links integer

Maksymalna liczba połączeń PostgreSQL na każdy proces, włączając w to połąćzenia stałe.


Dyrektywy konfiguracji SESAM

sesam_oml string

Nazwa biblioteki PLAM BS2000 zawierającej ładowalne moduły sterowników SESAM. Wymagane do użycia funkcji SESAM. Biblioteka PLAM BS2000 musi być ustawiona na ACCESS=READ,SHARE=YES, ponieważ musi być dostępna do odczytu dla użytkownika, jako który pracuje Apache.

sesam_configfile string

Nazwa pliku konfiguracyjnego aplikacji SESAM. Wymagane do użyca funkcji SESAM. Plik BS2000 musi być dostępny do odczytu dla użytkownika, jako który pracuje Apache.

Plik konfiguracyjny aplikacji zazwyczaj zawiera konfigurację podobną do tej (zobacz podręcznik do aplikacji SESAM):

CNF=B
NAM=K
NOTYPE

sesam_messagecatalog string

Nazwa pliku katalogującego wiadomości SESAM. W większości przypadków użycie tej dyrektywy nie jest konieczne. Jedynie jeśli plik miadomości nie jest zainstalowany w tablicy plików wiadomości BS2000 systemu, może on być ustalony przez tą dyrektywę.

Katalog wiadomości musi być ustawiony na ACCESS=READ,SHARE=YES ponieważ musi być on dostępny do odczytu dla użytkownika, jako który pracuje Apache.


Dyrektywy konfiguracji Sybase

sybase.allow_persistent boolean

Czy pozwalać na stałe połączenia Sybase.

sybase.max_persistent integer

Maksymalna liczba stałych połączeń Sybase na każdy proces.

sybase.max_links integer

Maksymalna liczba połączeń Sybase na każdy proces, włączając w to połączenia stałe.


Dyrektywy konfiguracji Sybase-CT

sybct.allow_persistent boolean

Czy pozwalać na stałe połączenia Sybase-CT. Domyślnie włączone.

sybct.max_persistent integer

Maksymalna liczba stałych połączeń Sybase-CT na każdy proces. Domyślą wartością jest -1, co oznacza brak limitu.

sybct.max_links integer

Maksymalna liczba połączeń Sybase-CT na proces, włączając w to połączenia stałe. Domyślna wartość to -1, co oznacza brak limitu.

sybct.min_server_severity integer

Wiadomości serwera z 'serverity' większą lub równą sybct.min_server_severity będą zgłaszane jako ostrzeżenia. Wartość ta może być zmieniona także przez wywołanie sybase_min_server_severity(). Domyślna wartość to 10. The default is 10 which reports errors of information severity or greater.

sybct.min_client_severity integer

Wiadomości biblioteki klienta z 'serverity' większą lub równą sybct.min_client_severity będą zgłaszane jako błędy. Wartość ta może być zmieniona także przez wywołanie sybase_min_client_severity(). Domyślna wartość to 10, co praktycznie wyłącza zgłaszanie błędów.

sybct.login_timeout integer

Maksymalny czas oczekiwania na połączenie zanim zwrócona będzie wartość porażki. Zauważ, że jeśli dojdzie do skończenia czasu max_execution_time w trakcie oczekiwania na połączenie, twój skrypt zostanie zakończony zanim będzie mógł podjąć jakiekolwiek działania zaplanowane na przypadek nieudanego połączenia. Domyślna wartość to jedna minuta.

sybct.timeout integer

Maksymalny czas (w sekundach) oczekiwania na wykonanie select_db lub zapytania po którym zwrócona zostanie wartość oznaczająca porażkę. Zauważ, że jeśli dojdzie do skończenia czasu max_execution_time w trakcie oczekiwania na połączenie, twój skrypt zostanie zakończony zanim będzie mógł podjąć jakiekolwiek działania zaplanowane na przypadek niewykonania polecenia. Domyślnie nie ma żadnych ograniczeń.

sybct.hostname string

Nazwa hosta, z którego twierdzisz że się łączysz, który będzie wyświetlany w sp_who. Domyślną wartością jest pusty ciąg.


Dyrektywy konfiguracji Informix

ifx.allow_persistent boolean

Czy pozwalać na stałe połączenia Informix.

ifx.max_persistent integer

Maksymalna liczba stałych połączeń Informix na każdy proces.

ifx.max_links integer

Maksymalna liczba połączeń Informix na każdy proces, włączając w to połączenia stałe.

ifx.default_host string

Domyślny host do połączenia jeśli nie podano innego w ifx_connect() lub ifx_pconnect().

ifx.default_user string

Domyślny identyfikator użytkownika używany jeśli nie podano innego w ifx_connect() lub ifx_pconnect().

ifx.default_password string

Domyślne hasło używane jeśli nie podano innego w ifx_connect() lub ifx_pconnect().

ifx.blobinfile boolean

Ustaw na TRUE jeśli chcesz zwracać kolumny blob w pliku, lub FALSE jeśli chcesz zwracać je w pamięci. Możesz zmienić wartość tej dyrektywy korzystając z ifx_blobinfile_mode().

ifx.textasvarchar boolean

Ustaw na TRUE jeśli chcesz w zapytaniach zwracać kolumny TEXT jako zwykłe stringi, lub FALSE jeśli chcesz używać parametrów identyfikatorów blob. Możesz zmienić wartość tej dyrektywy korzystając z ifx_textasvarchar().

ifx.byteasvarchar boolean

Ustaw na TRUE jeśli chcesz w zapytaniach zwracać kolumny BYTE jak zwykłe stringi, lub FALSE jeśli chcesz używać parametrów identyfikatorów blob. Możesz zmienić wartość tej dyrektywy korzystając z ifx_textasvarchar().

ifx.charasvarchar boolean

Ustaw na TRUE jeśli chcesz obcinać początkowe spacje z kolumn CHAR przy pobieraniu ich.

ifx.nullformat boolean

Ustaw na TRUE jeśli chcesz zwracać kolumny NULL jako string "NULL", lub na FALSE jeśli chcesz aby były zwracane jako pusty string. Możesz zmienić wartość tej dyrektywy korzystając z ifx_nullformat().


Dyrektywy konfiguracji BC Math

bcmath.scale integer

Liczba dziesiętnych cyfr dla wszystkich funkcji bcmath.


Dyrektywy konfiguracji Możliwości Przeglądarek

browscap string

Nazwa pliku opisującego możliwości przeglądarek. Zobacz także get_browser().


Dyrektywy konfiguracji Zunifikowanego ODBC

uodbc.default_db string

Źródło danych ODBC używane jeśli nie podane zostało inne w odbc_connect() lub odbc_pconnect().

uodbc.default_user string

Nazwa użytkownika używana jeśli inna nie została podana w odbc_connect() lub odbc_pconnect().

uodbc.default_pw string

Hasło używane jeśli inne nie zostało podane w odbc_connect() lub odbc_pconnect().

uodbc.allow_persistent boolean

Czy pozwalać na stałe połączenia ODBC.

uodbc.max_persistent integer

Maksymalna liczba stałych połączeń ODBC na każdy proces.

uodbc.max_links integer

Maksymalna liczba połączeń ODBC na każdy proces, włączając w to połączenia stałe.


Dyrektywy konfiguracji Multi-Byte String (Wielobajtowych Stringów)

mbstring.internal_encoding string

mbstring.internal_encoding definiuje domyślne wewnętrzne kodowanie znaków.

mbstring.http_input string

mbstring.http_input definiuje domyślne kodowanie znaków wejścia HTTP.

mbstring.http_output string

mbstring.http_output definiuje domyślne kodowanie znaków wyjścia HTTP.

mbstring.detect_order string

mbstring.detect_order definiuje domyślną kolejność wykrywania kodowania znaków.

mbstring.substitute_character string

mbstring.substitute_character definiuje znak zastępujące znaki o błędnych kodach.


Rozdział 4. Security

PHP is a powerful language and the interpreter, whether included in a web server as a module or executed as a separate CGI binary, is able to access files, execute commands and open network connections on the server. These properties make anything run on a web server insecure by default. PHP is designed specifically to be a more secure language for writing CGI programs than Perl or C, and with correct selection of compile-time and runtime configuration options, and proper coding practices, it can give you exactly the combination of freedom and security you need.

As there are many different ways of utilizing PHP, there are many configuration options controlling its behaviour. A large selection of options guarantees you can use PHP for a lot of purposes, but it also means there are combinations of these options and server configurations that result in an insecure setup.

The configuration flexibility of PHP is equally rivalled by the code flexibility. PHP can be used to build complete server applications, with all the power of a shell user, or it can be used for simple server-side includes with little risk in a tightly controlled environment. How you build that environment, and how secure it is, is largely up to the PHP developer.

This chapter starts with some general security advice, explains the different configuration option combinations and the situations they can be safely used, and describes different considerations in coding for different levels of security.


General considerations

A completely secure system is a virtual impossibility, so an approach often used in the security profession is one of balancing risk and usability. If every variable submitted by a user required two forms of biometric validation (such as a retinal scan and a fingerprint), you would have an extremely high level of accountability. It would also take half an hour to fill out a fairly complex form, which would tend to encourage users to find ways of bypassing the security.

The best security is often inobtrusive enough to suit the requirements without the user being prevented from accomplishing their work, or over-burdening the code author with excessive complexity. Indeed, some security attacks are merely exploits of this kind of overly built security, which tends to erode over time.

A phrase worth remembering: A system is only as good as the weakest link in a chain. If all transactions are heavily logged based on time, location, transaction type, etc. but the user is only verified based on a single cookie, the validity of tying the users to the transaction log is severely weakened.

When testing, keep in mind that you will not be able to test all possibilities for even the simplest of pages. The input you may expect will be completely unrelated to the input given by a disgruntled employee, a cracker with months of time on their hands, or a housecat walking across the keyboard. This is why it's best to look at the code from a logical perspective, to discern where unexpected data can be introduced, and then follow how it is modified, reduced, or amplified.

The Internet is filled with people trying to make a name for themselves by breaking your code, crashing your site, posting inappropriate content, and otherwise making your day interesting. It doesn't matter if you have a small or large site, you are a target by simply being online, by having a server that can be connected to. Many cracking programs do not discern by size, they simply trawl massive IP blocks looking for victims. Try not to become one.


Installed as CGI binary

Possible attacks

Using PHP as a CGI binary is an option for setups that for some reason do not wish to integrate PHP as a module into server software (like Apache), or will use PHP with different kinds of CGI wrappers to create safe chroot and setuid environments for scripts. This setup usually involves installing executable PHP binary to the web server cgi-bin directory. CERT advisory CA-96.11 recommends against placing any interpreters into cgi-bin. Even if the PHP binary can be used as a standalone interpreter, PHP is designed to prevent the attacks this setup makes possible:

  • Accessing system files: http://my.host/cgi-bin/php?/etc/passwd

    The query information in a url after the question mark (?) is passed as command line arguments to the interpreter by the CGI interface. Usually interpreters open and execute the file specified as the first argument on the command line.

    When invoked as a CGI binary, PHP refuses to interpret the command line arguments.

  • Accessing any web document on server: http://my.host/cgi-bin/php/secret/doc.html

    The path information part of the url after the PHP binary name, /secret/doc.html is conventionally used to specify the name of the file to be opened and interpreted by the CGI program. Usually some web server configuration directives (Apache: Action) are used to redirect requests to documents like http://my.host/secret/script.php to the PHP interpreter. With this setup, the web server first checks the access permissions to the directory /secret, and after that creates the redirected request http://my.host/cgi-bin/php/secret/script.php. Unfortunately, if the request is originally given in this form, no access checks are made by web server for file /secret/script.php, but only for the /cgi-bin/php file. This way any user able to access /cgi-bin/php is able to access any protected document on the web server.

    In PHP, compile-time configuration option --enable-force-cgi-redirect and runtime configuration directives doc_root and user_dir can be used to prevent this attack, if the server document tree has any directories with access restrictions. See below for full the explanation of the different combinations.


Case 1: only public files served

If your server does not have any content that is not restricted by password or ip based access control, there is no need for these configuration options. If your web server does not allow you to do redirects, or the server does not have a way to communicate to the PHP binary that the request is a safely redirected request, you can specify the option --enable-force-cgi-redirect to the configure script. You still have to make sure your PHP scripts do not rely on one or another way of calling the script, neither by directly http://my.host/cgi-bin/php/dir/script.php nor by redirection http://my.host/dir/script.php.

Redirection can be configured in Apache by using AddHandler and Action directives (see below).


Case 2: using --enable-force-cgi-redirect

This compile-time option prevents anyone from calling PHP directly with a url like http://my.host/cgi-bin/php/secretdir/script.php. Instead, PHP will only parse in this mode if it has gone through a web server redirect rule.

Usually the redirection in the Apache configuration is done with the following directives:

Action php-script /cgi-bin/php
AddHandler php-script .php

This option has only been tested with the Apache web server, and relies on Apache to set the non-standard CGI environment variable REDIRECT_STATUS on redirected requests. If your web server does not support any way of telling if the request is direct or redirected, you cannot use this option and you must use one of the other ways of running the CGI version documented here.


Case 3: setting doc_root or user_dir

To include active content, like scripts and executables, in the web server document directories is sometimes consider an insecure practice. If, because of some configuration mistake, the scripts are not executed but displayed as regular HTML documents, this may result in leakage of intellectual property or security information like passwords. Therefore many sysadmins will prefer setting up another directory structure for scripts that are accessible only through the PHP CGI, and therefore always interpreted and not displayed as such.

Also if the method for making sure the requests are not redirected, as described in the previous section, is not available, it is necessary to set up a script doc_root that is different from web document root.

You can set the PHP script document root by the configuration directive doc_root in the configuration file, or you can set the environment variable PHP_DOCUMENT_ROOT. If it is set, the CGI version of PHP will always construct the file name to open with this doc_root and the path information in the request, so you can be sure no script is executed outside this directory (except for user_dir below).

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.


Case 4: PHP parser outside of web tree

A very secure option is to put the PHP parser binary somewhere outside of the web tree of files. In /usr/local/bin, for example. The only real downside to this option is that you will now have to put a line similar to:

#!/usr/local/bin/php

as the first line of any file containing PHP tags. You will also need to make the file executable. That is, treat it exactly as you would treat any other CGI script written in Perl or sh or any other common scripting language which uses the #! shell-escape mechanism for launching itself.

To get PHP to handle PATH_INFO and PATH_TRANSLATED information correctly with this setup, the php parser should be compiled with the --enable-discard-path configure option.


Installed as an Apache module

When PHP is used as an Apache module it inherits Apache's user permissions (typically those of the "nobody" user). This has several impacts on security and authorization. For example, if you are using PHP to access a database, unless that database has built-in access control, you will have to make the database accessable to the "nobody" user. This means a malicious script could access and modify the database, even without a username and password. It's entirely possible that a web spider could stumble across a database administrator's web page, and drop all of your databases. You can protect against this with Apache authorization, or you can design your own access model using LDAP, .htaccess files, etc. and include that code as part of your PHP scripts.

Often, once security is established to the point where the PHP user (in this case, the apache user) has very little risk attached to it, it is discovered that PHP is now prevented from writing any files to user directories. Or perhaps it has been prevented from accessing or changing databases. It has equally been secured from writing good and bad files, or entering good and bad database transactions.

A frequent security mistake made at this point is to allow apache root permissions, or to escalate apache's abilitites in some other way.

Escalating the Apache user's permissions to root is extremely dangerous and may compromise the entire system, so sudo'ing, chroot'ing, or otherwise running as root should not be considered by those who are not security professionals.

There are some simpler solutions. By using open_basedir you can control and restrict what directories are allowed to be used for PHP. You can also set up apache-only areas, to restrict all web based activity to non-user, or non-system, files.


Filesystem Security

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/password, 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.

Przykład 4-1. Poor variable checking leads to....

<?php
// remove a file from the user's home directory
$username = $HTTP_POST_VARS['user_submitted_name'];
$homedir = "/home/$username";
$file_to_delete = "$userfile";
unlink ($homedir/$userfile);
echo "$file_to_delete has been deleted!";
?>
Since the username is postable from a user form, they can submit a username and file belonging to someone else, and delete files. 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:

Przykład 4-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 = "../etc/";
$homedir = "/home/../etc/";
$file_to_delete = "passwd";
unlink ("/home/../etc/passwd");
echo "/home/../etc/passwd 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:

Przykład 4-3. More secure file name checking

<?php
// removes a file from the hard drive that
// the PHP user has access to.
$username = $HTTP_SERVER_VARS['REMOTE_USER']; // using an authentication mechanisim

$homedir = "/home/$username";

$file_to_delete = basename("$userfile"); // strip paths
unlink ($homedir/$file_to_delete);

$fp = fopen("/home/logging/filedelete.log","+a"); //log the deletion
$logstring = "$username $homedir $file_to_delete";
fputs ($fp, $logstring);
fclose($fp);

echo "$file_to_delete has been deleted!";
?>
However, even this is not without it's 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:

Przykład 4-4. More secure file name checking

<?php
$username = $HTTP_SERVER_VARS['REMOTE_USER']; // using an authentication mechanisim
$homedir = "/home/$username";

if (!ereg('^[^./][^/]*$', $userfile))
     die('bad filename'); //die, do not process

if (!ereg('^[^./][^/]*$', $username))
     die('bad username'); //die, do not process
//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.


Database Security

Nowadays, databases are cardinal components of any web based application by enabling websites to provide varying dynamic content. Since very sensitive or secret informations can be stored in such database, you should strongly consider to protect them somehow.

To retrieve or to store any information you need to connect to the database, send a legitimate query, fetch the result, and close the connecion. Nowadays, the commonly used query language in this interaction is the Structured Query Language (SQL). See how an attacker can tamper with an SQL query.

As you can realize, PHP cannot protect your database by itself. The following sections aim to be an introduction into the very basics of how to access and manipulate databases within PHP scripts.

Keep in my mind this simple rule: defence in depth. In the more place you take the more action to increase the protection of your database, the less probability of that an attacker succeeds, and exposes or abuse any stored secret information. Good design of the database schema and the application deals with your greatest fears.


Designing Databases

The first step is always to create the database, unless you want to use an existing third party's one. When a database is created, it is assigned to an owner, who executed the creation statement. Usually, only the owner (or a superuser) can do anything with the objects in that database, and in order to allow other users to use it, privileges must be granted.

Applications should never connect to the database as its owner or a superuser, because these users can execute any query at will, for example, modifying the schema (e.g. dropping tables) or deleting its entire content.

You may create different database users for every aspect of your application with very limited rights to database objects. The most required privileges should be granted only, and avoid that the same user can interact with the database in different use cases. This means that if intruders gain access to your database using one of these credentials, they can only effect as many changes as your application can.

You are encouraged not to implement all the business logic in the web application (i.e. your script), instead to do it in the database schema using views, triggers or rules. If the system evolves, new ports will be intended to open to the database, and you have to reimplement the logic in each separate database client. Over and above, triggers can be used to transparently and automatically handle fields, which often provides insight when debugging problems with your application or tracing back transactions.


Connecting to Database

You may want to estabilish the connections over SSL to encrypt client/server communications for increased security, or you can use ssh to encrypt the network connection between clients and the database server. If either of them is done, then monitoring your traffic and gaining informations in this way will be a hard work.


Encrypted Storage Model

SSL/SSH protects data travelling from the client to the server, SSL/SSH does not protect the persistent data stored in a database. SSL is an on-the-wire protocol.

Once an attacker gains access to your database directly (bypassing the webserver), the stored sensitive data may be exposed or misused, unless the information is protected by the database itself. Encrypting the data is a good way to mitigate this threat, but very few databases offer this type of data encryption.

The easiest way to work around this problem is to first create your own encryption package, and then use it from within your PHP scripts. PHP can assist you in this case with its several extensions, such as Mcrypt and Mhash, covering a wide variety of encryption algorithms. The script encrypts the data be stored first, and decrypts it when retrieving. See the references for further examples how encryption works.

In case of truly hidden data, if its raw representation is not needed (i.e. not be displayed), hashing may be also taken into consideration. The well-known example for the hashing is storing the MD5 hash of a password in a database, instead of the password itself. See also crypt() and md5().

Przykład 4-5. Using hashed password field

// storing password hash
$query  = sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
            addslashes($username), md5($password));
$result = pg_exec($connection, $query);

// querying if user submitted the right password
$query = sprintf("SELECT 1 FROM users WHERE name='%s' AND pwd='%s';",
            addslashes($username), md5($password));
$result = pg_exec($connection, $query);

if (pg_numrows($result) > 0) {
    echo "Welcome, $username!";
}
else {
    echo "Authentication failed for $username.";
}

SQL Injection

Many web developers are unaware of how SQL queries can be tampered with, and assume that an SQL query is a trusted command. It means that SQL queries are able to circumvent access controls, thereby bypassing standard authentication and authorization checks, and sometimes SQL queries even may allow access to host operating system level commands.

Direct SQL Command Injection is a technique where an attacker creates or alters existing SQL commands to expose hidden data, or to override valuable ones, or even to execute dangerous system level commands on the database host. This is accomplished by the application taking user input and combining it with static parameters to build a SQL query. The following examples are based on true stories, unfortunately.

Owing to the lack of input validation and connecting to the database on behalf of a superuser or the one who can create users, the attacker may create a superuser in your database.

Przykład 4-6. Splitting the result set into pages ... and making superusers (PostgreSQL and MySQL)

$offset = argv[0]; // beware, no input validation!
$query  = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
// with PostgreSQL 
$result = pg_exec($conn, $query);
// with MySQL
$result = mysql_query($query);
Normal users click on the 'next', 'prev' links where the $offset is encoded into the URL. The script expects that the incoming $offset is decimal number. However, someone tries to break in with appending urlencode()'d form of the following to the URL

// in case of PostgreSQL
0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
    select 'crack', usesysid, 't','t','crack'
    from pg_shadow where usename='postgres';
--

// in case of MySQL
0;
UPDATE user SET Password=PASSWORD('crack') WHERE user='root';
FLUSH PRIVILEGES;

If it happened, then the script would present a superuser access to him. Note that 0; is to supply a valid offset to the original query and to terminate it.

Notatka: It is common technique to force the SQL parser to ignore the rest of the query written by the developer with -- which is the comment sign in SQL.

A feasible way to gain passwords is to circumvent your search result pages. What the attacker needs only is to try if there is any submitted variable used in SQL statement which is not handled properly. These filters can be set commonly in a preceding form to customize WHERE, ORDER BY, LIMIT and OFFSET clauses in SELECT statements. If your database supports the UNION construct, the attacker may try to append an entire query to the original one to list passwords from an arbitrary table. Using encrypted password fields is strongly encouraged.

Przykład 4-7. Listing out articles ... and some passwords (any database server)

$query  = "SELECT id, name, inserted, size FROM products
                  WHERE size = '$size'
                  ORDER BY $order LIMIT $limit, $offset;";
$result = odbc_exec($conn, $query);
The static part of the query can be combined with another SELECT statement which reveals all passwords:

'
union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable;
--

If this query (playing with the ' and --) were assigned to one of the variables used in $query, the query beast awakened.

SQL UPDATEs are also subject to attacking your database. These queries are also threatened by chopping and appending an entirely new query to it. But the attacker might fiddle with the SET clause. In this case some schema information must be possessed to manipulate the query successfully. This can be acquired by examing the form variable names, or just simply brute forcing. There are not so many naming convention for fields storing passwords or usernames.

Przykład 4-8. From resetting a password ... to gaining more privileges (any database server)

$query = "UPDATE usertable SET pwd='$pwd' WHERE uid='$uid';";
But a malicious user sumbits the value ' or uid like'%admin%'; -- to $uid to change the admin's password, or simply sets $pwd to "hehehe', admin='yes', trusted=100 " (with a trailing space) to gain more privileges. Then, the query will be twisted:

// $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 ...;"

A frightening example how operating system level commands can be accessed on some database hosts.

Przykład 4-9. Attacking the database host's operating system (MSSQL Server)

$query  = "SELECT * FROM products WHERE id LIKE '%$prod%'";
$result = mssql_query($query);
If attacker submits the value a%' exec master..xp_cmdshell 'net user test testpass /ADD' -- to $prod, then the $query will be:

$query  = "SELECT * FROM products WHERE id LIKE '%a%' exec master..xp_cmdshell 'net user test testpass /ADD'--";
$result = mssql_query($query);

MSSQL Server executes the SQL statements in the batch including a command to add a new user to the local accounts database. If this application were running as sa and the MSSQLSERVER service is running with sufficient privileges, the attacker would now have an account with which to access this machine.

Notatka: Some of the examples above is tied to a specific database server. This does not mean that a similar attack is impossible against other products. Your database server may be so vulnerable in other manner.


Avoiding techniques

You may plead that the attacker must possess a piece of information about the database schema in most examples. You are right, but you never know when and how it can be taken out, and if it happens, your database may be exposed. If you are using an open source, or publicly available database handling package, which may belong to a content management system or forum, the intruders easily produce a copy of a piece of your code. It may be also a security risk if it is a poorly designed one.

These attacks are mainly based on exploiting the code not being written with security in mind. Never trust on any kind of input, especially which comes from the client side, even though it comes from a select box, a hidden input field or a cookie. The first example shows that such a blameless query can cause disasters.

  • Never connect to the database as a superuser or as the database owner. Use always customized users with very limited privileges.

  • Check if the given input has the expected data type. PHP has a wide range of input validating functions, from the simplest ones found in Variable Functions and in Character Type Functions (e.g. is_numeric(), ctype_digit() respectively) onwards the Perl compatible Regular Expressions support.

  • If the application waits for numerical input, consider to verify data with is_numeric(), or silently change its type using settype(), or use its numeric representation by sprintf().

    Przykład 4-10. A more secure way to compose a query for paging

    settype($order, '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);

  • Quote each non numeric user input which is passed to the database with addslashes() or addcslashes(). See the first example. As the examples shows, quotes burnt into the static part of the query is not enough, and can be easily hacked.

  • Do not print out any database specific information, especially about the schema, by fair means or foul. See also Error Reporting and Error Handling and Logging Functions.

  • You may use stored procedures and previously defined cursors to abstract data access so that users do not directly access tables or views, but this solution has another impacts.

Besides these, you benefit from logging queries either within your script or by the database itself, if it supports. Obviously, the logging is unable to prevent any harmful attempt, but it can be helpful to trace back which application has been circumvented. The log is not useful by itself, but through the information it contains. The more detail is generally better.


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:

Przykład 4-11. Attacking Variables with a custom HTML page

<form method="post" action="attacktarget?username=badfoo&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 occured 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:

Przykład 4-12. Exploiting common debugging variables

<form method="post" action="attacktarget?errors=Y&amp;showerrors=1"&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 webserver 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, by using E_NONE, you insulate your code from probing.

Przykład 4-13. 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
    fpassthru ("/highly/sensitive/data/index.html");
}
?>


Using Register Globals

One feature of PHP that can be used to enhance security is configuring PHP with register_globals = off. By turning off the ability for any user-submitted variable to be injected into PHP code, you can reduce the amount of variable poisoning a potential attacker may inflict. They will have to take the additional time to forge submissions, and your internal variables are effectively isolated from user submitted data.

While it does slightly increase the amount of effort required to work with PHP, it has been argued that the benefits far outweigh the effort.

Przykład 4-14. Working without register_globals=off

<?php
if ($username) {  // can be forged by a user in get/post/cookies
    $good_login = 1;
}

if ($good_login == 1) { // can be forged by a user in get/post/cookies,
    fpassthru ("/highly/sensitive/data/index.html");
}
?>

Przykład 4-15. Working with register_globals = off

<?php
if($HTTP_COOKIE_VARS['username']){
    // can only come from a cookie, forged or otherwise
    $good_login = 1;
    fpassthru ("/highly/sensitive/data/index.html");
}
?>
By using this wisely, 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 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.

Przykład 4-16. Detecting simple variable poisoning

<?php
if ($HTTP_COOKIE_VARS['username'] &&
    !$HTTP_POST_VARS['username'] &&
    !$HTTP_GET_VARS['username'] ) {
    // Perform other checks to validate the user name...
    $good_login = 1;
    fpassthru ("/highly/sensitive/data/index.html");
} else {
   mail("admin@example.com", "Possible breakin attempt", $HTTP_SERVER_VARS['REMOTE_ADDR']);
   echo "Security violation, admin has been alerted.";
   exit;
}
?>
Of course, simply turning off register_globals does not mean code is secure. For every piece of data that is submitted, it should also be checked in other ways.


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.

Przykład 4-17. 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/password entry?
fputs ($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).


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 = 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:

Przykład 4-18. 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:

Przykład 4-19. 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:

Przykład 4-20. 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.


Keeping Current

PHP, like any other large system, is under constant scrutiny and improvement. Each new version will often include both major and minor changes to enhance and repair security flaws, configuration mishaps, and other issues that will affect the overall security and stability of your system.

Like other system-level scripting languages and programs, the best approach is to update often, and maintain awareness of the latest versions and their changes.


Rozdział 5. Podstawowa składnia

Wyskakiwanie z HTMLa

Kiedy PHP zaczyna przetwarzać plik, po prostu wyświetla tekst, który napotka. Zatem, jeśli zmienisz rozszerzenie pliku HTML na .php, ten plik będzie działał nadal.

Jeśli chcesz wstawić komendy PHP w jakimś miejscu w swoim dokumencie musisz to zasygnalizować, wchodząc w "tryb PHP" którymś ze sposobów podanych poniżej:

Przykład 5-1. Możliwości wyskoczenia z HTMLa

1.  <? echo ("To jest najprostszy test, instrukcja SGML\n"); ?>
    <?= wyrażenie ?> To jest skrót takiej formy: "<? echo wyrażenie ?>"

2.  <?php echo("Jeśli chcesz używać dokumentów XHTML i XML, rób to tak\n"); ?>

3.  <script language="php">
	echo ("Niektóre edytory (jak FrontPage)
	      nie lubią instrukcji wchodzących w 'tryb PHP'");
    </script>

4.  <% echo ("Możesz także użyć znaczników w stylu ASP"); %>
    <%= $variable; # To jest skrót takiej formy: "<%echo .." %>

Pierwszy sposób jest dostępny tylko kiedy zostały włączone krótkie znaczniki. Można to zrobić wpisując short_open_tag do pliku konfiguracyjnego PHP albo kompilując PHP dodając --enable-short-tags do configure.

Drugi sposób jest preferowany, zapewnia on następnej generacji XHTMLa łatwą implementację w PHP.

Czwarty sposób jest dostępny tylko kiedy znaczniki ASP zostały włączone poprzez uaktywnianie opcji konfiguracyjnej asp_tags.

Notatka: Obsługa dla znaczników ASP została dodana w wersji 3.0.4.

Znacznik zamykający blok będzie dodawał końcową nową linię, jeśli taka istnieje.

PHP pozawala ci używać takich struktur:

Przykład 5-2. Zaawansowane wyskakiwanie

<?php

if (wyrazenie-logiczne) {
    ?>
<strong>prawda </strong>
    <?php
} else {
    ?>
<strong>fałsz </strong>
    <?php
}
    ?>
Powyższy kod działa, ponieważ PHP traktuje tekst pomiędzy ?> i <?php jak gdyby była to funkcja echo().


Oddzielanie instrukcji

Instrukcje są oddzielane tak samo jak w C czy Perlu - należy kończyć każde wyrażenie średnikiem.

Znacznik zamykający (?>) także kończy instrukcję, więc poniższe przykłady są równoważne:

<?php
    echo "To jest test";
?>

<?php echo "To jest test" ?>


Kometarze

PHP obsługuje komentarze w stylu C, C++ oraz komentarze używane w powłokach uniksowych ("#"):

<?php
    echo "To jest test"; // to jest kometarz jednoliniowy w stylu C++
    /* to jest komentarz wieloliniowy
       a tutaj inna komentowana linia */
    echo "To jest jeszcze jeden test";
    echo "Ostatni test"; # to jest kometarz w stylu shell'a
?>

Komentarze typu jednoliniowego mają zasięg do końca linii w której się znajdują lub do końca bloku kodu PHP, zależnie co wystąpi pierwsze.

<h1>To jest <?php # echo "prosty";?> przykład.</h1>
<p>Powyższy kod wypisze zdanie "To jest przykład."

Pownieneś uważać by nie zagnieżdżać komentarzy w stylu C++ (szczególnie komentarzy wieloliniowych), co może się stać kiedy komentujesz dłuższy blok kodu.

<?php
 /*
    echo "To jest test"; /* ten komentarz spowoduje problem */
 */
?>


Rozdział 6. Types

Introduction

PHP supports eight primitive types.

Four scalar types:

Two compound types:

And finally two special types:

Notatka: In this manual you'll often find mixed parameters. This pseudo-type indicates multiple possiblities for that parameter.

The type of a variable is usually not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used.

Notatka: If you want to check out the type and value of a certain expression, use var_dump().

If you simply want a human-readable representation of the type for debugging, use gettype(). To check for a certain type, do not use gettype(), but use the is_type functions.

If you would like to force a variable to be converted to a certain type, you may either cast the variable or use the settype() function on it.

Note that a variable may behave in different manners in certain situations, depending on what type it is at the time. For more information, see the section on Type Juggling.


Booleans

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

Notatka: The boolean type was introduced in PHP 4.


Syntax

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

$foo = True; // assign the value TRUE to $foo

Usually you use some kind of operator which returns a boolean value, and then pass it on to a control structure.

// == is an operator which 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 you can simply type this:
if ($show_separators) {
    echo "<hr>\n";
}


Converting to boolean

To explicitly convert a value to boolean, use either the (bool) or the (boolean) cast. However, in most cases you do not need to use the cast, 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:

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

Ostrze¿enie

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


Integers

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

See also: Arbitrary precision integers and Floating point numbers


Syntax

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

If you use the octal notation, you must precede the number with a 0 (zero), to use hexadecimal notation precede the number with 0x.

Przykład 6-1. Integer literals

$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)
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 overflow

If you specify a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, if you perform an operation that results in a number beyond the bounds of the integer type, a float will be returned instead.

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

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

// this goes also for hexadecimal specified integers:
var_dump( 0x80000000 );
// output: float(2147483648)

$million = 1000000;
$large_number =  50000 * $million;
var_dump($large_number);
// output: float(50000000000)

Ostrze¿enie

Unfortunately, there was a bug in PHP so that this does not always work correctly when there are negative numbers involved. For example: when you do -50000 * $million, the result will be -429496728. However, when both operands are positive there is no problem.

This is solved in PHP 4.1.0.

There is no integer division operator in PHP. 1/2 yields the float 0.5.

var_dump( 25/7 );
// output: float(3.5714285714286)


Converting to integer

To explicitly convert a value to integer, use either the (int) or the (integer) cast. However, in most cases you do not need to use the cast, since a value will be automatically converted if an operator, function or control structure requires a integer argument.

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 hasn't got enough precision to give an exact integer result. No warning, not even a notice will be issued in this case!

Ostrze¿enie

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

echo (int) ( (0.1+0.7) * 10 ); // echoes 7!

See for more information the warning about float-precision.


From other types

Uwaga!

Behaviour of converting to integer is undefined for other types. Currently, the behaviour is the same as if the value was first converted to boolean. However, do not relay on this behaviour, as it can change without notice.


Floating point numbers

Floating point numbers (AKA "floats", "doubles" or "real numbers") can be specified using any of the following syntaxes:
$a = 1.234; $a = 1.2e3; $a = 7E-10;
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 (that's 64 bit IEEE format).

Floating point precision

It is quite usual that simple decimal fractions like 0.1 or 0.7 cannot be converted into their internal binary counterparts without a little 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 as the result of the internal representation really being something like 7.9999999999....

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

So never trust floating number results to the last digit and never compare floating point numbers for equality. If you really need higher precision, you should use the arbitrary precision math functions or gmp functions instead.


Strings

A string is series of characters. In PHP, 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.

Notatka: It is no problem for a string to become very large. There is no practical bound to the size of strings imposed by PHP, so there is no reason at all to worry about long strings.


Syntax

A string literal can be specified in three different ways.


Single quoted

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

To specify a literal single quote, you will need to escape it with a backslash (\), like in many other languages. If a backslash needs to occur before a single quote or at the end of the string, you need to double it. Note that if you try to escape any other character, the backslash too will be printed! So usually there is no need to escape the backslash itself.

Notatka: In PHP 3, a warning will be issued at the E_NOTICE level when this happens.

Notatka: Unlike the two other syntaxes, variables will not be expanded when they occur in single quoted strings.

echo 'this is a simple string';
echo 'You can also have embedded newlines in strings,
like this way.';
echo 'Arnold once said: "I\'ll be back"';
// output: ... "I'll be back"
echo 'Are you sure you want to delete C:\\*.*?';
// output: ... delete C:\*.*?
echo 'Are you sure you want to delete C:\*.*?';
// output: ... delete C:\*.*?
echo 'I am trying to include at this point: \n a newline';
// output: ... this point: \n a newline


Double quoted

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

Tabela 6-1. Escaped characters

sequencemeaning
\nlinefeed (LF or 0x0A (10) in ASCII)
\rcarriage return (CR or 0x0D (13) in ASCII)
\thorizontal tab (HT or 0x09 (9) in ASCII)
\\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

Again, if you try to escape any other character, the backslash will be printed too!

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


Heredoc

Another way to delimit strings is by using here doc syntax ("<<<"). One should provide an identifier after <<<, then the string, and then the same identifier to close the quotation.

The closing identifier must begin in the first column of the line. Also, the identifier used 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.

Ostrze¿enie

It is very important to note that the line with the closing identifier contains 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 after or before the semicolon.

Probably the nastiest gotcha is that there may also not be a carriage return (\r) at the end of the line, only a form feed, AKA newline (\n). Since Microsoft Windows uses the sequence \r\n as a line terminator, your heredoc may not work if you write your script in a Windows editor. However, most programming editors provide a way to save your files with a UNIX line terminator.

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

Przykład 6-2. Here doc 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;
?>

Notatka: Here doc support was added in PHP 4.


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 parse a variable, an array value, or an object property.

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


Simple syntax

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

$beer = 'Heineken';
echo "$beer's taste is great"; // works, "'" is an invalid character for varnames
echo "He drunk some $beers"; // won't work, 's' is a valid character for varnames
echo "He drunk some ${beer}s"; // works

Similarly, you can also have an array index or an object property parsed. With array indices, the closing square bracket (]) marks the end of the index. For object properties the same rules apply as to simple variables, though with object properties there doesn't exist a trick like the one with variables.

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

// note that this works differently outside string-quotes.
echo "A banana is $fruits[banana].";

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 you can include complex expressions this way.

In fact, you can include any value that is in the namespace in strings with this syntax. You simply write the expression the same way as you would outside the string, and then include it in { and }. Since you can't escape '{', this syntax will only be recognised when the $ is immediately following the {. (Use "{\$" or "\{$" to get a literal "{$"). Some examples to make it clear:

$great = 'fantastic';
echo "This is { $great}"; // won't work, outputs: This is { fantastic}
echo "This is {$great}";  // works, outputs: This is fantastic
echo "This square is {$square->width}00 centimeters broad."; 
echo "This works: {$arr[4][3]}";     

// This is wrong for the same reason
// as $foo[bar] is wrong outside a string. 
echo "This is wrong: {$arr[foo][3]}"; 

echo "You should do it this way: {$arr['foo'][3]}";
echo "You can even write {$obj->values[3]->name}";
echo "This is the value of the var named $name: {${$name}}";


String access by character

Characters within strings may be accessed by specifying the zero-based offset of the desired character after the string in curly braces.

Notatka: For backwards compatibility, you can still use the array-braces. However, this syntax is deprecated as of PHP 4.

Przykład 6-3. Some string examples

<?php
/* Assigning a string. */
$str = "This is a string";

/* Appending to it. */
$str = $str . " with some more text";

/* Another way to append, includes an escaped newline. */
$str .= " and a newline at the end.\n";

/* This string will end up being '<p>Number: 9</p>' */
$num = 9;
$str = "<p>Number: $num</p>";

/* This one will be '<p>Number: $num</p>' */
$num = 9;
$str = '<p>Number: $num</p>';

/* Get the first character of a string  */
$str = 'This is a test.';
$first = $str{0};

/* Get the last character of a string. */
$str = 'This is still a test.';
$last = $str{strlen($str)-1};
?>


Useful functions

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

There are a lot of useful functions for string modification.

See the string functions section for general functions, the regular expression functions for advanced find&replacing (in two tastes: Perl and POSIX extended).

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

Finally, if you still didn't find what you're looking for, see also the character type functions.


String conversion

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

The string will evaluate as a float if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will evaluate as an integer.

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.

When the first expression is a string, the type of the variable will depend on the second expression.

$foo = 1 + "10.5";              // $foo is float (11.5)
$foo = 1 + "-1.3e3";            // $foo is float (-1299)
$foo = 1 + "bob-1.3e3";         // $foo is integer (1)
$foo = 1 + "bob3";              // $foo is integer (1)
$foo = 1 + "10 Small Pigs";     // $foo is integer (11)
$foo = 1 + "10 Little Piggies"; // $foo is integer (11)
$foo = "10.0 pigs " + 1;        // $foo is integer (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).

If you would like to test any of the examples in this section, you can cut and paste the examples and insert the following line to see for yourself what's going on:

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


Arrays

An array in PHP is actually an ordered map. A map is a type that maps values to keys. This type is optimized in several ways, so you can use it as a real array, or a list (vector), hashtable (which is an implementation of a map), dictionary, collection, stack, queue and probably more. Because you can have another PHP-array as a value, you can also quite easily simulate trees.

Explanation of those structures is beyond the scope of this manual, but you'll find at least one example for each of those structures. For more information about those structures, we refer you to external literature about this broad topic.


Syntax

Specifying with array()

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

A key is either a nonnegative integer or a string. If a key is the standard representation of a non-negative integer, it will be interpreted as such (i.e. '8' will be interpreted as 8, while '08' will be interpreted as '08').

A value can be anything.

If you omit a key, the maximum of the integer-indices is taken, and the new key will be that maximum + 1. If no integer-indices exist yet, the key will be 0 (zero). If you specify a key that already has a value assigned to it, that value will be overwritten.

array( [key =>] value
     , ...
     )
// key is either string or nonnegative integer
// value can be anything


Creating/modifying with square-bracket syntax

You can also modify an existing array, by explicitly setting values.

This is done by assigning values to the array while specifying the key in brackets. You can also omit the key, add an empty pair of brackets ("[]") to the variable-name in that case.
$arr[key] = value;
$arr[] = value;
// key is either string or nonnegative integer
// value can be anything
If $arr doesn't exist yet, it will be created. So this is also an alternative way to specify an array. To change a certain value, just assign a new value to it. If you want to remove a key/value pair, you need to unset() it.


Useful functions

There are quite some useful function for working with arrays, see the array-functions section.

Notatka: The unset() function allows unsetting keys of an array. Be aware that the array will NOT be reindexed.

$a = array( 1 => 'one', 2 => 'two', 3 => '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');
*/

The foreach control structure exists specificly for arrays. It provides an easy way to traverse an array.


Array do's and don'ts

Why is $foo[bar] wrong?

You might have seen the following syntax in old scripts:

$foo[bar] = 'enemy';
echo $foo[bar];
// etc

This is wrong, but it works. Then, why is it wrong? The reason is that, as stated in the syntax section, there must be an expression between the square brackets ('[' and ']'). That means that you can write things like this:

echo $arr[ foo(true) ];

This is an example of using a function return value as the array index. PHP knows also about constants, and you may have seen the E_* before.

$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:

$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.

Then, how is it possible that $foo[bar] works? It works, because bar is due to its syntax expected to be a constant expression. However, in this case no constant with the name bar exists. PHP now assumes that you meant bar literally, as the string "bar", but that you forgot to write the quotes.


So why is it bad then?

At some point in the future, the PHP team might want to add another constant or keyword, and then you get in trouble. For example, you already cannot use the words empty and default this way, since they are special keywords.

And, if these arguments don't help: this syntax is simply deprecated, and it might stop working some day.

Notatka: When you turn error_reporting to E_ALL, you will see that PHP generates warnings whenever this construct is used. This is also valid for other deprecated 'features'. (put the line error_reporting(E_ALL); in your script)

Notatka: Inside a double-quoted string, an other syntax is valid. See variable parsing in strings for more details.


Examples

The array type in PHP is very versatile, so here will be some examples to show you the full power of arrays.

// this
$a = array( 'color' => 'red'
          , 'taste' => 'sweet'
          , 'shape' => 'round'
          , 'name'  => 'apple'
          ,            4        // key will be 0
          );

// is completely equivalent with
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name'] = 'apple';
$a[]        = 4;        // key will be 0

$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// will result in the array array( 0 => 'a' , 1 => 'b' , 2 => 'c' ),
// or simply array('a', 'b', 'c')

Przykład 6-4. Using array()

// 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();

Przykład 6-5. Collection

$colors = array('red','blue','green','yellow');

foreach ( $colors as $color ) {
    echo "Do you like $color?\n";
}

/* output:
Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?
*/

Note that it is currently not possible to change the values of the array directly in such a loop. A workaround is the following:

Przykład 6-6. Collection

foreach ($colors as $key => $color) {
    // won't work:
    //$color = strtoupper($color);
    
    //works:
    $colors[$key] = strtoupper($color);
}
print_r($colors);

/* output:
Array
(
    [0] => RED
    [1] => BLUE
    [2] => GREEN
    [3] => YELLOW
)
*/

This example creates a one-based array.

Przykład 6-7. One-based index

$firstquarter  = array(1 => 'January', 'February', 'March');
print_r($firstquarter);

/* output:
Array 
(
    [1] => 'January'
    [2] => 'February'
    [3] => 'March'
)
*/

Przykład 6-8. Filling real array

// fill an array with all items from a directory
$handle = opendir('.');
while ($file = readdir($handle)) 
{
    $files[] = $file;
}
closedir($handle);

Arrays are ordered. You can also change the order using various sorting-functions. See array-functions for more information.

Przykład 6-9. Sorting array

sort($files);
print_r($files);

Because the value of an array can be everything, it can also be another array. This way you can make recursive and multi-dimensional arrays.

Przykład 6-10. Recursive and multi-dimensional arrays

$fruits = array ( "fruits"  => array ( "a" => "orange"
                                     , "b" => "banana"
                                     , "c" => "apple"
                                     )
                , "numbers" => array ( 1
                                     , 2
                                     , 3
                                     , 4
                                     , 5
                                     , 6
                                     )
                , "holes"   => array (      "first"
                                     , 5 => "second"
                                     ,      "third"
                                     )
                );

Objects

Object Initialization

To initialize an object, you use the new statement to instantiate the object to a variable.

<?php
class foo
{
    function do_foo()
    {
        echo "Doing foo."; 
    }
}

$bar = new foo;
$bar->do_foo();
?>

For a full discussion, please read the section Classes and Objects.


Resource

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.

Notatka: The resource type was introduced in PHP 4


Freeing resources

Due to the reference-counting system introduced with PHP4's Zend-engine, it is automatically detected when a resource is no longer referred to (just like Java). When this is the case, all resources that were in use for this resource are made free by the garbage collector. For this reason, it is rarely ever necessary to free the memory manually by using some free_result function.

Notatka: Persistent database-links are special, they are not destroyed by the gc. See also persistent links


NULL

The special NULL value represents that a variable has no value. NULL is the only possible value of type NULL.

Notatka: The null type was introduced in PHP 4


Syntax

There is only one value of type NULL, and that is the case-insensitive keyword NULL.

$var = NULL;


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 that variable is used. That is to say, if you assign a string value to variable var, var becomes a string. If you then assign an integer value to var, it becomes an integer.

An example of PHP's automatic type conversion is the addition operator '+'. If any of the operands is a float, then all 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.

$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 = 5 + "10 Little Piggies"; // $foo is integer (15)
$foo = 5 + "10 Small Pigs";     // $foo is integer (15)

If the last two examples above seem odd, see String conversion.

If you wish to force a variable to be evaluated as a certain type, see the section on Type casting. If you wish to change the type of a variable, see settype().

If you would like to test any of the examples in this section, you can use the var_dump() function.

Notatka: The behaviour of an automatic conversion to array is currently undefined.

$a = 1;       // $a is an integer
$a[0] = "f";  // $a becomes an array, with $a[0] holding "f"

While the above example may seem like it should clearly result in $a becoming an array, the first element of which is 'f', consider this:

$a = "1";     // $a is a string
$a[0] = "f";  // What about string offsets? What happens?

Since PHP supports indexing into strings via offsets using the same syntax as array indexing, the example above leads to a problem: should $a become an array with its first element being "f", or should "f" become the first character of the string $a?

For this reason, as of PHP 3.0.12 and PHP 4.0b3-RC4, the result of this automatic conversion is considered to be undefined. Fixes are, however, being discussed.


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.

$foo = 10;   // $foo is an integer
$bar = (float) $foo;   // $bar is a float

The casts allowed are:

  • (int), (integer) - cast to integer

  • (bool), (boolean) - cast to boolean

  • (float), (double), (real) - cast to float

  • (string) - cast to string

  • (array) - cast to array

  • (object) - cast to object

Notatka: Instead of casting a variable to string, you can also enclose the variable in double quotes.

Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent:

$foo = (int) $bar;
$foo = ( int ) $bar;

It may not be obvious exactly what will happen when casting between certain types. For more info, see these sections:

When casting or forcing a conversion from array to string, the result will be the word Array. When casting or forcing a conversion from object to string, the result will be the word Object.

When casting from a scalar or a string variable to an array, the variable will become the first element of the array:

$var = 'ciao';
$arr = (array) $var;
echo $arr[0];  // outputs 'ciao'

When casting from a scalar or a string variable to an object, the variable will become an attribute of the object; the attribute name will be 'scalar':

$var = 'ciao';
$obj = (object) $var;
echo $obj->scalar;  // outputs 'ciao'


Rozdział 7. Zmienne

Podstawy

Każdą zmienną w PHP zapisuje się, poprzedzając jej nazwę znakiem dolara "$". Wielkość liter w nazwie zmiennej jest rozróżniana.

Nazw zmiennych dotyczą te same reguły, co innych rodzajów nazw w PHP. Poprawna nazwa zmiennej zaczyna się od litery lub znaku podkreślenia "_", po których może wystąpić dowolna ilość liter, cyfr lub znaków podkreślenia. Jako wyrażenie regularne, można to zapisać tak: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

Notatka: W naszym rozumieniu, litery to znaki a-z, A-Z i symbole ASCII od 127 do 255 (0x7f-0xff).

$var = "Bob";
$Var = "Joe";
echo "$var, $Var";      // wyświetla "Bob, Joe"

$4site = 'not yet';     // niepoprawna nazwa - zaczyna się od cyfry
$_4site = 'not yet';    // poprawna nazwa - zaczyna się znakiem podkreślenia
$jaźń = 'not yet';    // poprawna nazwa - "ń" i "ź" należą do ASCII > 127

W PHP 3, przypisanie zmiennych jest możliwe tylko przez wartość. Innymi słowy, jeśli przypiszesz do zmiennej jakieś wyrażenie, wartość tego wyrażenia zostanie skopiowana do zmiennej. Oznacza to, że po przypisaniu wartości jednej zmiennej do drugiej, późniejsza zmiana wartości jednej z nich nie spowoduje zmiany wartości drugiej. Więcej informacji na ten temat w rozdziale Wyrażenia.

PHP 4 oferuje jeszcze jeden sposób przypisywania wartości do zmiennych: przypisanie przez referencję. Oznacza to, że nowa zmienna tylko odnosi się (innymi słowy, "staje się aliasem" lub "wskazuje na") do pierwotnej zmiennej. Zmiany wykonane na nowej zmiennej oddziałują także na pierwotną zmienną i vice versa. Ma to też takie znaczenie, że nie następuje żadna operacja skopiowania, czyli przypisanie następuje szybciej. Jednakże wyraźne przyspieszenie działania może być widoczne tylko w pętlach zwartych (ang. tight loops), lub przy przypisywaniu dużych tablic lub obiektów.

Aby przypisać przez referencję, postaw znak ampersand (&) przed nazwą zmiennej przypisywanej (zmiennej od której pobierasz wartość). Na przykład poniższy kod wyświetla "To jest PHP" dwa razy:

<?php
$foo = "PHP";               // Przypisz wartość "PHP" do $foo.
$bar = &$foo;               // Przypisz referencyjnie $foo do $bar.
$bar = "To jest $bar";      // Zmień $bar...
echo $foo;                  // $foo też się zmieniło.
echo $bar;
?>

Należy pamiętać, że tylko wyrażenia posiadające nazwę mogą być przypisane przez referencję.

<?php
$foo = 25;
$bar = &$foo;      // Przypisanie poprawne.
$bar = &(24 * 7);  // Przypisanie niepoprawne - do nienazwanego wyrażenia.

function test()
{
   return 25;
}

$bar = &test();    // Niepoprawne.
?>


Zmienne predefiniowane

PHP udostępnia dużą ilość predefiniowanych zmiennych dla każdego pracującego skryptu. Jednakże wiele spośród tych zmiennych nie może być w pełni objaśnionych, gdyż są zależne od rodzaju serwera, jego wersji i ustawień i innych czynników. Niektóre z tych zmiennych nie będą dostępne dla skryptów PHP uruchomionych z linii poleceń.

Niezależnie od wymienionych czynników, poniżej przedstawiamy listę predefiniowanych zmiennych, dostępnych w typowej instalacji PHP 3, działającej jako moduł typowej instalacji Apache 1.3.6.

W celu zapoznania się ze wszystkimi predefiniowanymi zmiennymi (i mnóstwem innych, użytecznych informacji) użyj phpinfo().

Notatka: Poniższa lista nie jest i nie będzie wyczerpująca. Jest to wyłącznie wskazówka, jakich rodzajów predefiniowanych zmiennych możesz użyć w swoim skrypcie.


Zmienne Apache'a

Zmienne te dostarczane są przez serwer www Apache. Jeśli używasz innego serwera, nie ma żadnej gwarancji, że zmienne te będą dostępne. Inny serwer może pominąć jakąś zmienną lub dostarczać zmienne inne niż te. Jakkolwiek spora część tych zmiennych jest zarejestrowana w specyfikacji CGI 1.1, więc dostęp do nich powinien być możliwy.

Pamiętaj, że tylko kilka, jeśli w ogóle, spośród tych zmiennych jest dostępnych (albo będzie mieć jakiekolwiek znaczenie) kiedy skrypt PHP jest uruchomiony z linii poleceń.

$GATEWAY_INTERFACE

Określa wersję specyfikacji CGI obsługiwaną przez serwer, np. "CGI/1.1".

$SERVER_NAME

Nazwa hosta serwera, na którym skrypt jest wykonywany. Jeśli skrypt pracuje na hoście wirtualnym (ang. virtual host), zmienna będzie zawierać nazwę hosta wirtualnego.

$SERVER_SOFTWARE

Napis identyfikujący serwer, wysyłany z nagłówkami przy odpowiedzi na zapytanie.

$SERVER_PROTOCOL

Nazwa i wersja protokołu informacyjnego, przez który zostało wysłane zapytanie, np. "HTTP/1.1".

$REQUEST_METHOD

Metoda, która została użyta przy zapytaniu o dokument, np. "GET", "HEAD", "POST".

$QUERY_STRING

Łańcuch zapytania (np. ?foo=bar), o ile istnieje, jaki został przesłany z zapytaniem o stronę.

$DOCUMENT_ROOT

Folder główny na serwerze, taki jak określony w pliku konfiguracyjnym serwera.

$HTTP_ACCEPT

Zawartość nagłówka Accept: z aktualnego zapytania, o ile taki występuje.

$HTTP_ACCEPT_CHARSET

Zawartość nagłówka Accept-Charset: z aktualnego zapytania, o ile taki występuje, np. "iso-8859-1,*,utf-8". 'iso-8859-1,*,utf-8'.

$HTTP_ACCEPT_ENCODING

Zawartość nagłówka Accept-Encoding: z aktualnego zapytania, o ile taki występuje, np. "gzip".

$HTTP_ACCEPT_LANGUAGE

Zawartość nagłówka Accept-Language: z aktualnego zapytania, o ile taki występuje, np. "en".

$HTTP_CONNECTION

Zawartość nagłówka Connection: z aktualnego zapytania, o ile taki występuje, np. "Keep-Alive".

$HTTP_HOST

Zawartość nagłówka Host: z aktualnego zapytania, o ile taki występuje.

$HTTP_REFERER

Adres strony (o ile występuje) z której przeglądarka przeszła do tej strony. Nagłówek jest tworzony przez przeglądarkę użytkownika; nie wszystkie przeglądarki udostępniają taką informację.

$HTTP_USER_AGENT

Zawartość nagłówka User_Agent: z aktualnego zapytania, o ile taki występuje. Jest to napis identyfikujący oprogramowanie klienckie używane do obejrzenia danej strony, np. Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Można użyć tej informacji w połączeniu z get_browser(), aby dopasować stronę do możliwości przeglądarki użytkownika.

$REMOTE_ADDR

Numer IP zdalnego użytkownika przeglądającego stronę.

$REMOTE_PORT

Port używany na zdalnej maszynie, przez który następuje komunikacja z serwerem.

$SCRIPT_FILENAME

Bezwzględna ścieżka do aktualnie wykonywanego skrytpu.

$SERVER_ADMIN

Wartość podana w dyrektywie SERVER_ADMIN (dla Apache'a) w pliku konfiguracyjnym serwera. Jeśli skrypt jest uruchomiony na hoście wirtualnym, wtedy będzie to wartość określona dla tego hosta wirtualnego.

$SERVER_PORT

Port na serwerze, używany przez serwer www do komunikacji. Domyślnie jest to "80"; przy użyciu SSL, na przykład, będzie to numer portu na którym odbywają się zabezpieczone połączenia HTTP.

$SERVER_SIGNATURE

Napis zawierający nazwę i wersję serwera, oraz nazwę wirtualnego hosta, który jest dodawany do stron generowanych przez serwer, o ile włączony.

$PATH_TRANSLATED

Bezwzględna ścieżka do pliku, oparta na systemie plików (a nie wychodząca z folderu głównego serwera), określona po wykonaniu przez serwer ewentualnego mapowania ścieżki wirtualnej do rzeczywistej.

$SCRIPT_NAME

Zawiera ścieżkę do aktualnego skryptu. Przydatne przy stronach, które mają wskazywać na siebie same.

$REQUEST_URI

URI, który został podany, aby uzyskać dostęp do aktualnej strony, np. "/index.html".


Zmienne środowiskowe

Te zmienne są importowane do przestrzeni nazw globalnych PHP ze środowiska w jakim pracuje parser PHP. Wiele z nich jest udostępnianych przez powłokę systemu, w którym pracuje PHP, a ponieważ różne systemy używają różnych powłok, ścisła lista nie jest możliwa. Zapoznaj się z dokumentacją twojej powłoki (shella), aby dowiedzieć się, jakie zmienne środowiskowe ona udostępnia.

Niektóre zmienne środowiskowe zawierają zmienne CGI, w zależności od tego czy PHP pracuje jako moduł serwera, czy skrypt CGI.


Zmienne PHP

Zmienne te tworzone są przez PHP. Zmienne $HTTP_*_VARS są dostępne tylko, jeśli dyrektywa konfiguracyjna track_vars jest włączona. Kiedy dyrektywa jest włączona, zmienne są zawsze tworzone, nawet jeśli są pustymi tablicami. Zabezpiecza to przed złośliwymi użytkownikami, którzy mogliby podszywać swoje wartości pod te zmienne.

Notatka: Od PHP 4.0.3 dyrektywa track_vars jest zawsze włączona, niezależnie od wpisu w pliku konfiguracyjnym.

Notatka: Nowe "Superglobale" zostały dodane w PHP 4.1.0. Więcej szczegółów znajduje się w 4.1.0 Release Announcement. Są to tablice $_GET, $_POST, $_ENV, $_SERVER, $_COOKIE, $_REQUEST, $_FILES i $_SESSION; nieformalnie zwane Superglobale, ponieważ są zawsze dostępne dla programisty, niezależnie od aktualnego zasięgu innych zmiennych. Powyższe zmienne zastępują starsze tablice $HTTP_*_VARS.

Jeśli dyrektywa register_globals jest włączona, wtedy te zmienne będą również dostępne jako zmienne globalne, tzn. niezależnie od tablic $HTTP_*_VARS i $_*. Więcej informacji znajduje się w rozdziale poświęconym bezpieczeństwu, zatytułowanym Wykorzystywanie Zarejestrowanych Globali.

$argv

Tablica argumentów przekazanych do skryptu. Kiedy skrypt jest uruchamiany z linii poleceń, daje ona dostęp w stylu języka C do przełączników, z jakimi został wywołany skrypt. Kiedy skrypt zostanie wywołany metodą GET, tablica będzie zawierać łańcuch znaków zapytania (query string).

$argc

Liczba argumentów przekazanych do skryptu (jeśli uruchamiany z linii poleceń).

$PHP_SELF

Nazwa pliku aktualnie wykonywanego skryptu, ze ścieżką względną od głównego katalogu (document root). Jeśli PHP jest wywołane z linii poleceń, zmienna jest niedostępna. Zmienna ta zawiera informację o ścieżce do pliku, o ile taka istnieje (np. $PHP_SELF pod takim adresem: "http://example.com/test.php/foo.bar" zawierać będzie "/test.php/foo.bar").

$HTTP_COOKIE_VARS

Tablica asocjacyjna zmiennych przekazanych do skryptu przez ciasteczka HTTP.

$_COOKIE

Tablica asocjacyjna zmiennych przekazanych do skryptu przez ciasteczka HTTP. Zawsze globalna w każdym zasięgu. Wprowadzona w PHP 4.1.0.

$HTTP_GET_VARS

Tablica asocjacyjna zmiennych przekazanych do skryptu metodą GET protokołu HTTP.

$_GET

Tablica asocjacyjna zmiennych przekazanych do skryptu metodą GET protokołu HTTP. Zawsze globalna w każdym zasięgu. Wprowadzona w PHP 4.1.0.

$HTTP_POST_VARS

Tablica asocjacyjna zmiennych przekazanych do skryptu metodą POST protokołu HTTP.

$_POST

Tablica asocjacyjna zmiennych przekazanych do skryptu metodą POST protokołu HTTP. Zawsze globalna w każdym zasięgu. Wprowadzona w PHP 4.1.0.

$HTTP_POST_FILES

Tablica asocjacyjna zmiennych zawierających informację o plikach wysłanych do serwera (uploadowanych) metodą POST. Zobacz wysyłanie plików metodą POST aby dowiedzieć się więcej na temat zawartości $HTTP_POST_FILES. Wprowadzona w PHP 4.0.0.

$_FILES

Tablica asocjacyjna zmiennych zawierających informację o plikach wysłanych do serwera (uploadowanych) metodą POST. Zobacz wysyłanie plików metodą POST aby dowiedzieć się więcej na temat zawartości $_FILES. Zawsze globalna w każdym zasięgu. Wprowadzona w PHP 4.1.0.

$HTTP_ENV_VARS

Tablica asocjacyjna zmiennych przekazanych do skryptu ze środowiska operacyjnego serwera.

$_ENV

Tablica asocjacyjna zmiennych przekazanych do skryptu ze środowiska operacyjnego serwera. Zawsze globalna w każdym zasięgu. Wprowadzona w PHP 4.1.0.

$HTTP_SERVER_VARS

Tablica asocjacyjna zmiennych przekazanych do skryptu z serwera HTTP. Zmienne te są analogiczne do zmiennych Apache'a, opisanych powyżej.

$_SERVER

Tablica asocjacyjna zmiennych przekazanych do skryptu z serwera HTTP. Zmienne te są analogiczne do zmiennych Apache'a, opisanych powyżej. Zawsze globalna w każdym zasięgu. Wprowadzona w PHP 4.1.0.

$HTTP_SESSION_VARS

Tablica asocjacyjna zmiennych sesji przekazanych do skryptu.

$_SESSION

Tablica asocjacyjna zmiennych sesji przekazanych do skryptu. Zawsze globalna w każdym zasięgu. Dodawanie nowych wpisów do tablicy $_SESSION powoduje automatyczne zarejestrowanie ich jako zmiennych sesji, tak jakby wywołać session_register(). Wprowadzona w PHP 4.1.0.

$_REQUEST

Tablica asocjacyjna, stanowiąca połączenie zmiennych z GET, POST i ciasteczek. Innymi słowy - cała informacja przychodząca od użytkownika. Tablica ta z punktu widzenia bezpieczeństwa nie może być godna zaufania. Wprowadzona w PHP 4.1.0.


Zasięg zmiennych

Zasięg zmiennej jest zależny od miejsca, w jakim została zdefiniowana. Najczęściej zmienne PHP widoczne są tylko w pojedynczym zasięgu. Taki zasięg rozciąga się na pliki dołączane funkcjami include() i require(). Na przykład:

$a = 1;
include "b.inc";

Tutaj zmienna $a będzie dostępna także w dołączonym pliku b.inc. Jednakże w funkcjach zdefiniowanych przez użytkownika zmienne mają zasięg lokalny. Każda zmienna użyta wewnątrz funkcji jest domyślnie ograniczona do zasięgu lokalnego, np.

$a = 1; /* zasięg globalny */ 

function Test()
{ 
    echo $a; /* odwołanie do zmiennej o zasięgu lokalnym */ 
} 

Test();

Ten skrypt nie wyświetli niczego, ponieważ instrukcja echo odwołuje się do zmiennej lokalnej $a, której jak dotąd nie została przypisana żadna wartość. Można tu zauważyć różnicę w stosunku do języka C, gdzie zmienne globalne są zawsze dostępne wewnątrz definicji funkcji, o ile nie zostały nadpisane przez lokalną definicję zmiennej. Może to spowodować taki problem, że ktoś może nieodwracalnie zmienić wartość zmiennej globalnej. W PHP zmienne globalne muszą być jawnie określone jako globalne wewnątrz funkcji, w której mają być użyte, do czego używamy słowa kluczowego global. Na przykład:

$a = 1;
$b = 2;

function Sum()
{
    global $a, $b;

    $b = $a + $b;
} 

Sum();
echo $b;

Powyższy skrypt wyświetli wynik "3". Przez zadeklarowanie wewnątrz funkcji globalności zmiennych $a i $b, wszystkie odwołania do tych zmiennych będą odnosiły się do ich globalnych wersji. Nie ma żadnych ograniczeń w ilości zmiennych globalnych, na których chcemy operować wewnątrz funkcji.

Drugim sposobem uzyskania dostępu do zmiennych globalnych wewnątrz funkcji jest użycie specjalnej, zdefiniowanej przez PHP tablicy $GLOBALS. Powyższy przykład można zatem przepisać tak:

$a = 1;
$b = 2;

function Sum()
{
    $GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"];
} 

Sum();
echo $b;

$GLOBALS jest tablicą asocjacyjną, gdzie nazwa zmiennej jest kluczem, a zawartość zmiennej wartością komórki tablicy.

Jeszcze jedną ważną rzeczą, związaną z zasięgiem zmiennych jest zmienna statyczna (ang. static variable). Zmienna statyczna może mieć wyłącznie zasięg lokalny, ale nie traci swojej wartości, kiedy program opuści ten zasięg lokalny, w którym dana zmienna statyczna się znajduje. Proszę rozważyć poniższy przykład:

function Test ()
{
    $a = 0;
    echo $a;
    $a++;
}

Ta funkcja jest bezużyteczna, gdyż przy każdym jej wywołaniu zmienna $a otrzymuje wartość 0, w związku z czym funkcja stale wyświetla "0". Występująca potem inkrementacja $a++ nie ma żadnego znaczenia, gdyż funkcja się kończy i zmienna $a znika. Aby powyższa funkcja miała jakiś sens, należy zapobiec gubieniu wartości $a, do czego używamy słowa kluczowego static:

function Test()
{
    static $a = 0;
    echo $a;
    $a++;
}

Teraz, za każdym wywołaniem funkcji test, zostanie wyświetlona wartość zmiennej $a, po czym ta zmienna zostanie inkrementowana.

Zmienne statyczne pozwalają też na wykorzystanie funkcji rekurencyjnych, czyli takich, które wywołują same siebie. Funkcje rekurencyjne należy pisać ostrożnie, gdyż łatwo jest wywołać nieskończoną rekurencję. Musisz być pewny, że masz odpowiednie mechanizmy do zatrzymania rekurencji w pewnym momencie. Poniższa funkcja rekurencyjnie liczy do 10, używając zmiennej statycznej $licznik, aby wiedzieć, kiedy ma się zatrzymać:

function Test()
{
    static $licznik = 0;

    $licznik++;
    echo $licznik;
    if ($licznik < 10) {
        Test ();
    }
    $licznik--;
}


Zmienne zmienne

W niektórych przypadkach jest wygodne, by móc użyć zmiennej o zmiennej nazwie. To znaczy zmiennej, której nazwa może być zmieniana dynamicznie. Zwykła zmienna jest ustawiana wyrażeniem jak poniżej:

$a = "witaj";

Zmienna zmienna pobiera wartość jednej zmiennej i traktuje ją jako nazwę zmiennej. W powyższym przykładzie, witaj może stać się nazwą zmiennej, przy użyciu dwóch znaków dolara, tzn.

$$a = "świecie";

W tym momencie dwie zmienne zostały zdefiniowane i umieszczone w drzewie symbolicznym PHP: $a zawierająca "witaj" i $witaj zawierająca "świecie". Zatem poniższy zapis:

echo "$a ${$a}";

znaczy to samo, co:

echo "$a $witaj";

tzn. obydwa wyświetlą: witaj świecie.

Aby używać zmiennych zmiennych jako tablic, trzeba rozwiązać pewną niejasność. Mianowicie, jeśli napiszesz $$a[1], parser musi wiedzieć, czy chesz użyć $a[1] jako nazwy zmiennej, czy $$a jako nazwy tablicy, której rekord [1] cię interesuje. W tym przypadku należy zastosować odrębną składnię: ${$a[1]} dla pierwszego przypadku a ${$a}[1] dla drugiego.


Zmienne spoza PHP

Formularze HTML (GET i POST)

Kiedy do skryptu PHP zostanie wysłany formularz, każda zmienna z tego formularza zostanie automatycznie dostarczona do tego skryptu przez PHP. Jeśli dyrektywa track_vars jest włączona, to zmienne te będą umieszczone w tablicach asocjacyjnych $HTTP_POST_VARS (zmienne wysłane metodą POST), $HTTP_GET_VARS (zmienne wysłane metodą GET), i/lub $HTTP_POST_FILES (plik wysłane metodą POST), w zależności od rodzaju zmiennych w zapytaniu.

Więcej informacji na ten temat w rozdziale Zmienne predefiniowane.

Przykład 7-1. Prosty formularz ze zmienną

<form action="foo.php" method="post">
    Name: <input type="text" name="username"><br>
    <input type="submit">
</form>

Kiedy powyższy formularz zostanie wysłany, wartość wprowadzona do pola tekstowego będzię dostępna w $HTTP_POST_VARS['username']. Jeśli dyrektywa register_globals jest włączona, zmienna z formularza będzie także dostępna jako zmienna globalna $username.

Notatka: Dyrektywa konfiguracyjna magic_quotes_gpc oddziałuje na zmienne z Get, Post i Cookie. Jeśli włączona, tekst (It's "PHP!") automagicznie zmieni się w (It\'s \"PHP!\"). Jest to potrzebne przy wpisywaniu danych do baz danych. Zobacz też addslashes(), stripslashes() i magic_quotes_sybase.

PHP obsługuje także tablice w kontekście zmiennych z formularzy (zajrzyj do FAQ). Można na przykład pogrupować razem powiązane zmienne lub użyć tej możliwości do pobrania wartości z pola wyboru (select):

Przykład 7-2. Bardziej złożone zmienne w formularzach

<form action="array.php" method="post">
    Nazwisko: <input type="text" name="personal[nazwisko]">&lt;br>
    Email: <input type="text" name="personal[email]">&lt;br>
    Piwo: <br>
    <select multiple name="piwo[]">
        <option value="zywiec">Żywiec
        <option value="lech">Lech
        <option value="cooler">Cooler
        </select>
    <input type="submit">
</form>

W PHP 3 tablice w formularzach mogły być tylko jednowymiarowe. W PHP 4 nie ma takich ograniczeń.


Nazwy zmiennych dla SUBMIT w postaci obrazka

Przy tworzeniu formularza, można użyć obrazka, zamiast standardowego przycisku Wyślij, za pomocą takiego znacznika:

<input type="image" src="image.gif" name="sub">

Kiedy użytkownik kliknie gdzieś na obrazku, formularz, którego to dotyczy, zostanie wysłany do serwera z dwiema dodatkowymi zmiennymi, sub_x i sub_y. Zawierają one koordynaty miejsca kliknięcia na obrazek. Można przy tym zauważyć, że w nazwach zmiennych jest kropka a nie podkreślnik, ale PHP konwertuje kropkę na podkreślnik automatycznie. (Zobacz Kropki w nazwach nadchodzących zmiennych).


Ciasteczka HTTP

PHP bez problemu obsługuje ciasteczka HTTP, takie jak zdefiniowano w Specyfikacji Netscape'a. Ciasteczka są mechanizmem przechowywania informacji w przeglądarce klienta w celu śledzenia lub identyfikowania stałych bywalców strony. Ciasteczka ustawia się za pomocą funkcji setcookie(). Ciasteczka są częścią nagłówka HTTP, więc funkcja SetCookie musi być wywołana zanim jakakolwiek inna informacja zostanie wysłana do przeglądarki. Takie samo ograniczenie dotyczy funkcji header(). Wszystkie ciasteczka odebrane od klienta zostaną automatycznie zamienione w zmienne PHP, podobnie jak dane odebrane metodą GET lub POST.

Jeśli chcesz przypisać wiele wartości do jednego ciasteczka, dodaj [] do jego nazwy. Na przykład:

setcookie("MyCookie[]", "Testing", time()+3600);

Pamiętaj, że wysłane ciasteczko zastąpi wcześniejsze ciasteczko o tej nazwie, o ile ścieżka lub domena nie są różne. Na przykład dla koszyka do zakupów możesz potrzebować licznika a jego wartość stale przekazywać dalej, tzn.

Przykład 7-3. Przykład zastosowania SetCookie

$ilosc++;
setcookie("ilosc", $ilosc, time()+3600);
setcookie("koszyk[$ilosc]", $towar, time()+3600);
P&

Zmienne środowiskowe

PHP samoczynnie udostępnia zmienne środowiskowe jak zwykłe zmienne PHP.

echo $HOME;  /* Wyświetli zmienną środowiskową HOME, o ile ta ma jakąś wartość 
             */

Ponieważ informacje nadchdzące przez GET, POST i ciasteczka również są udostępniane jako zmienne, czasem jest lepiej odczytać zmienne środowiskowe bezpośrednio ze środowiska, aby mieć pewność, że otrzymuje się prawdziwą wartość zmiennej. W tym celu używa się funkcji getenv(). Można także samodzielnie ustawić wartość zmiennej środowiskowej za pomocą funkcji putenv().


Kropki w nazwach nadchodzących zmiennych

PHP normalnie nie zmienia nazw zmiennych przekazywanych do skryptu. Jednakże należy pamiętać, że kropka "." nie jest poprawnym znakiem w nazwie zmiennej. Dlaczego, proszę spojrzeć na to:
$varname.ext;  /* niepoprawna nazwa zmiennej */
To co widzi parser, to zmienna o nazwie $varname, po której pojawia się operator konkatenacji, a następnie pusty łańcuch (czyli taki, który nie jest żadnym słowem kluczowym, ani zarezerwowanym) "ext". Oczywiście, nie daje to żadnego sensownego wyniku.

Warto zatem wiedzieć, że PHP automatycznie zastąpi podkreślnikiem "_" każdą kropkę w nazwie nadchodzącej zmiennej.


Określanie typów zmiennych

Ponieważ PHP samodzielnie określa typy zmiennych i konwertuje je (zasadniczo) jak potrzeba, nie zawsze jest jasne, jakiego typu jest dana zmienna w danym momencie. PHP zawiera kilka funkcji do określania typów zmiennych. Są to: gettype(), is_long(), is_double(), is_string(), is_array()i is_object().


Rozdział 8. Stałe

Stała jest identyfikatorem (nazwą) dla prostej wartości. Jak sama nazwa wskazuje, wartość ta nie może się zmieniać podczas działania skryptu (poza wyjątkami: __FILE__ i __LINE__). Domyślnie, przy stałych uwzględniana jest wielkość liter. Przyjęto, że stałe są pisane dużymi literami.

Nazwa stałej podlega takim samym zasadom jak każda inna w PHP. Prawidłowa nazwa stałej rozpoczyna się literą, znakiem podkreślenia ("_"), następnie mogą występować litery, cyfry lub znaki podkreślenia. Dobrze reprezentuje to takie wyrażenie regularne: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Notatka: Na nasze potrzeby, litery to a-z, A-Z, oraz znaki ASCII od 127 do 255 (0x7f-0xff).

Zakres stałej jest globalny.


Składnia

Możesz definiować stałą używając funkcji define(). Kiedy stała zostanie zdefiniowana, nie może być już zmieniona albo undefined.

Tylko skalarne typy danych (boolean, integer, double i string) mogą być zawarte w stałych.

Możesz użyć wartości stałej poprzez zwykłe użycie jej nazwy. Inaczej niż przy zmiennych, w stałych NIE powinieneś prepend stałej znakiem $. Możesz także użyć funkcji constant(), aby odczytać wartość stałej, której nazwa jest przekazywana dynamicznie. Użyj funkcji get_defined_constants() aby otrzymać listę zdefiniowanych stałych.

Notatka: Stałe i globlane zmienne są pisane inaczej, a to oznacza, że np. TRUE i $TRUE są różne.

Jeśli użyjesz niezdefiniowanej stałej, PHP przyjmuje, że chcesz użyć nazwy stałej samej w sobie. Zostanie wtedy wysłane ostrzeżenie. Użyj funkcji defined() jeśli chcesz się dowiedzieć czy stała jest zdefiniowana.

Różnice pomiędzy stałymi, a zmiennymi:

  • Stałe nie mają znaku dolara ($) przed nazwą;

  • Stałe mogą być definiowane oraz używane wszędzie bez zważania na zasady dotyczące zakresu ich dostępności;

  • Stałe nie mogą być redefiniowane lub undefined po tym jak raz zostały zdefiniowane; i

  • Stałe mogą zawierać tylko wartości skalarne.

Przykład 8-1. Definiowanie stałych

<?php
define("STALA", "Hello world!");
echo STALA; // wyświetli "Hello world!"
echo Stala; // wyświetli "Stala" i zgłosi ostrzeżenie
?>


Predefiniowane stałe

Predefiniowanymi stałymi (zawsze dostępnymi) są:

__FILE__ (nieważna wielkość liter)

Nazwa pliku ze skryptem PHP, który jest aktualnie parsowany (przetwarzany); stała użyta w pliku, który został, który został włączony (include) lub jest wymagany (require), zwraca nazwę tego właśnie pliku, a nie nazwę pliku głównego.

__LINE__ (nieważna wielkość liter)

Numer linii w pliku, który jest aktualnie parsowany (przetwarzany). Stała użyta w pliku włączonym (include) zwraca pozycję w tym pliku.

PHP_VERSION

Łańcuch reprezentujący aktualnie używaną wersję parsera PHP, np. '4.0.7-dev'.

PHP_OS

Nazwa systemu operacyjnego, na którym uruchomiony jest parser PHP. Możliwe wartości to: "AIX", "Darwin" (MacOS), "Linux", "SunOS", "WIN32", "WINNT". Uwaga: inne wartości również mogą być dostępne.

TRUE (nieważna wielkość liter)

Wartość TRUE (zobacz: typ boolean).

FALSE (nieważna wielkość liter)

Wartość FALSE (zobacz: typboolean).

NULL (nieważna wielkość liter)

Wartość NULL (zobacz: typ null).

E_ERROR

Oznacza błąd inny niż błąd przy parsowaniu (przetwarzaniu), którego naprawienie nie jest możliwe.

E_WARNING

Oznacza stan, w którym PHP "wie", że coś jest źle, ale kontynuuje działanie; błędy takie mogą być przechwycone przez sam skrypt. Przykładem może być nieprawidłowe wyrażenie regularne w funkcji ereg().

E_PARSE

Parser stanął przy nieprawidłowej składni w skrypcie. Naprawa błędu i kontynuacja nie jest możliwa.

E_NOTICE

Zdarzyło się coś co może acz nie musi być błędem. PHP kontynuuje działanie. Przykładem może być używanie niepodanego łańcucha jako indeksu w tablicy albo żadanie dostępu do niezadeklarowanej zmiennej.

E_ALL

Wszystkie stałe E_* w jednej. Jeśli stała ta zostanie użyta z funkcją error_reporting(), spowoduje to, że jakiekolwiek problemy zauważone przez PHP będą zgłaszane przez funkcję.

Stałe E_* są zwykle używane z funkcją error_reporting() aby ustawić poziom zgłaszania błędów. Zobacz wszystkie takie stałe w rozdziale Obsługa błędów.

Przykład 8-2. Używanie __FILE__ i __LINE__

<?php
function report_error($plik, $linia, $komunikat)
{
    echo "Wystąpił błąd w $plik w linii $linia: $komunikat.";
}

report_error(__FILE__, __LINE__, "Coś poszło źle!");
?>


Rozdział 9. Wyrażenia

Wyrażenia są naważniejszymi elementami składowymi PHP. W PHP prawie wszystko co napiszesz jest wyrażeniem. Najprostszą i najdokładniejszą definicją wyrażenia jest "wszystko co ma wartość".

Najbardziej podstawową formą wyrażeń są stałe i zmienna. Jeśli napiszesz "$a = 5" przypisujesz '5' do '$a'. '5' ma oczywiście wartość 5, lub innymi słowy '5' jest wyrażeniem o wartości 5 (w tym przypadku, '5' jest stałą liczbą całkowitą).

Po tym przypisaniu możesz się spodziwać, że wartością $a jest także 5, więc jeśli napiszesz "$b = $a" możesz się spodziewać, że będzie to równoznaczne z napisaniem "$b = 5". Innymi słowy, $a jest wyrażeniem o wartości 5. Jeśli wszystko działa prawidłowo, to wszystko będzie tak jak się spodziewałeś.

Trochę bardziej złożonymi przykładami wyrażeń są funkcje. Przyjrzyj się poniższej funkcji:

function foo ()
{
    return 5;
}

Zakładając że oswoiłeś się z koncepcją funkcji (jeśli nie, przejrzyj najpierw rozdział o funkcjach), możesz założyć, że napisanie $c = foo() jest równoznaczne z napisaniem $c = 5, i masz racię. Funkcje są wyrażeniami o wartości którą zwracają. Ponieważ foo() zwraca 5, wartością wyrażenia 'foo()' jest 5. Zazwyczaj funkcje nie zwracają statycznej wartości, ale coś obliczają.

Oczywiście wartości w PHP nie muszą być liczbami całkowitymi, i bardzo często nie są nimi. PHP obsługuje 3 skalarne warotści danych: wartości całkowite, wartości rzeczywiste i ciągi znaków (string) (wartości skalarne to takie, których nie możesz 'rozbić' na mniejsze kawałki, w przeciwieństwie do np. tablic). PHP obsługuje także dwa złożone (nieskalarne) typy danych: tablice i obiekty. Każdą z tych wartości można przypisać do zmiennych lub może być zwrócona przez funkcję.

Jak narazie, użytkownicy PHP/FI 2 nie powinni odczuć żadnej zmiany. Jednakże PHP rozwija wyrażenia znacznie bardziej, podobnie jak wiele innych języków programowania. PHP jest językiem zorientowanym na wyrażenia, co oznacza że prawie wszystko jest wyrażeniem. Przyjrzyj się przykładowi który już analizowaliśmy, '$a = 5'. Łatwo jest zauważyć, że są tu dwie wartości. Wartość stałej całkowitej '5', a także wartość $a, która zostanie zamieniona na 5. Ale tak naprawdę jest tu jeszcze jedna wartość, którą jest wartość operacji przypisania. Przypisanie przyjmuje wartość przypisywanej wartości, w tym przypadku 5. W praktyce oznacza to, że '$a = 5', niezależnie co to robi, jest wyrażeniem o wartości 5. Wynika z tego, że napisanie '$b = ($a = 5)' jest równoznaczne napisaniu '$a = 5; $b = 5;' (średnik oznacza koniec instrukcji). Ponieważ przypisania są przetwarzane od prawej do lewej, możesz także napisać '$b = $a = 5'.

Kolejnym dobrym przykładem orientacji wyrażeniowej jest pre- i postinkrementacja i dekrementacja. Użytkownicy PHP/FI 2 i wielu innych języków mogą być już zaznajomieni z notacją zmienna++ i zmienna--. Są to operatory inkrementacji i dekrementacji. W PHP/FI 2 instrukcja '$a++' nie ma wartości (nie jest wyrażeniem), więc nie możesz jej przypisać lub użyć w jakikolwiek sposób. PHP rozszerza możliwości inkrementacji/dekrementacji robiąc także z nich wyrażenia, podobnie jak w C. W PHP, tak jak w C, sa dwa typy inkrementacji: preinkrementacja i postinkrementacja. I pre- i postinkrementacja zwiększają wartość zmiannej, więc efekt w stosunku do zmiennej jest taki sam. Różnica jest w wartości wyrażenia inkrementacji. Preinkrementacja, która jest oznaczana jako '++$zmienna', zwraca zwiększoną wartość (PHP zwiększa zmienną przed odczytaniem wartości, dlatego nazywa się to 'pre-inkrementacją'). Postinkrementacja, która jest oznaczana jako '$zmienna++', zwraca orginalną wartość $zmienna przed zwiększeniem jej wartości (PHP zwiększa wartość po odczytaniu jej wartości, stąd nazwa 'post-inkrementacja').

Popularnym typem wyrażeń są wyrażenia porównania. Te wyrażenia zwracają wartość 0 lub 1, oznaczając odpowiednio FALSE lub TRUE. PHP obsługuje > (większy), >= (większy lub równy), == (równy), != (nie równy), < (mniejszy) i <= (mniejszy lub równy). Wyrażenia te są powszechnie używane przy sprawdzaniu warunków, jak na przykład instrukcje if.

Ostatnim przykładem, którym będziemy się tu zajmować są połączone wyrażenia operacji i przypisania. Już wiesz, że jeśli chcesz zwiększyć wartość zmiennej $a o 1, możesz po prostu napisać '$a++' lub '++$a'. Ale co jeśli chcesz dodać do niej więcej niż jeden, na przykład 3? Mógłbyś napisać wielokrotnie '$a++', ale nie jest to sposób ani efektywny ani wygodny. Częściej spotykane jest używanie instrukcji '$a = $a + 3'. '$a + 4' zwraca wartość zmiennej $a plus 3, która jest przypisywana spowrotem do $a, co oznacza zwiększenie wartości zmiennej $a o 3. W PHP, tak jak kilku innych językach jak na przykład C, możesz napisać to krócej, co z czasem stanie się także bardziej przejrzyste i łatwiejsze do zrozumienia. Dodanie 4 do bieżącej wartości $a może być zapisane jako '$a += 4'. Oznacza to dokładnie "weź wartość $a, dodaj do niej 3 i przypisz ją spowrotem do $a". Oprócz bycia krótszą i bardziej przejrzystą, instrukcja ta jest także szybsza w wykonaniu. Wartość '$a += 5', tak jak wartość zwykłego przypisania, jest przypisywaną wartością. Zauważ, że NIE jest to 4, ale połączona warotść $a i 4 (jest to wartość która jest przypisywana do $a). Dowolne dwuoperandowe operatory mogą być użyte w trybie operacji-przypisania, na przykład '$a -= 5' (odejmij 5 od wartości $a), '$b *= 7' (pomnóż wartość $b przez 7), itp.

Jest jeszcze jedno wyrażenie, które może się wydać dziwne jeśli nie widziałeś go w innych językac, trójoperandowy operator warunkowy:

$pierwsze ? $drugie : $trzecie

Jeśli wartością pierwszego podwyrażenia jest TRUE (rózna od zera), to zwracany jest drugie podwyrażanie, i jest to wynik wyrażenia warunkowego. W przeciwnym wypadku, zwracana jest wartość trzeciego podwyrażenia.

Poniższy przykład powinien pomóc w lepszym zrozumieniu pre- i postinkrementacji i ogólnie koncepcji wyrażeń:

function double($i)
{
    return $i*2;
}
$b = $a = 5;        /* przypisz wartość pięc do zmiennej $a i $b */
$c = $a++;          /* postinkrementuj, przypisz początkową wartość
                       $a (5) do $c */
$e = $d = ++$b;     /* preinkrementuj, przypisz zwiększoną wartość
                       $b (6) to $d i $e */

/* w tym momencie i $d i $e są równe 6 */

$f = double($d++);  /* przypisz podwojoną wartość $d <emphasis>sprzed</emphasis>
                       inkrementacji, 2*6 = 12 do $f */
$g = double(++$e);  /* przypisz podwojoną wartość $e <emphasis>po</emphasis>
                       inkrementacji, 2*7 = 14 do $g */
$h = $g += 10;      /* na początku $g jest zwiększane o 10 i przyjmuje 
                       wartość 24; wartość przypisania (24) jest później
                       przypisywana do $h, które przyjmuje wartość 24. */

Na początku rozdziału powiedzieliśmy, że będziemy opisywać różne typy instrukcji, i tak jak obiecywaliśmy, wyrażenia mogą być instrukcjami. Jednakże nie każde wyrażenie jest instrukcją. W tym przypadku ma postać 'wyrażenie' ';', czyli wyrażenie a po nim średnik. W '$b=$a=5;', $a=5 jest poprawnym wyrażeniem, ale nie jest instrukcją. Jednakże '$b=$a=$b;' jest poprawną intrukcją.

Ostatnią rzeczą wartą uwagi jest wartość prawdy wyrażeń. W wielu przypadkach, głównie przy sprawdzaniu warunkow i w pętlach, nie interesuje cię wartość wyrażenia, ale tylko czy oznacza TRUE czy FALSE. Stałe TRUE i FALSE (niezależne od wielkości znaków) są dwiema możliwymi wartościami logicznymi. Kiedy to konieczne, wyrażenie jest automatycznie konwertowane na typ boolean. Zobacz rozdział o rzutowaniu typów jeśli interesują cię szczegóły jak to jest przeprowadzane.

PHP dostarcza pełnej i potężnej implementacji wyrażeń i całkowita ich dokumentacja przekracza ramy tego podręcznika. Powyższe przykłady powinny dać ci ogólne pojęcie czym są wyrażenia i jak możesz konstruować przydatne wyrażenia. Przez resztę podręcznika będziemy pisać expr aby oznaczyć dowolne poprawne wyrażenie PHP.


Rozdział 10. Operatory


Operatory Arytmetyczne

Czy pamiętasz podstawy arytmetyki ze szkoły? W PHP operatory działają niemalże tak samo.

Tabela 10-1. Operatory Arytmetyczne

PrzykładNazwaOpis
$a + $bDodawanieSuma $a i $b.
$a - $bOdejmowanieRóżnica $a od $b.
$a * $bMnożenieIloczyn $a i $b.
$a / $bDzielenieIloraz $a przez $b.
$a % $bModuloReszta z dzielenia $a przez $b.

Operator dzielenia ("/") zwraca wartość całkowitą (wynikiem dzielenia jest liczba całkowita) jeśli obydwa operandy są całkowite (lub są łańcuchami znaków skonwertowanymi do liczba całkowitych) i wynik ich dzielenia jest całkowity. Jeśli jednak któryś z operandów jest zmiennoprzecinkowy lub wynikiem dzielenia jest liczba niecałkowita, operator dzielenia zwraca wartość zmiennoprzecinkową.


Operatory Przypisania

Podstawowym operatorem przypisania jest "=". Twoim pierwszym skojarzeniem może być "jest równy". Nie! Tak naprawdę oznacza to, że operand z lewej strony operatora "=" otrzymuje wartość wyrażenia stojącego po prawej stronie (tak właśnie się tłumaczy: "otrzymuje wartość wyrażenia po prawej").

Wartością całego wyrażenia przypisania jest wartość przypisywana do zmiennej stojacej po lewej. Na przykład wartością "$a = 3" jest 3. To pozwala na wykonywanie bardziej skomplikowanych przypisań:

$a = ($b = 4) + 5; // teraz $a jest równe 9, a $b jest równe 4.

Poza podstawowym operatorem przypisania, istnieją jeszcze złożone operatory odnoszące się do wszystkich arytmetycznych i łańcuchowych operatorów. Pozwalają one użyć jednej zmiennej jako jednego z operandów, a następnie zapisanać wynik działania w tej właśnie zmiennej. Na przykład:

$a = 3;
$a += 5; // ustawia wartość $a na 8, tak jakby napisać: $a = $a + 5;
$b = "Witaj ";
$b .= "Świecie!"; // ustawia wartość $b na "Witaj Świecie!", dokładnie tak jak 
$b = $b . "Świecie!";

Zwróć uwagę, że przypisanie kopiuje wartość oryginalnej zmiennej do nowej zmiennej (tzw. przypisanie przez wartość). Skutki tego mogą być widoczne przy kopiowaniu np. dużej tablicy wewnątrz zwartej (ciasnej) pętli (ang. tight loop). PHP 4 pozwala na przypisanie przez referencję (odniesienie), za pomocą składni $zmienna = &$innaZmienna;. Taka możliwość pojawiła się dopiero w PHP 4 i nie była dostępna w PHP 3. "Przypisanie przez referencję" oznacza, że obydwie zmienne wskazują te same wartości, natomiast nic się nie kopiuje. Aby dowiedzieć się więcej na temat referencji, przeczytaj rodział wyjaśnienie referencji.


Operatory Bitowe

Operatory bitowe służą do operowania na wartościach konkretnych bitów w liczbie.

Tabela 10-2. Operatory Bitowe

PrzykładNazwaOpis
$a & $bMnożenieDany bit wynikowy jest równy 1 tylko jeśli obydwa bity składowe są równe 1.
$a | $bSumowanieDany bit wynikowy jest równy 1 jeśli conajmniej jeden bit składowy jest równy 1.
$a ^ $bSumowanie modulo 2Dany bit wynikowy jest równy 1 tylko jeśli jeden z bitów składowych jest równy 1 a drugi jest równy 0.
~ $aNegacjaBity w zmiennej $a mające wartość 1 otrzymują wartość 0 i na odwrót.
$a << $bPrzesunięcie w lewo Przesuwa bity w zmiennej $a o $b kroków w lewo (każdy krok znaczy "pomnożone przez dwa").
$a >> $bPrzesunięcie w prawo Przesuwa bity w zmiennej $a o $b kroków w prawo (każdy krok znaczy "podzielone przez dwa").

Operatory Porównania

Jak wskazuje ich nazwa, operatory te służą do porównywania dwóch wartości.

Tabela 10-3. Operaatory Porównania

PrzykładNazwaOpis
$a == $bRównyTRUE jesli $a jest równe $b
$a === $bIdentyczny TRUE jeśli $a jest równe $b, i obydwa operandy są tego samego typu. (tylko w PHP 4)
$a != $bRóżnyTRUE jeśli $a nie jest równy $b.
$a <> $bRóżnyTRUE jeśli $a nie jest równy $b.
$a !== $bNie identyczny TRUE jeśli $a nie jest równy $b, lub nie są tego samego typu. (tylko w PHP 4)
$a < $bMniejszy niżTRUE jeśli $a jest mniejszy od $b.
$a > $bWiększy niżTRUE jeśli $a jest większy od $b.
$a <= $bMniejszy lub równyTRUE jeśli $a jest mniejszy lub równy $b.
$a >= $bWiększy lub równyTRUE jeśli $a jest większy lub równy $b.

Jeszcze jednym operatorem warunkowym jest operator "?:", działający tak jak w C i wielu innych językach.

(expr1) ? (expr2) : (expr3);

Wartościa wyrażenia jest expr2 jeśli expr1 jest równe TRUE, lub expr3 jeśli expr1 jest równe FALSE.


Operatory Kontroli Błędów

PHP obsługuje obecnie jeden operator kontroli błędów: znak małpy (@). Jeśli znak ten zostanie postawiony przed dowolnym wyrażeniem w PHP, jakiekolwiek powiadomienia o błędach wygenerowane przez to wyrażenie zostaną pominięte (nie będą wyświetlone).

Jeśli mechanizm track_errors został włączony, jakiekolwiek powiadomienie o błędzie zostanie zapisane do zmiennej globalnej $php_errormsg. Należy jednak pamiętać, że zawartość tej zmiennej jest nadpisywana przy każdym błędzie, więc po wystąpieniu kolejnego błędu w skrypcie, informacja o poprzednim błędzie jest tracona.

<?php
/* Zamierzony błąd obsługi pliku */
$my_file = @file ('non_existent_file') or
    die ("Failed opening file: error was '$php_errormsg'");

// mechanizm ten działa dla wszystkich wyrażeń, nie tylko dla funkcji:
$value = @$cache[$key]; 
// spowoduje niewyświetlenie powiadomienia, jeśli nie istnieje wpis do tablicy o
indeksie $key.

?>

Notatka: Operator @ działa tylko na wyrażeniach. Tłumacząc to łopatologicznie: jeśli da się pobrać wartość czegoś, można postawić operator @ przed tym czymś. Zgodnie z powyższą regułą, można postawić @ przed zmiennymi, wywołaniami funkcji, instrukcjami include(), stałymi, itp. Nie można stawiać @ przed definicjami funkcji bądź klasy, lub strukturami warunkowymi, takimi jak if lub foreach, itd.

Zobacz także error_reporting().

Ostrze¿enie

Obecnie operator kontroli błędów "@" wyłączy wyświetlanie powiadomienia o błędzie nawet dla błędów krytycznych, które przerwą wykonywanie skryptu. Oznacza to, że jeśli użyjesz tego operatora przed wywołaniem funkcji, która jest nieosiągalna lub ma literówkę w nazwie, skrypt przerwie pracę nie powiadamiając dlaczego.


Operatory Wykonania Polecenia Systemowego

PHP posiada jeden operator wykoania polecenia systemowego: apostrof wsteczny (``). Zauważ że jest to coś innego niż apostrof zwykły! Zawartość apostrofu wstecznego zostanie wykonana jako polecenie systemowe. Wynik polecenia zostanie zwrócony (tzn. nie będzie wysłany do przeglądarki tylko będzie dostępny do przypisania do zmiennej).

$output = `ls -al`;
echo "<pre>$output</pre>";

Notatka: Operator ten nie działa kiedy safe mode jest włączony, lub shell_exec() jest zablokowana.

Zobacz też escapeshellcmd(), exec(), passthru(), popen(), shell_exec() i system().


Operatory Inkrementacji i Dekrementacji

PHP obsługuje te operatory w stylu języka C.

Tabela 10-4. Operatory Inkrementacji i Dekrementacji

PrzykładNazwaOpis
++$aPre-inkrementacjaNajpierw zwiększa wartość $a o jeden, potem zwraca $a.
$a++Post-inkrementacjaNajpierw zwraca $a, potem zwiększa $a o jeden.
--$aPre-dekrementacjaNajpierw zmniejsza wartość $a o jeden, potem zwraca $a.
$a--Post-dekrementacjaNajpierw zwraca $a, potem zmniejsza $a o jeden.

Prosty skrypt przykładowy:

<?php
echo "<h3&gt;Post-inkrementacja</h3&gt;";
$a = 5;
echo "Powinno być 5: " . $a++ . "<br>\n";
echo "Powinno być 6: " . $a . "<br>\n";

echo "<h3>Pre-inkrementacja</h3>";
$a = 5;
echo "Powinno być 6: " . ++$a . "<br>\n";
echo "Powinno być 6: " . $a . "<br>\n";

echo "<h3>Post-dekrementacja</h3>";
$a = 5;
echo "Powinno być 5: " . $a-- . "<br>\n";
echo "Powinno być 4: " . $a . "<br>\n";

echo "<h3>Pre-dekrementacja</h3>";
$a = 5;
echo "Powinno być 4: " . --$a . "<br>\n";
echo "Powinno być 4: " . $a . "<br>\n";
?>


Operatory Logiczne

Tabela 10-5. Opearotory Logiczne

PrzykładNazwaOpis
$a and $bITRUE jeśli zarówno $a jak i $b są TRUE.
$a or $bLubTRUE jeśli $a lub $b jest TRUE.
$a xor $bWyłacznie-LubTRUE jeśli $a lub $b jest TRUE, ale nie jednocześnie.
! $aNieTRUE jeśli $a nie jest TRUE.
$a && $bITRUE jeśli zarówno $a jak i $b są TRUE.
$a || $bLubTRUE jeśli $a lub $b jest TRUE.

Operatory "or" i "and" mają inny priorytet niż "||" i "&&" i właśnie z tego powodu w PHP są dwa rodzaje operatorów "lub" i "i". (Zobacz Priorytety Operatorów.)


Priorytety operatorów

Priorytet operatora określa, jak "silnie" operator wiąże ze sobą dwa stojące obok niego wyrażenia. Na przykład, w wyrażeniu 1 + 5 * 3, wynik wynosi 16, nie 18 ponieważ operator mnożenia ("*") ma wyższy priorytet niż operator dodawania ("+"). Za pomocą nawiasów można zmieniać priorytet działań według reguł arytmetyki. Na przykład: (1 + 5) * 3 jest równe 18.

Poniższa tabela zawiera priorytet operatorów, od najniższego priorytetu na górze.

Tabela 10-6. Priorytety operatorów

PowiązanieOperator
lewe,
leweor
lewexor
leweand
praweprint
lewe = += -= *= /= .= %= &= |= ^= ~= <<= >>=
lewe? :
lewe||
lewe&&
lewe|
lewe^
lewe&
bez powiązania== != === !==
bez powiązania< <= > >=
lewe<< >>
lewe+ - .
lewe* / %
prawe! ~ ++ -- (int) (double) (string) (array) (object) @
prawe[
bez powiązanianew


Operatory Łańcuchowe

W PHP są dwa operatory operujące na łańcuchach znaków (stringach). Pierwszym z nich jest operator konkatenacji (połączenia) ('.'), który zwraca łańcuch będący połączeniem zawartości lewego i prawego operandu. Drugim z nich jest operator przypisania konkatenacyjnego ('.='), który dołącza zawartość wyrażenia stojacego z prawej strony do zmiennej stojacej z lewej strony. Zobacz także Operatory Przypisania.

$a = "Witaj ";
$b = $a . "Świecie!"; // teraz $b zawiera ciąg "Witaj Świecie!"

$a = "Witaj ";
$a .= "Świecie!";     // teraz $a zawiera ciąg "Witaj Świecie!"


Rozdział 11. Control Structures

Any PHP script is built out of a series of statements. A statement can be an assignment, a function call, a loop, a conditional statement of even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well. The various statement types are described in this chapter.


if

The if construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an if structure that is similar to that of C:

if (expr)
    statement

As described in the section about expressions, expr is evaluated to its Boolean value. If expr evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it. More information about what values evaluate to FALSE can be found in the 'Converting to boolean' section>.

The following example would display a is bigger than b if $a is bigger than $b:

if ($a > $b)
    print "a is bigger than b";

Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group. For example, this code would display a is bigger than b if $a is bigger than $b, and would then assign the value of $a into $b:

if ($a > $b) {
    print "a is bigger than b";
    $b = $a;
}

If statements can be nested indefinitely within other if statements, which provides you with complete flexibility for conditional execution of the various parts of your program.


else

Often you'd want to execute a statement if a certain condition is met, and a different statement if the condition is not met. This is what else is for. else extends an if statement to execute a statement in case the expression in the if statement evaluates to FALSE. For example, the following code would display a is bigger than b if $a is bigger than $b, and a is NOT bigger than b otherwise:

if ($a > $b) {
    print "a is bigger than b";
} else {
    print "a is NOT bigger than b";
}

The else statement is only executed if the if expression evaluated to FALSE, and if there were any elseif expressions - only if they evaluated to FALSE as well (see elseif).


elseif

elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE. For example, the following code would display a is bigger than b, a equal to b or a is smaller than b:

if ($a > $b) {
    print "a is bigger than b";
} elseif ($a == $b) {
    print "a is equal to b";
} else {
    print "a is smaller than b";
}

There may be several elseifs within the same if statement. The first elseif expression (if any) that evaluates to TRUE would be executed. In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different (if you're familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior.

The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE.


Alternative syntax for control structures

PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.

<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>

In the above example, the HTML block "A = 5" is nested within an if statement written in the alternative syntax. The HTML block would be displayed only if $a is equal to 5.

The alternative syntax applies to else and elseif as well. The following is an if structure with elseif and else in the alternative format:

if ($a == 5):
    print "a equals 5";
    print "...";
elseif ($a == 6):
    print "a equals 6";
    print "!!!";
else:
    print "a is neither 5 nor 6";
endif;

See also while, for, and if for further examples.


while

while loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is:

while (expr) statement

The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once.

Like with the if statement, you can group multiple statements within the same while loop by surrounding a group of statements with curly braces, or by using the alternate syntax:

while (expr): statement ... endwhile;

The following examples are identical, and both print numbers from 1 to 10:

/* example 1 */

$i = 1;
while ($i <= 10) {
    print $i++;  /* the printed value would be
                    $i before the increment
                    (post-increment) */
}

/* example 2 */

$i = 1;
while ($i <= 10):
    print $i;
    $i++;
endwhile;


do..while

do..while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning. The main difference from regular while loops is that the first iteration of a do..while loop is guaranteed to run (the truth expression is only checked at the end of the iteration), whereas it's may not necessarily run with a regular while loop (the truth expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the beginning, the loop execution would end immediately).

There is just one syntax for do..while loops:

$i = 0;
do {
   print $i;
} while ($i>0);

The above loop would run one time exactly, since after the first iteration, when truth expression is checked, it evaluates to FALSE ($i is not bigger than 0) and the loop execution ends.

Advanced C users may be familiar with a different usage of the do..while loop, to allow stopping execution in the middle of code blocks, by encapsulating them with do..while(0), and using the break statement. The following code fragment demonstrates this:

do {
    if ($i < 5) {
        print "i is not big enough";
        break;
    }
    $i *= $factor;
    if ($i < $minimum_limit) {
        break;
    }
    print "i is ok";

     ...process i...

} while(0);

Don't worry if you don't understand this right away or at all. You can code scripts and even powerful scripts without using this `feature'.


for

for loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is:

for (expr1; expr2; expr3) statement

The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.

In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.

At the end of each iteration, expr3 is evaluated (executed).

Each of the expressions can be empty. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional break statement instead of using the for truth expression.

Consider the following examples. All of them display numbers from 1 to 10:

/* example 1 */

for ($i = 1; $i <= 10; $i++) {
    print $i;
}

/* example 2 */

for ($i = 1;;$i++) {
    if ($i > 10) {
        break;
    }
    print $i;
}

/* example 3 */

$i = 1;
for (;;) {
    if ($i > 10) {
        break;
    }
    print $i;
    $i++;
}

/* example 4 */

for ($i = 1; $i <= 10; print $i, $i++);

Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in for loops comes in handy in many occasions.

PHP also supports the alternate "colon syntax" for for loops.

for (expr1; expr2; expr3): statement; ...; endfor;

Other languages have a foreach statement to traverse an array or hash. PHP 3 has no such construct; PHP 4 does (see foreach). In PHP 3, you can combine while with the list() and each() functions to achieve the same effect. See the documentation for these functions for an example.


foreach

PHP 4 (not PHP 3) includes a foreach construct, much like Perl and some other languages. This simply gives an easy way to iterate over arrays. There are two syntaxes; the second is a minor but useful extension of the first:

foreach(array_expression as $value) statement
foreach(array_expression as $key => $value) statement

The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element).

The second form does the same thing, except that the current element's key will be assigned to the variable $key on each loop.

Notatka: When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.

Notatka: Also note that foreach operates on a copy of the specified array, not the array itself, therefore the array pointer is not modified as with the each() construct and changes to the array element returned are not reflected in the original array.

Notatka: foreach does not support the ability to suppress error messages using '@'.

You may have noticed that the following are functionally identical:

reset ($arr);
while (list(, $value) = each ($arr)) {
    echo "Value: $value<br>\n";
}

foreach ($arr as $value) {
    echo "Value: $value<br>\n";
}

The following are also functionally identical:

reset ($arr);
while (list($key, $value) = each ($arr)) {
    echo "Key: $key; Value: $value<br>\n";
}

foreach ($arr as $key => $value) {
    echo "Key: $key; Value: $value<br>\n";
}

Some more examples to demonstrate usages:

/* foreach example 1: value only */

$a = array (1, 2, 3, 17);

foreach ($a as $v) {
   print "Current value of \$a: $v.\n";
}

/* foreach example 2: value (with key printed for illustration) */

$a = array (1, 2, 3, 17);

$i = 0; /* for illustrative purposes only */

foreach($a as $v) {
    print "\$a[$i] => $v.\n";
    $i++;
}

/* foreach example 3: key and value */

$a = array (
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
);

foreach($a as $k => $v) {
    print "\$a[$k] => $v.\n";
}

/* foreach example 4: multi-dimensional arrays */

$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach($a as $v1) {
    foreach ($v1 as $v2) {
        print "$v2\n";
    }
}

/* foreach example 5: dynamic arrays */

foreach(array(1, 2, 3, 4, 5) as $v) {
    print "$v\n";
}


break

break ends execution of the current for, foreach while, do..while or switch structure.

break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.

$arr = array ('one', 'two', 'three', 'four', 'stop', 'five');
while (list (, $val) = each ($arr)) {
    if ($val == 'stop') {
        break;    /* You could also write 'break 1;' here. */
    }
    echo "$val<br>\n";
}

/* Using the optional argument. */

$i = 0;
while (++$i) {
    switch ($i) {
    case 5:
        echo "At 5<br>\n";
        break 1;  /* Exit only the switch. */
    case 10:
        echo "At 10; quitting<br>\n";
        break 2;  /* Exit the switch and the while. */
    default:
        break;
    }
}


continue

continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the beginning of the next iteration.

continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.

while (list ($key, $value) = each ($arr)) {
    if (!($key % 2)) { // skip odd members
        continue;
    }
    do_something_odd ($value);
}

$i = 0;
while ($i++ &lt; 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";
}


switch

The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.

The following two examples are two different ways to write the same thing, one using a series of if statements, and the other using the switch statement:

if ($i == 0) {
    print "i equals 0";
}
if ($i == 1) {
    print "i equals 1";
}
if ($i == 2) {
    print "i equals 2";
}

switch ($i) {
    case 0:
        print "i equals 0";
        break;
    case 1:
        print "i equals 1";
        break;
    case 2:
        print "i equals 2";
        break;
}

It is important to understand how the switch statement is executed in order to avoid mistakes. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example:

switch ($i) {
    case 0:
        print "i equals 0";
    case 1:
        print "i equals 1";
    case 2:
        print "i equals 2";
}

Here, if $i equals to 0, PHP would execute all of the print statements! If $i equals to 1, PHP would execute the last two print statements, and only if $i equals to 2, you'd get the 'expected' behavior and only 'i equals 2' would be displayed. So, it's important not to forget break statements (even though you may want to avoid supplying them on purpose under certain circumstances).

In a switch statement, the condition is evaluated only once and the result is compared to each case statement. In an elseif statement, the condition is evaluated again. If your condition is more complicated than a simple compare and/or is in a tight loop, a switch may be faster.

The statement list for a case can also be empty, which simply passes control into the statement list for the next case.

switch ($i) {
    case 0:
    case 1:
    case 2:
        print "i is less than 3 but not negative";
        break;
    case 3:
        print "i is 3";
}

A special case is the default case. This case matches anything that wasn't matched by the other cases, and should be the last case statement. For example:

switch ($i) {
    case 0:
        print "i equals 0";
        break;
    case 1:
        print "i equals 1";
        break;
    case 2:
        print "i equals 2";
        break;
    default:
        print "i is not equal to 0, 1 or 2";
}

The case expression may be any expression that evaluates to a simple type, that is, integer or floating-point numbers and strings. Arrays or objects cannot be used here unless they are dereferenced to a simple type.

The alternative syntax for control structures is supported with switches. For more information, see Alternative syntax for control structures .

switch ($i):
    case 0:
        print "i equals 0";
        break;
    case 1:
        print "i equals 1";
        break;
    case 2:
        print "i equals 2";
        break;
    default:
        print "i is not equal to 0, 1 or 2";
endswitch;


declare

The declare construct is used to set execution directives for a block of code. The syntax of declare is similar to the syntax of other flow control constructs:

declare (directive) statement

The directive section allows the behavior of the declare block to be set. Currently only one directive is recognized: the ticks directive. (See below for more information on the ticks directive)

The statement part of the declare block will be executed - how it is executed and what side-effects occur during execution may depend on the directive set in the directive block.


Ticks

A tick is an event that occurs for every N low-level statements executed by the parser within the declare block. The value for N is specified using ticks=N within the declare blocks's directive section.

The event(s) that occurs on each tick is specified using the register_tick_function(). See the example below for more details. Note that more than one event can occur for each tick.

Przykład 11-1. Profile a section of PHP code

<pre>
<?php
// A function that records the time when it is called
function profile ($dump = FALSE)
{
    static $profile;

    // Return the times stored in profile, then erase it
    if ($dump) {
        $temp = $profile;
        unset ($profile);
        return ($temp);
    }

    $profile[] = microtime ();
}

// Set up a tick handler
register_tick_function("profile");

// Initialize the function before the declare block
profile ();

// Run a block of code, throw a tick every 2nd statement
declare (ticks=2) {
    for ($x = 1; $x < 50; ++$x) {
        echo similar_text (md5($x), md5($x*$x)), "&lt;br&gt;";
    }
}

// Display the data stored in the profiler
print_r (profile (TRUE));
?>
</pre>
The example profiles the PHP code within the 'declare' block, recording the time at which every second low-level statement in the block was executed. This information can then be used to find the slow areas within particular segments of code. This process can be performed using other methods: using ticks is more convenient and easier to implement.

Ticks are well suited for debugging, implementing simple multitasking, backgrounded I/O and many other tasks.

See also register_tick_function() and unregister_tick_function().


return

If called from within a function, the return() statement immediately ends execution of the current function, and returns its argument as the value of the function call. return() will also end the execution of an eval() statement or script file.

If called from the global scope, then execution of the current script file is ended. If the current script file was include()ed or require()ed, then control is passed back to the calling file. Furthermore, if the current script file was include()ed, then the value given to return() will be returned as the value of the include() call. If return() is called from within the main script file, then script execution ends. If the current script file was named by the auto_prepend_file or auto_append_file configuration options in the configuration file, then that script file's execution is ended.

For more information, see Returning values.

Notatka: Note that since return() is a language construct and not a function, the parentheses surrounding its arguments are not required--in fact, it is more common to leave them out than to use them, although it doesn't matter one way or the other.


require()

The require() statement includes and evaluates the specific file.

require() includes and evaluates a specific file. Detailed information on how this inclusion works is described in the documentation for include().

require() and include() are identical in every way except how they handle failure. include() produces a Warning while require() results in a Fatal Error. In other words, don't hesitate to use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless. Be sure to have an appropriate include_path setting as well.

Przykład 11-2. Basic require() examples

<?php

require 'prepend.php';

require $somefile;

require ('somefile.txt');

?>

See the include() documentation for more examples.

Notatka: Prior to PHP 4.0.2, the following applies: require() will always attempt to read the target file, even if the line it's on never executes. The conditional statement won't affect require(). However, if the line on which the require() occurs is not executed, neither will any of the code in the target file be executed. Similarly, looping structures do not affect the behaviour of require(). Although the code contained in the target file is still subject to the loop, the require() itself happens only once.

See also include(), require_once(), include_once(), eval(), file(), readfile(), virtual() and include_path.


include()

The include() statement includes and evaluates the specified file.

The documentation below also applies to require(). The two constructs are identical in every way except how they handle failure. include() produces a Warning while require() results in a Fatal Error. In other words, use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless. Be sure to have an appropriate include_path setting as well.

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.

Przykład 11-3. Basic include() example

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

?>

If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function.

Przykład 11-4. Including within functions

<?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

?>

When a file is included, parsing drops out of PHP mode and into HTML mode at the beginning of the target file, and resumes again at the end. For this reason, any code inside the target file which should be executed as PHP code must be enclosed within valid PHP start and end tags.

If "URL fopen wrappers" are enabled in PHP (which they are in the default configuration), you can specify the file to be included using an URL (via HTTP) instead of a local pathname. If the target server interprets the target file as PHP code, variables may be passed to the included file using an URL request string as used with HTTP GET. This is not strictly speaking the same thing as including the file and having it inherit the parent file's variable scope; the script is actually being run on the remote server and the result is then being included into the local script.

Przykład 11-5. include() through HTTP

<?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.

?>
See also Remote files, fopen() and file() for related information.

Because include() and require() are special language constructs, you must enclose them within a statement block if it's inside a conditional block.

Przykład 11-6. include() and conditional blocks

<?php

// This is WRONG and will not work as desired.
if ($condition)
    include $file;
else
    include $other;


// This is CORRECT.
if ($condition) {
    include $file;
} else {
    include $other;
}

?>

Handling Returns: It is possible to execute a return() statement inside an included file in order to terminate processing in that file and return to the script which called it. Also, it's possible to return values from included files. You can take the value of the include call as you would a normal function.

Notatka: In PHP 3, the return may not appear inside a block unless it's a function block, in which case the return() applies to that function and not the whole file.

Przykład 11-7. include() and the return() statement

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

?>

$bar is the value 1 because the include was successful. Notice the difference between the above examples. The first uses return() within the included file while the other does not. A few other ways to "include" files into variables are with fopen(), file() or by using include() along with Output Control Functions.

See also require(), require_once(), include_once(), readfile(), virtual(), and include_path.


require_once()

The require_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the require() statement, with the only difference being that if the code from a file has already been included, it will not be included again. See the documentation for require() for more information on how this statement works.

require_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.

For examples on using require_once() and include_once(), look at the PEAR code included in the latest PHP source code distributions.

Notatka: require_once() was added in PHP 4.0.1pl2

See also: require(), include(), include_once(), get_required_files(), get_included_files(), readfile(), and virtual().


include_once()

The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.

include_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.

For more examples on using require_once() and include_once(), look at the PEAR code included in the latest PHP source code distributions.

Notatka: include_once() was added in PHP 4.0.1pl2

See also include(), require(), require_once(), get_required_files(), get_included_files(), readfile(), and virtual().


Rozdział 12. Funkcje

Funkcje zdefiniowane przez użytkownika

Funkcja może być zdefiniowana używając składni takiej jak poniższa:

function foo ($arg_1, $arg_2, ..., $arg_n)
{
    echo "Przykładowa funkcja.\n";
    return $retval;
}

Dowolny poprawny kod PHP może się pojawić wewnątrz funkcji, także definicje innych funkcji i klas.

W PHP 3, funkcje muszą być zdefiniowane przed odwołaniem do nich. W PHP 4 nie ma takiego wymagania.

PHP nie obsługuje przeciążania funkcji. Nie jest także możliwa od-definiowanie lub przedefiniowanie wcześniej zadeklarowanych funkcji.

PHP 3 nie obsługuje funkcji o zmiennej liczbie argumentów, ale obsługuje domyślne argumenty (zobacz rozdzial Wartości domyślne argumentów aby uzyskać więcej informacji). PHP 4 obsługuje jedne i drugie: zobacz Listy argumentów o zmiennej długości i opisy funkcji func_num_args(), func_get_arg(), i func_get_args() aby uzyskać więcej informacji.


Argumenty funkcji

Informacje mogą być przekazywane do funkcji przez listę argumentów, która jest separowaną przecinkami listą zmiennych i/lub stałych.

PHP obsługuje przekazywanie argumentów przez wartość (domyślnie), przez referencję , i wartości domyślne argumentów. Listy argumentów o zmiennej długości są obsługiwane tylko w PHP 4 i nowszych; zobacz rozdział Listy argumentów o zmiennej długości i opisy funkcji func_num_args(), func_get_arg(), i func_get_args() aby uzyskać więcej informacji. Podobny efekt może być uzyskany w PHP 3 przez przekazywanie tablicy argumentów do funkcji:

function pobiera_tablice($wejscie)
{
    echo "$wejscie[0] + $wejscie[1] = ", $wejscie[0]+$wejscie[1];
}


Przekazywanie argumentów przez referencję

Domyślnie, argumenty funkcji są przekazywane przez wartość (a więc jeśli zmienisz wartość argumentu wewnątrz funkcji, nie zmieni się ona poza funkcją). Jeśli chcesz pozwolić funkcji na modyfikację swoich argumentów, musisz przekazać je przez referencję.

Jeśli chcesz, aby argumenty były zawsze przekazywane przez referencję, przed nazwą zmiennej w definicji funkcji wstaw znak ampersand (&):

function dodaj_cos_extra(&$string)
{
    $string .= 'i coś extra.';
}
$str = 'To jest string, ';
dodaj_cos_extra($str);
echo $str;    // wyświetla 'To jest string string, i coś extra.'

Jeśli chcesz przekazać zmienną przez referencję do funkcji, która tego domyślnie tego nie robi, możesz wstawić ampersand przez nazwą argumentu przy wywołaniu funkcji:

function foo ($bar)
{
    $bar .= ' i coś ekstra.';
}
$str = 'To jest string, ';
foo ($str);
echo $str;    // wyświetla 'To jest string, '
foo (&$str);
echo $str;    // wyświetla 'To jest string, i coś extra.'


Wartości domyślne argumentów

Funkcja może definiować, podobnie jest w C++, wartości domyślne dla argumentów skalarnych:

function robkawe ($typ = "cappucino")
{
    return "Robię kubek $type.\n";
}
echo robkawe ();
echo robkawe ("espresso");

Powyższy kawałek kody wyświetli:
Robię kubek cappucino.
Robię kubek espresso.

Domyślna wartość musi być stałym wyrażeniem, nie (na przykład) zmienną lub członkiem klasy.

Zauważ, że używając domyślnych argumentów, argumenty zawierające wartości domyślne powinny być po prawej stronie tych nie zawierających wartości domyślnych; w przeciwnym przypadku funkcja może nie działać tak jak się tego spodziewałeś. Zobacz to na poniższym przykładzie:

function robjogurt ($typ = "acidophilus", $smak)
{
    return "Robię miskę $typ $smak.\n";
}
 
echo robjogurt ("malinowy");   // nie działa tak jak się spodziewaliśmy

Powyższa funkcja wyświetla:
Warning: Missing argument 2 in call to robjogurt() in 
/usr/local/etc/httpd/htdocs/php3test/functest.html on line 41
Robię miskę malinowy .

Porównaj powyższy przykład z tym:

function robjogurt ($smak, $typ = "acidophilus")
{
    return "Robię miskę $type $flavour.\n";
}
 
echo robjogurt ("malinowy");   // działa tak jak się spodziewaliśmy

Powyższy kod wyświetla:
Robię miskę acidophilus malinowy.


Listy argumentów o zmiennej długości

PHP 4 obsługuje listy o zmiennej długości w funkcjach zdefiniowanych przez użytkownika. Jest naprawdę prostę przy użyciu funkcji func_num_args(), func_get_arg() i func_get_args().

Nie wymagana jest żadna specjalna składnia. Listy argumentów mogą być ciągle jawnie podane przy definicji funkcji i będą się zachowywać normalnie.


Zwracane wartości

Wartości są zwracana przy użyciu opcjonalnej instrukcji return. Może być zwracany dowonlny typ, włączając w to tablice i obiekty.

function kwadrat ($num)
{
    return $num * $num;
}
echo kwadrat (4);   // wyświetla '16'.

Nie możesz zwracać zwracać wielu wartości z funkcji, ale podobne efekty mogą być uzyskane przez zwracanie listy.

function maleLiczby()
{
    return array (0, 1, 2);
}
list ($zero, $jeden, $dwa) = maleLiczby();

Aby funkcja zwracała referencję, musisz użyć operatora referencji & i w deklaracji funkcji i przy przypisywaniu zwracanej wartości do zmiennej:

function &zwrocReferencje()
{
    return $jakasref;
}

$nowaref =& zwrocReferencje();


old_function

Instrukcja old_function pozwala na zadeklarowanie funkcji korzystając ze składni takiej samej jak w PHP/FI2 (tylko że zamiast 'function' musisz użyć 'old_function'.

Jest to niezalecana opcja i powinna być używana tylko przez konwerter PHP/FI2->PHP 3.

Ostrze¿enie

Funkcje zadekladowane jako old_function nie mogą być wywołane z kodu wewnętrznego PHP. Między innymi oznacza to, że nie możesz używać ich z takich funkcji jak usort(), array_walk() i register_shutdown_function (). Możesz obejść to ograniczenie przez napisanie interfejsu (w normalnej dla PHP 3 postaci) wywołującego old_function.


Zmienne funkcje

PHP obsługuje koncepcję zmiennych funkcji. Oznacza to, że jeśli po nazwie zmiennej występują nawiasy, PHP będzie szukało funkcji o nazwie będącej wartością zmiennej i będzie próbowało wywołać ją. Między innymi może być to użyte do implementacji funkcji callback, tablicy funkcji itp.

Zmienne funkcje nie będą działać z elementami składowymi języka, takimi jak echo(), unset(), isset() i empty(). Jest to jedna z głównych różnic pomiędzy funkcjami PHP i elementami składowymi języka.

Przykład 12-1. Przykład zmiennej funkcji

<?php
function foo()
{
    echo "W foo()<br>\n";
}

function bar($arg = '')
{
    echo "W bar(); argumentem jest '$arg'.<br>\n";
}

$func = 'foo';
$func();
$func = 'bar';
$func('test');
?>


Rozdział 13. Klasy i Obiekty

klasa

Klasa jest to zbiór zmiennych i funkcji operujących na tych zmiennych. Do definicji klasy używana jest następująca składnia:

<?php
class Koszyk
{
    var $zakupy;  // Zakupy w naszym koszyku
   
    // Dodaj $num artykułów typu $artnr do wózka
 
    function dodaj_produkt ($artnr, $num)
    {
        $this->zakupy[$artnr] += $num;
    }
   
    // Usuń $num artykułów typu $artnr z wózka
 
    function usun_produkt ($artnr, $num)
    {
        if ($this->zakupy[$artnr] > $num) {
            $this->zakupy[$artnr] -= $num;
            return true;
        } else {
            return false;
        }   
    }
}
?>

Definiuje to klasę o nazwie Koszyk, która zawiera tablicę asocjacyjną artykułów znajdujących się w wózku i dwie funkcje do dodawania i usuwania produktów z koszyka.

Uwaga!

Poniższe uwagi dotyczą PHP 4.

Nazwa stdClass jest używana wewnętrznie przez Zend i jest zarezerwowana. W PHP nie możesz zdefiniować klasy o nazwie stdClass.

Nazwy funkcji __sleep i __wakeup mają magiczne znaczenie dla klas w PHP. Klasy nie mogą zawierać funkcji o tych nazwach, chyba że zgadzasz się na przypisanie do nich magicznej funkcjonalności. Poniżej możesz znaleźć więcej informacji.

PHP rezerwuje wszystkie nazwy funkcji zaczynające się od __ na funkcje magiczne. Zalecane jest nieużywanie funkcji z nazwami zaczynającymi się od __ chyba że chcesz jakiejś magicznej funkcjonalności.

Notatka: W PHP 4 dozwolone są tylko stałe inicjalizatory zmiennych var. Aby zainicjalizować zmienne z nie-stałymi wartościami, potrzebujesz funkcję inicjalizacyjną, która jest wywoływana automatycznie zaraz po utworzeniu obiektu z danej klasy. Taka funkcja zwana jest konstruktorem (zobacz poniżej).

/* Nic z tego nie będzie działać w PHP 4. */
class Koszyk
{
    var $dzisiejsza_data = date("Y-m-d");
    var $nazwa = $imie;
    var $wlasciciel = 'Fred ' . 'Jones';
    var $artykuly = array("VCR", "TV");
}

/* Teraz wszystko zadziala. */
class Koszyk
{
    var $dzisiejsza_data;
    var $nazwa;
    var $wlasciciel;
    var $artykuly;

    function Cart()
    {
        $this->dzisiejsza_data = date("Y-m-d");
        $this->nazwa = $GLOBALS['imie'];
        /* itp. . . */
    }
}

Klasy są typami, które są w zasadzie tylko schematami dla właściwych zmiennych. Zmienne pożądanego typu musisz stworzyć korzystając z operatora new.

$koszyk = new Koszyk;
$koszyk->dodaj_produkt("10", 1);

$inny_koszyk = new Koszyk;
$inny_koszyk->dodaj_produkt("0815", 3);

Kod ten tworzy obiekty $koszyk i $inny_koszyk, oba klasy Koszyk. Funkcja dodaj_produkt() obiektu $koszyk zostaje wywołana w celu dodania 1 artykułu typu "10" do koszyka $koszyk. 4 przedmioty typu "0815" dodawane są do koszyka $inny_koszyk.

I $koszyk i $inny_koszyk mają funkcje dodaj_produkt(), usun_produkt() i zmienne. Są to osobne funkcje i zmienne. Obiekty mogą być postrzegane jako katalogi w systemie plików. W systemie plików możesz mieć dwa różne pliki README.TXT, ale tylko jeśli istnieją w osobnych katalogach. Aby odczytać plik, będąc w głównym katalogu, musisz podać pełną ścieżkę do tego pliku. Tak samo jest przy obiektach: musisz podać pełną nazwę funkcji, z której chcesz skorzystać. W terminologii PHP katalogiem głównym będzie globalna przestrzeń nazw a separatorem ścieżki będzie ->. W związku z tym nazwy $koszyk i $inny_koszyk zawierają zupełnie inne zmienne. Zauważ, że zmienna nazywa się $koszyk->artykuly, a nie $koszyk->$artykuly, ponieważ nazwa zmiennej może zawierać tylko jeden znak dolara.

// poprawnie, jeden $
$koszyk->artykuly = array("10" => 1); 

// niepoprawnie, poniważ $koszyk->$artykuly zamienia się na $koszyk->""
$koszyk->$artykuly = array("10" => 1);

// poprawnie, ale może (ale nie musi) nie być tym, co zamierzaliśmy:
// $koszyk->$zmienna staje się $koszyk->artykuly
$zmienna = 'artykuly';
$koszyk->$zmienna = array("10" => 1);

Wewnątrz definicji klasy, nie wiesz pod jaką nazwą obiekt będzie dostępny dla twojego programu: w momencie pisania klasy Koszyk, nie było wiadomo, że obiekty będą się nazywać $koszyk lub $inny_koszyk. W związku z tym nie możesz napisać $koszyk->artykuly wewnątrz klasy Koszyk. Zamiast tego, aby uzyskać dostęp do funkcji i zmiennych zawartych w klasie, można użyć pseudo-zmiennej $this, która może być odczytana jako 'moje własne' lub 'bieżący obiekt'. A więc '$this->artykuly[$nrart] += $liczba' może być odczytane jako 'dodaj $liczba do licznika $nrart z mojej własnej tablicy artykuly' lub 'dodaj $liczba do licznika $nrartz tablicy artykuly zawartej w bieżącym obiekcie'.


extends

Bardzo często zachodzi potrzeba stworzenia klasy o funkcjach i zmiennych podobnych do już istniejącej klasy. Zasadniczo dobrze jest stworzyć szablonową klasę, która może być użyta we wszystkich twoich projektach i przystosowywać ją do specyficznych potrzeb twojego projektu. Aby ułatwić ten proces, klasy mogą być rozszerzeniami innych klas. Rozszerzone, lub mówiąc inaczej 'dziedziczone', klasy mają wszystkie zmienne i funkcje klasy podstawowej (nazywa się to dziedziczeniem, mimo że nikt nie umarł) oraz to co do niej dodałeś w definicji rozszerzenia. Nie można odjąć pewnych rzeczy z klasy podstawowej, czyli oddefiniować istniejących w klasie podstawowej funkcji i zmiennych. Rozszerzona klasa jest zawsze zależna od jednej klasy bazowej - dziedziczenie wielokrotne nie jest obsługiwane. Klasy można rozszerzyć używając słowa kluczowego 'extends'.

class Nazwany_Koszyk extends Koszyk
{
    var $wlasciciel;
  
    function ustaw_wlasciciela ($nazwa)
    {
        $this->wlasciciel = $nazwa;
    }
}

Definiuje to klasę Nazwany_Koszyk, który ma wszystkie zmienne i funkcje klasy Koszyk plus dodatkowa zmienna $wlasciciel i dodatkowa funkcja ustaw_wlasciciela(). Nazwany koszyk tworzy się normalnym sposobem. Możesz teraz ustawiać i pobierać nazwę właściciela koszyka. Cały czas możesz używać zwykłych funkcji koszyka dla nazwanego koszyka:

$nkoszyk = new Nazwany_Koszyk;        // Stwórz nazwany koszyk
$nkoszyk->ustaw_wlasciciela("kris");  // Nazwij koszyk
print $nkoszyk->wlasciciel;           // Wyświetl właściciela koszyka
$nkoszyk->dodaj_przedmiot("10", 1);   // (funkcjonalność odziedziczona z
                                      // koszyka)


Konstruktory

Uwaga!

Konstruktory zachowują się inaczej w PHP 3 i w PHP 4. Semantyka PHP 4 jest mocno zalecana.

Konstruktory są funkcjami klasy, które są automatycznie wywoływane przy tworzeniu nowej instancji klasy korzystając z operatora new. W PHP 3 funkcja staje się konstruktorem kiedy ma taką samą nazwę jak klasa. W PHP 4 funkcja staje się konstruktorem, kiedy ma taką samą nazwę jak klasa, w której ta funkcja została zdefiniowana - różnica jest subtelna, ale bardzo ważna (zobacz poniżej)

// Działa w PHP 3 i PHP 4.
class Auto_Koszyk extends Koszyk
{
    function Auto_Koszyk()
    {
        $this->dodaj_artykul ("10", 1);
    }
}

Ten kod definiuję klasę Auto_Koszyk, który jest klasą Koszyk pluc konstruktor, który inicjalizuje wózek z jednym artykułem "10" za każdym razem, kiedy Auto_Koszyk jest tworzony operatorem "new". Konstruktory mogą pobierać argumenty i te argumenty mogą być opcjonalne, przez co są jeszcze bardziej użyteczne. Aby w dalszym ciągu móc używać klasy bez parametrów, wszystkie parametry konstruktora powinny stać się opcjonalne przez dodanie domyślnych wartości.

// Działa w PHP 3 i PHP 4.
class Kontruktor_Koszyk extends Koszyk
{
    function Konstruktor_Koszyk($artykul = "10", $ilosc = 1)
    {
        $this->dodaj_artykul ($artykul, $ilosc);
    }
}
 
// Kup te same nudne rzeczy...
 
$zwykly_koszyk = new Konstruktor_Koszyk;
 
// Czas na prawdziwe zakupy...
 
$inny_koszyk = new Konstruktor_Koszyk("20", 17);

Uwaga!

W PHP 3, dziedziczone klasy i konstruktory mają wiele ograniczeń. Poniższe przykłady powinny być dokładnie przeczytane w celu zrozumienia tych ograniczeń.

class A
{
    function A()
    {
      echo "Jestem konstruktorem klasy A.<br>\n";
    }
}

class B extends A
{
    function C()
    {
        echo "Zwykła funkcja.<br>\n";
    }
}

// W PHP 3 nie zostanie wywołany żaden konstruktor.
$b = new B;

W PHP 3 w powyższym przykładzie nie będzie wywołany żaden konstruktor. Zasadą PHP 3 jest: 'Konstruktor to funkcja o takiej samej nazwie jak klasa'. Nazwą klasy jest B, a w klasie B nie ma funkcji o nazwie B(). Nic się nie dzieje.

Zostało to poprawione w PHP 4 przez wprowadzenie innej zasady: jeśli klasa nie ma konstruktora, używany jest konstruktor klasy bazowej, jeśli taki istnieje. W PHP 4 powyższy przykład wyświetli 'Jestem konstruktorem klasy A.<br>'.

class A
{
    function A()
    {
        echo "Jestem konstruktorem klasy A.<br>\n";
    }

    function B()
    {
        echo "Jestem zwykłą funkcją o nazwie B w klasie A.<br>\n";
        echo "Nie jestem konstruktorem w klasie A.<br>\n";
    }
}

class B extends A
{
    function C()
    {
        echo "Jestem zwykłą funkcją.<br>\n";
    }
}

// Wywoła to B() jako konstruktor.
$b = new B;

W PHP 3, funkcja B() z klasy A niespodziewanie stanie się konstruktorem w klasie B, pomimo że wcale nie miała nim być. Zasadą PHP 3 jest: 'Konstruktor to funkcja o takiej samej nazwie co klasa'. PHP 3 nie obchodzi czy funkcja została zdefiniowana w klasie B czy została odziedziczona.

Zostało to poprawione w PHP 4 przez modyfikację tej zasady do: 'Konstruktor to funkcja o tej samej nazwie co klasa w której została zdefiniowana'. W związku z tym w PHP 4 clasa B nie miałaby własnego konstruktora. Wywołany byłby tylko konstruktor klasy bazowej, wyświetlając 'Jestem konstruktorem klasy A.<br>'.

Uwaga!

Ani PHP 3 ani PHP 4 nie wywoła automatycznie konstruktora klasy bazowej z kontruktora klasy pochodnej. Twoim zadaniem jest propagacja wywołań konstruktorów klas nadrzędnych, jeśli to konieczne.

Notatka: Ani w PHP 3 ani w PHP 4 nie ma destruktorów. Zamiast tego możesz użyć register_shutdown_function() aby symulować działanie destruktorów.

Destruktory są funkcjami, które są wywoływanie automatycznie kiedy obiekty są niszczone albo przez użycie unset() albo przez wyjście z zasięgu. W PHP nie ma destruktorów.


::

Uwaga!

Poniższe dotyczy tylko PHP 4.

Czasami dobrze jest odnosić się do funkcji i zmiennych w klasie bazowej lub odnosić się do funkcji i klas które nie mają jeszcze instancji. Służy do tego operator ::.

class A
{
    function przyklad()
    {
        echo "Jestem orginalną funkcją A::przyklad().<br>\n";
    }
}

class B extends A
{
    function przyklad()
    {
        echo "Jestem przedefiniowaną funkcją B::przyklad().<br>\n";
        A::przyklad();
    }
}

// nie ma obiektu klasy A.
// poniższe wyświetli
//   Jestem orginalną funkcją A::przyklad().<br>
A::przyklad();

// stwórz nowy obiekt klasy B.
$b = new B;

// poniższe wyświetli
//   Jestem przedefiniowaną funkcją B::przyklad().<br>
//   Jestem orginalną funkcją A::przyklad().<br>
$b->przyklad();

Powyższy przekład wywołuje funkcję przyklad() z klasy A, ale nie tworząc obiektu tej klasy, przez co nie możemy napisać nic w stylu $a->przyklad(). Zamiast tego możemy wywołać przyklad() jako 'funkcję klasy', czyli jako funkcję tylko klasy, nie żadnego obiektu tej klasy.

Istnieją funkcje klasy, ale nie ma zmiennych klasy. Faktycznie w czasie wykonania nie ma żadnego obiektu. W związku z tym funkcje klasy nie mogą używać żadnych zmiennych obiektu (ale mogą używać zmiennych lokalnych i globalnych), ani w ogóle $this.

W powyższym przykładzie, klasa B przedefiniowuje funkcję przyklad(). Orginalna definicja z klasy A jest zasłonięta i niedostępna, chyba że odwołasz się do konkretnej implementacji poprzez operator ::. Aby to zrobić, napisz A::przyklad() (powinieneś jednak użyć parent::przyklad(), tak jak to pokazano w następnej części).

W tym kontekście, istnieje bieżący obiekt i który ma zmienne obiektu. W związu z tym jeśli funkcja jest użyta Z WEWNĄTRZ funkcji obiektu, możesz używać $this i zmiennych obiektu.


parent

Może się zdarzyć, że będziesz pisał kod, który odnosi się do funkcji i zmiennych klasy bazowej. Jest to możliwe jeśli twoja klasa pochodna jest uściśleniem lub specjalizacją klasy bazowej.

Zamiast jawnego podawania nazwy klasy bazowej w kodzie, powinieneś użyć specjalnej nazwy parent, która odnosi się do nazwy klasy bazowej podanej przy extends podczas deklaracji twojej klasy. Robiąc to, unikasz użycia nazwy klasy bazowej w więcej niż jednym miejscu. Jeśli twoje drzewo dziedziczenia zmieniłoby się podczas implementacji, zmiana będzie wymagała poprawki tylko w jednym miejscu - przy słowie kluczowym extends w deklaracji klasy.

class A
{
    function przyklad()
    {
        echo "Jestem A::przyklad() I dostarczam podstawową funkcjonalność.<br>\n";
    }
}

class B extends A
{
    function przyklad()
    {
        echo "Jestem B::przyklad() i dostarczam dodatkową funkcjonalność.<br>\n";
        parent::przyklad();
    }
}

$b = new B;

// Wywoła to B::przyklad(), który z kolei wywoła A::przyklad().
$b->przyklad();


Serializacja obiektów - obiekty w sesjach

Notatka: W PHP 3 obiekty tracą powiązania między klasami w czasie procesu serializacji i odserializacji. Wynikowa zmienna będzie typu obiekt, ale bez klasy i bez metod, a więc w zasadzie bezużyteczną (zostanie poprostu zmienną ze śmieszną składnią).

Uwaga!

Poniższe informacje dotyczą tylko PHP 4.

serialize() zwraca string będący reprezentacją dowolnej wartości, która może być przechowywana przez PHP. unserialize() może użyć tego stringu aby odtworzyć orginalne wartości zmiennej. Użycie serializacji do zapisania obiektu zachowa wszystkie zmienne z obiektu. Zapisane nie będą funkcje z obiektu, a jedynie nazwa klasy.

Aby istniała możliwość użycia funkcji unserialize() do odzyskania obiektu, musi być zdefiniowana klasa tego obiektu. Oznacza to, że jeśli obiekt $a klasy A istnieje na page1.php i zserializujesz go, otrzymasz string, który odnosi się do klasy A i zawiera wartości wszystkich zmiennych zawartych w $a. Jeśli chcesz, aby istniała możliwość odserializacji tego obiektu na page2.php, na page2.php musi istnieć definicja klasy A. Można to zrobić na przykład przez przechowywanie definicji klasy A w zewnętrznym pliku includowanym przez page1.php i page2.php.

classa.inc:
  class A 
  {
      var $jeden = 1;
    
      function pokaz_jeden()
      {
          echo $this->jeden;
      }
  }
  
page1.php:
  include("classa.inc");
  
  $a = new A;
  $s = serialize($a);
  // przechowaj $s gdzieś, gdzie page2.php będzie mogła go znaleźć
  $fp = fopen("store", "w");
  fputs($fp, $s);
  fclose($fp);

page2.php:
  // to jest niezbędne aby funkcja unserialize działała prawidłowo.
  include("classa.inc");

  $s = implode("", @file("store"));
  $a = unserialize($s);

  // teraz użyj funkcji pokaz_jeden z obiektu $a.
  $a->pokaz_jeden();

Jeśli używasz sesji i session_register() do rejestracji obiektów, te obiekty są serializowane automatycznie na końcu każdej strony PHP i odserializowane automatycznie na każdej z następnych stron. Zasadniczo znaczy to, że te obiekty mogą pokazać się na dowolnej z twoich stron jeśli tylko staną się częścią twojej sesji.

Mocno zalecane jest includowanie definicji klas wszystkich zarejestrowanych obiektów na wszystkich twoich stronach, nawet jeśli nie używasz tych zmiennych na twoich stronach. Jeśli tego nie zrobisz a obiekty zostaną odserializowane bez definicji klasy, powiązania klasowe zostaną utracone a obiek stanie się obiektem klasy stdClass bez żadnych dostępnych funkcji, a więc będzie całkiem bezużyteczny.

A więc jeśli w powyższym przykładzie $a stanie się częścią sesji przez wywołanie session_register("a"), powinieneć includować plik classa.inc na wszystkich stronach, nie tylko page1.php i page2.php.


Magiczne funkcje __sleep i __wakeup

serialize() sprawdza, czy twoja klasa zawiera funkcję o magicznej nazwie __sleep. Jeśli tak, ta funkcja jest wywoływana przed każdą serializacją. Może ona czyścić obiekt i powinna zwracać tablicę z nazwami wszystkich zmiennych obiektu, które powinny być serializowane.

Założonym użyciem __sleep jest zamknięcie wszystkich połączeń do baz danych, które obiekt może utrzymywać, zatwierdzenie wszystkich oczekujących danych lub wykonanie innych podobnych czynności czyszczących. Funkcja ta jest także przydatna jeśli masz bardzo duże obiekty, które nie muszą być zachowane w całości.

Analogicznie, unserialize() sprawdza czy istnieje funkcja o magicznej nazwie __wakeup. Jeśli tak, funkcja może rekonstruować dowolne zasoby które obiekt może posiadać.

Założonym użyciem __wakeup jest odnowienie połączeń z bazami danych, które mogły zostac utracone w procesie serializacji, oraz wykonanie innych czynności odbudowujących obiekt.


Referencje wewnątrz konstruktora

Tworzenie referencji wewnątrz konstruktora może prowadzić do dziwnych efektów. Ten rozdział ma pomóc w unikaniu takich problemów.

class Foo
{
    function Foo($nazwa)
    {
        // stworz referencje wewnatrz globalnej tablicy $globalref
        global $globalref;
        $globalref[] = &$this;
        // ustaw nazwę na przekazaną wartość
        $this->ustawNazwe($nazwa);
        // i wyświetl ją
        $this->wyswietlNazwe();
    }

    function wyswietlNazwe()
    {
        echo "<br>",$this->nazwa;
    }
	
    function ustawNazwe($nazwa)
    {
        $this->nazwa = $nazwa;
    }
}

Sprawdźmy, czy jest jakaś różnica pomiędzy $bar1, który jest tworzony przy pomocy operatora przypisania =, a $bar2, który został stworzony używając operatora referencji =&...

$bar1 = new Foo('ustawione w konstruktorze');
$bar1->wyswietlNazwe();
$globalref[0]->wyswietlNazwe();

/* wyjście:
ustawione w konstruktorze
ustawione w konstruktorze
ustawione w konstruktorze */

$bar2 =& new Foo('ustawione w konstruktorze');
$bar2->wyswietlNazwe();
$globalref[1]->wyswietlNazwe();

/* wyjście:
ustawione w konstruktorze
ustawione w konstruktorze
ustawione w konstruktorze */

Wydaje się, że nie ma żadnej różnicy, ale na prawdę jest jedna, i to bardzo istotna: $bar1 i $globalref[0] NIE są referencjami, NIE są tą samą zmienna. Dzieje się tak, ponieważ "new" nie zwraca domyślnie referencji, ale kopię.

Notatka: Zwracanie kopii zamiast referencji nie powoduje utraty wydajności (od PHP 4 używane jest zliczanie referencji). Jednakże zazwyczaj lepiej jest pracować poprostu z kopiami zamiast referencji, poniewać tworzenie referencji zabiera trochę czasu, podczas gdy tworzenie kopii obiektów teoretycznie w ogóle nie zabiera czasu (chyba że któraś z tych zmiennych jest dużą tablicą lub obiektem i jedno z nich ulega zmianie, po czym tej samej zmianie ulegają pozostałe zmienne; wtedy lepiej jest użyć referencji do zmieniania ich równolegle).

Aby udowodnić to, co zostało zapisane powyżej, przyjrzyjmy się poniższemu programowi.

// teraz zmienimy nazwę. czego się spodziewasz?
// możesz się spodziewać, że i $bar1 i $globalref[0] zmienią swoje nazwy...
$bar1->ustawNazwe('ustawiona z zewnątrz');

// jak napisano powyżej, nic takiego się nie stanie
$bar1->wyswietlNazwe();
$globalref[0]->wyswietlNazwe();

/* wyjście:
ustawiona z zewnątrz
ustawiona w konstruktorze */

// zobaczmy co się dzieje z $bar2 i $globalref[1]
$bar2->ustawNazwe('ustawiona z zewnątrz');

// na szczęście ta zmienna nie zachowuje się jak ta z poprzedniego przypadku
// są to te same zmienne, z więc $bar2->nazwa i $globalref[1]->nazwa są także
// tymi samymi zmiennymi
$bar2->wyswietlNazwe();
$globalref[1]->wyswietlNazwe();

/* wyjście:
ustawiona z zewnątrz
ustawiona z zewnątrz */

Ustatni przykład. Postaraj się go zrozumieć/

class A
{
    function A($i)
    {
        $this->wartosc = $i;
        // domyśl się dlaczego nie potrzebujemy tutaj referencji
        $this->b = new B($this);
    }

    function stworzRef()
    {
        $this->c = new B($this);
    }

    function wyswietlWartosc()
    {
        echo "<br>","klasa ",get_class($this),': ',$this->value;
    }
}


class B
{
    function B(&$a)
    {
        $this->a = &$a;
    }

    function wyswietlWartosc()
    {
        echo "<br>","klasa ",get_class($this),': ',$this->a->value;
    }
}
// spróbuj zrozumieć dlaczego użycie tu prostego kopiowania może powodować
// nieporządany efekt w linii uznaczonej znaczkiem '*'
$a =& new A(10);
$a->stworzRef();

$a->wyswietlWartosc();
$a->b->wyswietlWartosc();
$a->c->wyswietlWartosc();

$a->value = 11;

$a->wyswietlWartosc();
$a->b->wyswietlWartosc(); // *
$a->c->wyswietlWartosc();

/*
wyjście:
klasa A: 10
klasa B: 10
klasa B: 10
klasa A: 11
klasa B: 11
klasa B: 11
*/


Rozdział 14. References Explained

What References Are

References are a means in PHP to access the same variable content by different names. They are not like C pointers, they are symbol table aliases. Note that in PHP, variable name and variable content are different, so the same content can have different names. The most close analogy is with Unix filenames and files - variable names are directory entries, while variable contents is the file itself. References can be thought of as hardlinking in Unix filesystem.


What References Do

PHP references allow you to make two variables to refer to the same content. Meaning, when you do:

$a =& $b

it means that $a and $b point to the same variable.

Notatka: $a and $b are completely equal here, that's not $a is pointing to $b or vice versa, that's $a and $b pointing to the same place.

The same syntax can be used with functions, that return references, and with new operator (in PHP 4.0.4 and later):

$bar =& new fooclass();
$foo =& find_var ($bar);

Notatka: Not using the & operator causes a copy of the object to be made. If you use $this in the class it will operate on the current instance of the class. The assignment without & will copy the instance (i.e. the object) and $this will operate on the copy, which is not always what is desired. Usually you want to have a single instance to work with, due to performance and memory consumption issues.

The second thing references do is to pass variables by-reference. This is done by making a local variable in a function and a variable in the calling scope reference to the same content. Example:

function foo (&$var)
{
    $var++;
}

$a=5;
foo ($a);

will make $a to be 6. This happens because in the function foo the variable $var refers to the same content as $a. See also more detailed explanations about passing by reference.

The third thing reference can do is return by reference.


What References Are Not

As said before, references aren't pointers. That means, the following construct won't do what you expect:

function foo (&$var)
{
    $var =& $GLOBALS["baz"];
}
foo($bar);

What happens is that $var in foo will be bound with $bar in caller, but then it will be re-bound with $GLOBALS["baz"]. There's no way to bind $bar in the calling scope to something else using the reference mechanism, since $bar is not available in the function foo (it is represented by $var, but $var has only variable contents and not name-to-value binding in the calling symbol table).


Passing by Reference

You can pass variable to function by reference, so that function could modify its arguments. The syntax is as follows:

function foo (&$var)
{
    $var++;
}

$a=5;
foo ($a);
// $a is 6 here

Note that there's no reference sign on function call - only on function definition. Function definition alone is enough to correctly pass the argument by reference.

Following things can be passed by reference:

  • Variable, i.e. foo($a)

  • New statement, i.e. foo(new foobar())

  • Reference, returned from a function, i.e.:

    function &bar()
    {
        $a = 5;
        return $a;
    }
    foo(bar());

    See also explanations about returning by reference.

Any other expression should not be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid:

function bar() // Note the missing &
{
    $a = 5;
    return $a;
}
foo(bar());

foo($a = 5) // Expression, not variable
foo(5) // Constant, not variable

These requirements are for PHP 4.0.4 and later.


Returning References

Returning by-reference is useful when you want to use a function to find which variable a reference should be bound to. When returning references, use this syntax:

function &find_var ($param)
{
    ...code...
    return $found_var;
}

$foo =& find_var ($bar);
$foo->x = 2;

In this example, the property of the object returned by the find_var function would be set, not the copy, as it would be without using reference syntax.

Notatka: Unlike parameter passing, here you have to use & in both places - to indicate that you return by-reference, not a copy as usual, and to indicate that reference binding, rather than usual assignment, should be done for $foo.


Unsetting References

When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed. For example:

$a = 1;
$b =& $a;
unset ($a);

won't unset $b, just $a.

Again, it might be useful to think about this as analogous to Unix unlink call.


Spotting References

Many syntax constructs in PHP are implemented via referencing mechanisms, so everything told above about reference binding also apply to these constructs. Some constructs, like passing and returning by-reference, are mentioned above. Other constructs that use references are:


global References

When you declare variable as global $var you are in fact creating reference to a global variable. That means, this is the same as:

$var =& $GLOBALS["var"];

That means, for example, that unsetting $var won't unset global variable.


$this

In an object method, $this is always reference to the caller object.


Rozdział 15. Error Handling

There are several types of errors and warnings in PHP. They are:

Tabela 15-1. PHP error types

ValueConstantDescriptionNote
1E_ERRORfatal run-time errors 
2E_WARNINGrun-time warnings (non fatal errors) 
4E_PARSEcompile-time parse errors 
8E_NOTICE run-time notices (less serious than warnings)  
16E_CORE_ERRORfatal errors that occur during PHP's initial startupPHP 4 only
32E_CORE_WARNING warnings (non fatal errors) that occur during PHP's initial startup PHP 4 only
64E_COMPILE_ERRORfatal compile-time errorsPHP 4 only
128E_COMPILE_WARNINGcompile-time warnings (non fatal errors)PHP 4 only
256E_USER_ERRORuser-generated error messagePHP 4 only
512E_USER_WARNINGuser-generated warning messagePHP 4 only
1024E_USER_NOTICE user-generated notice messagePHP 4 only
 E_ALLall of the above, as supported 

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, however, and that no bitwise operators will be understood within php3.ini.

In PHP 4, the default error_reporting setting is E_ALL & ~E_NOTICE, meaning to display all errors and warnings which are not E_NOTICE-level. In PHP 3, the default setting is (E_ERROR | E_WARNING | E_PARSE), meaning the same thing. Note, however, that since constants are not supported in PHP 3's php3.ini, the error_reporting setting there must be numeric; hence, it is 7.

The initial setting can be changed in the ini file with the error_reporting directive, in your Apache httpd.conf file with the php_error_reporting (php3_error_reporting for PHP 3) directive, and lastly it may be set at runtime within a script by using the error_reporting() function.

Ostrze¿enie

When upgrading code or servers from PHP 3 to PHP 4 you should check these settings and calls to error_reporting() or you might disable reporting the new error types, especially E_COMPILE_ERROR. This may lead to empty documents without any feedback of what happened or where to look for the problem.

All PHP expressions can also be called with the "@" prefix, which turns off error reporting for that particular expression. If an error occurred during such an expression and the track_errors feature is enabled, you can find the error message in the global variable $php_errormsg.

Notatka: The @ error-control operator prefix will not disable messages that are the result of parse errors.

Ostrze¿enie

Currently the @ error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use @ to suppress errors from a certain function and either it isn't available or has been mistyped, the script will die right there with no indication as to why.

Below we can see an example of using the error handling capabilities in PHP. We define a 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.

Przykład 15-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 2,8,256,512 and 1024
    $errortype = array (
                1   =>  "Error",
                2   =>  "Warning",
                4   =>  "Parsing Error",
                8   =>  "Notice",
                16  =>  "Core Error",
                32  =>  "Core Warning",
                64  =>  "Compile Error",
                128 =>  "Compile Warning",
                256 =>  "User Error",
                512 =>  "User Warning",
                1024=>  "User Notice"
                );
    // set of errors for which a var trace will be saved
    $user_errors = array(E_USER_ERROR, E_USER_WARNING, E_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($err, 3, "/usr/local/php4/error.log");
    if ($errno == E_USER_ERROR)
        mail("phpdev@mydomain.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(2,3,"foo");
$b = array(5.5, 4.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";

?>
This is just a simple example showing how to use the Error Handling and Logging functions.

See also error_reporting(), error_log(), set_error_handler(), restore_error_handler(), trigger_error(), user_error()


Rozdział 16. Tworzenie i manipulacja obrazkami

PHP nie ogranicza się jedynie do generowania kodu HTML. Może również służyć do tworzenia i manipulacji plikami graficznymi w różnych formatach: gif, png, jpg, wbmp i xpm. PHP potrafi wysłać obrazek strumieniem do przeglądarki. Aby użyć funkcji operujących na obrazkach, należy skompilować PHP z obsługą biblioteki GD. GD i PHP mogą potrzebować również innych bibliotek, w zależności od tego z jakim formatem graficznym chcesz pracować. GD od wersji 1.6 nie obsługuje formatu GIF.

Przykład 16-1. Tworzenie orazka PNG za pomocą PHP

<?php
    Header("Content-type: image/png");
    $string=implode($argv," ");
    $im = imageCreateFromPng("images/button1.png");
    $orange = ImageColorAllocate($im, 220, 210, 60);
    $px = (imagesx($im)-7.5*strlen($string))/2;
    ImageString($im,3,$px,9,$string,$orange);
    ImagePng($im);
    ImageDestroy($im);
?>
Ten przykład powinien być wywołany ze strony przy użyciu <img src="button.php?tekst"> Powyższy skrypt button.php pobiera "tekst", umieszcza go na obrazku, którym w tym przypadku jest "images/button1.png", i zwraca wynikowy obrazek. Jest to bardzo wygodny sposób uniknięcia tworzenia nowych przycisków graficznych za każdym razem gdy chcesz zmienić tekst na nich. Za pomocą tej metody są one generowane dynamicznie.


Rozdział 17. Autoryzacja HTTP w PHP

Autoryzacja HTTP jest obsługiwana przez PHP tylko wtedy, gdy PHP pracuje jako moduł Apache'a, nie jest dostępna w trybie CGI. W skrypcie można użyć funkcji header() by wysłać do przeglądarki komunikat "Wymagana autoryzacja", co spowoduje wyświetlenie okienka z polami Użytkownik i Hasło. Po wypełnieniu przez użytkownika tych pól, URL zawierający skrypt PHP zostanie ponownie wywołany ze zmiennymi $PHP_AUTH_USER, $PHP_AUTH_PW i $PHP_AUTH_TYPE zawierającymi odpowiednio nazwę użytkownika, hasło i typ autoryzacji. Obecnie obsługiwany jest jedynie typ "Basic". Więcej informacji znajdziesz w opisie funkcji header().

Przykładowy skrypt wymuszający autoryzację klienta:

Przykład 17-1. Autoryzacja HTTP

<?php
  if (!isset($PHP_AUTH_USER)) {
    header("WWW-Authenticate: Basic realm=\"My Realm\"");
    header("HTTP/1.0 401 Unauthorized");
    echo "Tekst do wysłania, jeśli użytkownik wciśnie przycisk Anuluj\n";
    exit;
  } else {
    echo "<p>Hej $PHP_AUTH_USER.</p>";
    echo "<p>Twoje hasło to $PHP_AUTH_PW.</p>";
  }
?>

Notatka: Należy uważać z linijkami dodawanymi do nagłówka HTTP. W celu zachowania maksymalnej zgodności ze wszystkimi klientami, słowo Basic powinno zaczynać się dużą literą "B", wartość realm powinna być otoczona cudzysłowami (nie apostrofami), i dokładnie jeden znak odstępu powinien poprzedzać kod 401 w linii "HTTP/1.0 401".

Zamiast wyświetlać wartości $PHP_AUTH_USER i $PHP_AUTH_PW, zapewne zechcesz sprawdzić poprawność nazwy użytkownika i hasła. Na przykład poprzez zapytanie do bazy danych lub odnalezienie użytkownika w pliku dbm.

Należy uważać na kapryśne przeglądarki Internet Explorer. Są wrażliwe na kolejność wysyłanych nagłówków HTTP. Wysłanie nagłowka WWW-Authenticate przed HTTP/1.0 401 powinno rozwiązać problem.

Aby zapobiec sytuacji w której ktoś napisze skrypt wykradający hasło wysłane tradycyjnym zewnętrznym mechanizmem, zmienne PHP_AUTH nie będą ustawiane, jeśli dla danej strony aktywna jest autoryzacja zewnętrzna. W tym wypadku, aby uzyskać nazwę użytkownika zautoryzowanego zewnętrznie, należy skorzystać ze zmiennej $REMOTE_USER.

Notatka: Aby wykryć czy miała miejsce zewnętrzna autoryzacja, PHP sprwadza obecność dyrektywy AuthType. Pamiętaj zatem, by nie stosować tej dyrektywy w miejscach, gdzie będzie używana autoryzacja PHP. Inaczej każda próba autoryzacji zakończy się niepowodzeniem.

Powyższa metoda nie zapobiega jednak wykradaniu haseł do stron wymagających autoryzacji przez kogoś, kto na tym samym serwerze kontroluje strony nie wymagające autoryzacji.

Zarówno Netscape Navigator jak i Internet Explorer opróżnią bufor autoryzacji po otrzymaniu od serwera kodu 401. Można w ten sposób wylogowanić użytkownika i zmusić go do ponownego wysłania nazwy użytkownika i hasła. Tej metody można użyć do wylogowania użytkownika po określonym czasie lub stworzenia przycisku "Wyloguj".

Przykład 17-2. Autoryzacja HTTP z wymuszeniem przelogowania

<?php
  function authenticate() {
    header( "WWW-Authenticate: Basic realm=\"Testowy system autoryzacji\"");
    header( "HTTP/1.0 401 Unauthorized");
    echo "Musisz podać poprawny login i hasło by wejść na tę stronę\n";
    exit;
  }
 
  if (!isset($PHP_AUTH_USER) || ($SeenBefore == 1 && !strcmp($OldAuth, $PHP_AUTH_USER))) {
   authenticate();
  } 
  else {
   echo "<p>Witaj: $PHP_AUTH_USER<br>";
   echo "Poprzenio: $OldAuth";
   echo "<form action='$PHP_SELF' METHOD='POST'>\n";
   echo "<input type='hidden' name='SeenBefore' value='1'>\n";
   echo "<input type='hidden' name='OldAuth' value='$PHP_AUTH_USER'>\n";
   echo "<input type='submit' value='Re Authenticate'>\n";
   echo "</form></p>\n";
  }
?>

Powyższa metoda nie jest wymagana przez autoryzację HTTP typu "Basic", więc nie można na niej polegać. Testy z przeglądarką Lynx pokazały, że Lynx nie usuwa danych o autoryzacji po odebraniu od serwera kodu 401, zatem przejście wstecz a następnie do przodu otworzy stronę, chyba, że wymagania co do danych autoryzacji zmieniły się. Użytkownik może jednak użyć klawisza '_' by usunąc dane o autoryzacji.

Autoryzacja HTTP nie działa jeśli używasz serwera Microsoft IIS i PHP w wersji CGI. Powodem są pewne ograniczenia IIS.


Rozdział 18. Ciasteczka (cookies)

PHP obsługuje ciasteczka HTTP (cookies). Jest to mechanizm służący do przechowywania danych w przeglądarce i w ten sposób śledzenia lub identyfikowania powracających użytkowników. Można je ustawiać używając funkcji setcookie(). Ciasteczka stanowią część nagłówka HTTP, więc funkcja setcookie() musi być wywoływana zanim jakiekolwiek dane zostaną wysłane do przeglądarki. Występuje tu to samo ograniczenie, co w przypadku header().

Każde ciasteczko wysłane do ciebie od klienta, będzie automatycznie przekształcone w zmienną PHP, podobnie, jak przy użyciu metod POST i GET. Jeśli chcesz przypisać wiele wartości do pojedynczego ciasteczka, po prostu dodaj [] do nazwy ciasteczka. Po więcej detali sięgnij do funkcji setcookie().


Rozdział 19. Handling file uploads

POST method uploads

PHP is capable of receiving file uploads from any RFC-1867 compliant browser (which includes Netscape Navigator 3 or later, Microsoft Internet Explorer 3 with a patch from Microsoft, or later without a patch). This feature lets people upload both text and binary files. With PHP's authentication and file manipulation functions, you have full control over who is allowed to upload and what is to be done with the file once it has been uploaded.

Note that PHP also supports PUT-method file uploads as used by Netscape Composer and W3C's Amaya clients. See the PUT Method Support for more details.

A file upload screen can be built by creating a special form which looks something like this:

Przykład 19-1. File Upload Form

<form enctype="multipart/form-data" action="_URL_" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000">
Send this file: <input name="userfile" type="file">
<input type="submit" value="Send File">
</form>
The _URL_ should point to a PHP file. The MAX_FILE_SIZE hidden field must precede the file input field and its value is the maximum filesize accepted. The value is in bytes.

Ostrze¿enie

The MAX_FILE_SIZE is advisory to the browser. It is easy to circumvent this maximum. So don't count on it that the browser obeys you wish! The PHP-settings for maximum-size, however, cannot be fooled.

Variables defined for uploaded files differs depends on PHP version and configuration. Following variables will be defined within the destination script upon a successful upload. When track_vars is enabled, $HTTP_POST_FILES/$_FILES array is initialized. Finally, related variables may be initialized as globals when register_globals is turned on. However, use of globals is not recommended anymore.

Notatka: track_vars is always on from PHP 4.0.3. From PHP 4.1.0 or later, $_FILES may be used instead of $HTTP_POST_FILES. $_FILES is always global, so global is should not be used for $_FILES in function scope.

$HTTP_POST_FILES/$_FILES is provided to contain the uploaded file information.

The contents of $HTTP_POST_FILES are as follows. Note that this assumes the use of the file upload name 'userfile', as used in the example script above:

$HTTP_POST_FILES['userfile']['name']

The original name of the file on the client machine.

$HTTP_POST_FILES['userfile']['type']

The mime type of the file, if the browser provided this information. An example would be "image/gif".

$HTTP_POST_FILES['userfile']['size']

The size, in bytes, of the uploaded file.

$HTTP_POST_FILES['userfile']['tmp_name']

The temporary filename of the file in which the uploaded file was stored on the server.

Notatka: PHP 4.1.0 or later supports a short track variable $_FILES. PHP 3 does not support $HTTP_POST_FILES.

When register_globals is turned on in php.ini. Note that the following variable names assume the use of the file upload name 'userfile', as used in the example script above:

  • $userfile - The temporary filename in which the uploaded file was stored on the server machine.

  • $userfile_name - The original name or path of the file on the sender's system.

  • $userfile_size - The size of the uploaded file in bytes.

  • $userfile_type - The mime type of the file if the browser provided this information. An example would be "image/gif".

Note that the "$userfile" part of the above variables is whatever the name of the <input> field of type="file" is in the upload form. In the above upload form example, we chose to call it "userfile".

Notatka: register_globals = On is not recommended for security and performance reason.

Files will by default be stored in the server's default temporary directory, unless another location has been given with the upload_tmp_dir directive in php.ini. The server's default directory can be changed by setting the environment variable TMPDIR in the environment in which PHP runs. Setting it using putenv() from within a PHP script will not work. This environment variable can also be used to make sure that other operations are working on uploaded files, as well.

Przykład 19-2. Validating file uploads

The following examples are for versions of PHP 4 greater than 4.0.2. See the function entries for is_uploaded_file() and move_uploaded_file().

<?php 
// In PHP 4.1.0 or later, $_FILES should be used instead of $HTTP_POST_FILES.
if (is_uploaded_file($HTTP_POST_FILES['userfile']['tmp_name'])) {
    copy($HTTP_POST_FILES['userfile']['tmp_name'], "/place/to/put/uploaded/file");
} else {
    echo "Possible file upload attack. Filename: " . $HTTP_POST_FILES['userfile']['name'];
}
/* ...or... */
move_uploaded_file($HTTP_POST_FILES['userfile']['tmp_name'], "/place/to/put/uploaded/file");
?>

The PHP script which receives the uploaded file should implement whatever logic is necessary for determining what should be done with the uploaded file. You can for example use the $HTTP_POST_FILES['userfile']['size'] variable to throw away any files that are either too small or too big. You could use the $HTTP_POST_FILES['userfile']['type'] variable to throw away any files that didn't match a certain type criteria. Whatever the logic, you should either delete the file from the temporary directory or move it elsewhere.

The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed.


Common Pitfalls

The MAX_FILE_SIZE item cannot specify a file size greater than the file size that has been set in the upload_max_filesize ini-setting. The default is 2 Megabytes.

If memory limit is enabled, larger memory_limit may be needed. Make sure to set memory_limit large enough.

If max_execution_time is set too small, script execution may be exceeded the value. Make sure to set max_execution_time large enough.

If post_max_size is set too small, large file cannot be uploaded. Make sure to set post_max_size large enough.

Not validating which file you operate on may mean that users can access sensitive information in other directories.

Please note that the CERN httpd seems to strip off everything starting at the first whitespace in the content-type mime header it gets from the client. As long as this is the case, CERN httpd will not support the file upload feature.


Uploading multiple files

Multiple files can be uploaded using different name for input.

It is also possible to upload multiple files simultaneously and have the information organized automatically in arrays for you. To do so, you need to use the same array submission syntax in the HTML form as you do with multiple selects and checkboxes:

Notatka: Support for multiple file uploads was added in version 3.0.10.

Przykład 19-3. Uploading multiple files

<form action="file-upload.php" method="post" enctype="multipart/form-data">
  Send these files:<br>
  <input name="userfile[]" type="file"><br>
  <input name="userfile[]" type="file"><br>
  <input type="submit" value="Send files">
</form>

When the above form is submitted, the arrays $HTTP_POST_FILES['userfile'], $HTTP_POST_FILES['userfile']['name'], and $HTTP_POST_FILES['userfile']['size'] will be initialized. (As well as in $_FILES for PHP 4.1.0 or later. $HTTP_POST_VARS in PHP 3. When register_globals is on, globals for uploaded files are also initialized). Each of these will be a numerically indexed array of the appropriate values for the submitted files.

For instance, assume that the filenames /home/test/review.html and /home/test/xwp.out are submitted. In this case, $HTTP_POST_FILES['userfile']['name'][0] would contain the value review.html, and $HTTP_POST_FILES['userfile']['name'][1] would contain the value xwp.out. Similarly, $HTTP_POST_FILES['userfile']['size'][0] would contain review.html's filesize, and so forth.

$HTTP_POST_FILES['userfile']['name'][0], $HTTP_POST_FILES['userfile']['tmp_name'][0], $HTTP_POST_FILES['userfile']['size'][0], and $HTTP_POST_FILES['userfile']['type'][0] are also set.


PUT method support

PHP provides support for the HTTP PUT method used by clients such as Netscape Composer and W3C Amaya. PUT requests are much simpler than a file upload and they look something like this:

PUT /path/filename.html HTTP/1.1

This would normally mean that the remote client would like to save the content that follows as: /path/filename.html in your web tree. It is obviously not a good idea for Apache or PHP to automatically let everybody overwrite any files in your web tree. So, to handle such a request you have to first tell your web server that you want a certain PHP script to handle the request. In Apache you do this with the Script directive. It can be placed almost anywhere in your Apache configuration file. A common place is inside a <Directory> block or perhaps inside a <Virtualhost> block. A line like this would do the trick:

Script PUT /put.php

This tells Apache to send all PUT requests for URIs that match the context in which you put this line to the put.php script. This assumes, of course, that you have PHP enabled for the .php extension and PHP is active.

Inside your put.php file you would then do something like this:

<?php copy($PHP_UPLOADED_FILE_NAME,$DOCUMENT_ROOT.$REQUEST_URI); ?>

This would copy the file to the location requested by the remote client. You would probably want to perform some checks and/or authenticate the user before performing this file copy. The only trick here is that when PHP sees a PUT-method request it stores the uploaded file in a temporary file just like those handled but the POST-method. When the request ends, this temporary file is deleted. So, your PUT handling PHP script has to copy that file somewhere. The filename of this temporary file is in the $PHP_PUT_FILENAME variable, and you can see the suggested destination filename in the $REQUEST_URI (may vary on non-Apache web servers). This destination filename is the one that the remote client specified. You do not have to listen to this client. You could, for example, copy all uploaded files to a special uploads directory.


Rozdział 20. Korzystanie ze zdalnych plików

Jeżeli PHP zostanie skonfigurowany z włączoną obsługą "URL fopen wrapper", będzie można używać adresów HTTP i FTP w większości funkcji, które jako parametr przyjmują nazwę pliku, włączając w to instrukcje require() i include(). Obsługa "URL fopen wrapper" jest włączona domyślnie, chyba, że dodasz opcję --disable-url-fopen-wrapper do ./configure (w wersjach do 4.0.3) lub ustawisz allow_url_fopen na off w pliku php.ini (w nowszych wersjach).

Notatka: Nie możesz używać zdalnych plików w include() i require() w systemie Windows.

Możesz wykorzystać tę własność aby otworzyć plik na zdalnym serwrze, przetworzyć jego zawartość i użyć wyników w zapytaniu do bazy danych, lub po prostu wyświetlić plik dostosowując jego wygląd do swojej strony.

Przykład 20-1. Pobieranie tytułu zdalnej strony

<?php
$file = fopen ("http://www.php.net/", "r");
if (!$file) {
    echo "<p>Nie można otworzyć zdalnego pliku.\n";
    exit;
}
while (!feof ($file)) {
    $line = fgets ($file, 1024);
    /* Zadziała tylko wtedy, gdy tytuł i jego znaczniki są w tej samej linii */
    if (eregi ("<title>(.*)</title>", $line, $out)) {
        $title = $out[1];
        break;
    }
}
fclose($file);
?>

Możesz również zapisywać pliki na serwerach FTP, jeśli połączysz się jako użytkownik z odpowiednimi prawami dostepu i jeśli plik wcześniej nie istniał. Aby połączyć się jako użytkownik inny niż 'anonymous', musisz przesłać nazwę użytkonika (i najprawdopodobniej hasło) w URLu, np. 'ftp://uzytkownik:haslo@ftp.example.com/sciezka/do/pliku'. Możesz użyć tej samej składni przy dostępie do plików przez HTTP, jeśli wymagana jest autoryzacja.

Przykład 20-2. Zapisywanie danych na zdalnym serwerze.

<?php
$file = fopen ("ftp://ftp.php.net/incoming/outputfile", "w");
if (!$file) {
    echo "<p>Nie można otworzyć zdalnego pliku do zapisu.\n";
    exit;
}
/* Tutaj zapisujemy dane. */
fputs ($file, "$HTTP_USER_AGENT\n");
fclose ($file);
?>

Notatka: Być może powyższy przykład nasunął ci pomysł, by użyć tej metody do zdalnego zapisywania logów, ale, jak wspomniano wyżej, możesz tworzyć jedynie nowe pliki. Aby zrealizować zdalne logowanie powinieneś przyjrzeć się funkcji syslog().


Rozdział 21. Obsługa połączeń

Notatka: Ten rozdział dotyczy wersji 3.0.7 i późniejszych.

PHP wewnętrznie zarządza stanem połączenia. Mogą wystąpić trzy stany:

  • 0 - NORMAL

  • 1 - ABORTED (przerwany)

  • 2 - TIMEOUT (przekroczony czas)

Kiedy skrypt PHP się wykonuje, aktywny jest stan NORMAL. Jeśli klient się rozłączy, stan przechodzi w ABORTED. Zwykle ma to miejsce gdy użytkownik naciśnie przycisk STOP w przeglądarce. Jeśli przekroczony zostanie narzucony limit czasu (patrz set_time_limit()), stan zmienia się na TIMEOUT.

Możesz zdecydować czy po rozłączeniu klienta praca skryptu ma zostać przerwana. Czasem przydatne jest by skrypty działały do końca, nawet gdy braknie przeglądarki do której można wysyłać dane. Domyślnie, po rozłączeniu się klienta, działanie skryptu jest przerywane. To zachowanie można zmienić dzięki opcji ignore_user_abort w php.ini, jak również dyrektywie Apache "php_value ignore_user_abort" lub funkcji ignore_user_abort(). Jeśli nie każesz PHP ignorować rozłączeń klienta, a klient rozłączy się, skrypt zakończy działanie. Jedyny wyjątek wystąpi, jeśli zarejestrujesz funkcję zamykającą, używając register_shutdown_function(). Wtedy, gdy użytkownik wciśnie przycisk STOP i przy kolejnej próbie wysłania wyniku PHP wykryje przerwanie połączenia, zostanie wykonana funkcja zamykająca. Będzie ona również wywoływana przy normalnym zakończeniu pracy skryptu, zatem, by wykonać inne czynności gdy klient się rozłączy, można użyć funkcji connection_aborted(). Zwraca ona TRUE jeśli połączenie zostało przerwane.

Skrypt może zostać również zakończony przez wbudowany licznik czasu. Domyślnie czas ten wynosi 30 sekund. Wartość tę można zmienić używając opcji max_execution_time w php.ini, jak również dyrektywy Apache "php_value max_execution_time" lub funkcji set_time_limit(). Kiedy czas na wykonanie się skończy, skrypt zostanie przerwany podobnie jak w przypadku rozłączenia się klienta (patrz wyżej). Jeśli funkcja zamykająca była zarejestrowana, zostanie wywołana. Wewnątrz funkcji zamykającej możesz sprawdzić czy została ona wywołana wskutek przekroczenia czasu. Do tego celu użyj funkcji connection_timeout(), która zwróci TRUE jeśli to przekroczenie limitu czasu spowodowało wywołanie funkcji zamykającej.

Należy zwrócić uwagę, że stany ABORTED i TIMEOUT mogą być aktywne jednocześnie. Jest to możliwe, jeśli każesz PHP ignorować rozłączenia klienta. PHP będzie brało pod uwagę fakt, że połączenie z klientem mogło zostać zerwane, ale skrypt będzie pracował dalej. Gdy minie czas przeznaczony na wykonanie skryptu, zostanie on przerwany i uruchomiona zostanie funkcja zamykająca (jeśli była ustawiona). W tym momencie funkcje connection_timeout() i connection_aborted() będą zwracały TRUE. Możesz także sprawdzić oba stany przy pomocy funkcji connection_status(). Zwróci ona aktywne stany ustawione bitowo. Dla przykładu, jeśli oba stany są aktywne, zostanie zwrócona liczba 3.


Rozdział 22. Stałe połączenia z bazami danych

Stałe połączenia (persistent connections) to połączenia, które nie są zamykane po wykonaniu skryptu. Kiedy skrypt próbuje nawiązać stałe połączenie, PHP sprawdza czy istnieje już identyczne połączenie (otwarte wcześniej) i jeśli istnieje, używa go. Jeżeli nie, tworzone jest nowe. Połączenie 'identyczne' to połączenie z tym samym hostem, z taką samą nazwą użytkownika i hasłem.

Ludzie niezbyt dobrze znający zasady działania serwerów mogą czasem brać stałe połączenia za coś, czym te nie są. Stałe połączenia nie stwarzają możliwości otwarcia połączenia dla konkretnego użytkonika, nie pozwalają na skuteczne stworzenie systemu transakcji, i nie robią wielu innych rzeczy. Powiedzmy to jasno, stałe połączenia nie oferują nic ponad to, co robią 'zwykłe' połączenia.

Dlaczego?

Jest to związane z zasadą działania serwerów. Są trzy sposoby na które serwer może wykorzystac PHP do generowania stron.

Pierwsza metoda to wykorzystanie PHP jako "wrappera" CGI. Przy wywołaniu skryptu każdorazowo uruchamiany i niszczony jest egzamplarz PHP. Jako, że jest on niszczony po każdym wywołaniu, wszystkie zasoby przez niego posiadane (na przykład połączenia z bazą danych) są tracone. W tym przypadku używanie stałych połączeń nie przynosi korzyści, one po prostu nie są stałe.

Druga, najpopularniejsza metoda, to uruchomienie PHP jako modułu w wieloprocesowym serwerze, co obecnie dotyczy jedynie serwera Apache. Serwer wieloprocesowy zwykle uruchamia jeden proces (rodzica), który koordynuje inne procesy (potomne) zajmujące się dostarczaniem stron. Kiedy nadchodzi żądanie od klienta, jest ono przekazywane jednemu z procesów potomnych, który w danym momencie nie obsługuje innego klienta. Oznacza to, że gdy ten sam klient wyśle do serwera kolejne żądanie, może zostać obsłużony przez inny proces niż za pierwszym razem. Stałe połączenie w tym przypadku oznacza, że każdy proces potomny ustanawia połączenie z serwerem SQL przy pierwszym wywołaniu strony, która takiego połączenia używa. Jeśli inna strona potrzebuje połączenia z serwerem SQL, może wykorzystać połączenie, które dany proces ustanowił wcześniej.

Ustatnia metoda to wykorzystanie PHP jako wtyczki (plug-in) do serwera wielowątkowego. Obecnie PHP4 zawiera obsługę mechanizmów ISAPI, WSAPI i NSAPI (w Windows), które umożliwiają uruchomienie PHP jako wtyczki do wielowątkowych serwerów takich jak Netscape FastTrack (iPlanet), Microsoft Internet Information Server (IIS) i O'Reilly WebSite Pro. Zachowanie PHP jest zasadniczo takie samo jak w przypadku opisanego wcześniej modelu wieloprocesowego. Mechanizmy SAPI nie są obsługiwane przez PHP 3.

Skoro stałe połączenia nie dostarczają większej funkcjonalności, do czego mogą być przydatne?

Odpowiedź jest niezwykle prosta -- wydajność. Stałe połączenia sprawdzają się w przypadku, gdy koszt nawiązania połączenia z SQL serwerem jest wysoki. To czy koszt jest duży czy nie zależy od wielu czynników. Na przykład od typu bazy danych, od tego czy znajduje się ona na tym samym serwerze, od obciążenia maszyny, która obsługuje serwer SQL, itd. Jeśli zatem koszt połączenia jest wysoki, stałe połączenia znacznie pomagają. Sprawiają, że proces potomny łączy się z serwerem SQL tylko raz podczas swojego życia, zamiast otwierać połączenie za każdym razem gdy zażąda tego skrypt. Oznacza to, że każdy proces potomny, który nawiązał stałe połączenie, będzie posiadał własne połączenie z serwerem bazy danych. Dla przykładu, jeżeli 20 procesów potomnych uruchomi skrypt, który ustanowi stałe połączenie z serwerem SQL, będziesz mieć 20 różnych połączeń z serwerem, jedno na każdy proces.

Trzeba jednak zauważyć, że może to mieć swoje ujemne strony w przypadku gdy, limit połączeń do bazy danych zostanie przekroczony przez stałe połączenia z procesów potomnych. Jeśli twoja baza danych posiada limit szesnastu jednoczesnych połączeń, a w danej chwili obciążenie jest wysokie, siedemnasty proces nie będzie mógł się połączyć. Jeśli twoje skrypty zawierają błędy, które nie pozwalają zamknąć połączeń (na przykłąd nieskończone pętle), baza danych z limitem 32 połączeń może szybko zostać zapchana. Poszukaj w dokumentacji swojej bazy danych w jaki sposób radzi sobie ona z porzuconymi lub bezczynnymi połączeniami.

Ważne podsumowanie. Stałe połączenia zostały zaprojektowane tak, by odpowiadać zwykłym połączeniom. Oznacza to, że zawsze możesz zastąpić stałe połączenia zwykłymi i nie zmieni to zachowania skryptu. Natomiast może zmienić (i pewnie zmieni) jego wydajność!


Rozdział 23. Tryb bezpieczny

Tryb bezpieczny (safe mode) jest próbą rozwiązania problemów bezpieczeństwa na współdzielnym serwerze. Co prawda rozwiązywanie ich na poziomie PHP nie jest najlepszym rozwiązaniem, ale jeśli nie ma możliwości zrobienia tego na poziomie serwera www lub systemu operacyjnego, na wielu serwerach, zwłaszcza u usługodawców internetowych, używa się trybu bezpiecznego.

Dyrektywy konfiguracyjne odpowiadające za tryb bezpieczny:
safe_mode = Off
open_basedir =
safe_mode_exec_dir =
safe_mode_allowed_env_vars = PHP_
safe_mode_protected_env_vars = LD_LIBRARY_PATH
disable_functions =

Gdy opcja safe_mode jest włączona, PHP sprawdza czy właścicielem pliku na którym na którym funkcja chce operować i właścicielem uruchamianego skryptu jest ten sam użytkownik. Na przykład:
-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
Uruchomienie script.php
<?php
 readfile('/etc/passwd');
?>
z uruchomionym trybem bezpiecznym spowoduje wyświetlenie błędu:
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

Jeśli zamiast włączać opcję safe_mode ustawisz katalog open_basedir, wtedy wszystkie operacje plikowe bedą ograniczone do tego katalogu. Na przykład (dla httpd.conf Apache'a):
<Directory /docroot>
php_admin_value open_basedir /docroot
</Directory>
Uruchomienie tego samego skryptu script.php z ustawionym katalogiem open_basedir spowoduje wyświetlenie:
Warning: open_basedir restriction in effect. File is in wrong directory in
/docroot/script.php on line 2

Możesz także wyłączyć pojedyncze funkcje. Jeśli do pliku php.ini dodasz:
disable_functions readfile,system
po uruchomieniu skryptu otrzymasz:
Warning: readfile() has been disabled for security reasons in
/docroot/script.php on line 2


Funkcje ograniczone/wyłączone w trybie bezpiecznym

Jest to najprawdopodobniej wciąż niekompletna lista funkcji ograniczonych przez tryb bezpieczny.

Tabela 23-1. Funkcje ograniczone w trybie bezpiecznym

FunkcjaOgraniczenia
dbmopen()Sprawdza czy plik(i)/katalogi, na których chcesz operować, mają takie same UID jak skrypt, który jest aktualnie wykonywany.
dbase_open()Sprawdza czy plik(i)/katalogi, na których chcesz operować, mają takie same UID jak skrypt, który jest aktualnie wykonywany.
filepro()Sprawdza czy plik(i)/katalogi, na których chcesz operować, mają takie same UID jak skrypt, który jest aktualnie wykonywany.
filepro_rowcount()Sprawdza czy plik(i)/katalogi, na których chcesz operować, mają takie same UID jak skrypt, który jest aktualnie wykonywany.
filepro_retrieve()Sprawdza czy plik(i)/katalogi, na których chcesz operować, mają takie same UID jak skrypt, który jest aktualnie wykonywany.
ifx_*()Podlega ograniczeniom narzuconym przez sql_safe_mode, (!= tryb bezpieczny)
ingres_*()Podlega ograniczeniom narzuconym przez sql_safe_mode, (!= tryb bezpieczny)
mysql_*()Podlega ograniczeniom narzuconym przez sql_safe_mode, (!= tryb bezpieczny)
pg_loimport()Sprawdza czy plik(i)/katalogi, na których chcesz operować, mają takie same UID jak skrypt, który jest aktualnie wykonywany.
posix_mkfifo()Sprawdza, czy katalog, na którym chesz operować, ma takie same UID jak skrypt, który jest aktualnie wykonywany.
putenv()Podlega dyrektywom safe_mode_protected_env_vars i safe_mode_allowed_env_vars w php.ini. Zobacz również dokumantację do putenv()
move_uploaded_file()Sprawdza czy plik(i)/katalogi, na których chcesz operować, mają takie same UID jak skrypt, który jest aktualnie wykonywany.
chdir()Sprawdza, czy katalog, na którym chesz operować, ma takie same UID jak skrypt, który jest aktualnie wykonywany.
dl()Ta funkcja jest niedostępna w trybie bezpiecznym
lewy apostrofTa funkcja jest niedostępna w trybie bezpiecznym
shell_exec() (funkcja równoważna z lewym apostrofem)Ta funkcja jest niedostępna w trybie bezpiecznym
exec()Możesz uruchamiać programy jedynie z katalogu zdefiniowanego dyrektywą safe_mode_exec_dir. Ze względów praktycznych obecnie nie ma możliwości stosowania .. w ścieżce do programu.
system()Można uruchamiać programy jedynie z katalogu zdefiniowanego dyrektywą safe_mode_exec_dir. Ze względów praktycznych obecnie nie ma możliwości stosowania .. w ścieżce do programu.
passthru()Można uruchamiać programy jedynie z katalogu zdefiniowanego dyrektywą safe_mode_exec_dir. Ze względów praktycznych obecnie nie ma możliwości stosowania .. w ścieżce do programu.
popen()Można uruchamiać programy jedynie z katalogu zdefiniowanego dyrektywą safe_mode_exec_dir. Ze względów praktycznych obecnie nie ma możliwości stosowania .. w ścieżce do programu.
mkdir()Sprawdza, czy katalog, na którym chesz operować, ma takie same UID jak skrypt, który jest aktualnie wykonywany.
rmdir()Sprawdza czy plik(i)/katalogi, na których chcesz operować, mają takie same UID jak skrypt, który jest aktualnie wykonywany.
rename()Sprawdza czy plik(i)/katalogi, na których chcesz operować, mają takie same UID jak skrypt, który jest aktualnie wykonywany. Sprawdza, czy katalog, na którym chesz operować, ma takie same UID jak skrypt, który jest aktualnie wykonywany.
unlink()Sprawdza czy plik(i)/katalogi, na których chcesz operować, mają takie same UID jak skrypt, który jest aktualnie wykonywany. Sprawdza, czy katalog, na którym chesz operować, ma takie same UID jak skrypt, który jest aktualnie wykonywany.
copy()Sprawdza czy plik(i)/katalogi, na których chcesz operować, mają takie same UID jak skrypt, który jest aktualnie wykonywany. Sprawdza, czy katalog, na którym chesz operować, ma takie same UID jak skrypt, który jest aktualnie wykonywany. (dla źródła i przeznaczenia)
chgrp()Sprawdza czy plik(i)/katalogi, na których chcesz operować, mają takie same UID jak skrypt, który jest aktualnie wykonywany.
chown()Sprawdza czy plik(i)/katalogi, na których chcesz operować, mają takie same UID jak skrypt, który jest aktualnie wykonywany.
chmod()Sprawdza czy plik(i)/katalogi, na których chcesz operować, mają takie same UID jak skrypt, który jest aktualnie wykonywany. Dodatkowo, nie można ustawić bitów SUID, SGID i sticky bit.
touch()Sprawdza czy plik(i)/katalogi, na których chcesz operować, mają takie same UID jak skrypt, który jest aktualnie wykonywany. Sprawdza, czy katalog, na którym chesz operować, ma takie same UID jak skrypt, który jest aktualnie wykonywany.
symlink()Sprawdza czy plik(i)/katalogi, na których chcesz operować, mają takie same UID jak skrypt, który jest aktualnie wykonywany. Sprawdza, czy katalog, na którym chesz operować, ma takie same UID jak skrypt, który jest aktualnie wykonywany. (sprawdzany jest jedynie element do którego tworzony jest link)
link()Sprawdza czy plik(i)/katalogi, na których chcesz operować, mają takie same UID jak skrypt, który jest aktualnie wykonywany. Sprawdza, czy katalog, na którym chesz operować, ma takie same UID jak skrypt, który jest aktualnie wykonywany. (sprawdzany jest jedynie element do którego tworzony jest link)
getallheaders() W tybie bezpiecznym, nagłowki zaczynające się od 'authorization' (wielkość liter bez znaczenia) nie będą zwracane. Uwaga: w implementacji dla serwera AOL ta funkcjonalność jest uszkodzona
Każda funkcja korzystająca z php4/main/fopen_wrappers.c ??

IV. Opis funkcji

Spis treści
I. Apache
II. Tablice
III. Aspell [przestarzałe]
IV. BCMath Operacje arytmetyczne na liczbach o dużej precyzji
V. Bzip2 Compression Functions
VI. Calendar functions
VII. CCVS API Functions
VIII. COM support functions for Windows
IX. Class/Object Functions
X. ClibPDF functions
XI. Crack functions
XII. CURL, Client URL Library Functions
XIII. Cybercash payment functions
XIV. Crédit Mutuel CyberMUT functions
XV. Cyrus IMAP administration functions
XVI. Character type functions
XVII. Database (dbm-style) abstraction layer functions
XVIII. Date and Time functions
XIX. dBase functions
XX. DBM Functions
XXI. dbx functions
XXII. DB++ Functions
XXIII. Direct IO functions
XXIV. Directory functions
XXV. DOM XML functions
XXVI. .NET functions
XXVII. Error Handling and Logging Functions
XXVIII. FrontBase Functions
XXIX. filePro functions
XXX. System plików
XXXI. Forms Data Format functions
XXXII. FriBiDi functions
XXXIII. FTP
XXXIV. Function Handling functions
XXXV. Gettext
XXXVI. GMP functions
XXXVII. HTTP
XXXVIII. Hyperwave functions
XXXIX. ICAP Functions [deprecated]
XL. iconv
XLI. Image functions
XLII. IMAP, POP3 and NNTP functions
XLIII. Informix functions
XLIV. InterBase functions
XLV. Ingres II functions
XLVI. IRC Gateway Functions
XLVII. Java
XLVIII. LDAP functions
XLIX. Poczta elektroniczna
L. mailparse functions
LI. Matematyka
LII. Multi-Byte String Functions
LIII. MCAL functions
LIV. Mcrypt Encryption Functions
LV. Mhash Functions
LVI. Microsoft SQL Server functions
LVII. Ming functions for Flash
LVIII. Miscellaneous functions
LIX. mnoGoSearch Functions
LX. mSQL functions
LXI. MySQL
LXII. Mohawk Software session handler functions
LXIII. muscat functions
LXIV. Network Functions
LXV. Ncurses terminal screen control functions
LXVI. Lotus Notes functions
LXVII. Unified ODBC functions
LXVIII. Oracle 8 functions
LXIX. OpenSSL functions
LXX. Oracle functions
LXXI. Ovrimos SQL functions
LXXII. Output Control Functions
LXXIII. Object property and method call overloading
LXXIV. PDF functions
LXXV. Verisign Payflow Pro functions
LXXVI. PHP Options&Information
LXXVII. POSIX functions
LXXVIII. PostgreSQL functions
LXXIX. Process Control Functions
LXXX. Program Execution functions
LXXXI. Printer functions
LXXXII. Pspell Functions
LXXXIII. GNU Readline
LXXXIV. GNU Recode functions
LXXXV. Regular Expression Functions (Perl-Compatible)
LXXXVI. qtdom functions
LXXXVII. Regular Expression Functions (POSIX Extended)
LXXXVIII. Semaphore and Shared Memory Functions
LXXXIX. SESAM database functions
XC. Sesje
XCI. Shared Memory Functions
XCII. Shockwave Flash functions
XCIII. SNMP functions
XCIV. Socket functions
XCV. String functions
XCVI. Sybase functions
XCVII. URL
XCVIII. Variable Functions
XCIX. vpopmail functions
C. W32api functions
CI. WDDX Functions
CII. XML parser functions
CIII. XMLRPC functions
CIV. XSLT functions
CV. YAZ functions
CVI. YP/NIS Functions
CVII. Zip File Functions (Read Only Access)
CVIII. Zlib Compression Functions

I. Apache

Spis treści
apache_lookup_uri --  Wywołuje wewnętrzne żądanie dla określonego URI i zwraca całą informację o nim
apache_note -- Pobiera lub ustawia noty odpowiedzi Apache'a
ascii2ebcdic -- Konwertuje łańcuch znaków z ASCII do EBCDIC
ebcdic2ascii -- Kownersja łańcucha znaków z EBCDIC do ASCII
getallheaders -- Odczytuje wszystkie nagłówki HTTP z aktualnego zapytania
virtual -- Wywołuje wewnętrzne żądanie Apache'a
apache_child_terminate -- Zakańcza proces Apache'a po zakończeniu tego zapytania
apache_setenv -- Ustawia zmienną Apache'a subprocess_env

apache_lookup_uri

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

apache_lookup_uri --  Wywołuje wewnętrzne żądanie dla określonego URI i zwraca całą informację o nim

Opis

object apache_lookup_uri ( string nazwa_pliku)

Ta funkcja wywołuje wewnętrzne żądanie dla określonego URI. Funkcja zbiera wszystkie istotne informacje odnośnie podanego źródła informacji i zwraca je w postaci klasy. Właściwości zwróconej klasy to:

status
the_request
status_line
method
content_type
handler
uri
filename
path_info
args
boundary
no_cache
no_local_copy
allowed
send_bodyct
bytes_sent
byterange
clength
unparsed_uri
mtime
request_time

Notatka: apache_lookup_uri() działa jedynie wówczas, kiedy PHP jest zainstalowane jako moduł serwera Apache.

apache_note

(PHP 3>= 3.0.2, PHP 4 >= 4.0.0)

apache_note -- Pobiera lub ustawia noty odpowiedzi Apache'a

Opis

string apache_note ( string nazwa_noty [, string wartość_noty])

apache_note() jest funkcją dotyczącą jedynie serwera Apache, która pobiera lub ustawia wartości not w odpowiedzi http. Jeśli wywołana z jednym argumentem, funkcja zwraca aktualną wartość noty nazwa_noty. Jeśli wywołana z dwoma argumentami, ustawi wartość noty nazwa_noty na wartość_noty i zwróci poprzednią wartość noty nazwa_noty.

ascii2ebcdic

(PHP 3>= 3.0.17)

ascii2ebcdic -- Konwertuje łańcuch znaków z ASCII do EBCDIC

Opis

int ascii2ebcdic ( string łańcuch_ascii)

ascii2ebcdic() jest funkcją właściwą jedynie Apache'owi, dostępną wyłącznie w systemach EBCDIC (OS/390, BS2000). Funkcja konwertuje łańcuch znaków ASCII łańcuch_ascii do odpowiadającej mu postaci EBCDIC (bezpiecznie dla binariów) i zwraca wynik.

Zobacz też funkcję odwrotną ebcdic2ascii()

ebcdic2ascii

(PHP 3>= 3.0.17)

ebcdic2ascii -- Kownersja łańcucha znaków z EBCDIC do ASCII

Opis

int ebcdic2ascii ( string łańcuch_ebcdic)

ebcdic2ascii() jest funkcją właściwą jedynie Apache'owi, dostępną wyłącznie w systemach EBCDIC (OS/390, BS2000). Funkcja konwertuje łańcuch znaków EBCDIC łańcuch_ebcdic do odpowiadającej mu postaci ASCII (bezpiecznie dla binariów) i zwraca wynik.

Zobacz też funkcję odwrotną ascii2ebcdic()

getallheaders

(PHP 3, PHP 4 >= 4.0.0)

getallheaders -- Odczytuje wszystkie nagłówki HTTP z aktualnego zapytania

Opis

array getallheaders ( void)

Funkcja zwraca tablicę asocjacyjną zawierającą wszystkie nagłówki HTTP z aktualnego zapytania.

Notatka: Można też odczytywać wartość typowych zmiennych CGI ze środowiska, co działa niezależnie od tego, czy PHP jest modułem Apache'a, czy nie. Użyj funkcji phpinfo() aby zapoznać się z listą wszystkich dostępnych zmiennych środowiskowych.

Przykład 1. Przykład zastosowania getallheaders()

$naglowki = getallheaders();
while (list ($naglowek, $wartosc) = each ($naglowki)) {
    echo "$naglowek: $wartosc&lt;br&gt;\n";
}

Powyższy przykład wyświetli wszystkie nagłówki z aktualnego zapytania.

Notatka: Funkcja getallheaders() aktualnie działa tylko wówczas, kiedy PHP działa jako moduł serwera Apache.

virtual

(PHP 3, PHP 4 >= 4.0.0)

virtual -- Wywołuje wewnętrzne żądanie Apache'a

Opis

int virtual ( string nazwa_pliku)

virtual() jest funkcją właściwą jedynie Apache'owi, która jest odpowiednikiem <!--#include virtual...--> w mod_include. Funkcja wywołuje wewnętrzne żądanie Apache'a. Przydaje się do dołączania (inkludowania) skryptów CGI lub plików .shtml, lub czegokolwiek innego, co jest przetwarzane przez serwer Apache. Zwróć uwagę przy skrypcie CGI, że musi on generować poprawne nagłówki CGI, przynajmniej nagłówek Content-type. Dla plików PHP użyj funkcji include() lub require(); nie można użyć virtual() do wczytywania plików, które są same plikami PHP.

apache_child_terminate

(PHP 4 >= 4.0.5)

apache_child_terminate -- Zakańcza proces Apache'a po zakończeniu tego zapytania

Opis

string apache_child_terminate ( void)

apache_child_terminate() zakończy proces Apache'a, wykonujący aktualne zapytanie PHP, kiedy tylko zapytanie zostanie zakończone. Można tego używać do zakończenia procesu po uruchomieniu skryptu o dużych zapotrzebowaniach na pamięć, gdyż zwykle pamięć zostaje zwolniona wewnętrznie, ale nie zwrócona systemowi operacyjnemu.

Zobacz też exit().

apache_setenv

(PHP 4 CVS only)

apache_setenv -- Ustawia zmienną Apache'a subprocess_env

Opis

int apache_setenv ( string nazwa_zmiennej, string wartość [, bool nadrzędność])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

II. Tablice

Funkcje te pozwalają na operowanie i manipulowanie tablicami na wiele różnych sposobów. Tablice są kluczowym elementem przechowywania, zarządzania i operowania na zbiorach zmiennych.

Obsługiwane są proste i wielowymiarowane tablica, które mogą być stworzone przez użytkownika lub przez funkcję. Istnieją specjalne funkcje obsługi baz danych odpowiedzialne za wypełnianie tablic danymi z zapytań do baz danych, a także kilka innych funkcji zwracających tablice.

Zobacz rozdział podręcznika Tablice aby uzyskać dokładne wyjaśnienie jak tablice zostały zaimplementowane i jak się ich używa w PHP.

Patrz także is_array(), explode(), implode(), split() i join().

Spis treści
array --  Stwórz tablicę
array_change_key_case --  Zwraca tablicę ze wszystkimi kluczami tekstowymi zamienionymi na wyłącznie małe lub wyłącznie duże litery
array_chunk -- Podziel tablicę na kawałki
array_count_values -- Zlicza wszystkie wartości w tablicy
array_diff -- Zwraca różnice pomiędzy tablicami
array_filter --  Filtruje elementy przy użyciu funkcji zwrotnej
array_flip -- Odwraca wszystkie wartości w tablicy
array_fill -- Wypełnij tablicę podanymi wartościami
array_intersect -- Zwraca przecięcie tablic
array_key_exists --  Sprawdza czy podany klucz lub indeks istnieje w tablicy
array_keys -- Zwraca wszystkie klucze z tablicy
array_map --  Wykonuje funkcję zwrotną na elementach podanej tablicy
array_merge -- Łączy dwie lub więcej tablic
array_merge_recursive -- Łączy dwie lub więcej tablic rekurencyjnie
array_multisort -- Sortuje wiele tablic lub wielowymiarowe tablice
array_pad --  Dopełnij tablicę do podanej długości podanymi wartościami
array_pop -- Zdejmij element z końca tablicy
array_push --  Wstaw jeden lub więcej elementów na koniec tablicy
array_rand --  Wybierz jeden lub więcej losowych elementów z tablicy
array_reverse --  Zwraca tablicę z elementami ustawionymi w porządku odwrotnym
array_reduce --  Iteracyjnie zredukuj tablicę do pojedyńczej wartości używając funkcji zwrotnej
array_shift --  Usuń element z początku tablicy
array_slice -- Wytnij kawałek tablicy
array_splice --  Usuń część tablicy i zamień ją na coś innego
array_sum --  Oblicza sumę wartości w tablicy
array_unique -- Usuwa duplikaty wartości z tablicy
array_unshift --  Wstaw jeden lub więcej elementów na początek tablicy
array_values -- Zwraca wszystkie wartości z tablicy
array_walk --  Zastosuj funkcję użytkownika do każdego elementu tablicy
arsort --  Sortuj tablicę w porządku odwrotnym i zachowaj skojarzenia kluczy
asort -- Posortuj tablicę zachowując skojarzenia kluczy
compact --  Stwórz tablicę zawierającą zmienne i ich wartości
count -- Zlicza ilość elementów w tablicy
current -- Zwraca bieżący element tablicy
each --  Zwraca bieżącą parę klucza i wartości z tablicy i przesuwa kursor tablicy
end --  Ustaw wewnętrzny wskaźnik tablicy na ostatnim elemencie
extract --  Importuj zmienne do tabeli symboli z tablicy
in_array -- Zwraca TRUE jeśli wartość istnieje w tablicy
array_search --  Przeszukuje tablicę pod kątem podane wartości i w przypadku sukcesu zwraca odpowiedni klucz
key -- Pobiera klucz z tablicy asocjacyjnej
krsort -- Sortuj tablicę według kluczy w porządku odwrotnym
ksort -- Sortuj tablicę według klucza
list --  Przypisz zmienne tak jakby były tablicą
natsort --  Sortuj tablicę używając algortmu "porządek naturalny"
natcasesort --  Sortuj tablicę używając algorytmu "porządek naturalny" ignorującego wielkość znaków
next --  Przesuń do przodu wewnętrzny wskaźnik tablicy
pos -- Pobierz bieżący element z tablicy
prev -- Cofnij wewnętrzny wskaźnik tablicy
range --  Stwórz tablicę zawierającą przedział elementów
reset --  Ustaw wewnętrzny wskaźnik tablicy na jej pierwszy element
rsort -- Sortuj tablicę w porządku odwrotnym
shuffle -- Przetasuj tablicę
sizeof -- Policz ilość elementów w zmiennej
sort -- Sortuj tablicę
uasort --  Sortuj tablicę korzystając ze zdefiniowanej przez użytkownika funkcji porównującej i zachowując skojarzenia kluczy
uksort --  Sortuj tablicę według kluczy korzystając ze zdefiniowanej przez użytkownika funcji porównującej
usort --  Sortuj tablicę według wartości korzystając ze zdefiniowanej przez użytkownika funkcji porównującej

array

(unknown)

array --  Stwórz tablicę

Opis

array array ( [mixed ...])

Zwraca tablicę stworzoną z podanych parametrów. Parametry mogą być indeksowane przy pomocy operatora => operator.

Notatka: array() jest składnią języka używaną do tekstowej reprezentacji tablic, a nie zwykłą funkcją.

Składnia "index => wartości", oddzielona przecinkami, definiuje pary indeksów i wartości. Indeks może być stringiem lub liczbą. Jeśli indeks zostanie pominięty, automatycznie wygenerowany zostanie indeks będący liczbą całkowitą, poczynając od 0. Jeśli indeks jest liczbą całkowitą, następny wygenerowany indeks będzie miał wartość "największy indeks + 1". Zauważ, że jeśli pojawią się dwie wartości o tym samym indeksie, ostatnia nadpisze wcześniejsze.

Poniższy przykład demonstruje jak stworzyć wielowymiarową tablicę, jak określić klucze w tablicy asocjacyjnej i jak pominąć-i-kontynuować liczbowe indeksy w normalnych tablicach.

Przykład 1. Przykład użycia array()

$owoce = array (
   "owoce"  => array ("a"=&gt;"pomarańcza", "b"=&gt;"banan", "c"=&gt;"jabłko"),
   "liczby" => array (1, 2, 3, 4, 5, 6),
   "dziury" => array ("pierwszy", 5 =&gt; "drugi", "trzeci")
);

Przykład 2. Automatyczne indeksowanie w funkcji array()

$array = array( 1, 1, 1, 1,  1, 8=>1,  4=>1, 19, 3=>13);
print_r($array);

wyświetli:
Array 
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 13
    [4] => 1
    [8] => 1
    [9] => 19
)

Zauważ, że indeks '3' jest zdefiniowany dwa razy i przchowuje on końcową wartość 13. Indeks 4 jest zdefiniowany po indeksie 8, a następnym wygenerowanym indeksem (dla wartości 19) jest 9, ponieważ największym poprzednim indeksem było 8.

Ten przykład tworzy tablicę o początku 1.

Przykład 3. Indeksowanie od 1 w array()

$pierwszy_kwartal  = array(1 => 'Styczeń', 'Luty', 'Marzec');
print_r($pierwszy_kwartal);

wyświetli:
Array 
(
    [1] => 'Styczeń'
    [2] => 'Luty'
    [3] => 'Marzec'
)

Patrz także: list().

array_change_key_case

(PHP 4 CVS only)

array_change_key_case --  Zwraca tablicę ze wszystkimi kluczami tekstowymi zamienionymi na wyłącznie małe lub wyłącznie duże litery

Opis

array array_change_key_case ( array wejście [, int wielkość])

array_change_key_case() zmienia klucze w tablicy wejście aby były pisane tylko dużymi lub tylko małymi literami. Zmiana zależy od ostatniego opcjonalnego parametru case. Można do niego przekazać jedną z dwóch stałych: CASE_UPPER lub CASE_LOWER. Domyślną wartością jest CASE_LOWER. Indeksy liczbowe będą pozostawione takie jakie są.

Przykład 1. Przykład użycia array_change_key_case()

$wejscie = array("PierWszy" => 1, "DruGi" => 4);
print_r(array_change_key_case($wejscie, CASE_UPPER);

Powyższy przykład wyświetli:
Array
(
    [PIERWSZY] => 1
    [DRUGI] => 2
)

array_chunk

(PHP 4 CVS only)

array_chunk -- Podziel tablicę na kawałki

Description

array array_chunk ( array wejście, int rozmiar [, bool zachowaj_klucze])

array_chunk() dzieli tablicę na kilka mniejszych, każda po rozmiar elementów. Istnieje możliwość, że ostatnia tablica będzie mniejsza. Otrzymujesz tablice jako elementy wielowymiarowej tablicy indeksowanej przez liczby zaczynając od zera.

Ustawiając opcjonalny parametr zachowaj_klucze na TRUE możesz zmusić PHP do zachowywania orginalnych kluczy z tablicy wejściowej. Jełi podasz w tym miejscu FALSE, to w każdej nowej tablicy użyte będą nowe indeksy liczbowe zaczynające się od zera. Domyślną wartością jest FALSE.

Przykład 1. Przykład użycia array_chunk()

$tablica_wejsciowa = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($tablica_wejsciowa, 2));
print_r(array_chunk($tablica_wejsciowa, 2, TRUE));

Powyższy program wyświetli:
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [2] => c
            [3] => d
        )

    [2] => Array
        (
            [4] => e
        )

)

array_count_values

(PHP 4 >= 4.0.0)

array_count_values -- Zlicza wszystkie wartości w tablicy

Opis

array array_count_values ( array wejście)

array_count_values() zwraca tablicę zawierającą wartości tablicy wejście jako klucze i częstość ich występowania w tablicy wejście jako wartości.

Przykład 1. Przykład użycia array_count_values()

$tablica = array (1, "witaj", 1, "świecie", "witaj");
array_count_values ($tablica); // zwraca tablicę (1=>2, "witaj"=>2, "świecie"=>1)

array_diff

(PHP 4 )

array_diff -- Zwraca różnice pomiędzy tablicami

Opis

array array_diff ( array tabela1, array tabela2 [, array ...])

array_diff() zwraca tablicę zawierającą wszystkie wartości tablicy tabela1 które nie są obecne w innych tablicach-argumentach. Zauważ, że zachowywane są klucze.

Przykład 1. Przykład użycia array_diff()

$tablica1 = array ("a" =&gt; "zielony", "czerwony", "niebieski", "czerwony");
$tablica2 = array ("b" =&gt; "zielony", "żółty", "czerwony");
$wynik = array_diff ($tablica1, $tablica2);

W powyższym przykładzie zmienna $wynik zawiera array ("niebieski");. Wielokrotne wystąpienia w $tablica1 są traktowane w taki sam sposób.

Notatka: Dwa elementy tablicy uważane są za identyczne wtedy i tylko wtedy jeśli (string) $element1 === (string) $element2. Słownie: kiedy reprezentacje elementów w postaci stringów są identyczne.

Ostrze¿enie

Ta funkcja była zepsuta w PHP 4.0.4!

Patrz także array_intersect().

array_filter

(PHP 4 >= 4.0.6)

array_filter --  Filtruje elementy przy użyciu funkcji zwrotnej

Opis

array array_filter ( array wejście [, mixed funkcja_zwrotna])

array_filter() zwraca tablicę zawierającą wszystkie elementy tablicy wejście przefitrowane przez podaną funkcję zwrotną. Jeśli wejście jest tablicą asocjacyjną, przypisania klucz pozostają zachowane.

Przykład 1. Przykład użycia array_filter()

function nieparzysta($var) {
    return ($var % 2 == 1);
}

function parzysta($var) {
    return ($var % 2 == 0); 
}

$tablica1 = array ("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$tablica2 = array (6, 7, 8, 9, 10, 11, 12);

$nieparzyste = array_filter($tablica1, "nieparzyste");
$parzyste    = array_filter($tablica2, "parzyste");

W tym przykładzie tablica $nieparzyste zawiera array ("a"=>1, "c"=>3, "e"=>5);, a tablica $parzyste zawiera array (6, 8, 10, 12);,

Patrz także array_map(), array_reduce().

array_flip

(PHP 4 >= 4.0.0)

array_flip -- Odwraca wszystkie wartości w tablicy

Opis

array array_flip ( array trans)

array_flip() zwraca tablicę w odwróconym porządku, tzn. klucze z tabeli trans stają się wartościami a wartości trans stają się kluczami.

Zauważ, że wszystkie wartości tablicy trans muszą mieć poprawne klucze, tzn. muszą być albo typu integer lub string. Jeśli wartość nie ma prawidłego typu, wyświetlone zostanie ostrzeżenie, a para klucz/wartość nie będzie odwrócona.

Jeśli wartość występuje wielokrotnie, ostatni klucz będzie użyty jako jej wartość po odwróceniu, a wszystkie inne zostaną stracone.

array_flip() zwraca FALSE jeśli nie powiedzie się odwracanie tablicy.

Przykład 1. Przykład użycia array_flip()

$trans = array_flip ($trans);
$original = strtr ($str, $trans);

Przykład 2. Przykład użycia array_flip() : kolizja

$trans = array ("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip ($trans);
// teraz $trans zawiera : array(1 => "b", 2 => "c");

array_fill

(PHP 4 CVS only)

array_fill -- Wypełnij tablicę podanymi wartościami

Opis

array array_fill ( int indeks_początkowy, int num, mixed wartość)

array_fill() wypełni tablicę wartością value, począwszy od indeksu indeks_początkowy przez num kolejnych elementów tablicy.

Przykład 1. Przykład użycia array_fill()

$a = array_fill(5, 6, 'banan');

/*
$a zawiera teraz takie elementy:

$a[5]  = "banan";
$a[6]  = "banan";
$a[7]  = "banan";
$a[8]  = "banan";
$a[9]  = "banan";
$a[10] = "banan";
*/

array_intersect

(PHP 4 )

array_intersect -- Zwraca przecięcie tablic

Opis

array array_intersect ( array tablica1, array tablica2 [, array ...])

array_intersect() zwraca tablicę zawierającą wszystkie wartości tablicy tablica1 które istnieją we wszystkich argumentach. Zauważ, ża zachowywane są przypisania kluczy.

Przykład 1. Przykład użycia array_intersect()

$tablica1 = array ("a" => "zielony", "czerwony", "niebieski");
$tablica2 = array ("b" => "zielony", "żółty", "czerwony");
$wynik = array_intersect ($tablica1, $tablica2);

W powyższym przykładzie tablica $wynik zawiera array ("a" => "zielony", "czerwony");

Notatka: Dwa elementy tablicy uważane są za identyczne wtedy i tylko wtedy jeśli (string) $element1 === (string) $element2. Słownie: kiedy reprezentacje elementów w postaci stringów są identyczne.

Ostrze¿enie

Ta funkcja była zepsuta w PHP 4.0.4! This was broken in PHP 4.0.4!

Patrz także array_diff().

array_key_exists

(PHP 4 >= 4.1.0)

array_key_exists --  Sprawdza czy podany klucz lub indeks istnieje w tablicy

Description

bool array_key_exists ( mixed igła, array stóg_siana)

array_key_exists() zwraca TRUE jeśli igła jest ustawiona w tablicy stóg_siana. igła może być dowolną wartością możliwą dla indksu tablicy.

Przykład 1. array_key_exists() example

$stog_siana = array("pierwszy" => 1, "drugi" => 4);
if (array_key_exists("pierwszy", $stog_siana)) {
    echo "'Pierwszy' element istnieje w tablicy";
}

Notatka: W PHP 4.0.6 ta funkcja nazywa się key_exists().

Patrz także isset().

array_keys

(PHP 4 >= 4.0.0)

array_keys -- Zwraca wszystkie klucze z tablicy

Opis

array array_keys ( array wejście [, mixed szukana_wartość])

array_keys() zwraca klucze, liczbowe i tekstowe, z tablicy wejście.

Jeśli podany został opcjonalny parameter szukana_wartość , zwracane są tylko klucze dla danej do których przypisana jest podana wartość. W przeciwnym przypadku zwracane są wszystkie klucze z tablicy wejście.

Przykład 1. Przykład użycia array_keys()

$tablica = array (0 => 100, "kolor" => "czerwony");
array_keys ($tablica);       // zwraca array (0, "kolor")

$tablica = array ("niebieski", "czerwony", "zielony", "niebieski", "niebieski");
array_keys ($tablica, "niebieski");  //  zwraca array (0, 3, 4) 

$tablica = array ("kolor" => array("niebieski", "czerwony", "zielony"), "rozmiar" => array("mały", "średni", "duży"));
array_keys ($tablica);  //  zwraca array ("kolor", "rozmiar")

Notatka: Ta funkcja została dodana w PHP 4. Poniżej znajduje się implementacja tej funkcji dla tych, którzy jeszcz używają PHP 3.

Przykład 2. Implementacja array_keys() dla użytkowników

function array_keys ($arr, $term="") {
    $t = array();
    while (list($k,$v) = each($arr)) {
        if ($term &amp;&amp; $v != $term) {
            continue;
            $t[] = $k;
        }
        return $t;
    }
}

Patrz także array_values().

array_map

(PHP 4 >= 4.0.6)

array_map --  Wykonuje funkcję zwrotną na elementach podanej tablicy

Opis

array array_map ( mixed funkcja_zwrotna, array tbl1 [, array tbl2...])

array_map() zwraca tablicę zawierającą wszystkie elementy tablicy tbl1 po użyciu na każdej z nich funkcji zwrotnej. Liczba parametrów funkcji zwrotnej powinna być równa liczbie tablic przekazanych do funkcji array_map().

Przykład 1. Przykład użycia array_map()

function szescian($n) {
    return $n*$n*$n;
}

$a = array(1, 2, 3, 4, 5);
$b = array_map("szescian", $a);

W powyższej funkcji tablica $b zawiera array (1, 8, 27, 64, 125);

Przykład 2. array_map() - używanie większej ilości tablic

function pokaz_po_Hiszpansku($n, $m) {
    return "Po Hiszpańsku liczba $n to $m";
}

function mapuj_na_Hiszpanski($n, $m) {
    return array ($n => $m);
}

$a = array(1, 2, 3, 4, 5);
$b = array("uno", "dos", "tres", "cuatro", "cinco");

$c = array_map("pokaz_po_Hiszpansku", $a, $b);

print_r($c);

// will output:
// Array 
// (
//     [0] => Po Hiszpańsku liczba 1 to uno
//     [1] => Po Hiszpańsku liczba 2 to dos
//     [2] => Po Hiszpańsku liczba 3 to tres
//     [3] => Po Hiszpańsku liczba 4 to cuatro
//     [4] => Po Hiszpańsku liczba 5 to cinco
// )

$d = array_map("mapuj_po_Hiszpansku", $a , $b);

print_r($d);

// wyświetli:
// Array 
// (
//     [0] => Array
//         (
//             [1] => uno
//         )
// 
//     [1] => Array
//         (
//             [2] => dos
//         )
// 
//     [2] => Array
//         (
//             [3] => tres
//         )
// 
//     [3] => Array
//         (
//             [4] => cuatro
//         )
// 
//     [4] => Array
//         (
//             [5] => cinco
//         )
// 
// )

Zazwyczaj używając dwóch lub więcej tablic, powinny one być równej długości, ponieważ funkcja zwrotna jest wykonywana na odpowiadających sobie elementach tablic. Jeśli tablice są różnych długości, krótsze będą rozszerzane używając pustych elementów.

Interesującym sposobem użycia tej funkcji jest kontruowanie tablicy tablic, co może być łatwo przeprowadzone przez podanie NULL jako nazwy funkcji zwrotnej.

Przykład 3. Tworzenie tablicy tablic

$a = array(1, 2, 3, 4, 5);
$b = array("one", "two", "three", "four", "five");
$c = array("uno", "dos", "tres", "cuatro", "cinco");
$d = array("jeden", "dwa", "trzy", "cztery", "pięć");

$e = array_map(null, $a, $b, $c, $d);
print_r($e);

// wyświetli:
// Array
// (
//     [0] => Array
//         (
//             [0] => 1
//             [1] => one
//             [2] => uno
//             [3] => jeden
//         )
// 
//     [1] => Array
//         (
//             [0] => 2
//             [1] => two
//             [2] => dos
//             [3] => dwa
//         )
// 
//     [2] => Array
//         (
//             [0] => 3
//             [1] => three
//             [2] => tres
//             [3] => trzy
//         )
// 
//     [3] => Array
//         (
//             [0] => 4
//             [1] => four
//             [2] => cuatro
//             [3] => cztery
//         )
// 
//     [4] => Array
//         (
//             [0] => 5
//             [1] => five
//             [2] => cinco
//             [3] => pięć
//         )
// 
// )

Patrz także array_filter(), array_reduce().

array_merge

(PHP 4 >= 4.0.0)

array_merge -- Łączy dwie lub więcej tablic

Opis

array array_merge ( array tablica1, array tablica2 [, array ...])

array_merge() łączy elementy dwóch lub więcej tablic razem, tak że wartości jednej tablicy są wstawiane na koniec poprzedniej tablicy. Funkcja ta zwraca tabelę wynikową.

Jeśli tablice wejściowe mają takie same klucze tekstowe, najnowsza wartość nadpisze starszą. Jednakże jeśłi tablice będą miały takie same klucze liczbowe, późniejsza wartość nie nadpisze starszej, lecz zostanie dopisana na koniec tablicy.

Przykład 1. Przykład użycia array_merge()

$tablica1 = array ("kolor" => "czerwony", 2, 4);
$tablica2 = array ("a", "b", "kolor" => "zielony", "kształt" => "trapezoid", 4);
$wynik = array_merge ($tablica1, $tablica2);

W powyższym przykładze tablica $wynik zawiera array("kolor" => "zielony", 2, 4, "a", "b", "kształt" => "trapezoid", 4).

Patrz także array_merge_recursive().

array_merge_recursive

(PHP 4 )

array_merge_recursive -- Łączy dwie lub więcej tablic rekurencyjnie

Opis

array array_merge_recursive ( array tablica1, array tablica2 [, array ...])

array_merge_recursive() łączy elementy dwóch lub więcej tablic tak, że wartości jednej tablicy są dopisywane na koniec poprzedniej. Zwracana jest tablica wynikowa.

Jeśli wejściowe tablice mają jakieś klucze tekstowe, to wartości dla tych kluczy są łączone w tablicę, co jest robione rekurencyjnie, a więc jeśli jedną z wartości jest tablica, funkcja połączy ją z odpowiadającą jej wartością z innej tablicy. Jednakże jeśli tablice mają takie same klucze liczbowe, późniejsza wartość nie nadpisze początkowej wartości, lecz zostanie dopisana na koniec.

Przykład 1. Przykład użycia array_merge_recursive()

$tbl1 = array ("kolor" => array ("ulubiony" => "czerwony"), 5);
$tbl2 = array (10, "kolor" => array ("ulubiony" => "zielony", "niebieski"));
$wynik = array_merge_recursive ($tbl1, $tbl2);

W powyższym przykładzie tablica $wynik zawiera array ("kolor" => array ("ulubiony" => array ("czerwony", "zielony"), "niebieski"), 5, 10).

Patrz także array_merge().

array_multisort

(PHP 4 >= 4.0.0)

array_multisort -- Sortuje wiele tablic lub wielowymiarowe tablice

Opis

bool array_multisort ( array tbl1 [, mixed arg [, mixed ... [, array ...]]])

array_multisort() może być użyta do sortowania kilku tablic na raz lub wielowymiarowej tablicy na podstawie jednego z większej liczby wymiarów. Zachowywane są przypisania kluczy.

Tablice wejściowe są traktowane jak kolumy tabeli, które mają być posortowane wierszami - odpowiada to funkcjonalności warunku SQL ORDER BY. Pierwsza tablica jest tablicą priorytetową do sortowania. Wiersze (wartości) w tej tablicą które są takie sane sortowane są według następnej tablicy wejściowej i tak dalej.

Struktura argumentów tej funkcji nie jest zwyczajna, ale jest ona elastyczna. Pierwszy argument musi być tablicą. Każdy następny argument musi być tablicą lub flagą oznaczającą porządek sortowania - jeden z poniższych.

Flagi porządku sortowania:

  • SORT_ASC - sortuj w porządku rosnącym

  • SORT_DESC - sortuj w porządku malejącym

Flagi typu sortowania:

  • SORT_REGULAR - porównuj elementy normalnie

  • SORT_NUMERIC - porównuj elementy numerycznie

  • SORT_STRING - porówuj elementy jak stringi

Nie można podać żadnych dwóch flag tego samego typu dla jednej tablicy. Flagi sortowania podane pod argumencie-tablicy dotyczą tylko tej tablicy - są one zerowane do domyślnych wartośći SORT_ASC i SORT_REGULAR po każdym argumencie tablicowym.

Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.

Przykład 1. Sortowanie wielu tablic

$tbl1 = array ("10", 100, 100, "a");
$tbl2 = array (1, 3, "2", 1);
array_multisort ($tbl1, $tbl2);

W tym przypadku, po sortowaniu, pierwsza tablica będzie zawierać 10, "a", 100, 100, a druga 1, 1, "2", 3. Elementy drugiej tablicy odpowiadające identycznym elementom pierwszej tablicy (100 i 100) także zostały posortowane.

Przykład 2. Sortowanie wielowymiarowych tablic

$tbl = array (array ("10", 100, 100, "a"), array (1, 3, "2", 1));
array_multisort ($tbl[0], SORT_ASC, SORT_STRING, 
                 $tbl[1], SORT_NUMERIC, SORT_DESC);

W tym przykładzie, po sortowaniu, pierwsza tablica zawiera 10, 100, 100, "a" (została posortowana według wartości tekstowych w porządku rosnącym), a druga 1, 3, "2", 1 (sortowana jak liczby w porządku malejącym).

array_pad

(PHP 4 >= 4.0.0)

array_pad --  Dopełnij tablicę do podanej długości podanymi wartościami

Opis

array array_pad ( array wejście, int rozmiar, mixed wartość)

array_pad() zwraca kopię tablicy input dopełnioną do rozmiaru określonego przez rozmiar wartością wartość. Jeśli rozmiar jest wartością dodatnią, to tablica jest dopełniana z prawej strony, jeśli ujemna to z lewej. Jeśli wartość bezwzględna parametru rozmiar jest mniejsza lub równa długości tablicy wejście, to tablica nie jest dopełniana.

Przykład 1. Przykład użycia array_pad()

$wejscie = array (12, 10, 9);

$wynik = array_pad ($wejscie, 5, 0);
// wynik to array (12, 10, 9, 0, 0)

$wynik = array_pad ($wejscie, -7, -1);
// wynik to array (-1, -1, -1, -1, 12, 10, 9)

$wynik = array_pad ($wejscie, 2, "noop");
// nie ma dopełniania

array_pop

(PHP 4 >= 4.0.0)

array_pop -- Zdejmij element z końca tablicy

Opis

mixed array_pop ( array tablica)

array_pop() zdejmuje i zwraca ostatnią wartość tablicy tablica, skracając tą tablicę o jeden element. Jeśli tablica jest pusta (lub nie jest tablicą), zwracana jest wartość NULL.

Przykład 1. Przykład użycia array_pop()

$stos = array ("pomarańcza", "jabłko", "malina");
$owoc = array_pop ($stos);

Po wykonaniu powyższego kodu $stos będzie miał tylko dwa elementy: "pomarańcza" i "jabłko", a zmienna $owoc będzie zawierała string "malina".

Patrz także array_push(), array_shift() i array_unshift().

array_push

(PHP 4 >= 4.0.0)

array_push --  Wstaw jeden lub więcej elementów na koniec tablicy

Opis

int array_push ( array tablica, mixed wartosc [, mixed ...])

array_push() traktuje zmienną tablica jako stos i wstawia przekazane parametry na koniec podanej tablicy. Długość parametru tablica zwiększa się o liczbę przekazanych wartości. Ma to taki sam efekt jak kod:
$tablica[] = $wartosc;
powtórzony dla każdego parametru wartosc.

Funkcja zwraca nową liczbę elementów tablicy.

Przykład 1. Przykład użycia array_push()

$stos = array (1, 2);
array_push ($stos, "+", 3);

Po wykonaniu powyższego kodu zmienna $stos będzie zawierała 4 elementy: 1, 2, "+" i 3.

Patrz także array_pop(), array_shift() i array_unshift().

array_rand

(PHP 4 >= 4.0.0)

array_rand --  Wybierz jeden lub więcej losowych elementów z tablicy

Opis

mixed array_rand ( array wejście [, int ilość])

Funkcja array_rand() jest przydatna jeśli chcesz wyciągnąć jeden lub więcej losowych elementów z tablicy. Jako parametry pobiera tablicę wejście i opcjonalny parameter ilość który określa ile elementów tablicy chcesz wyciągnąć - jeśli nie podano, przymowana jest domyślna wartość 1.

Jeśli wyciągasz tylko jeden element, array_rand() zwraca klucz losowego wpisu. W przeciwnym przypadku zwracana jest tablica zawierająca klucze losowych wpisów. Dzieje się tak, żeby można było wyciągnąć jednocześnie klucze i wartości losowych elementów tablicy.

Nie zapomnij wywołać srand() aby zainicjować ziarno generatora liczb pseudolosowych.

Przykład 1. Przykład użycia array_rand()

srand ((float) microtime() * 10000000);
$wejscie = array ("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$losowe_klucze = array_rand ($wejscie, 2);
print $wejscie[$losowe_klucze[0]]."\n";
print $wejscie[$losowe_klucze[1]]."\n";

array_reverse

(PHP 4 >= 4.0.0)

array_reverse --  Zwraca tablicę z elementami ustawionymi w porządku odwrotnym

Opis

array array_reverse ( array wejście [, bool zachowaj_klucze])

array_reverse() pobiera tablicę wejście i zwraca nową tablicę z odwróconym porządkiem występowania elementów, zachowując klucze tylko jeśli wartość parametru zachowaj_klucze to TRUE.

Przykład 1. Przykład użycia array_reverse()

$wejscie = array ("php", 4.0, array ("zielony", "czerwony"));
$wynik = array_reverse ($wejscie);
$wynik_kluczowany = array_reverse ($input, TRUE);

I $wynik i $wynik_kluczowany będą zawierały array(array ("zielony", "czerwony"), 4.0, "php"). Ale $wynik_kluczowany[0] ciągle będzie zawierał "php".

Notatka: Drugi parametr został dodany w PHP 4.0.3.

array_reduce

(PHP 4 >= 4.0.5)

array_reduce --  Iteracyjnie zredukuj tablicę do pojedyńczej wartości używając funkcji zwrotnej

Opis

mixed array_reduce ( array wejście, mixed funkcja_zwrotna [, int początek])

array_reduce() iteracyjnie stosuje funkcję funkcja_zwrotna na każdym elemencie tablicy wejście aby zredukować tablicę to pojedyńczej wartości. Jeśli podany został opcjonalny parametr początek , będzie on użyty na początku procesu, lub jako zwracana wartość jeśli tablica jest pusta.

Przykład 1. Przykład użycia array_reduce()

function rsum($v, $w) {
    $v += $w;
    return $v;
}

function rmul($v, $w) {
    $v *= $w;
    return $v;
}

$a = array(1, 2, 3, 4, 5);
$x = array();
$b = array_reduce($a, "rsum");
$c = array_reduce($a, "rmul", 10);
$d = array_reduce($x, "rsum", 1);

Po wykonaniu powyższego kodu zmienna $b będzie zawierała 15, $c 1200 (= 1*2*3*4*5*10) a $d containing 1.

Patrz także array_filter(), array_map().

array_shift

(PHP 4 >= 4.0.0)

array_shift --  Usuń element z początku tablicy

Opis

mixed array_shift ( array tablica)

array_shift() usuwa pierwszą wartość parametru tablica i zwraca go skracając tą tablicę o jeden element przesuwając wszystkie pozostałe elementy w dół. Jeśli tablica jest pusta (lub nie jest tablicą), zwracana jest wartość NULL.

Przykład 1. Przykład użycia array_shift()

$argumenty = array ("-v", "-f");
$opcja = array_shift ($argument);

Po wykonaniu powyższego kodu zmienna $args będzie zawierała jeden element "-f" a $opcja będzie zawierała string "-v".

Patrz także array_unshift(), array_push() i array_pop().

array_slice

(PHP 4 >= 4.0.0)

array_slice -- Wytnij kawałek tablicy

Opis

array array_slice ( array tablica, int przesunięcie [, int długość])

array_slice() zwraca sekwencję elementów z tablicy tablica określony przez parametry przesunięcie i długość.

Jeśli przesunięcie jest dodatnie, sekwencja zacznie się od miejsca wskazanego w tym parametrze. Jeśli przesunięcie jest ujemne, sekwencja zacznie się o tyle elementów od końca tablicy tablica.

Jeśli podany jest parametr długość i jest on dodatni, to sekwencja będzie miała tyle elementów ile podano w tym parameterz. Jeśli długość jest ujemna, to sekwencja skończy się o tyle elementów od końca tablicy. Jeśli został pominięty, to sekwencja będzie zawierać wszystko od przesunięcie do końca parametru tablica.

Przykład 1. Przykład użycia array_slice()

$wejscie = array ("a", "b", "c", "d", "e");

$wyjscie = array_slice ($wejscie, 2);      // zwraca "c", "d" i "e"
$wyjscie = array_slice ($wejscie, 2, -1);  // zwraca "c", "d"
$wyjscie = array_slice ($wejscie, -2, 1);  // zwraca "d"
$wyjscie = array_slice ($wejscie, 0, 3);   // zwraca "a", "b" i "c"

Patrz także array_splice().

array_splice

(PHP 4 >= 4.0.0)

array_splice --  Usuń część tablicy i zamień ją na coś innego

Opis

array array_splice ( array wejście, int przesunięcie [, int długość [, array zamiennik]])

array_splice() usuwa z tablicy wejście elementy określone przez parametry przesunięcie i długość, i zamienia je przez elementy tablicy zamiennik, jeśli została ona podana.

Jeśli przesunięcie jest dodatnie, to początek usuwanej części tablicy wejście znajduje się w miejscu określonym przez ten parametr. Jeśli przesunięcie jest ujemne, to wycinanie zaczyna się o tyle elementów od końca tablicy wejście.

Jeśli długość została pominięta, to usunięte jest wszystko od przesunięcie do końca tablicy. Jeśli długość jest podana i dodatnia, to tyle elementów zostanie usuniętych. Jeśli długość jest podana i jest ujemna, to koniec usuwanego kawałka tablicy będzie się znajdował o tyle elementów od końca tablicy. Wskazówka: aby usunąć wszystko od przesunięcie do końca tablicy podając także parametr zamiennik, użyj count($wejście) jako długość.

Jeśli podana została tablica zamiennik, to wszystkie usunięte elementy są zamieniane na elementy z tej tablicy. Jeśli przesunięcie i długość zostały podane tak, że żadne elementy nie zostaną usunięte, to elementy z tablicy zamiennik są wstawiane w miejsce określone przez przesunięcie. Wskazówka: jeśli zamiennik to tylko jeden element, to nie trzeba go wstawiać do array(), chyba że element jest właśnie tablicą.

Równoznaczności kodu:
array_push ($wejscie, $x, $y)     array_splice ($wejscie, count ($wejscie), 0, 
                                               array ($x, $y))
array_pop ($wejscie)              array_splice ($wejscie, -1)
array_shift ($wejscie)            array_splice ($wejscie, 0, 1)
array_unshift ($wejscie, $x, $y)  array_splice ($wejscie, 0, 0, array ($x, $y))
$a[$x] = $y                       array_splice ($wejscie, $x, 1, $y)

Funkcja zwraca tablicę zawierającą usunięte elementy.

Przykład 1. Przykład użycia array_splice()

$wejscie = array ("czerwony", "zielony", "niebieski", "żółty");
array_splice ($wejscie, 2);      
// $wejscie to teraz array ("czerwony", "zielony")

$wejscie = array ("czerwony", "zielony", "niebieski", "żółty");
array_splice ($wejscie, 1, -1);  
// $wejscie to teraz array ("czerwony", "żółty")

$wejscie = array ("czerwony", "zielony", "niebieski", "żółty");
array_splice ($wejscie, 1, count($wejscie), "pomarańczowy");  
// $wejscie to teraz array ("czerwony", "pomarańczowy")

$wejscie = array ("czerwony", "zielony", "niebieski", "żółty");
array_splice ($wejscie, -1, 1, array("czarny", "kasztanowy")); 
// $wejscie to teraz array ("czerwony", "zielony", 
//          "niebieski", "czarny", "kasztanowy")

Patrz także array_slice().

array_sum

(PHP 4 >= 4.0.4)

array_sum --  Oblicza sumę wartości w tablicy

Opis

mixed array_sum ( array tablica)

array_sum() zwraca sumę wszystkich wartości w tablicy jako liczbę całkowitą lub rzeczywistą.

Przykład 1. Przykład użycia array_sum()

$a = array(2, 4, 6, 8);
echo "sum(a) = ".array_sum($a)."\n";
// wyświetla: sum(a) = 20

$b = array("a"=>1.2,"b"=>2.3,"c"=>3.4);
echo "sum(b) = ".array_sum($b)."\n";
// wyświetla: sum(b) = 6.9

array_unique

(PHP 4 )

array_unique -- Usuwa duplikaty wartości z tablicy

Opis

array array_unique ( array tablica)

array_unique() pobiera parametr tablica i zwraca nową tablicę bez duplikatów wartości.

Zauważ, że klucze są zachowywane. array_unique() zachowa pierwszy napotkany klucz dla każdej wartości ignorując wszystkie pozostałe.

Notatka: Dwa elementy tablicy są uważane za równe wtedy i tylko wtedy jeśli (string) $elem1 === (string) $elem2, czyli jeśli reprezentacje wartości w postaci stringów są takie same.

Używany będzie pierwszy element.

Ostrze¿enie

Ta funkcja była zepsuta w PHP 4.0.4!

Przykład 1. Przykład użycia array_unique()

$wejscie = array ("a" => "zielony", "czerwony", "b" => "zielony", "niebieski", "czerwony");
$wynik = array_unique ($wejscie);
print_r($wynik);
// wyświetli się :
//Array
//(
//    [a] => zielony
//    [0] => czerwony
//    [1] => niebieski
//)

Przykład 2. array_unique() i typy

$wejscie = array (4,"4","3",4,3,"3");
$wynik = array_unique ($wejscie);
var_dump($wynik);

/* wyjście:
array(2) {
   [0]=>
   int(4)
   [1]=>
   string(1) "3"
}
*/

array_unshift

(PHP 4 >= 4.0.0)

array_unshift --  Wstaw jeden lub więcej elementów na początek tablicy

Opis

int array_unshift ( array tablica, mixed wartość [, mixed ...])

array_unshift() wstawia jeden lub więcej przekazanych jako parametry elementów na początek tablicy tablica. Zauważ, że lista elementów wstawiana jako całość, więc elementy zostają w takim samym porządku.

Funkcja zwraca nową liczbę elementów w tablicy tablica.

Przykład 1. Przykład użycia array_unshift()

$kolejka = array ("p1", "p3");
array_unshift ($kolejka, "p4", "p5", "p6");

Po wykonaniu powyższego kodu zmienna $kolejka będzie zawierała 5 elementów: "p4", "p5", "p6", "p1", and "p3".

Patrz także array_shift(), array_push() i array_pop().

array_values

(PHP 4 >= 4.0.0)

array_values -- Zwraca wszystkie wartości z tablicy

Opis

array array_values ( array wejście)

array_values() zwraca wszystkie wartości z tablicy wejście.

Przykład 1. Przykład użycia array_values()

$tablica = array ("rozmiar" => "XL", "kolor" => "złoty");
array_values ($tablica);    // zwraca array ("XL", "złoty")

Notatka: Ta funkcja została dodana w PHP 4. Poniżej znajduje się implementacja tej funkcji dla osób używających PHP 3.

Przykład 2. Implementacja funkcji array_values() dla użytkowników PHP 3

function array_values ($arr) {
    $t = array();
    while (list($k, $v) = each ($arr)) {
        $t[] = $v;
    }
    return $t;
}

Patrz także array_keys().

array_walk

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

array_walk --  Zastosuj funkcję użytkownika do każdego elementu tablicy

Opis

int array_walk ( array tbl, string funk [, mixed dane])

Wykonuje zdefuniowaną przez użytkownika funkcję o nazwie funk na każdym elemencie tablicy tbl. Wartość elementu będzie przekazana do funk jako pierwszy parametr, a klucz jako drugi. Jeśli podany zostanie parametr dane, to będzie on przekazany do funkcji jako trzeci parametr. funk musi być funkcją zdefiniowaną przez użytkownika, a nie natywną funkcją PHP. W związku z tym nie możesz bezpośrednio użyć array_walk() z str2lower(). Musisz najpierw napisać funkcję zawierającą str2lower() i przekazać tą funkcję jako parametr.

Jeśli funk wymaga więcej niż dwóch lub trzech parametrów, zależnie od parametru dane, wygenerowane będzie ostrzeżenie za każdym razem, kiedy array_walk() będzie wywoływała funk. Ostrzeżenia te mogą być ukryte przez dodanie znaku '@' przed wywołaniem array_walk() lub używając error_reporting().

Notatka: Jeśli funk ma zmieniać wartości tablicy, określ pierwszy parametr funk jako referencję. W tym przypadku wszystkie zmiany dokonane przez tą funkcję będą dokonywane bezpośrednio na tablicy.

Notatka: Przekazywanie klucza i danych użytkownika do funk zostało dodane w PHP 4.0

W PHP 4 konieczne jest wywołanie reset() ponieważ array_walk() nie resetuje tablicy domyślnie.

Przykład 1. Przykład użycia array_walk()

$owoce = array ("d"=>"cytryna", "a"=>"pomarańcza", "b"=>"banan", "c"=>"jabłko");

function test_zmiana (&amp;$element1, $klucz, $prefiks) {
    $element1 = "$prefiks: $element1";
}

function test_wyswietlanie ($element2, $klucz) {
    echo "$klucz. $element2<br>\n";
}

array_walk ($owoce, 'test_wyswietlanie');
reset ($owoce);
array_walk ($owoce, 'test_zmiana', 'owoc');
reset ($owoce);
array_walk ($owoce, 'test_wyswietlanie');

Patrz także each() i list().

arsort

(PHP 3, PHP 4 >= 4.0.0)

arsort --  Sortuj tablicę w porządku odwrotnym i zachowaj skojarzenia kluczy

Opis

void arsort ( array tablica [, int flagi])

Ta funkcja sortuje tablicę w taki sposób, że klucze zachowują przypisanie do odpowiednich wartości. Ten sposób sortowania jest używany głównie przy sortowaniu tablic asocjacyjnych, gdzie znacząca jest kolejność występowania elementów w tablicy.

Przykład 1. Przykład użycia arsort()

$owoce = array ("d"=>"cytryna, "a"=>"pomarańcza", "b"=>"banan", "c"=>"jabłko");
arsort ($owoce);
reset ($owoce);
while (list ($key, $val) = each ($owoce)) {
    echo "$key = $val\n";
}

Ten przykład wyświetli:
a = pomarańcza
c = jabłko
d = cytryna
b = banan

Owoce zostały posortowane w odwrotnym porządku alfabetycznym a skojarzenia kluczy dla każdego elementu zostały zachowane.

Możesz zmodyfikować zachowanie sortowania przez użycie opcjonalnego parametru flagi. Aby uzyskać szczegóły zobacz sort().

Patrz także asort(), rsort(), ksort() i sort().

asort

(PHP 3, PHP 4 >= 4.0.0)

asort -- Posortuj tablicę zachowując skojarzenia kluczy

Opis

void asort ( array tablica [, int flagi])

Funkcja ta sortuje tablicę w taki sposób, że klucze zachowują przypisanie do odpowiednich wartości. Ten sposób sortowania jest używany głównie przy sortowaniu tablic asocjacyjnych, gdzie znacząca jest kolejność występowania elementów w tablicy.

Przykład 1. Przykład użycia asort()

$owoce = array ("d"=>"cytryna, "a"=>"pomarańcza", "b"=>"banan", "c"=>"jabłko");
arsort ($owoce);
reset ($owoce);
while (list ($key, $val) = each ($owoce)) {
    echo "$key = $val\n";
}

Ten przykład wyświetli:
b = banan
d = cytryna
c = jabłko
a = pomarańcza

Owoce zostały posortowane w porządku alfabetycznym a skojarzenia kluczy dla każdego elementu zostały zachowane.

Możesz zmodyfikować zachowanie sortowania przez użycie opcjonalnego parametru flagi. Aby uzyskać szczegóły zobacz sort().

Patrz także arsort(), rsort(), ksort() i sort().

compact

(PHP 4 >= 4.0.0)

compact --  Stwórz tablicę zawierającą zmienne i ich wartości

Opis

array compact ( mixed nazwa_zmiennej [, mixed ...])

compact() pobiera zmienną liczbę parametrów. Każdy parametr może być albo stringiem zawierającym nazwę zmiennej lub tablicę nazw zmiennych. Tablica może zaierać w sobie inne tablice nazw zmiennych; compact() obsłuży je rekurencyjnie.

Dla każdej z nich compact() sprawdza zmienną o nazwie określnej przez bieżący symbol w tablicy i dodaje ją do tablicy wyjściowej tak, że nazwa zmiennej staje się kluczem z zawartość zmiennej wartością dla tego klucza. W skrócie, funkcja ta jest przeciwnością extract(). Zwraca ona tablicę zawierającą zmienne do niej dodane.

Dowolne stringi, które nie są ustawione, poprostu będą pominięte.

Przykład 1. Przykład użycia compact()

$miasto = "San Francisco";
$stan = "CA";
$wydarzenie = "SIGGRAPH";

$zmienne_lokalizacyjne = array ("miasto", "stan");

$wynik = compact ("wydarzenie", "nic", $zmienne_lokalizacyjne);

Po tym $wynik będzie zawierał array ("wydarzenie" => "SIGGRAPH", "miasto" => "San Francisco", "stan" => "CA").

Patrz także extract().

count

(PHP 3, PHP 4 >= 4.0.0)

count -- Zlicza ilość elementów w tablicy

Opis

int count ( mixed zmienna)

Zwraca ilość elementów w parametrze zmienna, która zazwyczaj będzie tablicą (ponieważ wszstko inne będzie miało jeden element).

Jeśli zmienna nie jest tablicą, to zwracana będzie wartość 1 (wyjątek: count(NULL) jest równe 0).

Ostrze¿enie

count() może zwrócić 0 dla zmiennej, która nie została zainicjalizowana, ale możę zwrócić także 0 dla zmiennej która została zainicjalizowana pustą tablicą. Użyj isset() aby sprawdzić czy zmienna została ustawiona.

Zobacz rozdział podręcznika Tablice aby dowiedzieć się jak tablice zostały zaimplementowane w PHP.

Przykład 1. Przykład użycia count()

$a[0] = 1; 
$a[1] = 3; 
$a[2] = 5; 
$wynik = count ($a);
// $wynik == 3

$b[0] = 7;
$b[5] = 9;
$b[10] = 11;
$wynik = count ($b);
// $wynik == 3;

Notatka: Funkcja sizeof() jest aliasem dla count().

Patrz także sizeof(), isset() i is_array().

current

(PHP 3, PHP 4 >= 4.0.0)

current -- Zwraca bieżący element tablicy

Opis

mixed current ( array tablica)

Każda tablica ma wewnętrzny wskaźnik bo swojego "bieżącego" elementu, który jest inicjalizowany do pierwszego elementu wstawionego do tablicy.

Funkcja current() po prostu zwraca element tablicy, na który aktualnie wskazuje wewnętrzny wskaźnik. Nie przesuwa ona wskaźnika. Jeśli wewnętrzny wskaźnik jest poza końcem listy elementów, current() zwraca FALSE.

Ostrze¿enie

Jeśli tablica zawiera puste elementy (0 lub "", czyli pusty string), to funkcja zwróci FALSE także dla tych elementów. Przez to nie jest możliwe stwierdzenie, czy jesteś już poza tablicą, używając funkcji current(). Aby prawidłowo przejść przez tablicę która zwiera puste elementy, skorzystaj z funkcji each().

Patrz także end(), next(), prev() i reset().

each

(PHP 3, PHP 4 >= 4.0.0)

each --  Zwraca bieżącą parę klucza i wartości z tablicy i przesuwa kursor tablicy

Opis

array each ( array tablica)

Zwraca bieżącą parę klucza i wartości z tablicy tablica i przesuwa wewnętrzny wskaźnik tablicy do przodu o jeden element. Para ta jest zwracana jako czteroelementowa tablica, z kluczami 0, 1, key i value. Elementy 0 i key zawierają nazwę klucza elementu tablicy, a 1 i value zawierają wartość elementu tablicy.

Jeśli wewnętrzny wskaźnik tablicy wskazuje na miejsce poza końcem zawartości tablicy, each() zwraca FALSE.

Przykład 1. Przykłady użycia each()

$foo = array ("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each ($foo);

$bar zawiera teraz następujące pary klucz/wartość

  • 0 => 0
  • 1 => 'bob'
  • key => 0
  • value => 'bob'
$foo = array ("Robert" => "Bob", "Seppo" => "Sepi");
$bar = each ($foo);

$bar zawiera teraz następujące pary klucz/wartość:

  • 0 => 'Robert'
  • 1 => 'Bob'
  • key => 'Robert'
  • value => 'Bob'

each() jest zazwyczaj używana w połączeniu z list() aby przejść przez tablicę; na przykład $HTTP_POST_VARS:

Przykład 2. Przechodzenie przez $HTTP_POST_VARS używając each()

echo "Wartości wysłane metodą POST:<br>";
reset ($HTTP_POST_VARS);
while (list ($key, $val) = each ($HTTP_POST_VARS)) {
    echo "$key => $val<br>";
}

Po wykonaniu each(), wewnętrzny wskaźnik tablicy będzie pozostawiony na następnym elementcie tablicy, lub ostatnim elemencie jeśli dojdzie ona do końca tablicy. Musisz użyć reset() jeśli chcesz przejść przez tablicę jeszcze raz korzystając z funkcji each.

Patrz także key(), list(), current(), reset(), next() i prev().

end

(PHP 3, PHP 4 >= 4.0.0)

end --  Ustaw wewnętrzny wskaźnik tablicy na ostatnim elemencie

Opis

mixed end ( array tablica)

end() przesuwa wewnętrzny wskaźnik tablicy tablica na ostatnim elemencie i zwraca ten element.

Patrz także current(), each(), end(), next() i reset().

extract

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

extract --  Importuj zmienne do tabeli symboli z tablicy

Opis

int extract ( array tablica_zmiennych [, int typ_ekstrakcji [, string prefiks]])

Ta funkcja służy do importowania zmiennych z tablicy do bieżącej tabeli symboli. Pobiera jako parametr tablicę asocjacyjną tablica_zmiennych i traktuje klucze jako nazwy zmiennych a wartości jako wartości tych zmiennych. Dla każdej pary klucz/wartość w bieżącej tabeli symboli będzie stworzona zmienna, zależna od parametrów typ_ekstrakcji i prefiks.

Notatka: Od wersji 4.0.5 ta funkcja zwraca liczbę wyekstraktowanych zmiennych.

extract() sprawdza każdy klucz aby sprawdzić, czy zawiera prawidłową nazwę zmiennej a także czy istnieją kolizje z zmiennymi istniejącymi w tablicy symboli. Sposób traktowania złych nazw zmiennych i kolizji jest określony przez parametr typ_ekstrakcji. Może być jedną z poniższych wartości:

EXTR_OVERWRITE

Jeśli istnieje kolizja, nadpisz istniejącą zmienną.

EXTR_SKIP

Jeśli istnieje kolizja, nie nadpisuj istniejącej zmiennej.

EXTR_PREFIX_SAME

Jeśli istnieje kolizja, na początek nazwy zmiennej wstaw prefiks.

EXTR_PREFIX_ALL

Na początek każdej nazwy zmiennej wstaw prefiks. Od PHP 4.0.5 dotyczy to także nazw numerycznych.

EXTR_PREFIX_INVALID

Wstaw prefiks na początek złych/numerycznych nazw. Ta flaga została dodana w PHP 4.0.5.

Jeśli typ_ekstrakcji nie został podany, to zakładana jest opcja EXTR_OVERWRITE.

Zauważ, że parametr prefiks jest wymagany tylko jeśli typ_ekstrakcji to EXTR_PREFIX_SAME, EXTR_PREFIX_ALL i EXTR_PREFIX_INVALID. Jeśli nazwa zmiennej po dodaniu prefiksa nie jest prawidłową nazwą zmiennej, nie jest portowana do tablicy symboli.

extract() zwraca liczbę zmiennych szczęśliwie zaimportowanych do tablicy symboli.

Możliwy jest import zmiennych zawartych w tablicy asocjacyjnej zwróconej przez wddx_deserialize().

Przykład 1. Przykład użycia extract()

<?php

/* Załóżmy, że $tablica_zmiennych jest tablicą zwróconą przez 
   wddx_deserialize */

$rozmiar = "duży";
$tablica_zmiennych = array ("kolor"    => "niebieski",
                            "rozmiar"  => "średni",
                            "ksztalt"  => "kulisty");
extract ($tablica_zmiennych, EXTR_PREFIX_SAME, "wddx");

print "$kolor, $rozmiar, $ksztalt, $wddx_rozmiar\n";

?>

Powyższy przykład wyświetli:
niebieski, duży, kulisty, średni

$rozmiar nie został nadpisany, ponieważ podany został parametr EXTR_PREFIX_SAME, przez co stworzona został zmienna $wddx_rozmiar. Jeśli podana by była flaga EXTR_SKIP, to zmienna $wddx_rozmiar nie zostałaby stworzona. Flaga EXTR_OVERWRITE spowodowałaby, że zmienna $rozmiar miałaby wartość "średni", a EXTR_PREFIX_ALL spowodowałaby że wszystkie nowe zmienne zostałyby nazwane $wddx_kolor, $wddx_rozmiar, and $wddx_ksztalt.

Musisz użyć tablic asocjacyjnych. Tablica indeksowana liczbowo nie da żadnych efektów.

Patrz także compact().

in_array

(PHP 4 >= 4.0.0)

in_array -- Zwraca TRUE jeśli wartość istnieje w tablicy

Opis

bool in_array ( mixed igła, array stóg_siana [, bool ścisłe])

Przeszukuje stóg_siana w poszukiwaniu parametru igła i zwraca TRUE jeśli wartość została znaleziona lub FALSE w przeciwnym przypadku.

Jeśli trzeci parametr ścisły jest ustawiony na TRUE to in_array() porówna także typy parametru igła z tymi z parametru stóg_siana.

Przykład 1. Przykład użycia in_array()

$os = array ("Mac", "NT", "Irix", "Linux");
if (in_array ("Irix", $os)) {
    print "Znaleziono Irix";
}

Przykład 2. Przykład użycia in_array() z parametrem strict

<?php
$a = array('1.10', 12.4, 1.13);

if (in_array('12.4', $a, TRUE))
    echo "'12.4' znalezione ze ścisłym sprawdzaniem\n";
if (in_array(1.13, $a, TRUE))
    echo "1.13 znalezione ze ścisłym sprawdzaniem\n";
?>
// Wyświetli to:

1.13 znalezione ze ścisłym sprawdzaniem

Patrz także array_search().

array_search

(PHP 4 >= 4.0.5)

array_search --  Przeszukuje tablicę pod kątem podane wartości i w przypadku sukcesu zwraca odpowiedni klucz

Opis

mixed array_search ( mixed igła, array stóg_siana [, bool ścisły])

Przeszukuje stóg_siana w poszukiwaniu parametru igła i zwraca odpowiedni klucz jeśli został on znaleziony lub FALSE w przeciwnym przypadku.

Jeśli trzeci parametr ścisły jest ustawiony na TRUE to array_search() porówna także typy parametru igła z tymi z parametru stóg_siana.

Patrz także in_array().

key

(PHP 3, PHP 4 >= 4.0.0)

key -- Pobiera klucz z tablicy asocjacyjnej

Opis

mixed key ( array tablica)

key() zwraza klucz bieżącego elementu z tablicy asocjacyjnej.

Patrz także current() i next().

krsort

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

krsort -- Sortuj tablicę według kluczy w porządku odwrotnym

Opis

int krsort ( array tablica [, int flagi])

Sortuje trablicę według klucza w porządku odwrotnym utrzymując skojarzenia kluczy z danymi. Jest to przydatne głównie w przypadku tablic asocjacyjnych.

Przykład 1. Przykład użycia krsort()

$owoce = array ("d"=>"cytryna", "a"=>"pomarańcza", "b"=>"banan", "c"=>"jabłko");
krsort ($owoce);
reset ($owoce);
while (list ($key, $val) = each ($owoce)) {
    echo "$key = $val\n";
}

Ten przykład wyświetli:

d = cytryna
c = jabłko
b = banan
a = pomarańcza

Możesz zmodyfikować zachowanie sortowania przez użycie opcjonalnego parametru flagi. Aby uzyskać szczegóły zobacz sort().

Patrz także asort(), arsort(), ksort() sort(), natsort() i rsort().

ksort

(PHP 3, PHP 4 >= 4.0.0)

ksort -- Sortuj tablicę według klucza

Opis

int ksort ( array tablica [, int flagi])

Sortuje tablicę według klucza zachowując skojarzenia kluczy z danymi. Jest to przydatne głównie w przypadku tablic asocjacyjnych.

Przykład 1. Przykład użycia ksort()

$owoce = array ("d"=>"cytryna", "a"=>"pomarańcza", "b"=>"banan", "c"=>"jabłko");
ksort ($owoce);
reset ($owoce);
while (list ($key, $val) = each ($owoce)) {
    echo "$key = $val\n";
}

Ten przykład wyświetli:

a = pomarańcza
b = banan
c = jabłko
d = cytryna

Możesz zmodyfikować zachowanie sortowania przez użycie opcjonalnego parametru flagi. Aby uzyskać szczegóły zobacz sort().

Patrz także asort(), arsort(), sort(), natsort() i rsort().

Notatka: Drugi parametr został dodany w PHP 4.

list

(unknown)

list --  Przypisz zmienne tak jakby były tablicą

Opis

void list ( mixed ...)

Podobna do array(), ale to nie jest na prawdę funkcja, ale składnia języka. Instrukcja list() jest używana do przypisywania listy zmiennych w jednej operacji.

Przykład 1. Przykład użycia list()

<table>
 <tr>
  <th>Nazwisko pracownika</th>
  <th>Pensja</th>
 </tr>

<?php

$wynik = mysql_query ($conn, "SELECT id, nazwisko, pensja FROM pracownicy");
while (list ($id, $nazwisko, $pensja) = mysql_fetch_row ($wynik)) {
   print (" <tr>\n".
          "  <td><a href=\"info.php3?id=$id\">$nazwisko</a></td>\n".
          "  <td>$pensja</td>\n".
          " </tr>\n");
}

?>

</table>

Patrz także each() i array().

natsort

(PHP 4 >= 4.0.0)

natsort --  Sortuj tablicę używając algortmu "porządek naturalny"

Opis

void natsort ( array tablica)

Funkcja ta implementuje algorytm sortowania, który sortuje stringi alfanumeryczne tak, jak posortowałby je człowiek. Jest on określany jako "porządkowanie naturalne". Przykład różnicy między tym algorytmem a zwykłymi komputerowymi algorytmami sortowania stringów (używanymi w funkcji sort()) można zobaczyć poniżej:

Przykład 1. Przykład użycia natsort()

$tablica1 = $tablica2 = array ("img12.png", "img10.png", "img2.png", "img1.png");
 
sort($tablica1);
echo "Standardowe sortowanie\n";
print_r($tablica1);

natsort($tablica2);
echo "\nSortowanie w porządku naturalnym\n";
print_r($tablica2);

Powyższy kod wyświetlni następujące dane:

Standardowe sortowanie
Array
(
    [0] => img1.png
    [1] => img10.png
    [2] => img12.png
    [3] => img2.png
)

Sortowanie w porządku naturalnym
Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

Aby uzyskać więcej informacji zobacz stronę Martina Poola Natural Order String Comparison.

Patrz także natcasesort(), strnatcmp() i strnatcasecmp().

natcasesort

(PHP 4 >= 4.0.0)

natcasesort --  Sortuj tablicę używając algorytmu "porządek naturalny" ignorującego wielkość znaków

Opis

void natcasesort ( array tablica)

Ta funkcja implementuje algorytm sortowania który porządkuje stringi alfanumeryczne tak, jak zrobiłby to człowiek. Jest on określany jako "porządkowanie naturalne".

natcasesort() jest wersją funkcji natsort() ignorującą wielkość znaków. Zobacz natsort() aby zobaczyć różnicę między tym algorytmem a zwykłymi komputerowymi algorytmami sortowania stringów.

Aby uzyskać więcej informacji zobacz stronę Martina Poola Natural Order String Comparison.

Patrz także sort(), natsort(), strnatcmp() i strnatcasecmp().

next

(PHP 3, PHP 4 >= 4.0.0)

next --  Przesuń do przodu wewnętrzny wskaźnik tablicy

Opis

mixed next ( array tablica)

Przesuwa wewnętrzny wskaźnik tablicy i jedną pozycję do przodu i zwraca element tablicy aktualnie wskazywany przez wskaźnik, lub FALSE jeśli nie ma już więcej elementów.

next() zachowuje się jak current(), ale z jedną różnicą. Przesuwa wewnętrzny wskaźnik tablicy o jeden element do przodu przed zwróceniem elementu. Oznacza to, że zwraca następny element tablicy i przesuwa wewnętrzny wskaźnik tablicy o jeden element do przodu. Jeśli przesunięcie wewnętrznego wskaźnika tablicy powoduje przesunięcie poza koniec listy elementów, next() zwraca FALSE.

Ostrze¿enie

Jeśli tablica zawiera puste elementy lub elementy które mają klucze o wartości 0, to funkcja zwróci FALSE także dla tych elementów. Aby prawidłowo przejść przez tablice które mogą zawierać puste elementy lub elementy o wartościach kluczy 0, musisz użyć funkcji each().

Patrz także current(), end(), prev() i reset().

pos

(PHP 3, PHP 4 >= 4.0.0)

pos -- Pobierz bieżący element z tablicy

Opis

mixed pos ( array tablica)

Jest to alias dla funkcji current().

Patrz także end(), next(), prev() and reset().

prev

(PHP 3, PHP 4 >= 4.0.0)

prev -- Cofnij wewnętrzny wskaźnik tablicy

Opis

mixed prev ( array tablica)

Zwraca element tablicy z miejsca poprzedniego od tego na które wskazywał wewnętrzny wskaźnik pliku, lub FALSE jeśli nie ma już więcej elementów.

Ostrze¿enie

Jeśli tablica zawiera puste elementy, to będzie zwracać FALSE także dla tych elementów. Aby prawidłowo przejść przez tablicę, która może zawierać puste elementy, użyj funkcji each().

prev() zachowuje się tak jak next(), z tym że cofa wewnętrzny wskaźnik tablicy o jeden element do tyłu, zamiast przesuwać go do przodu.

Patrz także current(), end(), next() i reset().

range

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

range --  Stwórz tablicę zawierającą przedział elementów

Opis

array range ( mixed dolny, mixed górny)

range() zwraca tablicę elementów od dolny do górny, włącznie. Jeśli dolny > górny, to sekwencja będzie od górnego do dolnego.

Przykład 1. Przykłady użycia range()

foreach(range(0, 9) as $liczba) {
    echo $liczba;
}
foreach(range('a', 'z') as $litera) {
    echo $litera;
}
foreach(range('z', 'a') as $litera) {
    echo $litera;
}

Notatka: Do wersji 4.1.0, funkcja range() generowała tylko rosnące tablice liczbowe. Obsługa dla sekwencji znakowych i tablic malejących została dodana w 4.1.0.

Patrz także shuffle() aby zobaczyć inny przykład wykorzystania tej funkcji.

reset

(PHP 3, PHP 4 >= 4.0.0)

reset --  Ustaw wewnętrzny wskaźnik tablicy na jej pierwszy element

Opis

mixed reset ( array tablica)

reset() przewija wewnętrzny wskaźnik tablicy parametru tablica na jego pierwszy element.

reset() zwraca wartość pierwszego elementu tablicy.

Patrz także current(), each(), next() i prev().

rsort

(PHP 3, PHP 4 >= 4.0.0)

rsort -- Sortuj tablicę w porządku odwrotnym

Opis

void rsort ( array tablica [, int flagi])

Ta funkcja sortuje tablicę w porządku odwrotnym (od największego do najmniejszego).

Przykład 1. Przykład użycia rsort()

$owoce = array ("cytryna", "pomarańcza", "banan", "jabłko");
rsort ($owoce);
reset ($owoce);
while (list ($key, $val) = each ($owoce)) {
    echo "$key = $val\n";
}

Ten przykład wyświetli:

0 = pomarańcza
1 = cytryna
2 = banan
3 = jabłko

Owoce zostały posortowane w odwrotnym porządku alfabetycznym.

Możesz zmodyfikować zachowanie sortowania przez użycie opcjonalnego parametru flagi. Aby uzyskać szczegóły zobacz sort().

Patrz także arsort(), asort(), ksort(), sort() i usort().

shuffle

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

shuffle -- Przetasuj tablicę

Opis

void shuffle ( array tablica)

Ta funkcja tasuje tablicę (losuje kolejność elementów w niej). Musisz użyć srand() aby przygotować ziarno dla tej funkcji.

Przykład 1. Przykład użycia shuffle()

$liczby = range (1,20);
srand ((float)microtime()*1000000);
shuffle ($liczby);
while (list (, $liczba) = each ($liczby)) {
    echo "$liczba ";
}

Patrz także arsort(), asort(), ksort(), rsort(), sort() i usort().

sizeof

(PHP 3, PHP 4 >= 4.0.0)

sizeof -- Policz ilość elementów w zmiennej

Opis

int sizeof ( mixed zmienna)

Funkcja sizeof() jest aliasem funkcji count().

Patrz także count().

sort

(PHP 3, PHP 4 >= 4.0.0)

sort -- Sortuj tablicę

Opis

void sort ( array tablica [, int flagi])

Funkcja ta sortuje tablicę. Po zakończeniu działania funkcji elementy będą ułożone od najmniejszego do najwiekszego.

Przykład 1. Przykład użycia sort()

<?php

$owoce = array ("cytryna", "pomarańca", "banan", "jabłko");
sort ($owoce);
reset ($owoce);
while (list ($key, $val) = each ($owoce)) {
    echo "owoce[".$key."] = ".$val."\n";
}

?>

Ten przykład wyświetli:

owoce[0] = banan
owoce[1] = cytryna
owoce[2] = jabłko
owoce[3] = pomarańcza

Owoce zostały posortowane w porządku alfabetycznym.

Opcjonalny drugi parametr flagi może być użyty do zmiany zachowania sortowania przy pomocy tych wartości:

Flagi typu sortowania:

  • SORT_REGULAR - porównuj elementy normalnie

  • SORT_NUMERIC - porównuj elementy jako liczby

  • SORT_STRING - porównuj elementy jako stringi

Patrz także arsort(), asort(), ksort(), natsort(), natcasesort(), rsort(), usort(), array_multisort() i uksort().

Notatka: Drugi parametr został dodany w PHP 4.

uasort

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

uasort --  Sortuj tablicę korzystając ze zdefiniowanej przez użytkownika funkcji porównującej i zachowując skojarzenia kluczy

Opis

void uasort ( array tablica, function funkcja_por)

Funkcja ta sortuje tablicę w taki sposób, że klucze zachowują przypisanie do odpowiednich wartości. Jest to używane głównie przy sortowaniu tablic asocjacyjnych, gdzie znacząca jest kolejność elementów. Funkcja porównująca jest zdefiniowana przez użytkowanika.

Notatka: Zobacz usort() i uksort() aby zobaczyć przykłady zdefiniowanych przez użytkownika funkcji porównujących.

Patrz także usort(), uksort(), sort(), asort(), arsort(), ksort() i rsort().

uksort

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

uksort --  Sortuj tablicę według kluczy korzystając ze zdefiniowanej przez użytkownika funcji porównującej

Opis

void uksort ( array tablica, function funkcja_por)

Funkcja ta posortuje tablicę wedłu kluczy korzystając z podanej przez użytkownika funkcji porównującej. Jeśli chcesz posortować tablicę według skomplikowanych kryteriów, to powinieneś użyć tej funkcji.

Przykład 1. Przykład użycia uksort()

function cmp ($a, $b) {   
    if ($a == $b) return 0;
    return ($a > $b) ? -1 : 1;
}

$a = array (4 => "cztery", 3 => "trzy", 20 => "dwadzieścia", 10 => "dziesięć");

uksort ($a, "cmp");

while (list ($key, $value) = each ($a)) {
    echo "$key: $value\n";
}

Ten przykład wyświetli:

20: dwadzieścia
10: dziesięć
4: cztery
3: trzy

Patrz także usort(), uasort(), sort(), asort(), arsort(), ksort(), natsort() i rsort().

usort

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

usort --  Sortuj tablicę według wartości korzystając ze zdefiniowanej przez użytkownika funkcji porównującej

Opis

void usort ( array tablica, string funkcja_por)

Funkcja ta posortuje tablicę według jej wartości korzystając z podanej przez użytkownika funkcji porównującej. Jeśli chcesz posortować tablicę według skomplikowanych kryteriów, to powinieneś użyć tej funkcji.

Funkcja porównująca musi zwracać liczbę całkowitą mniejszą, równą lub większą od zera jeśli pierwszy argument jest odpowiednio mniejszy, równy lub większy niż drugi. Jeśli dwa elementy tablicy są równe, to ich kolejność występowania w posortowanej tablicy pozostaje niezdefiniowany.

Istenieje także możliwość użycia funkcji składowej obiektu jako funkcji porównującej. Zobacz przykład nr 3 poniżej.

Przykład 1. Przykład użycia usort()

function cmp ($a, $b) {   
    if ($a == $b) return 0;
    return ($a > $b) ? -1 : 1;
}

$a = array (3, 2, 5, 6, 1);

usort ($a, "cmp");

while (list ($key, $value) = each ($a)) {
    echo "$key: $value\n";
}

Powyższy przykład wyświetli:

0: 6
1: 5
2: 3
3: 2
4: 1

Notatka: Oczywiście w prostszych przypadkach lepiej jest skorzystać z funkcji rsort().

Przykład 2. Przykład użycia usort() do sortowania wielowymiarowych tablic

function cmp ($a, $b) {
    return strcmp($a["owoc"], $b["owoc"]);
} 

$owocs[0]["owoc"] = "cytryny";
$owocs[1]["owoc"] = "jabłka";
$owocs[2]["owoc"] = "winogrona";

usort($owocs, "cmp"); 

while (list ($key, $value) = each ($owocs)) {
    echo "\$owocs[$key]: " . $value["owoc"] . "\n";
}

Sortując tablicę wielowymiarową, $a i $b zawierają referencję do pierwszego indeksu tablicy.

Ten przykład wyświetli:

$fruits[0]: cytryny
$fruits[1]: jabłka
$fruits[2]: winogrona

Przykład 3. Przykład użycia usort() używając funkcji składowej obiektu

class TestObj {
    var $name;
     
    function TestObj($name)
    {
        $this->name = $name;
    }
    
    /* Statyczna funkcja porównująca */
    function cmp_obj($a, $b) 
    {
        $al = strtolower($a->name);
        $bl = strtolower($b->name);
        if ($al == $bl) return 0;
        return ($al > $bl) ? +1 : -1;
    }
}

$a[] = new TestObj("c");
$a[] = new TestObj("b");
$a[] = new TestObj("d");

uasort($a, array ("TestObj", "cmp_obj"));

foreach ($a as $item) {
    print $item->name."\n";
}

Ten przykład wyświetli:

b
c
d

Ostrze¿enie

Używana do sortowania funkcja quicksort w niektórych bibliotekach C (jak na przykład na systemach Solaris) może spowodować zawieszanie się PHP jeśli funkcja porównująca zwraca niespójne wartości.

Patrz także uasort(), uksort(), sort(), asort(), arsort(),ksort(), natsort() i rsort().

III. Aspell [przestarzałe]

Funkcje aspell() pozwalają na sprawdzanie pisowni i proponowanie poprawek.

Notatka: aspell działa wyłącznie z bardzo starą (do .27.* lub podobną) wersją biblioteki aspell. Zarówno ten moduł jak i te wersje biblioteki aspell nie są już obsługiwane. Jeśli chcesz skorzystać z mechanizmów sprawdzania pisowni dostępnych w php, użyj funkcji pspell. Funkcje te wykorzystują bibliotekę pspell i działają z nowszymi wersjami aspell.

Bibliotekę aspell można pobrać z: http://aspell.sourceforge.net/.

Spis treści
aspell_new -- Ładuje nowy słownik [przestarzałe]
aspell_check -- Sprawdź słowo [przestarzałe]
aspell_check_raw --  Sprawdza słowo bez zmieniania wielkości liter i bez trymowania [przestarzałe]
aspell_suggest -- Proponuje pisownię słowa [przestarzałe]

aspell_new

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

aspell_new -- Ładuje nowy słownik [przestarzałe]

Opis

int aspell_new ( string główny [, string użytkownika])

aspell_new() otwiera słownik i zwraca uchwyt do niego, używany w innych funkcjach aspell. W razie błędu zwraca FALSE.

Przykład 1. aspell_new()

$aspell_link = aspell_new("english");

aspell_check

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

aspell_check -- Sprawdź słowo [przestarzałe]

Opis

bool aspell_check ( int słownik, string słowo)

aspell_check() sprawdza pisownię słowa i zwraca TRUE jeśli jest poprawna lub FALSE jeśli jest błędna.

Przykład 1. aspell_check()

$aspell_link = aspell_new("english");

if (aspell_check($aspell_link, "testt")) {
    echo "Pisownia poprawna";
} else {
    echo "Zła pisownia";
}

aspell_check_raw

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

aspell_check_raw --  Sprawdza słowo bez zmieniania wielkości liter i bez trymowania [przestarzałe]

Opis

bool aspell_check_raw ( int słownik, string słowo)

aspell_check_raw() sprawdza pisownię słowa bez zmieniania wielkości liter oraz bez próby trymowania go w żaden sposób i zwraca TRUE jeśli pisownia jest poprawna lub FALSE, jeśli niepoprawna.

Przykład 1. aspell_check_raw()

$aspell_link = aspell_new("english");

if (aspell_check_raw($aspell_link, "test")) {
    echo "Pisownia poprawna";
} else {
    echo "Zła pisownia";
}

aspell_suggest

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

aspell_suggest -- Proponuje pisownię słowa [przestarzałe]

Opis

array aspell_suggest ( int słownik, string słowo)

aspell_suggest() zwraca tablicę możliwych pisowni podanego słowa.

Przykład 1. aspell_suggest()

$aspell_link = aspell_new("english");

if (!aspell_check($aspell_link, "test")) {
    $suggestions = aspell_suggest($aspell_link, "test");

    foreach ($suggestions as $suggestion) {
        echo "Możliwe pisownie: $suggestion<br>\n"; 
    }
}

IV. BCMath Operacje arytmetyczne na liczbach o dużej precyzji

Dla potrzeb obliczeń arytmetycznych o dużej precyzji, PHP oferuje Kalkulator Binarny (ang. Binary Calculator). Kalkulator Binarny operuje na liczbach dowolnej wielkości i precyzji, zapisanych jako typ string.

W PHP 4 poniższe funkcje są dostępne tylko, jeśli PHP zostało skonfigurowane z --enable-bcmath. W PHP 3 poniższe funkcje są dostępne tylko, jeśli PHP nie zostało skonfigurowane z --disable-bcmath.

Notatka: Z powodu zmian w licencji, biblioteka BCMATH jest dystrybuowana osobno od standardowej źródłowej dystrybucji PHP. Archiwum spakowane tar-gz można pobrać z http://www.php.net/extra/number4.tar.gz. Aby uzyskać więcej informacji, przeczytaj plik README.BCMATH, znajdujący się w dystrybucji PHP.

Spis treści
bcadd -- Dodaje dwie liczby o dużej precyzji
bccomp -- Porównuje dwie liczby o dużej precyzji
bcdiv -- Dzieli dwie liczby o dużej precyzji
bcmod --  Dzieli w module liczbę o dużej precyzji
bcmul -- Mnoży dwie liczby o dużej precyzji
bcpow --  Podnosi liczbę o dużej precyzji do potęgi
bcscale --  Ustala domyślną precyzję obliczeń BCMath
bcsqrt --  Wyciąga pierwiastek kwadratowy z liczby o dużej precyzji
bcsub --  Odejmuje jedną liczbę o dużej precyzji od drugiej

bcadd

(PHP 3, PHP 4 >= 4.0.0)

bcadd -- Dodaje dwie liczby o dużej precyzji

Opis

string bcadd ( string lewy_operand, string prawy_operand [, int precyzja])

Dodaje lewy_operand do prawy_operand i zwraca ich sumę jako ciąg znaków. Opcjonalnego argumentu precyzja używa się do określenia ilości miejsc po przecinku dziesiętnym w wyniku.

Zobacz też bcsub().

bccomp

(PHP 3, PHP 4 >= 4.0.0)

bccomp -- Porównuje dwie liczby o dużej precyzji

Opis

int bccomp ( string lewy_operand, string prawy_operand [, int precyzja])

Porównuje lewy_operand z prawy_operand i zwraca rezultat w postaci liczby całkowitej. Opcjonalnego argumentu precyzja używa się do ustalenia ilości cyfr po przecinku, które będą wzięte pod uwagę przy porównywaniu. Funkcja zwraca wartość 0, jeśli operandy są sobie równe. Jeśli lewy_operand jest większy niż prawy_operand, to funkcja zwraca +1, zaś jeśli lewy_operand jest mniejszy niż prawy_operand, to funkcja zwraca -1.

bcdiv

(PHP 3, PHP 4 >= 4.0.0)

bcdiv -- Dzieli dwie liczby o dużej precyzji

Opis

string bcdiv ( string lewy_operand, string prawy_operand [, int precyzja])

Dzieli lewy_operand przez prawy_operand i zwraca wynik. Opcjonalnego argumentu precyzja używa się do określenia ilości miejsc po przecinku dziesiętnym w wyniku.

Zobacz też bcmul(), bcmod().

bcmod

(PHP 3, PHP 4 >= 4.0.0)

bcmod --  Dzieli w module liczbę o dużej precyzji

Opis

string bcmod ( string lewy_operand, string moduł)

Zwraca moduł (resztę z dzielenia) z liczby lewy_operand dzielonej przez moduł.

Zobacz też bcdiv().

bcmul

(PHP 3, PHP 4 >= 4.0.0)

bcmul -- Mnoży dwie liczby o dużej precyzji

Opis

string bcmul ( string lewy_operand, string prawy_operand [, int precyzja])

Mnoży lewy_operand przez prawy_operand i zwraca wynik. Opcjonalnego argumentu precyzja używa się do określenia ilości miejsc po przecinku dziesiętnym w wyniku.

Zobacz też bcdiv().

bcpow

(PHP 3, PHP 4 >= 4.0.0)

bcpow --  Podnosi liczbę o dużej precyzji do potęgi

Opis

string bcpow ( string x, string y [, int precyzja])

Podnosi liczbę x do potęgi y. Opcjonalnego argumentu precyzja używa się do określenia ilości miejsc po przecinku dziesiętnym w wyniku.

Zobacz też bcsqrt().

bcscale

(PHP 3, PHP 4 >= 4.0.0)

bcscale --  Ustala domyślną precyzję obliczeń BCMath

Opis

string bcscale ( int precyzja)

Za pomocą tej funkcji ustala się domyślną wartość argumentu precyzja dla wszystkich wywołań funkcji BCMath, w których argument ten nie jest jawnie podany.

bcsqrt

(PHP 3, PHP 4 >= 4.0.0)

bcsqrt --  Wyciąga pierwiastek kwadratowy z liczby o dużej precyzji

Opis

string bcsqrt ( string operand [, int precyzja])

Zwraca pierwiastek kwadratowy z liczby operand. Opcjonalnego argumentu precyzja używa się do określenia ilości miejsc po przecinku dziesiętnym w wyniku.

Zobacz też bcpow().

bcsub

(PHP 3, PHP 4 >= 4.0.0)

bcsub --  Odejmuje jedną liczbę o dużej precyzji od drugiej

Opis

string bcsub ( string lewy_operand, string prawy_operand [, int precyzja])

Odejmuje prawy_operand od lewy_operand i zwraca wynik jako ciąg znaków. Opcjonalnego argumentu precyzja używa się do określenia ilości miejsc po przecinku dziesiętnym w wyniku.

Zobacz też bcadd().

V. Bzip2 Compression Functions

This module uses the functions of the bzip2 library by Julian Seward to transparently read and write bzip2 (.bz2) compressed files.

Bzip2 support in PHP is not enabled by default. You will need to use the --with-bz2 configuration option when compiling PHP to enable bzip2 support. This module requires bzip2/libbzip2 version >= 1.0.x.


Small code example

This example opens a temporary file and writes a test string to it, then prints out the contents of the file.

Przykład 1. Small bzip2 Example

<?php

$filename = "/tmp/testfile.bz2";
$str = "This is a test string.\n";

// open file for writing
$bz = bzopen($filename, "w");

// write string to file
bzwrite($bz, $str);

// close file
bzclose($bz);

// open file for reading
$bz = bzopen($filename, "r");

// read 10 characters
print bzread($bz, 10);

// output until end of the file (or the next 1024 char) and close it.  
print bzread($bz);

bzclose($bz);

?>
Spis treści
bzclose -- Close a bzip2 file pointer
bzcompress -- Compress a string into bzip2 encoded data
bzdecompress -- Decompresses bzip2 encoded data
bzerrno -- Returns a bzip2 error number
bzerror -- Returns the bzip2 error number and error string in an array
bzerrstr -- Returns a bzip2 error string
bzflush -- Force a write of all buffered data
bzopen -- Open a bzip2 compressed file
bzread -- Binary safe bzip2 file read
bzwrite -- Binary safe bzip2 file write

bzclose

(PHP 4 >= 4.0.4)

bzclose -- Close a bzip2 file pointer

Description

int bzclose ( int bz)

Closes the bzip2 file referenced by the pointer bz.

Returns TRUE on success and FALSE on failure.

The file pointer must be valid, and must point to a file successfully opened by bzopen().

See also bzopen().

bzcompress

(PHP 4 >= 4.0.4)

bzcompress -- Compress a string into bzip2 encoded data

Description

string bzcompress ( string source [, int blocksize [, int workfactor]])

bzcompress() compresses the source string and returns it as bzip2 encoded data.

The optional parameter blocksize specifies the blocksize used during compression and should be a number from 1 to 9 with 9 giving the best compression, but using more resources to do so. blocksize defaults to 4.

The optional parameter workfactor controls how the compression phase behaves when presented with worst case, highly repetitive, input data. The value can be between 0 and 250 with 0 being a special case and 30 being the default value. Regardless of the workfactor, the generated output is the same.

Przykład 1. bzcompress() Example

<?php
$str = "sample data";
$bzstr = bzcompress($str, 9);
print( $bzstr );
?>

See also bzdecompress().

bzdecompress

(PHP 4 >= 4.0.4)

bzdecompress -- Decompresses bzip2 encoded data

Description

string bzdecompress ( string source [, int small])

bzdecompress() decompresses the source string containing bzip2 encoded data and returns it. If the optional parameter small is TRUE, an alternative decompression algorithm will be used which uses less memory (the maximum memory requirement drops to around 2300K) but works at roughly half the speed. See the bzip2 documentation for more information about this feature.

Przykład 1. bzdecompress()

<?php
$start_str = "This is not an honest face?";
$bzstr = bzcompress($start_str);

print( "Compressed String: " );
print( $bzstr );
print( "\n<br>\n" );

$str = bzdecompress($bzstr);
print( "Decompressed String: " );
print( $str );
print( "\n<br>\n" );
?>

See also bzcompress().

bzerrno

(PHP 4 >= 4.0.4)

bzerrno -- Returns a bzip2 error number

Description

int bzerrno ( int bz)

Returns the error number of any bzip2 error returned by the file pointer bz.

See also bzerror() and bzerrstr().

bzerror

(PHP 4 >= 4.0.4)

bzerror -- Returns the bzip2 error number and error string in an array

Description

array bzerror ( int bz)

Returns the error number and error string, in an associative array, of any bzip2 error returned by the file pointer bz.

Przykład 1. bzerror() Example

<?php
$error = bzerror($bz);

echo $error["errno"];
echo $error["errstr"];
?>

See also bzerrno() and bzerrstr().

bzerrstr

(PHP 4 >= 4.0.4)

bzerrstr -- Returns a bzip2 error string

Description

string bzerrstr ( int bz)

Returns the error string of any bzip2 error returned by the file pointer bz.

See also bzerrno() and bzerror().

bzflush

(PHP 4 >= 4.0.4)

bzflush -- Force a write of all buffered data

Description

int bzflush ( int bz)

Forces a write of all buffered bzip2 data for the file pointer bz.

Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.

See also bzread() and bzwrite().

bzopen

(PHP 4 >= 4.0.4)

bzopen -- Open a bzip2 compressed file

Description

int bzopen ( string filename, string mode)

Opens a bzip2 (.bz2) file for reading or writing. filename is the name of the file to open. mode is similar to the fopen() function (`r' for read, `w' for write, etc.).

If the open fails, the function returns FALSE, otherwise it returns a pointer to the newly opened file.

Przykład 1. bzopen() Example

<?php
$bz = bzopen("/tmp/foo.bz2", "r");
$decompressed_file = bzread($bz, filesize("/tmp/foo.bz2"));
bzclose($bz);

print( "The contents of /tmp/foo.bz2 are: " );
print( "\n<br>\n" );
print( $decompressed_file );
?>

See also bzclose().

bzread

(PHP 4 >= 4.0.4)

bzread -- Binary safe bzip2 file read

Description

string bzread ( int bz [, int length])

bzread() reads up to length bytes from the bzip2 file pointer referenced by bz. Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first. If the optional parameter length is not specified, bzread() will read 1024 (uncompressed) bytes at a time.

Przykład 1. bzread() Example

<?php
$bz = bzopen("/tmp/foo.bz2", "r");
$str = bzread($bz, 2048);
print( $str );
?>

See also bzwrite() and bzopen().

bzwrite

(PHP 4 >= 4.0.4)

bzwrite -- Binary safe bzip2 file write

Description

int bzwrite ( int bz, string data [, int length])

bzwrite() writes the contents of the string data to the bzip2 file stream pointed to by bz. If the optional length argument is given, writing will stop after length (uncompressed) bytes have been written or the end of string is reached, whichever comes first.

Przykład 1. bzwrite() Example

<?php
$str = "uncompressed data";
$bz = bzopen("/tmp/foo.bz2", "w");
bzwrite($bz, $str, strlen($str));
bzclose($bz);
?>

See also bzread() and bzopen().

VI. Calendar functions

Introduction

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 way earlier than any date most people would need to track (somewhere around 4000bc). 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 calendar systems visit http://genealogy.org/~scottlee/cal-overview.html. Excerpts from this page are included in these instructions, and are in quotes.


Installation

To get these functions to work, you have to compile PHP with --enable-calendar.

Spis treści
JDToGregorian -- Converts Julian Day Count to Gregorian date
GregorianToJD --  Converts a Gregorian date to Julian Day Count
JDToJulian --  Converts a Julian Day Count to a Julian Calendar Date
JulianToJD --  Converts a Julian Calendar date to Julian Day Count
JDToJewish --  Converts a Julian Day Count to the Jewish Calendar
JewishToJD --  Converts a date in the Jewish Calendar to Julian Day Count
JDToFrench --  Converts a Julian Day Count to the French Republican Calendar
FrenchToJD --  Converts a date from the French Republican Calendar to a Julian Day Count
JDMonthName -- Returns a month name
JDDayOfWeek -- Returns the day of the week
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
unixtojd -- Convert UNIX timestamp to Julian Day
jdtounix -- Convert Julian Day to UNIX timestamp
cal_days_in_month -- Return the number of days in a month for a given year and calendar
cal_to_jd -- Converts from a supported calendar to Julian Day Count
cal_from_jd -- Converts from Julian Day Count to a supported calendar and return extended information
cal_info -- Returns information about a particular calendar

JDToGregorian

(PHP 3, PHP 4 >= 4.0.0)

JDToGregorian -- Converts Julian Day Count to Gregorian date

Description

string jdtogregorian ( int julianday)

Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year".

GregorianToJD

(PHP 3, PHP 4 >= 4.0.0)

GregorianToJD --  Converts a Gregorian date to Julian Day Count

Description

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.

Przykład 1. Calendar functions

<?php
$jd = GregorianToJD (10,11,1970);
echo "$jd\n";
$gregorian = JDToGregorian ($jd);
echo "$gregorian\n";
?>

JDToJulian

(PHP 3, PHP 4 >= 4.0.0)

JDToJulian --  Converts a Julian Day Count to a Julian Calendar Date

Description

string jdtojulian ( int julianday)

Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year".

JulianToJD

(PHP 3, PHP 4 >= 4.0.0)

JulianToJD --  Converts a Julian Calendar date to Julian Day Count

Description

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.

JDToJewish

(PHP 3, PHP 4 >= 4.0.0)

JDToJewish --  Converts a Julian Day Count to the Jewish Calendar

Description

string jdtojewish ( int julianday)

Converts a Julian Day Count the the Jewish Calendar.

JewishToJD

(PHP 3, PHP 4 >= 4.0.0)

JewishToJD --  Converts a date in the Jewish Calendar to Julian Day Count

Description

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.

JDToFrench

(PHP 3, PHP 4 >= 4.0.0)

JDToFrench --  Converts a Julian Day Count to the French Republican Calendar

Description

string jdtofrench ( int juliandaycount)

Converts a Julian Day Count to the French Republican Calendar.

FrenchToJD

(PHP 3, PHP 4 >= 4.0.0)

FrenchToJD --  Converts a date from the French Republican Calendar to a Julian Day Count

Description

int frenchtojd ( int month, int day, int year)

Converts a date from the French Republican Calendar to a Julian Day Count.

These routines only convert dates in years 1 through 14 (Gregorian dates 22 September 1792 through 22 September 1806). This more than covers the period when the calendar was in use.

JDMonthName

(PHP 3, PHP 4 >= 4.0.0)

JDMonthName -- Returns a month name

Description

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.

Tabela 1. Calendar modes

ModeMeaningValues
0Gregorian - abbreviatedJan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
1GregorianJanuary, February, March, April, May, June, July, August, September, October, November, December
2Julian - abbreviatedJan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
3JulianJanuary, February, March, April, May, June, July, August, September, October, November, December
4JewishTishri, Heshvan, Kislev, Tevet, Shevat, AdarI, AdarII, Nisan, Iyyar, Sivan, Tammuz, Av, Elul
5French RepublicanVendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra

JDDayOfWeek

(PHP 3, PHP 4 >= 4.0.0)

JDDayOfWeek -- Returns the day of the week

Description

mixed jddayofweek ( int julianday, int mode)

Returns the day of the week. Can return a string or an integer depending on the mode.

Tabela 1. Calendar week modes

ModeMeaning
0 Returns the day number as an int (0=sunday, 1=monday, etc)
1 Returns string containing the day of week (english-gregorian)
2 Returns a string containing the abbreviated day of week (english-gregorian)

easter_date

(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)

easter_date --  Get UNIX timestamp for midnight on Easter of a given year

Description

int easter_date ( int year)

Returns the UNIX timestamp corresponding to midnight on Easter of the given year. If no year is specified, the current year is assumed.

Warning: This function will generate a warning if the year is outside of the range for UNIX timestamps (i.e. before 1970 or after 2037).

Przykład 1. easter_date() example

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" */

The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.

(The code is based on a C program by Simon Kershaw, <webmaster@ely.anglican.org>)

See easter_days() for calculating Easter before 1970 or after 2037.

easter_days

(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)

easter_days --  Get number of days after March 21 on which Easter falls for a given year

Description

int easter_days ( int year)

Returns the number of days after March 21 on which Easter falls for a given year. If no year is specified, the current year is assumed.

This function can be used instead of easter_date() to calculate Easter for years which fall outside the range of UNIX timestamps (i.e. before 1970 or after 2037).

Przykład 1. easter_days() example

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  */

The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.

(The code is based on a C program by Simon Kershaw, <webmaster@ely.anglican.org>)

See also easter_date().

unixtojd

(PHP 4 >= 4.0.0)

unixtojd -- Convert UNIX timestamp to Julian Day

Description

int unixtojd ( [int timestamp])

Return the Julian Day for a UNIX timestamp (seconds since 1.1.1970), or for the current day if no timestamp is given.

See also jdtounix().

jdtounix

(PHP 4 >= 4.0.0)

jdtounix -- Convert Julian Day to UNIX timestamp

Description

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 )

See also unixtojd().

cal_days_in_month

(PHP 4 >= 4.1.0)

cal_days_in_month -- Return the number of days in a month for a given year and calendar

Description

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.

See also jdtounix().

cal_to_jd

(PHP 4 >= 4.1.0)

cal_to_jd -- Converts from a supported calendar to Julian Day Count

Description

int cal_to_jd ( int calendar, int month, int day, int year)

cal_from_jd

(PHP 4 >= 4.1.0)

cal_from_jd -- Converts from Julian Day Count to a supported calendar and return extended information

Description

array cal_from_jd ( int jd, int calendar)

cal_info

(PHP 4 >= 4.1.0)

cal_info -- Returns information about a particular calendar

Description

array cal_info ( int calendar)

VII. CCVS API Functions

These functions interface the CCVS API, allowing you to directly work with CCVS from your PHP scripts. CCVS is RedHat's solution to the "middle-man" in credit card processing. It lets you directly address the credit card clearing houses via your *nix box and a modem. Using the CCVS module for PHP, you can process credit cards directly through CCVS via your PHP Scripts. The following references will outline the process.

To enable CCVS Support in PHP, first verify your CCVS installation directory. You will then need to configure PHP with the --with-ccvs option. If you use this option without specifying the path to your CCVS installation, PHP Will attempt to look in the default CCVS Install location (/usr/local/ccvs). If CCVS is in a non-standard location, run configure with: --with-ccvs=$ccvs_path, where $ccvs_path is the path to your CCVS installation. Please note that CCVS support requires that $ccvs_path/lib and $ccvs_path/include exist, and include cv_api.h under the include directory and libccvs.a under the lib directory.

Additionally, a ccvsd process will need to be running for the configurations you intend to use in your PHP scripts. You will also need to make sure the PHP Processes are running under the same user as your CCVS was installed as (e.g. if you installed CCVS as user 'ccvs', your PHP processes must run as 'ccvs' as well.)

Additional information about CCVS can be found at http://www.redhat.com/products/ccvs.

This documentation section is being worked on. Until then, RedHat maintains slightly outdated but still useful documentation at http://www.redhat.com/products/ccvs/support/CCVS3.3docs/ProgPHP.html.

Update: CCVS has been discontinued by Red Hat and there are no plans to issue further keys or support contracts. Those looking for a replacement can consider MCVE by Main Street Softworks as a potential replacement. It is similar in design and has documented PHP support!

Spis treści
ccvs_init -- Initialize CCVS for use
ccvs_done -- Terminate CCVS engine and do cleanup work
ccvs_new -- Create a new, blank transaction
ccvs_add -- Add data to a transaction
ccvs_delete -- Delete a transaction
ccvs_auth --  Perform credit authorization test on a transaction
ccvs_return --  Transfer funds from the merchant to the credit card holder
ccvs_reverse --  Perform a full reversal on an already-processed authorization
ccvs_sale --  Transfer funds from the credit card holder to the merchant
ccvs_void --  Perform a full reversal on a completed transaction
ccvs_status -- Check the status of an invoice
ccvs_count --  Find out how many transactions of a given type are stored in the system
ccvs_lookup --  Look up an item of a particular type in the database #
ccvs_report -- Return the status of the background communication process
ccvs_command --  Performs a command which is peculiar to a single protocol, and thus is not available in the general CCVS API
ccvs_textvalue -- Get text return value for previous function call

ccvs_init

(PHP 4 >= 4.0.2)

ccvs_init -- Initialize CCVS for use

Description

string ccvs_init ( string name)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ccvs_done

(PHP 4 >= 4.0.2)

ccvs_done -- Terminate CCVS engine and do cleanup work

Description

string ccvs_done ( string sess)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ccvs_new

(PHP 4 >= 4.0.2)

ccvs_new -- Create a new, blank transaction

Description

string ccvs_new ( string session, string invoice)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ccvs_add

(PHP 4 >= 4.0.2)

ccvs_add -- Add data to a transaction

Description

string ccvs_add ( string session, string invoice, string argtype, string argval)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ccvs_delete

(PHP 4 >= 4.0.2)

ccvs_delete -- Delete a transaction

Description

string ccvs_delete ( string session, string invoice)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ccvs_auth

(PHP 4 >= 4.0.2)

ccvs_auth --  Perform credit authorization test on a transaction

Description

string ccvs_auth ( string session, string invoice)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ccvs_return

(PHP 4 >= 4.0.2)

ccvs_return --  Transfer funds from the merchant to the credit card holder

Description

string ccvs_return ( string session, string invoice)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ccvs_reverse

(PHP 4 >= 4.0.2)

ccvs_reverse --  Perform a full reversal on an already-processed authorization

Description

string ccvs_reverse ( string session, string invoice)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ccvs_sale

(PHP 4 >= 4.0.2)

ccvs_sale --  Transfer funds from the credit card holder to the merchant

Description

string ccvs_sale ( string session, string invoice)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ccvs_void

(PHP 4 >= 4.0.2)

ccvs_void --  Perform a full reversal on a completed transaction

Description

string ccvs_void ( string session, string invoice)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ccvs_status

(PHP 4 >= 4.0.2)

ccvs_status -- Check the status of an invoice

Description

string ccvs_status ( string session, string invoice)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ccvs_count

(PHP 4 >= 4.0.2)

ccvs_count --  Find out how many transactions of a given type are stored in the system

Description

int ccvs_count ( string session, string type)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ccvs_lookup

(PHP 4 >= 4.0.2)

ccvs_lookup --  Look up an item of a particular type in the database #

Description

string ccvs_lookup ( string session, string invoice, int inum)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ccvs_report

(PHP 4 >= 4.0.2)

ccvs_report -- Return the status of the background communication process

Description

string ccvs_report ( string session, string type)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ccvs_command

(PHP 4 >= 4.0.2)

ccvs_command --  Performs a command which is peculiar to a single protocol, and thus is not available in the general CCVS API

Description

string ccvs_command ( string session, string type, string argval)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ccvs_textvalue

(PHP 4 >= 4.0.2)

ccvs_textvalue -- Get text return value for previous function call

Description

string ccvs_textvalue ( string session)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

VIII. COM support functions for Windows

COM is a technology which allows the reuse of code written in any language (by any language) using a standard calling convention and hiding behind APIs the implementation details such as what machine the Component is stored on and the executable which houses it. It can be thought of as a super Remote Procedure Call (RPC) mechanism with some basic object roots. It separates implementation from interface.

COM encourages versioning, separation of implementation from interface and hiding the implementation details such as executable location and the language it was written in.

COM functions are only available on the Windows version of PHP.

For further information on COM read the COM specification or perhaps take a look at Don Box's Yet Another COM Library (YACL)

Spis treści
COM -- COM class
VARIANT -- VARIANT class
com_load --  Creates a new reference to a COM component
com_invoke --  Calls a COM component's method.
com_propget --  Gets the value of a COM Component's property
com_get --  Gets the value of a COM Component's property
com_propput --  Assigns a value to a COM component's property
com_propset --  Assigns a value to a COM component's property
com_set --  Assigns a value to a COM component's property
com_addref --  Increases the components reference counter.
com_release --  Decreases the components reference counter.
com_isenum -- Grabs an IEnumVariant
com_load_typelib -- Loads a Typelib

COM

(unknown)

COM -- COM class

Synopsis

$obj = new COM("server.object")

Description

The COM class provides a framework to integrate (D)COM components into your php scripts.

Methods

string COM::COM ( string module_name [, string server_name [, int codepage]])

COM class constructor. Parameters:

module_name

name or class-id of the requested component.

server_name

name of the DCOM server from which the component should be fetched. If NULL, localhost is assumed. To allow DCOM com.allow_dcom has to be set to TRUE in php.ini.

codepage

specifies the codepage that is used to convert php-strings to unicode-strings and vice versa. Possible values are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 and CP_UTF8.

Przykład 1. COM example (1)

// starting word
$word = new COM("word.application") or die("Unable to instanciate Word");
print "Loaded Word, version {$word->Version}\n";

//bring it to front
$word->Visible = 1;

//open an empty document
$word->Documents->Add();

//do some weird stuff
$word->Selection->TypeText("This is a test...");
$word->Documents[1]->SaveAs("Useless test.doc");

//closing word
$word->Quit();

//free the object
$word->Release();
$word = null;

Przykład 2. COM example (2)

$conn = new COM("ADODB.Connection") or die("Cannot start ADO");
$conn->Open("Provider=SQLOLEDB; Data Source=localhost;
Initial Catalog=database; User ID=user; Password=password");

$rs = $conn->Execute("SELECT * FROM sometable");    // Recordset

$num_columns = $rs->Fields->Count();
echo $num_columns . "\n";

for ($i=0; $i < $num_columns; $i++)
{
    $fld[$i] = $rs->Fields($i);
}

$rowcount = 0;
while (!$rs->EOF)
{
    for ($i=0; $i < $num_columns; $i++)
    {
        echo $fld[$i]->value . "\t";
    }
    echo "\n";
    $rowcount++;            // increments rowcount
    $rs->MoveNext();
}

$rs->Close();
$conn->Close();

$rs->Release();
$conn->Release();

$rs = null;
$conn = null;

VARIANT

(unknown)

VARIANT -- VARIANT class

Synopsis

$vVar = new VARIANT($var)

Description

A simple container to wrap variables into VARIANT structures.

Methods

string VARIANT::VARIANT ( [mixed value [, int type [, int codepage]]])

VARIANT class constructor. Parameters:

value

initial value. if omitted an VT_EMPTY object is created.

type

specifies the content type of the VARIANT object. Possible values are VT_UI1, VT_UI2, VT_UI4, VT_I1, VT_I2, VT_I4, VT_R4, VT_R8, VT_INT, VT_UINT, VT_BOOL, VT_ERROR, VT_CY, VT_DATE, VT_BSTR, VT_DECIMAL, VT_UNKNOWN, VT_DISPATCH and VT_VARIANT. These values are mutual exclusive, but they can be combined with VT_BYREF to specify being a value. If omitted, the type of value is used. Consult the msdn library for additional information.

codepage

specifies the codepage that is used to convert php-strings to unicode-strings and vice versa. Possible values are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 and CP_UTF8.

com_load

(PHP 3>= 3.0.3)

com_load --  Creates a new reference to a COM component

Description

string com_load ( string module name [, string server name [, int codepage]])

com_load() creates a new COM component and returns a reference to it. Returns FALSE on failure. Possible values for codepage are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 and CP_UTF8.

com_invoke

(PHP 3>= 3.0.3)

com_invoke --  Calls a COM component's method.

Description

mixed com_invoke ( resource com_object, string function_name [, mixed function parameters, ...])

com_invoke() invokes a method of the COM component referenced by com_object. Returns FALSE on error, returns the function_name's return value on success.

com_propget

(PHP 3>= 3.0.3, PHP 4 >= 4.0.5)

com_propget --  Gets the value of a COM Component's property

Description

mixed com_propget ( resource com_object, string property)

This function is an alias for com_get().

com_get

(PHP 3>= 3.0.3, PHP 4 >= 4.0.5)

com_get --  Gets the value of a COM Component's property

Description

mixed com_get ( resource com_object, string property)

Returns the value of the property of the COM component referenced by com_object. Returns FALSE on error.

com_propput

(PHP 3>= 3.0.3, PHP 4 >= 4.0.5)

com_propput --  Assigns a value to a COM component's property

Description

void com_propput ( resource com_object, string property, mixed value)

This function is an alias for com_set().

com_propset

(PHP 3>= 3.0.3, PHP 4 >= 4.0.5)

com_propset --  Assigns a value to a COM component's property

Description

void com_propset ( resource com_object, string property, mixed value)

This function is an alias for com_set().

com_set

(PHP 3>= 3.0.3, PHP 4 >= 4.0.5)

com_set --  Assigns a value to a COM component's property

Description

void com_set ( resource com_object, string property, mixed value)

Sets the value of the property of the COM component referenced by com_object. Returns the newly set value if succeeded, FALSE on error.

com_addref

(PHP 4 >= 4.1.0)

com_addref --  Increases the components reference counter.

Description

void com_addref ( void)

Increases the components reference counter.

com_release

(PHP 4 >= 4.1.0)

com_release --  Decreases the components reference counter.

Description

void com_release ( void)

Decreases the components reference counter.

com_isenum

(PHP 4 >= 4.1.0)

com_isenum -- Grabs an IEnumVariant

Description

void com_isenum ( object com_module)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

com_load_typelib

(PHP 4 >= 4.1.0)

com_load_typelib -- Loads a Typelib

Description

void com_load_typelib ( string typelib_name [, int case_insensitive])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

IX. Class/Object Functions

Introduction

About

These functions allow you to obtain information about classes and instance objects. You can obtain the name of the class to which a object belongs, as well as its member properties and methods. Using these functions, you can find out not only the class membership of an object, but also its parentage (i.e. what class is the object class extending).


An example of use

In this example, we first define a base class and an extension of the class. The base class describes a general vegetable, whether it is edible or not and what is its color. The subclass Spinach adds a method to cook it and another to find out if it is cooked.

Przykład 1. classes.inc

<?php

// base class with member properties and methods
class Vegetable {

    var $edible;
    var $color;

    function Vegetable( $edible, $color="green" ) {
        $this->edible = $edible;
        $this->color = $color;
    }

    function is_edible() {
        return $this->edible;
    }

    function what_color() {
        return $this->color;
    }
    
} // end of class Vegetable


// extends the base class
class Spinach extends Vegetable {

    var $cooked = false;

    function Spinach() {
        $this->Vegetable( true, "green" );
    }

    function cook_it() {
        $this->cooked = true;
    }

    function is_cooked() {
        return $this->cooked;
    }
    
} // end of class Spinach

?>

We then instantiate 2 objects from these classes and print out information about them, including their class parentage. We also define some utility functions, mainly to have a nice printout of the variables.

Przykład 2. test_script.php

<pre>
<?php

include "classes.inc";

// utility functions

function print_vars($obj) {
    $arr = get_object_vars($obj);
    while (list($prop, $val) = each($arr))
        echo "\t$prop = $val\n";
}

function print_methods($obj) {
    $arr = get_class_methods(get_class($obj));
    foreach ($arr as $method)
        echo "\tfunction $method()\n";
}

function class_parentage($obj, $class) {
    global $$obj;
    if (is_subclass_of($$obj, $class)) {
        echo "Object $obj belongs to class ".get_class($$obj);
        echo " a subclass of $class\n";
    } else {
        echo "Object $obj does not belong to a subclass of $class\n";
    }
}

// instantiate 2 objects

$veggie = new Vegetable(true,"blue");
$leafy = new Spinach();

// print out information about objects
echo "veggie: CLASS ".get_class($veggie)."\n";
echo "leafy: CLASS ".get_class($leafy);
echo ", PARENT ".get_parent_class($leafy)."\n";

// show veggie properties
echo "\nveggie: Properties\n";
print_vars($veggie);

// and leafy methods
echo "\nleafy: Methods\n";
print_methods($leafy);

echo "\nParentage:\n";
class_parentage("leafy", "Spinach");
class_parentage("leafy", "Vegetable");
?>
</pre>

One important thing to note in the example above is that the object $leafy is an instance of the class Spinach which is a subclass of Vegetable, therefore the last part of the script above will output:

[...]
Parentage:
Object leafy does not belong to a subclass of Spinach
Object leafy belongs to class spinach a subclass of Vegetable

Spis treści
call_user_method_array --  Call a user method given with an array of parameters
call_user_method --  Call a user method on an specific object
class_exists -- Checks if the class has been defined
get_class -- Returns the name of the class of an object
get_class_methods -- Returns an array of class methods' names
get_class_vars --  Returns an array of default properties of the class
get_declared_classes -- Returns an array with the name of the defined classes
get_object_vars -- Returns an associative array of object properties
get_parent_class -- Retrieves the parent class name for object or class
is_a --  Returns true if the object is of this class or has this class as one of its parents
is_subclass_of --  Returns true if the object has this class as one of its parents
method_exists -- Checks if the class method exists

call_user_method_array

(PHP 4 >= 4.0.5)

call_user_method_array --  Call a user method given with an array of parameters

Description

mixed call_user_method_array ( string method_name, object obj [, array paramarr])

Calls a the method referred by method_name from the user defined obj object, using the parameters in paramarr.

See also: call_user_func_array(), call_user_func(), call_user_method().

Notatka: This function was added to the CVS code after release of PHP 4.0.4pl1

call_user_method

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

call_user_method --  Call a user method on an specific object

Description

mixed call_user_method ( string method_name, object obj [, mixed parameter [, mixed ...]])

Calls a the method referred by method_name from the user defined obj object. An example of usage is below, where we define a class, instantiate an object and use call_user_method() to call indirectly its print_info method.

<?php
class Country {
    var $NAME;
    var $TLD;
    
    function Country($name, $tld) {
        $this->NAME = $name;
        $this->TLD = $tld;
    }

    function print_info($prestr="") {
        echo $prestr."Country: ".$this->NAME."\n";
        echo $prestr."Top Level Domain: ".$this->TLD."\n";
    }
}

$cntry = new Country("Peru","pe");

echo "* Calling the object method directly\n";
$cntry->print_info();

echo "\n* Calling the same method indirectly\n";
call_user_method ("print_info", $cntry, "\t");
?>

See also call_user_func_array(), call_user_func(), call_user_method_array().

class_exists

(PHP 4 >= 4.0.0)

class_exists -- Checks if the class has been defined

Description

bool class_exists ( string class_name)

This function returns TRUE if the class given by class_name has been defined, FALSE otherwise.

get_class

(PHP 4 >= 4.0.0)

get_class -- Returns the name of the class of an object

Description

string get_class ( object obj)

This function returns the name of the class of which the object obj is an instance. Returns FALSE if obj is not an object.

Notatka: get_class() returns a user defined class name in lowercase. A class defined in a PHP extension is returned in its original notation.

See also get_parent_class(), get_type(), and is_subclass_of()

get_class_methods

(PHP 4 >= 4.0.0)

get_class_methods -- Returns an array of class methods' names

Description

array get_class_methods ( string class_name)

This function returns an array of method names defined for the class specified by class_name.

Notatka: As of PHP 4.0.6, you can specify the object itself instead of class_name. For example:

$class_methods = get_class_methods($my_class);

Przykład 1. get_class_methods() example

<?php

class myclass {
    // constructor
    function myclass() {
        return(true);
    }
    
    // method 1
    function myfunc1() {
        return(true);
    }

    // method 2
    function myfunc2() {
        return(true);
    }
}

$my_class = new myclass();

$class_methods = get_class_methods(get_class($my_class));

foreach ($class_methods as $method_name) {
    echo "$method_name\n";
}

?>

Will produce:

myclass
myfunc1
myfunc2

See also get_class_vars(), get_object_vars()

get_class_vars

(PHP 4 >= 4.0.0)

get_class_vars --  Returns an array of default properties of the class

Description

array get_class_vars ( string class_name)

This function will return an associative array of default properties of the class. The resulting array elements are in the form of varname => value.

Notatka: Uninitialized class variables will not be reported by get_class_vars().

Przykład 1. get_class_vars() example

<?php

class myclass {

    var $var1; // this has no default value...
    var $var2 = "xyz";
    var $var3 = 100;
    
    // constructor
    function myclass() {
        return(true);
    }

}

$my_class = new myclass();

$class_vars = get_class_vars(get_class($my_class));

foreach ($class_vars as $name => $value) {
    echo "$name : $value\n";
}

?>

Will produce:

var2 : xyz
var3 : 100

See also get_class_methods(), get_object_vars()

get_declared_classes

(PHP 4 >= 4.0.0)

get_declared_classes -- Returns an array with the name of the defined classes

Description

array get_declared_classes ( void)

This function returns an array of the names of the declared classes in the current script.

Notatka: In PHP 4.0.1pl2, three extra classes are returned at the beginning of the array: stdClass (defined in Zend/zend.c), OverloadedTestClass (defined in ext/standard/basic_functions.c) and Directory (defined in ext/standard/dir.c).

Also note that depending on what libraries you have compiled into PHP, additional classes could be present.

get_object_vars

(PHP 4 >= 4.0.0)

get_object_vars -- Returns an associative array of object properties

Description

array get_object_vars ( object obj)

This function returns an associative array of defined object properties for the specified object obj. If variables declared in the class of which the obj is an instance, have not been assigned a value, those will not be returned in the array.

Przykład 1. Use of get_object_vars()

<?php
class Point2D {
    var $x, $y;
    var $label;

    function Point2D($x, $y) {
        $this->x = $x;
        $this->y = $y;
    }

    function setLabel($label) {
        $this->label = $label;
    }

    function getPoint() {
        return array("x" => $this->x,
                     "y" => $this->y,
                     "label" => $this->label);
    }
}

$p1 = new Point2D(1.233, 3.445);
print_r(get_object_vars($p1));
// "$label" is declared but not defined
// Array
// (
//     [x] => 1.233
//     [y] => 3.445
// )

$p1->setLabel("point #1");
print_r(get_object_vars($p1));
// Array
// (
//     [x] => 1.233
//     [y] => 3.445
//     [label] => point #1
// )

?>

See also get_class_methods(), get_class_vars()

get_parent_class

(PHP 4 >= 4.0.0)

get_parent_class -- Retrieves the parent class name for object or class

Description

string get_parent_class ( mixed obj)

If obj is an object, returns the name of the parent class of the class of which obj is an instance.

If obj is a string, returns the name of the parent class of the class with that name. This functionality was added in PHP 4.0.5.

See also get_class() and is_subclass_of()

is_a

(PHP 4 CVS only)

is_a --  Returns true if the object is of this class or has this class as one of its parents

Description

bool is_a ( object object, string class_name)

This function returns TRUE if the object is of this class or has this class as one of its parents, FALSE otherwise.

See also get_class(), get_parent_class() and is_subclass_of().

is_subclass_of

(PHP 4 >= 4.0.0)

is_subclass_of --  Returns true if the object has this class as one of its parents

Description

bool is_subclass_of ( object object, string class_name)

This function returns TRUE if the object object, belongs to a class which is a subclass of class_name, FALSE otherwise.

See also get_class(), get_parent_class() and is_a().

method_exists

(PHP 4 >= 4.0.0)

method_exists -- Checks if the class method exists

Description

bool method_exists ( object object, string method_name)

This function returns TRUE if the method given by method_name has been defined for the given object, FALSE otherwise.

X. ClibPDF functions

ClibPDF lets you create PDF documents with PHP. It is available for download from FastIO, but requires that you purchase a license for commercial use. ClibPDF functionality and API is similar to PDFlib.

This documentation should be read alongside the ClibPDF manual since it explains the library in much greater detail.

Many functions in the native ClibPDF and the PHP module, as well as in PDFlib, have the same name. All functions except for cpdf_open() take the handle for the document as their first parameter.

Currently this handle is not used internally since ClibPDF does not support the creation of several PDF documents at the same time. Actually, you should not even try it, the results are unpredictable. I can't oversee what the consequences in a multi threaded environment are. According to the author of ClibPDF this will change in one of the next releases (current version when this was written is 1.10). If you need this functionality use the pdflib module.

Notatka: The function cpdf_set_font() has changed since PHP 3 to support asian fonts. The encoding parameter is no longer an integer but a string.

A nice feature of ClibPDF (and PDFlib) is the ability to create the pdf document completely in memory without using temporary files. It also provides the ability to pass coordinates in a predefined unit length. (This feature can also be simulated by pdf_translate() when using the PDFlib. functions.)

Another nice feature of ClibPDF is the fact that any page can be modified at any time even if a new page has been already opened. The function cpdf_set_current_page() allows to leave the current page and presume modifying an other page.

Most of the functions are fairly easy to use. The most difficult part is probably creating a very simple PDF document at all. The following example should help you to get started. It creates a document with one page. The page contains the text "Times-Roman" in an outlined 30pt font. The text is underlined.

Przykład 1. Simple ClibPDF Example

<?php
$cpdf = cpdf_open(0);
cpdf_page_init($cpdf, 1, 0, 595, 842, 1.0);
cpdf_add_outline($cpdf, 0, 0, 0, 1, "Page 1");
cpdf_begin_text($cpdf);
cpdf_set_font($cpdf, "Times-Roman", 30, "WinAnsiEncoding");
cpdf_set_text_rendering($cpdf, 1);
cpdf_text($cpdf, "Times Roman outlined", 50, 750);
cpdf_end_text($cpdf);
cpdf_moveto($cpdf, 50, 740);
cpdf_lineto($cpdf, 330, 740);
cpdf_stroke($cpdf);
cpdf_finalize($cpdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($cpdf);
cpdf_close($cpdf);
?>

The pdflib distribution contains a more complex example which creates a series of pages with an analog clock. Here is that example converted into PHP using the ClibPDF extension:

Przykład 2. pdfclock example from pdflib 2.0 distribution

<?php
$radius = 200;
$margin = 20;
$pagecount = 40;

$pdf = cpdf_open(0);
cpdf_set_creator($pdf, "pdf_clock.php3");
cpdf_set_title($pdf, "Analog Clock");
  
while($pagecount-- > 0) {
  cpdf_page_init($pdf, $pagecount+1, 0, 2 * ($radius + $margin), 2 * ($radius + $margin), 1.0);
  
  cpdf_set_page_animation($pdf, 4, 0.5, 0, 0, 0);  /* wipe */
  
  cpdf_translate($pdf, $radius + $margin, $radius + $margin);
  cpdf_save($pdf);
  cpdf_setrgbcolor($pdf, 0.0, 0.0, 1.0);
  
  /* minute strokes */
  cpdf_setlinewidth($pdf, 2.0);
  for ($alpha = 0; $alpha &lt; 360; $alpha += 6)
    {
    cpdf_rotate($pdf, 6.0);
    cpdf_moveto($pdf, $radius, 0.0);
    cpdf_lineto($pdf, $radius-$margin/3, 0.0);
    cpdf_stroke($pdf);
    }
  
  cpdf_restore($pdf);
  cpdf_save($pdf);
 
  /* 5 minute strokes */
  cpdf_setlinewidth($pdf, 3.0);
  for ($alpha = 0; $alpha &lt; 360; $alpha += 30)
  {
    cpdf_rotate($pdf, 30.0);
    cpdf_moveto($pdf, $radius, 0.0);
    cpdf_lineto($pdf, $radius-$margin, 0.0);
    cpdf_stroke($pdf);
  }

  $ltime = getdate();

  /* draw hour hand */
  cpdf_save($pdf);
  cpdf_rotate($pdf, -(($ltime['minutes']/60.0) + $ltime['hours'] - 3.0) * 30.0);
  cpdf_moveto($pdf, -$radius/10, -$radius/20);
  cpdf_lineto($pdf, $radius/2, 0.0);
  cpdf_lineto($pdf, -$radius/10, $radius/20);
  cpdf_closepath($pdf);
  cpdf_fill($pdf);
  cpdf_restore($pdf);

  /* draw minute hand */
  cpdf_save($pdf);
  cpdf_rotate($pdf, -(($ltime['seconds']/60.0) + $ltime['minutes'] - 15.0) * 6.0);
  cpdf_moveto($pdf, -$radius/10, -$radius/20);
  cpdf_lineto($pdf, $radius * 0.8, 0.0);
  cpdf_lineto($pdf, -$radius/10, $radius/20);
  cpdf_closepath($pdf);
  cpdf_fill($pdf);
  cpdf_restore($pdf);

  /* draw second hand */
  cpdf_setrgbcolor($pdf, 1.0, 0.0, 0.0);
  cpdf_setlinewidth($pdf, 2);
  cpdf_save($pdf);
  cpdf_rotate($pdf, -(($ltime['seconds'] - 15.0) * 6.0));
  cpdf_moveto($pdf, -$radius/5, 0.0);
  cpdf_lineto($pdf, $radius, 0.0);
  cpdf_stroke($pdf);
  cpdf_restore($pdf);

  /* draw little circle at center */
  cpdf_circle($pdf, 0, 0, $radius/30);
  cpdf_fill($pdf);

  cpdf_restore($pdf);

  cpdf_finalize_page($pdf, $pagecount+1);
}

cpdf_finalize($pdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($pdf);
cpdf_close($pdf);
?>
Spis treści
cpdf_add_annotation -- Adds annotation
cpdf_add_outline -- Adds bookmark for current page
cpdf_arc -- Draws an arc
cpdf_begin_text -- Starts text section
cpdf_circle -- Draw a circle
cpdf_clip -- Clips to current path
cpdf_close -- Closes the pdf document
cpdf_closepath -- Close path
cpdf_closepath_fill_stroke -- Close, fill and stroke current path
cpdf_closepath_stroke -- Close path and draw line along path
cpdf_continue_text -- Output text in next line
cpdf_curveto -- Draws a curve
cpdf_end_text -- Ends text section
cpdf_fill -- Fill current path
cpdf_fill_stroke -- Fill and stroke current path
cpdf_finalize -- Ends document
cpdf_finalize_page -- Ends page
cpdf_global_set_document_limits -- Sets document limits for any pdf document
cpdf_import_jpeg -- Opens a JPEG image
cpdf_lineto -- Draws a line
cpdf_moveto -- Sets current point
cpdf_newpath -- Starts a new path
cpdf_open -- Opens a new pdf document
cpdf_output_buffer -- Outputs the pdf document in memory buffer
cpdf_page_init -- Starts new page
cpdf_place_inline_image -- Places an image on the page
cpdf_rect -- Draw a rectangle
cpdf_restore -- Restores formerly saved environment
cpdf_rlineto -- Draws a line
cpdf_rmoveto -- Sets current point
cpdf_rotate -- Sets rotation
cpdf_rotate_text --  Sets text rotation angle
cpdf_save -- Saves current environment
cpdf_save_to_file -- Writes the pdf document into a file
cpdf_scale -- Sets scaling
cpdf_set_char_spacing -- Sets character spacing
cpdf_set_creator -- Sets the creator field in the pdf document
cpdf_set_current_page -- Sets current page
cpdf_set_font -- Select the current font face and size
cpdf_set_horiz_scaling -- Sets horizontal scaling of text
cpdf_set_keywords -- Sets the keywords field of the pdf document
cpdf_set_leading -- Sets distance between text lines
cpdf_set_page_animation -- Sets duration between pages
cpdf_set_subject -- Sets the subject field of the pdf document
cpdf_set_text_matrix -- Sets the text matrix
cpdf_set_text_pos -- Sets text position
cpdf_set_text_rendering -- Determines how text is rendered
cpdf_set_text_rise -- Sets the text rise
cpdf_set_title -- Sets the title field of the pdf document
cpdf_set_word_spacing -- Sets spacing between words
cpdf_setdash -- Sets dash pattern
cpdf_setflat -- Sets flatness
cpdf_setgray -- Sets drawing and filling color to gray value
cpdf_setgray_fill -- Sets filling color to gray value
cpdf_setgray_stroke -- Sets drawing color to gray value
cpdf_setlinecap -- Sets linecap parameter
cpdf_setlinejoin -- Sets linejoin parameter
cpdf_setlinewidth -- Sets line width
cpdf_setmiterlimit -- Sets miter limit
cpdf_setrgbcolor -- Sets drawing and filling color to rgb color value
cpdf_setrgbcolor_fill -- Sets filling color to rgb color value
cpdf_setrgbcolor_stroke -- Sets drawing color to rgb color value
cpdf_show -- Output text at current position
cpdf_show_xy -- Output text at position
cpdf_stringwidth -- Returns width of text in current font
cpdf_set_font_directories --  Sets directories to search when using external fonts
cpdf_set_font_map_file --  Sets fontname to filename translation map when using external fonts
cpdf_set_viewer_preferences --  How to show the document in the viewer
cpdf_stroke -- Draw line along path
cpdf_text -- Output text with parameters
cpdf_translate -- Sets origin of coordinate system
cpdf_set_action_url --  Sets hyperlink

cpdf_add_annotation

(PHP 3>= 3.0.12, PHP 4 >= 4.0.0)

cpdf_add_annotation -- Adds annotation

Description

void cpdf_add_annotation ( int pdf document, float llx, float lly, float urx, float ury, string title, string content [, int mode])

The cpdf_add_annotation() adds a note with the lower left corner at (llx, lly) and the upper right corner at (urx, ury).

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

cpdf_add_outline

(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)

cpdf_add_outline -- Adds bookmark for current page

Description

void cpdf_add_outline ( int pdf document, string text)

The cpdf_add_outline() function adds a bookmark with text text that points to the current page.

Przykład 1. Adding a page outline

<?php
$cpdf = cpdf_open(0);
cpdf_page_init($cpdf, 1, 0, 595, 842);
cpdf_add_outline($cpdf, 0, 0, 0, 1, "Page 1");
// ...
// some drawing
// ...
cpdf_finalize($cpdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($cpdf);
cpdf_close($cpdf);
?>

cpdf_arc

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_arc -- Draws an arc

Description

void cpdf_arc ( int pdf document, float x-coor, float y-coor, float radius, float start, float end [, int mode])

The cpdf_arc() function draws an arc with center at point (x-coor, y-coor) and radius radius, starting at angle start and ending at angle end.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_circle().

cpdf_begin_text

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_begin_text -- Starts text section

Description

void cpdf_begin_text ( int pdf document)

The cpdf_begin_text() function starts a text section. It must be ended with cpdf_end_text().

Przykład 1. Text output

<?php
cpdf_begin_text($pdf);
cpdf_set_font($pdf, 16, "Helvetica", "WinAnsiEncoding");
cpdf_text($pdf, 100, 100, "Some text");
cpdf_end_text($pdf)
?>

See also cpdf_end_text().

cpdf_circle

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_circle -- Draw a circle

Description

void cpdf_circle ( int pdf document, float x-coor, float y-coor, float radius [, int mode])

The cpdf_circle() function draws a circle with center at point (x-coor, y-coor) and radius radius.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_arc().

cpdf_clip

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_clip -- Clips to current path

Description

void cpdf_clip ( int pdf document)

The cpdf_clip() function clips all drawing to the current path.

cpdf_close

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_close -- Closes the pdf document

Description

void cpdf_close ( int pdf document)

The cpdf_close() function closes the pdf document. This should be the last function even after cpdf_finalize(), cpdf_output_buffer() and cpdf_save_to_file().

See also cpdf_open().

cpdf_closepath

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_closepath -- Close path

Description

void cpdf_closepath ( int pdf document)

The cpdf_closepath() function closes the current path.

cpdf_closepath_fill_stroke

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_closepath_fill_stroke -- Close, fill and stroke current path

Description

void cpdf_closepath_fill_stroke ( int pdf document)

The cpdf_closepath_fill_stroke() function closes, fills the interior of the current path with the current fill color and draws current path.

See also cpdf_closepath(), cpdf_stroke(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().

cpdf_closepath_stroke

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_closepath_stroke -- Close path and draw line along path

Description

void cpdf_closepath_stroke ( int pdf document)

The cpdf_closepath_stroke() function is a combination of cpdf_closepath() and cpdf_stroke(). Then clears the path.

See also cpdf_closepath(), cpdf_stroke().

cpdf_continue_text

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_continue_text -- Output text in next line

Description

void cpdf_continue_text ( int pdf document, string text)

The cpdf_continue_text() function outputs the string in text in the next line.

See also cpdf_show_xy(), cpdf_text(), cpdf_set_leading(), cpdf_set_text_pos().

cpdf_curveto

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_curveto -- Draws a curve

Description

void cpdf_curveto ( int pdf document, float x1, float y1, float x2, float y2, float x3, float y3 [, int mode])

The cpdf_curveto() function draws a Bezier curve from the current point to the point (x3, y3) using (x1, y1) and (x2, y2) as control points.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_moveto(), cpdf_rmoveto(), cpdf_rlineto(), cpdf_lineto().

cpdf_end_text

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_end_text -- Ends text section

Description

void cpdf_end_text ( int pdf document)

The cpdf_end_text() function ends a text section which was started with cpdf_begin_text().

Przykład 1. Text output

<?php
cpdf_begin_text($pdf);
cpdf_set_font($pdf, 16, "Helvetica", "WinAnsiEncoding");
cpdf_text($pdf, 100, 100, "Some text");
cpdf_end_text($pdf)
?>

See also cpdf_begin_text().

cpdf_fill

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_fill -- Fill current path

Description

void cpdf_fill ( int pdf document)

The cpdf_fill() function fills the interior of the current path with the current fill color.

See also cpdf_closepath(), cpdf_stroke(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().

cpdf_fill_stroke

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_fill_stroke -- Fill and stroke current path

Description

void cpdf_fill_stroke ( int pdf document)

The cpdf_fill_stroke() function fills the interior of the current path with the current fill color and draws current path.

See also cpdf_closepath(), cpdf_stroke(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().

cpdf_finalize

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_finalize -- Ends document

Description

void cpdf_finalize ( int pdf document)

The cpdf_finalize() function ends the document. You still have to call cpdf_close()

See also cpdf_close().

cpdf_finalize_page

(PHP 3>= 3.0.10, PHP 4 >= 4.0.0)

cpdf_finalize_page -- Ends page

Description

void cpdf_finalize_page ( int pdf document, int page number)

The cpdf_finalize_page() function ends the page with page number page number.

This function is only for saving memory. A finalized page takes less memory but cannot be modified anymore.

See also cpdf_page_init().

cpdf_global_set_document_limits

(PHP 4 >= 4.0.0)

cpdf_global_set_document_limits -- Sets document limits for any pdf document

Description

void cpdf_global_set_document_limits ( int maxpages, int maxfonts, int maximages, int maxannotations, int maxobjects)

The cpdf_global_set_document_limits() function sets several document limits. This function has to be called before cpdf_open() to take effect. It sets the limits for any document open afterwards.

See also cpdf_open().

cpdf_import_jpeg

(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)

cpdf_import_jpeg -- Opens a JPEG image

Description

int cpdf_import_jpeg ( int pdf document, string file name, float x-coor, float y-coor, float angle, float width, float height, float x-scale, float y-scale [, int mode])

The cpdf_import_jpeg() function opens an image stored in the file with the name file name. The format of the image has to be jpeg. The image is placed on the current page at position (x-coor, y-coor). The image is rotated by angle degrees.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_place_inline_image().

cpdf_lineto

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_lineto -- Draws a line

Description

void cpdf_lineto ( int pdf document, float x-coor, float y-coor [, int mode])

The cpdf_lineto() function draws a line from the current point to the point with coordinates (x-coor, y-coor).

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_moveto(), cpdf_rmoveto(), cpdf_curveto().

cpdf_moveto

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_moveto -- Sets current point

Description

void cpdf_moveto ( int pdf document, float x-coor, float y-coor [, int mode])

The cpdf_moveto() function set the current point to the coordinates x-coor and y-coor.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

cpdf_newpath

(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)

cpdf_newpath -- Starts a new path

Description

void cpdf_newpath ( int pdf document)

The cpdf_newpath() starts a new path on the document given by the pdf document parameter.

cpdf_open

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_open -- Opens a new pdf document

Description

int cpdf_open ( int compression [, string filename])

The cpdf_open() function opens a new pdf document. The first parameter turns document compression on if it is unequal to 0. The second optional parameter sets the file in which the document is written. If it is omitted the document is created in memory and can either be written into a file with the cpdf_save_to_file() or written to standard output with cpdf_output_buffer().

Notatka: The return value will be needed in further versions of ClibPDF as the first parameter in all other functions which are writing to the pdf document.

The ClibPDF library takes the filename "-" as a synonym for stdout. If PHP is compiled as an apache module this will not work because the way ClibPDF outputs to stdout does not work with apache. You can solve this problem by skipping the filename and using cpdf_output_buffer() to output the pdf document.

See also cpdf_close(), cpdf_output_buffer().

cpdf_output_buffer

(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)

cpdf_output_buffer -- Outputs the pdf document in memory buffer

Description

void cpdf_output_buffer ( int pdf document)

The cpdf_output_buffer() function outputs the pdf document to stdout. The document has to be created in memory which is the case if cpdf_open() has been called with no filename parameter.

See also cpdf_open().

cpdf_page_init

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_page_init -- Starts new page

Description

void cpdf_page_init ( int pdf document, int page number, int orientation, float height, float width [, float unit])

The cpdf_page_init() function starts a new page with height height and width width. The page has number page number and orientation orientation. orientation can be 0 for portrait and 1 for landscape. The last optional parameter unit sets the unit for the coordinate system. The value should be the number of postscript points per unit. Since one inch is equal to 72 points, a value of 72 would set the unit to one inch. The default is also 72.

See also cpdf_set_current_page().

cpdf_place_inline_image

(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)

cpdf_place_inline_image -- Places an image on the page

Description

void cpdf_place_inline_image ( int pdf document, int image, float x-coor, float y-coor, float angle, float width, float height [, int mode])

The cpdf_place_inline_image() function places an image created with the php image functions on the page at position (x-coor, y-coor). The image can be scaled at the same time.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_import_jpeg().

cpdf_rect

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_rect -- Draw a rectangle

Description

void cpdf_rect ( int pdf document, float x-coor, float y-coor, float width, float height [, int mode])

The cpdf_rect() function draws a rectangle with its lower left corner at point (x-coor, y-coor). This width is set to width. This height is set to height.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

cpdf_restore

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_restore -- Restores formerly saved environment

Description

void cpdf_restore ( int pdf document)

The cpdf_restore() function restores the environment saved with cpdf_save(). It works like the postscript command grestore. Very useful if you want to translate or rotate an object without effecting other objects.

Przykład 1. Save/Restore

<?php
cpdf_save($pdf);
// do all kinds of rotations, transformations, ...
cpdf_restore($pdf)
?>

See also cpdf_save().

cpdf_rlineto

(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)

cpdf_rlineto -- Draws a line

Description

void cpdf_rlineto ( int pdf document, float x-coor, float y-coor [, int mode])

The cpdf_rlineto() function draws a line from the current point to the relative point with coordinates (x-coor, y-coor).

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_moveto(), cpdf_rmoveto(), cpdf_curveto().

cpdf_rmoveto

(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)

cpdf_rmoveto -- Sets current point

Description

void cpdf_rmoveto ( int pdf document, float x-coor, float y-coor [, int mode])

The cpdf_rmoveto() function set the current point relative to the coordinates x-coor and y-coor.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_moveto().

cpdf_rotate

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_rotate -- Sets rotation

Description

void cpdf_rotate ( int pdf document, float angle)

The cpdf_rotate() function set the rotation in degrees to angle.

cpdf_rotate_text

(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)

cpdf_rotate_text --  Sets text rotation angle

Description

void cpdf_rotate_text ( int pdfdoc, float angle)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

cpdf_save

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_save -- Saves current environment

Description

void cpdf_save ( int pdf document)

The cpdf_save() function saves the current environment. It works like the postscript command gsave. Very useful if you want to translate or rotate an object without effecting other objects.

See also cpdf_restore().

cpdf_save_to_file

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_save_to_file -- Writes the pdf document into a file

Description

void cpdf_save_to_file ( int pdf document, string filename)

The cpdf_save_to_file() function outputs the pdf document into a file if it has been created in memory.

This function is not needed if the pdf document has been open by specifying a filename as a parameter of cpdf_open().

See also cpdf_output_buffer(), cpdf_open().

cpdf_scale

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_scale -- Sets scaling

Description

void cpdf_scale ( int pdf document, float x-scale, float y-scale)

The cpdf_scale() function set the scaling factor in both directions.

cpdf_set_char_spacing

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_set_char_spacing -- Sets character spacing

Description

void cpdf_set_char_spacing ( int pdf document, float space)

The cpdf_set_char_spacing() function sets the spacing between characters.

See also cpdf_set_word_spacing(), cpdf_set_leading().

cpdf_set_creator

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_set_creator -- Sets the creator field in the pdf document

Description

void cpdf_set_creator ( string creator)

The cpdf_set_creator() function sets the creator of a pdf document.

See also cpdf_set_subject(), cpdf_set_title(), cpdf_set_keywords().

cpdf_set_current_page

(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)

cpdf_set_current_page -- Sets current page

Description

void cpdf_set_current_page ( int pdf document, int page number)

The cpdf_set_current_page() function set the page on which all operations are performed. One can switch between pages until a page is finished with cpdf_finalize_page().

See also cpdf_finalize_page().

cpdf_set_font

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_set_font -- Select the current font face and size

Description

void cpdf_set_font ( int pdf document, string font name, float size, string encoding)

The cpdf_set_font() function sets the current font face, font size and encoding. Currently only the standard postscript fonts are supported.

The last parameter encoding can take the following values: "MacRomanEncoding", "MacExpertEncoding", "WinAnsiEncoding", and "NULL". "NULL" stands for the font's built-in encoding.

See the ClibPDF Manual for more information, especially how to support asian fonts.

cpdf_set_horiz_scaling

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_set_horiz_scaling -- Sets horizontal scaling of text

Description

void cpdf_set_horiz_scaling ( int pdf document, float scale)

The cpdf_set_horiz_scaling() function sets the horizontal scaling to scale percent.

cpdf_set_keywords

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_set_keywords -- Sets the keywords field of the pdf document

Description

void cpdf_set_keywords ( string keywords)

The cpdf_set_keywords() function sets the keywords of a pdf document.

See also cpdf_set_title(), cpdf_set_creator(), cpdf_set_subject().

cpdf_set_leading

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_set_leading -- Sets distance between text lines

Description

void cpdf_set leading ( int pdf document, float distance)

The cpdf_set_leading() function sets the distance between text lines. This will be used if text is output by cpdf_continue_text().

See also cpdf_continue_text().

cpdf_set_page_animation

(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)

cpdf_set_page_animation -- Sets duration between pages

Description

void cpdf_set_page_animation ( int pdf document, int transition, float duration)

The cpdf_set_page_animation() function set the transition between following pages.

The value of transition can be

0 for none,
1 for two lines sweeping across the screen reveal the page,
2 for multiple lines sweeping across the screen reveal the page,
3 for a box reveals the page,
4 for a single line sweeping across the screen reveals the page,
5 for the old page dissolves to reveal the page,
6 for the dissolve effect moves from one screen edge to another,
7 for the old page is simply replaced by the new page (default)

The value of duration is the number of seconds between page flipping.

cpdf_set_subject

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_set_subject -- Sets the subject field of the pdf document

Description

void cpdf_set_subject ( string subject)

The cpdf_set_subject() function sets the subject of a pdf document.

See also cpdf_set_title(), cpdf_set_creator(), cpdf_set_keywords().

cpdf_set_text_matrix

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_set_text_matrix -- Sets the text matrix

Description

void cpdf_set_text_matrix ( int pdf document, array matrix)

The cpdf_set_text_matrix() function sets a matrix which describes a transformation applied on the current text font.

cpdf_set_text_pos

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_set_text_pos -- Sets text position

Description

void cpdf_set_text_pos ( int pdf document, float x-coor, float y-coor [, int mode])

The cpdf_set_text_pos() function sets the position of text for the next cpdf_show() function call.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_show(), cpdf_text().

cpdf_set_text_rendering

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_set_text_rendering -- Determines how text is rendered

Description

void cpdf_set_text_rendering ( int pdf document, int mode)

The cpdf_set_text_rendering() function determines how text is rendered.

The possible values for mode are 0=fill text, 1=stroke text, 2=fill and stroke text, 3=invisible, 4=fill text and add it to clipping path, 5=stroke text and add it to clipping path, 6=fill and stroke text and add it to clipping path, 7=add it to clipping path.

cpdf_set_text_rise

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_set_text_rise -- Sets the text rise

Description

void cpdf_set_text_rise ( int pdf document, float value)

The cpdf_set_text_rise() function sets the text rising to value units.

cpdf_set_title

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_set_title -- Sets the title field of the pdf document

Description

void cpdf_set_title ( string title)

The cpdf_set_title() function sets the title of a pdf document.

See also cpdf_set_subject(), cpdf_set_creator(), cpdf_set_keywords().

cpdf_set_word_spacing

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_set_word_spacing -- Sets spacing between words

Description

void cpdf_set_word_spacing ( int pdf document, float space)

The cpdf_set_word_spacing() function sets the spacing between words.

See also cpdf_set_char_spacing(), cpdf_set_leading().

cpdf_setdash

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_setdash -- Sets dash pattern

Description

void cpdf_setdash ( int pdf document, float white, float black)

The cpdf_setdash() function set the dash pattern white white units and black black units. If both are 0 a solid line is set.

cpdf_setflat

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_setflat -- Sets flatness

Description

void cpdf_setflat ( int pdf document, float value)

The cpdf_setflat() function set the flatness to a value between 0 and 100.

cpdf_setgray

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_setgray -- Sets drawing and filling color to gray value

Description

void cpdf_setgray ( int pdf document, float gray value)

The cpdf_setgray() function sets the current drawing and filling color to the given gray value.

See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor_fill().

cpdf_setgray_fill

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_setgray_fill -- Sets filling color to gray value

Description

void cpdf_setgray_fill ( int pdf document, float value)

The cpdf_setgray_fill() function sets the current gray value to fill a path.

See also cpdf_setrgbcolor_fill().

cpdf_setgray_stroke

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_setgray_stroke -- Sets drawing color to gray value

Description

void cpdf_setgray_stroke ( int pdf document, float gray value)

The cpdf_setgray_stroke() function sets the current drawing color to the given gray value.

See also cpdf_setrgbcolor_stroke().

cpdf_setlinecap

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_setlinecap -- Sets linecap parameter

Description

void cpdf_setlinecap ( int pdf document, int value)

The cpdf_setlinecap() function set the linecap parameter between a value of 0 and 2. 0 = butt end, 1 = round, 2 = projecting square.

cpdf_setlinejoin

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_setlinejoin -- Sets linejoin parameter

Description

void cpdf_setlinejoin ( int pdf document, long value)

The cpdf_setlinejoin() function set the linejoin parameter between a value of 0 and 2. 0 = miter, 1 = round, 2 = bevel.

cpdf_setlinewidth

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_setlinewidth -- Sets line width

Description

void cpdf_setlinewidth ( int pdf document, float width)

The cpdf_setlinewidth() function set the line width to width.

cpdf_setmiterlimit

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_setmiterlimit -- Sets miter limit

Description

void cpdf_setmiterlimit ( int pdf document, float value)

The cpdf_setmiterlimit() function set the miter limit to a value greater or equal than 1.

cpdf_setrgbcolor

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_setrgbcolor -- Sets drawing and filling color to rgb color value

Description

void cpdf_setrgbcolor ( int pdf document, float red value, float green value, float blue value)

The cpdf_setrgbcolor() function sets the current drawing and filling color to the given rgb color value.

See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor_fill().

cpdf_setrgbcolor_fill

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_setrgbcolor_fill -- Sets filling color to rgb color value

Description

void cpdf_setrgbcolor_fill ( int pdf document, float red value, float green value, float blue value)

The cpdf_setrgbcolor_fill() function sets the current rgb color value to fill a path.

See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor().

cpdf_setrgbcolor_stroke

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_setrgbcolor_stroke -- Sets drawing color to rgb color value

Description

void cpdf_setrgbcolor_stroke ( int pdf document, float red value, float green value, float blue value)

The cpdf_setrgbcolor_stroke() function sets the current drawing color to the given rgb color value.

See also cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().

cpdf_show

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_show -- Output text at current position

Description

void cpdf_show ( int pdf document, string text)

The cpdf_show() function outputs the string in text at the current position.

See also cpdf_text(), cpdf_begin_text(), cpdf_end_text().

cpdf_show_xy

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_show_xy -- Output text at position

Description

void cpdf_show_xy ( int pdf document, string text, float x-coor, float y-coor [, int mode])

The cpdf_show_xy() function outputs the string text at position with coordinates (x-coor, y-coor).

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

Notatka: The function cpdf_show_xy() is identical to cpdf_text() without the optional parameters.

See also cpdf_text().

cpdf_stringwidth

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_stringwidth -- Returns width of text in current font

Description

float cpdf_stringwidth ( int pdf document, string text)

The cpdf_stringwidth() function returns the width of the string in text. It requires a font to be set before.

See also cpdf_set_font().

cpdf_set_font_directories

(PHP 4 >= 4.0.6)

cpdf_set_font_directories --  Sets directories to search when using external fonts

Description

void cpdf_set_font_directories ( int pdfdoc, string pfmdir, string pfbdir)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

cpdf_set_font_map_file

(PHP 4 >= 4.0.6)

cpdf_set_font_map_file --  Sets fontname to filename translation map when using external fonts

Description

void cpdf_set_font_map_file ( int pdfdoc, string filename)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

cpdf_set_viewer_preferences

(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)

cpdf_set_viewer_preferences --  How to show the document in the viewer

Description

void cpdf_set_viewer_preferences ( int pdfdoc, array preferences)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

cpdf_stroke

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_stroke -- Draw line along path

Description

void cpdf_stroke ( int pdf document)

The cpdf_stroke() function draws a line along current path.

See also cpdf_closepath(), cpdf_closepath_stroke().

cpdf_text

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_text -- Output text with parameters

Description

void cpdf_text ( int pdf document, string text, float x-coor, float y-coor [, int mode [, float orientation [, int alignmode]]])

The cpdf_text() function outputs the string text at position with coordinates (x-coor, y-coor).

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit. The optional parameter orientation is the rotation of the text in degree. The optional parameter alignmode determines how the text is aligned.

See the ClibPDF documentation for possible values.

See also cpdf_show_xy().

cpdf_translate

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

cpdf_translate -- Sets origin of coordinate system

Description

void cpdf_translate ( int pdf document, float x-coor, float y-coor [, int mode])

The cpdf_translate() function set the origin of coordinate system to the point (x-coor, y-coor).

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

cpdf_set_action_url

(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)

cpdf_set_action_url --  Sets hyperlink

Description

void cpdf_set_action_url ( int pdfdoc, float xll, float yll, float xur, float xur, string url [, int mode])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

XI. Crack functions

These functions allow you to use the CrackLib library to test the 'strength' of a password. In order to use these functions, you must compile PHP with Crack support by using the --with-crack[=DIR] option.

More information regarding CrackLib along with the library can be found at http://www.users.dircon.co.uk/~crypto/.

Cracklib is useful in testing the 'strength' of a password that checks length, use of upper and lower case and a check against the specified CrackLib dictionary. CrackLib will also give helpful diagnostic messages that will help 'strengthen' the password.

This example shows how to open a CrackLib dictionary, test a given password, retrieve any diagnostic messages, and close the dictionary.

Przykład 1. CrackLib example

<?php
// Open CrackLib Dictionary
$dictionary = crack_opendict('/usr/local/lib/pw_dict')
     or die('Unable to open CrackLib dictionary');

// Perform password check
$check = crack_check($dictionary, 'gx9A2s0x');

// Retrieve messages
$diag = crack_getlastmessage();
echo $diag; // 'strong password'

// Close dictionary
crack_closedict($dictionary);
?>

Notatka: If crack_check() returns TRUE, crack_getlastmessage() will return 'strong password'.

Spis treści
crack_opendict -- Opens a new CrackLib dictionary
crack_closedict -- Closes an open CrackLib dictionary
crack_check -- Performs an obscure check with the given password
crack_getlastmessage -- Returns the message from the last obscure check

crack_opendict

(PHP 4 >= 4.0.5)

crack_opendict -- Opens a new CrackLib dictionary

Description

resource crack_opendict ( string dictionary)

Returns a dictionary resource identifier on success, or FALSE on failure.

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

crack_opendict() opens the specified CrackLib dictionary for use with crack_check().

Notatka: Only one dictionary may be open at a time.

See also: crack_check(), and crack_closedict().

crack_closedict

(PHP 4 >= 4.0.5)

crack_closedict -- Closes an open CrackLib dictionary

Description

bool crack_closedict ( [resource dictionary])

Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

crack_closedict() closes the specified dictionary identifier. If dictionary is not specified, the current dictionary is closed.

crack_check

(PHP 4 >= 4.0.5)

crack_check -- Performs an obscure check with the given password

Description

bool crack_check ( [resource dictionary, string password])

Returns TRUE if password is strong, or FALSE otherwise.

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

crack_check() performs an obscure check with the given password on the specified dictionary . If dictionary is not specified, the last opened dictionary is used.

crack_getlastmessage

(PHP 4 >= 4.0.5)

crack_getlastmessage -- Returns the message from the last obscure check

Description

string crack_getlastmessage ( void)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

crack_getlastmessage() returns the message from the last obscure check.

XII. CURL, Client URL Library Functions

PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

In order to use the CURL functions you need to install the CURL package. PHP requires that you use CURL 7.0.2-beta or higher. PHP will not work with any version of CURL below version 7.0.2-beta.

To use PHP's CURL support you must also compile PHP --with-curl[=DIR] where DIR is the location of the directory containing the lib and include directories. In the "include" directory there should be a folder named "curl" which should contain the easy.h and curl.h files. There should be a file named "libcurl.a" located in the "lib" directory.

These functions have been added in PHP 4.0.2.

Once you've compiled PHP with CURL support, you can begin using the curl functions. The basic idea behind the CURL functions is that you initialize a CURL session using the curl_init(), then you can set all your options for the transfer via the curl_exec() and then you finish off your session using the curl_close(). Here is an example that uses the CURL functions to fetch the PHP homepage into a file:

Przykład 1. Using PHP's CURL module to fetch the PHP homepage

<?php

$ch = curl_init ("http://www.php.net/");
$fp = fopen ("php_homepage.txt", "w");

curl_setopt ($ch, CURLOPT_FILE, $fp);
curl_setopt ($ch, CURLOPT_HEADER, 0);

curl_exec ($ch);
curl_close ($ch);
fclose ($fp);
?>

Spis treści
curl_init -- Initialize a CURL session
curl_setopt -- Set an option for a CURL transfer
curl_exec -- Perform a CURL session
curl_close -- Close a CURL session
curl_version -- Return the current CURL version
curl_errno -- Return an integer containing the last error number
curl_error --  Return a string contain the last error for the current session
curl_getinfo --  Get information regarding a specific transfer

curl_init

(PHP 4 >= 4.0.2)

curl_init -- Initialize a CURL session

Description

int curl_init ( [string url])

The curl_init() will initialize a new session and return a CURL handle for use with the curl_setopt(), curl_exec(), and curl_close() functions. If the optional url parameter is supplied then the CURLOPT_URL option will be set to the value of the parameter. You can manually set this using the curl_setopt() function.

Przykład 1. Initializing a new CURL session and fetching a webpage

<?php
$ch = curl_init();

curl_setopt ($ch, CURLOPT_URL, "http://www.zend.com/");
curl_setopt ($ch, CURLOPT_HEADER, 0);

curl_exec ($ch);

curl_close ($ch);
?>

See also: curl_close(), curl_setopt()

curl_setopt

(PHP 4 >= 4.0.2)

curl_setopt -- Set an option for a CURL transfer

Description

bool curl_setopt ( int ch, string option, mixed value)

The curl_setopt() function will set options for a CURL session identified by the ch parameter. The option parameter is the option you want to set, and the value is the value of the option given by the option.

The value should be a long for the following options (specified in the option parameter):

  • CURLOPT_INFILESIZE: When you are uploading a file to a remote site, this option should be used to tell PHP what the expected size of the infile will be.

  • CURLOPT_VERBOSE: Set this option to a non-zero value if you want CURL to report everything that is happening.

  • CURLOPT_HEADER: Set this option to a non-zero value if you want the header to be included in the output.

  • CURLOPT_NOPROGRESS: Set this option to a non-zero value if you don't want PHP to display a progress meter for CURL transfers

    Notatka: PHP automatically sets this option to a non-zero parameter, this should only be changed for debugging purposes.

  • CURLOPT_NOBODY: Set this option to a non-zero value if you don't want the body included with the output.

  • CURLOPT_FAILONERROR: Set this option to a non-zero value if you want PHP to fail silently if the HTTP code returned is greater than 300. The default behavior is to return the page normally, ignoring the code.

  • CURLOPT_UPLOAD: Set this option to a non-zero value if you want PHP to prepare for an upload.

  • CURLOPT_POST: Set this option to a non-zero value if you want PHP to do a regular HTTP POST. This POST is a normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.

  • CURLOPT_FTPLISTONLY: Set this option to a non-zero value and PHP will just list the names of an FTP directory.

  • CURLOPT_FTPAPPEND: Set this option to a non-zero value and PHP will append to the remote file instead of overwriting it.

  • CURLOPT_NETRC: Set this option to a non-zero value and PHP will scan your ~./netrc file to find your username and password for the remote site that you're establishing a connection with.

  • CURLOPT_FOLLOWLOCATION: Set this option to a non-zero value to follow any "Location: " header that the server sends as a part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent.)

  • CURLOPT_PUT: Set this option a non-zero value to HTTP PUT a file. The file to PUT must be set with the CURLOPT_INFILE and CURLOPT_INFILESIZE.

  • CURLOPT_MUTE: Set this option to a non-zero value and PHP will be completely silent with regards to the CURL functions.

  • CURLOPT_TIMEOUT: Pass a long as a parameter that contains the maximum time, in seconds, that you'll allow the curl functions to take.

  • CURLOPT_LOW_SPEED_LIMIT: Pass a long as a parameter that contains the transfer speed in bytes per second that the transfer should be below during CURLOPT_LOW_SPEED_TIME seconds for PHP to consider it too slow and abort.

  • CURLOPT_LOW_SPEED_TIME: Pass a long as a parameter that contains the time in seconds that the transfer should be below the CURLOPT_LOW_SPEED_LIMIT for PHP to consider it too slow and abort.

  • CURLOPT_RESUME_FROM: Pass a long as a parameter that contains the offset, in bytes, that you want the transfer to start from.

  • CURLOPT_SSLVERSION: Pass a long as a parameter that contains the SSL version (2 or 3) to use. By default PHP will try and determine this by itself, although, in some cases you must set this manually.

  • CURLOPT_SSL_VERIFYHOST: Pass a long if cURL should verify the Common name of the peer certificate in the SSL handshake. A value of 1 denotes that we should check for the existence of the common name, a value of 2 denotes that we should make sure it matches the provided hostname.

  • CURLOPT_TIMECONDITION: Pass a long as a parameter that defines how the CURLOPT_TIMEVALUE is treated. You can set this parameter to TIMECOND_IFMODSINCE or TIMECOND_ISUNMODSINCE. This is a HTTP-only feature.

  • CURLOPT_TIMEVALUE: Pass a long as a parameter that is the time in seconds since January 1st, 1970. The time will be used as specified by the CURLOPT_TIMEVALUE option, or by default the TIMECOND_IFMODSINCE will be used.

  • CURLOPT_RETURNTRANSFER: Pass a non-zero value if you want cURL to directly return the transfer instead of printing it out directly.

The value parameter should be a string for the following values of the option parameter:

  • CURLOPT_URL: This is the URL that you want PHP to fetch. You can also set this option when initializing a session with the curl_init() function.

  • CURLOPT_USERPWD: Pass a string formatted in the [username]:[password] manner, for PHP to use for the connection. connection.

  • CURLOPT_PROXYUSERPWD: Pass a string formatted in the [username]:[password] format for connection to the HTTP proxy.

  • CURLOPT_RANGE: Pass the specified range you want. It should be in the "X-Y" format, where X or Y may be left out. The HTTP transfers also support several intervals, separated with commas as in X-Y,N-M.

  • CURLOPT_POSTFIELDS: Pass a string containing the full data to post in an HTTP "POST" operation.

  • CURLOPT_REFERER: Pass a string containing the "referer" header to be used in an HTTP request.

  • CURLOPT_USERAGENT: Pass a string containing the "user-agent" header to be used in an HTTP request.

  • CURLOPT_FTPPORT: Pass a string containing the which will be used to get the IP address to use for the ftp "POST" instruction. The POST instruction tells the remote server to connect to our specified IP address. The string may be a plain IP address, a hostname, a network interface name (under UNIX), or just a plain '-' to use the systems default IP address.

  • CURLOPT_COOKIE: Pass a string containing the content of the cookie to be set in the HTTP header.

  • CURLOPT_SSLCERT: Pass a string containing the filename of PEM formatted certificate.

  • CURLOPT_SSLCERTPASSWD: Pass a string containing the password required to use the CURLOPT_SSLCERT certificate.

  • CURLOPT_COOKIEFILE: Pass a string containing the name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file.

  • CURLOPT_CUSTOMREQUEST: Pass a string to be used instead of GET or HEAD when doing an HTTP request. This is useful for doing DELETE or other, more obscure, HTTP requests. Valid values are things like GET, POST, and so on; i.e. do not enter a whole HTTP request line here. For instance, entering 'GET /index.html HTTP/1.0\r\n\r\n' would be incorrect.

    Notatka: Don't do this without making sure your server supports the command first.

  • CURLOPT_PROXY: Give the name of the HTTP proxy to tunnel requests through.

  • CURLOPT_INTERFACE: Pass the name of the outgoing network interface to use. This can be an interface name, an IP address or a host name.

  • CURLOPT_KRB4LEVEL: Pass the KRB4 (Kerberos 4) security level. This anyone of the following strings (in order from least powerful, to most powerful): 'clear', 'safe', 'confidential', 'private'. If the string does not match one of these, then 'private' is used. If you set this to NULL, this disables KB4 security. KB4 security only works with FTP transactions currently.

  • CURLOPT_HTTPHEADER: Pass an array of HTTP header fields to set.

  • CURLOPT_QUOTE: Pass an array of FTP commands to perform on the server prior to the FTP request.

  • CURLOPT_POSTQUOTE: Pass an array of FTP commands to execute on the server, after the FTP request has been performed.

The following options expect a file descriptor that is obtained by using the fopen() function:

  • CURLOPT_FILE: The file where the output of your transfer should be placed, the default is STDOUT.

  • CURLOPT_INFILE: The file where the input of your transfer comes from.

  • CURLOPT_WRITEHEADER: The file to write the header part of the output into.

  • CURLOPT_STDERR: The file to write errors to instead of stderr.

curl_exec

(PHP 4 >= 4.0.2)

curl_exec -- Perform a CURL session

Description

bool curl_exec ( int ch)

This function is should be called after you initialize a CURL session and all the options for the session are set. Its purpose is simply to execute the predefined CURL session (given by the ch).

Podpowiedź: Ze wszystkim, co wysyła dane bezpośrednio do przeglądarki, możesz używać funkcji kontroli wyjścia aby przejąć wyjście tej funkcji i zapisać je - na przykład - w zmiennej tekstowej.

curl_close

(PHP 4 >= 4.0.2)

curl_close -- Close a CURL session

Description

void curl_close ( int ch)

This function closes a CURL session and frees all resources. The CURL handle, ch, is also deleted.

curl_version

(PHP 4 >= 4.0.2)

curl_version -- Return the current CURL version

Description

string curl_version ( void)

The curl_version() function returns a string containing the current CURL version.

curl_errno

(PHP 4 >= 4.0.3)

curl_errno -- Return an integer containing the last error number

Description

int curl_errno ( int ch)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

curl_error

(PHP 4 >= 4.0.3)

curl_error --  Return a string contain the last error for the current session

Description

string curl_error ( int ch)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

curl_getinfo

(PHP 4 >= 4.0.4)

curl_getinfo --  Get information regarding a specific transfer

Description

string curl_getinfo ( int ch, int opt)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

XIII. Cybercash payment functions

These functions are only available if the interpreter has been compiled with the --with-cybercash=[DIR]. These functions have been added in PHP 4.

Spis treści
cybercash_encr -- Cybercash encrypt
cybercash_decr -- Cybercash decrypt
cybercash_base64_encode -- base64 encode data for Cybercash
cybercash_base64_decode -- base64 decode data for Cybercash

cybercash_encr

(PHP 4 >= 4.0.0)

cybercash_encr -- Cybercash encrypt

Description

array cybercash_encr ( string wmk, string sk, string inbuff)

The function returns an associative array with the elements "errcode" and, if "errcode" is FALSE, "outbuff" (string), "outLth" (long) and "macbuff" (string).

cybercash_decr

(PHP 4 >= 4.0.0)

cybercash_decr -- Cybercash decrypt

Description

array cybercash_decr ( string wmk, string sk, string inbuff)

The function returns an associative array with the elements "errcode" and, if "errcode" is FALSE, "outbuff" (string), "outLth" (long) and "macbuff" (string).

cybercash_base64_encode

(PHP 4 >= 4.0.0)

cybercash_base64_encode -- base64 encode data for Cybercash

Description

string cybercash_base64_encode ( string inbuff)

cybercash_base64_decode

(PHP 4 >= 4.0.0)

cybercash_base64_decode -- base64 decode data for Cybercash

Description

string cybercash_base64_decode ( string inbuff)

XIV. Crédit Mutuel CyberMUT functions

This extension allows you to process credit cards transactions using Crédit Mutuel CyberMUT system ( http://www.creditmutuel.fr/centre_commercial/vendez_sur_internet.html).

CyberMUT is a popular Web Payment Service in France, provided by the Crédit Mutuel bank. If you are foreign in France, these functions will not be useful for you.

These functions are only available if PHP has been compiled with the --with-cybermut[=DIR] option, where DIR is the location of libcm-mac.a and cm-mac.h. You will require the appropriate SDK for your platform, which may be sent to you after your CyberMUT's subscription (contact them via Web, or go to the nearest Crédit Mutuel).

The use of these functions is almost identical to the original functions, except for the parameters of return for cybermut_creerformulairecm() and cybermut_creerreponsecm(), which are returned directly by functions PHP, whereas they had passed in reference in the original functions.

These functions have been added in PHP 4.0.6.

Notatka: These functions only provide a link to CyberMUT SDK. Be sure to read the CyberMUT Developers Guide for full details of the required parameters.

Spis treści
cybermut_creerformulairecm -- Generate HTML form of request for payment
cybermut_testmac --  Make sure that there no was data diddling contained in the received message of confirmation
cybermut_creerreponsecm --  Generate the acknowledgement of delivery of the confirmation of payment

cybermut_creerformulairecm

(PHP 4 >= 4.0.5)

cybermut_creerformulairecm -- Generate HTML form of request for payment

Description

string cybermut_creerformulairecm ( string url_CM, string version, string TPE, string montant, string ref_commande, string texte_libre, string url_retour, string url_retour_ok, string url_retour_err, string langue, string code_societe, string texte_bouton)

cybermut_creerformulairecm() is used to generate the HTML form of request for payment.

Przykład 1. First step of payment (equiv cgi1.c)

<?php
// Directory where are located the keys
putenv("CMKEYDIR=/var/creditmut/cles");
 
// Version number
$VERSION="1.2";

  $retour =  cybermut_creerformulairecm(
  "https://www.creditmutuel.fr/test/telepaiement/paiement.cgi",
  $VERSION,
  "1234567890",
  "300FRF",
  $REFERENCE,
  $TEXTE_LIBRE,
  $URL_RETOUR,
  $URL_RETOUR_OK,
  $URL_RETOUR_ERR,
  "francais",
  "company",
  "Paiement par carte bancaire");
 
  echo $retour;                                                               
?>

See also cybermut_testmac() and cybermut_creerreponsecm().

cybermut_testmac

(PHP 4 >= 4.0.5)

cybermut_testmac --  Make sure that there no was data diddling contained in the received message of confirmation

Description

bool cybermut_testmac ( string code_MAC, string version, string TPE, string cdate, string montant, string ref_commande, string texte_libre, string code-retour)

cybermut_testmac() is used to make sure that there was not data diddling contained in the received message of confirmation. Pay attention to parameters code-retour and texte-libre, which cannot be evaluated as is, because of the dash. You must retrieve them by using:
<?php
  $code_retour=$HTTP_GET_VARS["code-retour"];
  $texte_libre=$HTTP_GET_VARS["texte-libre"];
?>

Przykład 1. Last step of payment (equiv cgi2.c)

<?php
// Make sure that Enable Track Vars is ON.
// Directory where are located the keys
putenv("CMKEYDIR=/var/creditmut/cles");
 
// Version number
$VERSION="1.2";

$texte_libre = $HTTP_GET_VARS["texte-libre"];
$code_retour = $HTTP_GET_VARS["code-retour"];                                     

$mac_ok = cybermut_testmac($MAC,$VERSION,$TPE,$date,$montant,$reference,$texte_libre,$code_retour);

if ($mac_ok) {

  //
  // insert data processing here
  //
  //

  $result=cybermut_creerreponsecm("OK");
} else {
  $result=cybermut_creerreponsecm("Document Falsifie");
}
 
?>

See also cybermut_creerformulairecm() and cybermut_creerreponsecm().

cybermut_creerreponsecm

(PHP 4 >= 4.0.5)

cybermut_creerreponsecm --  Generate the acknowledgement of delivery of the confirmation of payment

Description

string cybermut_creerreponsecm ( string phrase)

cybermut_creerreponsecm() returns a string containing delivery acknowledgement message.

The parameter is "OK" if the message of confirmation of the payment was correctly identified by cybermut_testmac(). Any other chain is regarded as an error message.

See also cybermut_creerformulairecm() and cybermut_testmac().

XV. Cyrus IMAP administration functions

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Spis treści
cyrus_connect -- Connect to a Cyrus IMAP server
cyrus_authenticate -- Authenticate agaings a Cyrus IMAP server
cyrus_bind -- Bind callbacks to a Cyrus IMAP connection
cyrus_unbind -- Unbind ...
cyrus_query -- Send a query to a Cyrus IMAP server
cyrus_close -- Close connection to a cyrus server

cyrus_connect

(PHP 4 >= 4.1.0)

cyrus_connect -- Connect to a Cyrus IMAP server

Description

resource cyrus_connect ( [string host [, string port [, int flags]]])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

cyrus_authenticate

(PHP 4 >= 4.1.0)

cyrus_authenticate -- Authenticate agaings a Cyrus IMAP server

Description

bool cyrus_authenticate ( resource connection [, string mechlist [, string service [, string user [, int minssf [, int maxssf]]]]])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

cyrus_bind

(PHP 4 >= 4.1.0)

cyrus_bind -- Bind callbacks to a Cyrus IMAP connection

Description

bool cyrus_bind ( resource connection, array callbacks)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

cyrus_unbind

(PHP 4 >= 4.1.0)

cyrus_unbind -- Unbind ...

Description

bool cyrus_unbind ( resource connection, string trigger_name)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

cyrus_query

(PHP 4 >= 4.1.0)

cyrus_query -- Send a query to a Cyrus IMAP server

Description

bool cyrus_query ( resource connection, string query)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

cyrus_close

(PHP 4 >= 4.1.0)

cyrus_close -- Close connection to a cyrus server

Description

bool cyrus_close ( resource connection)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

XVI. Character type functions

These functions check whether a character or string falls into a certain character class according to the current locale.

When called with an integer argument these functions behave exactly like their C counterparts.

When called with a string argument they will check every character in the string and will only return TRUE if every character in the string matches the requested criteria.

Passing anything else but a string or integer will return FALSE immediately.

Spis treści
ctype_alnum -- Check for alphanumeric character(s)
ctype_alpha -- Check for alphabetic character(s)
ctype_cntrl -- Check for control character(s)
ctype_digit -- Check for numeric character(s)
ctype_lower -- Check for lowercase character(s)
ctype_graph -- Check for any printable character(s) except space
ctype_print -- Check for printable character(s)
ctype_punct --  Check for any printable character which is not whitespace or an alphanumeric character
ctype_space -- Check for whitespace character(s)
ctype_upper -- Check for uppercase character(s)
ctype_xdigit --  Check for character(s) representing a hexadecimal digit

ctype_alnum

(PHP 4 >= 4.0.4)

ctype_alnum -- Check for alphanumeric character(s)

Description

bool ctype_alnum ( string c)

See also setlocale().

ctype_alpha

(PHP 4 >= 4.0.4)

ctype_alpha -- Check for alphabetic character(s)

Description

bool ctype_alpha ( string c)

ctype_cntrl

(PHP 4 >= 4.0.4)

ctype_cntrl -- Check for control character(s)

Description

bool ctype_cntrl ( string c)

ctype_digit

(PHP 4 >= 4.0.4)

ctype_digit -- Check for numeric character(s)

Description

bool ctype_digit ( string c)

ctype_lower

(PHP 4 >= 4.0.4)

ctype_lower -- Check for lowercase character(s)

Description

bool ctype_lower ( string c)

ctype_graph

(PHP 4 >= 4.0.4)

ctype_graph -- Check for any printable character(s) except space

Description

bool ctype_graph ( string c)

ctype_print

(PHP 4 >= 4.0.4)

ctype_print -- Check for printable character(s)

Description

bool ctype_print ( string c)

ctype_punct

(PHP 4 >= 4.0.4)

ctype_punct --  Check for any printable character which is not whitespace or an alphanumeric character

Description

bool ctype_punct ( string c)

ctype_space

(PHP 4 >= 4.0.4)

ctype_space -- Check for whitespace character(s)

Description

bool ctype_space ( string c)

ctype_upper

(PHP 4 >= 4.0.4)

ctype_upper -- Check for uppercase character(s)

Description

bool ctype_upper ( string c)

ctype_xdigit

(PHP 4 >= 4.0.4)

ctype_xdigit --  Check for character(s) representing a hexadecimal digit

Description

bool ctype_xdigit ( string c)

XVII. Database (dbm-style) abstraction layer functions

These functions build the foundation for accessing Berkeley DB style databases.

This is a general abstraction layer for several file-based databases. As such, functionality is limited to a common subset of features supported by modern databases such as Sleepycat Software's DB2. (This is not to be confused with IBM's DB2 software, which is supported through the ODBC functions.)

The behaviour of various aspects depends on the implementation of the underlying database. Functions such as dba_optimize() and dba_sync() will do what they promise for one database and will do nothing for others.

When invoking the dba_open() or dba_popen() functions, one of the following handler names must be supplied as an argument. The actually available list of handlers is displayed by invoking phpinfo(). (To add support for any of the following handlers during the production of PHP, add the specified --with-XXXX configure switch to your PHP configure line.)

Tabela 1. List of DBA handlers

HandlerNotes
dbm Dbm is the oldest (original) type of Berkeley DB style databases. You should avoid it, if possible. We do not support the compatibility functions built into DB2 and gdbm, because they are only compatible on the source code level, but cannot handle the original dbm format. (--with-dbm)
ndbm Ndbm is a newer type and more flexible than dbm. It still has most of the arbitrary limits of dbm (therefore it is deprecated). (--with-ndbm)
gdbm Gdbm is the GNU database manager. (--with-gdbm)
db2 DB2 is Sleepycat Software's DB2. It is described as "a programmatic toolkit that provides high-performance built-in database support for both standalone and client/server applications." (--with-db2)
db3 DB3 is Sleepycat Software's DB3. (--with-db3)
cdb Cdb is "a fast, reliable, lightweight package for creating and reading constant databases." It is from the author of qmail and can be found here. Since it is constant, we support only reading operations. (--with-cdb)

Przykład 1. DBA example

<?php

$id = dba_open ("/tmp/test.db", "n", "db2");

if (!$id) {
    echo "dba_open failed\n";
    exit;
}

dba_replace ("key", "This is an example!", $id);

if (dba_exists ("key", $id)) {
    echo dba_fetch ("key", $id);
    dba_delete ("key", $id);
}

dba_close ($id);
?>

DBA is binary safe and does not have any arbitrary limits. However, it inherits all limits set by the underlying database implementation.

All file-based databases must provide a way of setting the file mode of a new created database, if that is possible at all. The file mode is commonly passed as the fourth argument to dba_open() or dba_popen().

You can access all entries of a database in a linear way by using the dba_firstkey() and dba_nextkey() functions. You may not change the database while traversing it.

Przykład 2. Traversing a database

<?php

# ...open database...

$key = dba_firstkey ($id);

while ($key != false) {
    if (...) { # remember the key to perform some action later
        $handle_later[] = $key;
    }
    $key = dba_nextkey ($id);
}

for ($i = 0; $i < count($handle_later); $i++)
    dba_delete ($handle_later[$i], $id);

?>

Spis treści
dba_close -- Close database
dba_delete -- Delete entry specified by key
dba_exists -- Check whether key exists
dba_fetch -- Fetch data specified by key
dba_firstkey -- Fetch first key
dba_insert -- Insert entry
dba_nextkey -- Fetch next key
dba_popen -- Open database persistently
dba_open -- Open database
dba_optimize -- Optimize database
dba_replace -- Replace or insert entry
dba_sync -- Synchronize database

dba_close

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

dba_close -- Close database

Description

void dba_close ( int handle)

dba_close() closes the established database and frees all resources specified by handle.

handle is a database handle returned by dba_open().

dba_close() does not return any value.

See also: dba_open() and dba_popen()

dba_delete

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

dba_delete -- Delete entry specified by key

Description

bool dba_delete ( string key, int handle)

dba_delete() deletes the entry specified by key from the database specified with handle.

key is the key of the entry which is deleted.

handle is a database handle returned by dba_open().

dba_delete() returns TRUE or FALSE, if the entry is deleted or not deleted, respectively.

See also: dba_exists(), dba_fetch(), dba_insert(), and dba_replace().

dba_exists

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

dba_exists -- Check whether key exists

Description

bool dba_exists ( string key, int handle)

dba_exists() checks whether the specified key exists in the database specified by handle.

Key is the key the check is performed for.

Handle is a database handle returned by dba_open().

dba_exists() returns TRUE or FALSE, if the key is found or not found, respectively.

See also: dba_fetch(), dba_delete(), dba_insert(), and dba_replace().

dba_fetch

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

dba_fetch -- Fetch data specified by key

Description

string dba_fetch ( string key, int handle)

dba_fetch() fetches the data specified by key from the database specified with handle.

Key is the key the data is specified by.

Handle is a database handle returned by dba_open().

dba_fetch() returns the associated string or FALSE, if the key/data pair is found or not found, respectively.

See also: dba_exists(), dba_delete(), dba_insert(), and dba_replace().

dba_firstkey

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

dba_firstkey -- Fetch first key

Description

string dba_firstkey ( int handle)

dba_firstkey() returns the first key of the database specified by handle and resets the internal key pointer. This permits a linear search through the whole database.

Handle is a database handle returned by dba_open().

dba_firstkey() returns the key or FALSE depending on whether it succeeds or fails, respectively.

See also: dba_nextkey() and example 2 in the DBA overview

dba_insert

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

dba_insert -- Insert entry

Description

bool dba_insert ( string key, string value, int handle)

dba_insert() inserts the entry described with key and value into the database specified by handle. It fails, if an entry with the same key already exists.

key is the key of the entry to be inserted.

value is the value to be inserted.

handle is a database handle returned by dba_open().

dba_insert() returns TRUE or FALSE, depending on whether it succeeds of fails, respectively.

See also: dba_exists() dba_delete() dba_fetch() dba_replace()

dba_nextkey

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

dba_nextkey -- Fetch next key

Description

string dba_nextkey ( int handle)

dba_nextkey() returns the next key of the database specified by handle and advances the internal key pointer.

handle is a database handle returned by dba_open().

dba_nextkey() returns the key or FALSE depending on whether it succeeds or fails, respectively.

See also: dba_firstkey() and example 2 in the DBA overview

dba_popen

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

dba_popen -- Open database persistently

Description

int dba_popen ( string path, string mode, string handler [, ...])

dba_popen() establishes a persistent database instance for path with mode using handler.

path is commonly a regular path in your filesystem.

mode is "r" for read access, "w" for read/write access to an already existing database, "c" for read/write access and database creation if it doesn't currently exist, and "n" for create, truncate and read/write access.

handler is the name of the handler which shall be used for accessing path. It is passed all optional parameters given to dba_popen() and can act on behalf of them.

dba_popen() returns a positive handle or FALSE, in the case the open is successful or fails, respectively.

See also: dba_open() dba_close()

dba_open

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

dba_open -- Open database

Description

int dba_open ( string path, string mode, string handler [, ...])

dba_open() establishes a database instance for path with mode using handler.

path is commonly a regular path in your filesystem.

mode is "r" for read access, "w" for read/write access to an already existing database, "c" for read/write access and database creation if it doesn't currently exist, and "n" for create, truncate and read/write access.

handler is the name of the handler which shall be used for accessing path. It is passed all optional parameters given to dba_open() and can act on behalf of them.

dba_open() returns a positive handle or FALSE, in the case the open is successful or fails, respectively.

See also: dba_popen() dba_close()

dba_optimize

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

dba_optimize -- Optimize database

Description

bool dba_optimize ( int handle)

dba_optimize() optimizes the underlying database specified by handle.

handle is a database handle returned by dba_open().

dba_optimize() returns TRUE or FALSE, if the optimization succeeds or fails, respectively.

See also: dba_sync()

dba_replace

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

dba_replace -- Replace or insert entry

Description

bool dba_replace ( string key, string value, int handle)

dba_replace() replaces or inserts the entry described with key and value into the database specified by handle.

key is the key of the entry to be inserted.

value is the value to be inserted.

handle is a database handle returned by dba_open().

dba_replace() returns TRUE or FALSE, depending on whether it succeeds of fails, respectively.

See also: dba_exists(), dba_delete(), dba_fetch(), and dba_insert().

dba_sync

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

dba_sync -- Synchronize database

Description

bool dba_sync ( int handle)

dba_sync() synchronizes the database specified by handle. This will probably trigger a physical write to disk, if supported.

handle is a database handle returned by dba_open().

dba_sync() returns TRUE or FALSE, if the synchronization succeeds or fails, respectively.

See also: dba_optimize()

XVIII. Date and Time functions

Spis treści
checkdate -- Validate a gregorian date/time
date -- Format a local time/date
getdate -- Get date/time information
gettimeofday -- Get current time
gmdate -- Format a GMT/CUT date/time
gmmktime -- Get UNIX timestamp for a GMT date
gmstrftime --  Format a GMT/CUT time/date according to locale settings
localtime -- Get the local time
microtime --  Return current UNIX timestamp with microseconds
mktime -- Get UNIX timestamp for a date
strftime --  Format a local time/date according to locale settings
time -- Return current UNIX timestamp
strtotime --  Parse about any English textual datetime description into a UNIX timestamp

checkdate

(PHP 3, PHP 4 >= 4.0.0)

checkdate -- Validate a gregorian date/time

Description

bool checkdate ( int month, int day, int year)

Returns TRUE if the date given is valid; otherwise returns FALSE. Checks the validity of the date formed by the arguments. A date is considered valid if:

  • year is between 1 and 32767 inclusive

  • month is between 1 and 12 inclusive

  • Day is within the allowed number of days for the given month. Leap years are taken into consideration.

See also mktime() and strtotime().

date

(PHP 3, PHP 4 >= 4.0.0)

date -- Format a local time/date

Description

string date ( string format [, int timestamp])

Returns a string formatted according to the given format string using the given integer timestamp or the current local time if no timestamp is given.

Notatka: 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.)

To generate a timestamp from a string representation of the date, you may be able to use strtotime(). Additionally, some databases have functions to convert their date formats into timestamps (such as MySQL's UNIX_TIMESTAMP function).

The following characters are recognized in the format string:

  • a - "am" or "pm"

  • A - "AM" or "PM"

  • B - Swatch Internet time

  • d - day of the month, 2 digits with leading zeros; i.e. "01" to "31"

  • D - day of the week, textual, 3 letters; i.e. "Fri"

  • F - month, textual, long; i.e. "January"

  • g - hour, 12-hour format without leading zeros; i.e. "1" to "12"

  • G - hour, 24-hour format without leading zeros; i.e. "0" to "23"

  • h - hour, 12-hour format; i.e. "01" to "12"

  • H - hour, 24-hour format; i.e. "00" to "23"

  • i - minutes; i.e. "00" to "59"

  • I (capital i) - "1" if Daylight Savings Time, "0" otherwise.

  • j - day of the month without leading zeros; i.e. "1" to "31"

  • l (lowercase 'L') - day of the week, textual, long; i.e. "Friday"

  • L - boolean for whether it is a leap year; i.e. "0" or "1"

  • m - month; i.e. "01" to "12"

  • M - month, textual, 3 letters; i.e. "Jan"

  • n - month without leading zeros; i.e. "1" to "12"

  • O - Difference to Greenwich time in hours; i.e. "+0200"

  • r - RFC 822 formatted date; i.e. "Thu, 21 Dec 2000 16:01:07 +0200" (added in PHP 4.0.4)

  • s - seconds; i.e. "00" to "59"

  • S - English ordinal suffix for the day of the month, 2 characters; i.e. "th", "nd"

  • t - number of days in the given month; i.e. "28" to "31"

  • T - Timezone setting of this machine; i.e. "MDT"

  • U - seconds since the epoch

  • w - day of the week, numeric, i.e. "0" (Sunday) to "6" (Saturday)

  • W - ISO-8601 week number of year, weeks starting on monday (added in PHP 4.1.0) (Saturday)

  • Y - year, 4 digits; i.e. "1999"

  • y - year, 2 digits; i.e. "99"

  • z - day of the year; i.e. "0" to "365"

  • Z - timezone offset in seconds (i.e. "-43200" to "43200"). The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.

Unrecognized characters in the format string will be printed as-is. The "Z" format will always return "0" when using gmdate().

Przykład 1. date() example

echo date ("l dS of F Y h:i:s A");
echo "July 1, 2000 is on a " . date ("l", mktime(0,0,0,7,1,2000));

You can prevent a recognized character in the format string from being expanded by escaping it with a preceding backslash. If the character with a backslash is already a special sequence, you may need to also escape the backslash.

Przykład 2. Escaping characters in date()

echo date("l \\t\h\e jS"); // prints something like 'Saturday the 8th'

It is possible to use date() and mktime() together to find dates in the future or the past.

Przykład 3. date() and mktime() example

$tomorrow  = mktime (0,0,0,date("m")  ,date("d")+1,date("Y"));
$lastmonth = mktime (0,0,0,date("m")-1,date("d"),  date("Y"));
$nextyear  = mktime (0,0,0,date("m"),  date("d"),  date("Y")+1);

Notatka: This can be more reliable than simply adding or subtracting the number of seconds in a day or month to a timestamp because of daylight savings time.

Some examples of date() formatting. Note that you should escape any other characters, as any which currently have a special meaning will produce undesirable results, and other characters may be assigned meaning in future PHP versions. When escaping, be sure to use single quotes to prevent characters like \n from becoming newlines.

Przykład 4. date() Formatting

/* 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, m, Y");                       // 10, 3, 2001
$today = date("Ymd");                           // 20010310
$today = date('h-i-s, j-m-y, it is w Day z ');  // 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 15:16:08 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:17 m is month
$today = date("H:i:s");                         // 17:16:17

To format dates in other languages, you should use the setlocale() and strftime() functions.

See also getlastmod(), gmdate(), mktime(), strftime() and time().

getdate

(PHP 3, PHP 4 >= 4.0.0)

getdate -- Get date/time information

Description

array getdate ( [int timestamp])

Returns an associative array containing the date information of the timestamp, or the current local time if no timestamp is given, as the following array elements:

  • "seconds" - seconds

  • "minutes" - minutes

  • "hours" - hours

  • "mday" - day of the month

  • "wday" - day of the week, numeric : from 0 as Sunday up to 6 as Saturday

  • "mon" - month, numeric

  • "year" - year, numeric

  • "yday" - day of the year, numeric; i.e. "299"

  • "weekday" - day of the week, textual, full; i.e. "Friday"

  • "month" - month, textual, full; i.e. "January"

Przykład 1. getdate() example

$today = getdate(); 
$month = $today['month']; 
$mday = $today['mday']; 
$year = $today['year']; 
echo "$month $mday, $year";

gettimeofday

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

gettimeofday -- Get current time

Description

array gettimeofday ( void)

This is an interface to gettimeofday(2). It returns an associative array containing the data returned from the system call.

  • "sec" - seconds

  • "usec" - microseconds

  • "minuteswest" - minutes west of Greenwich

  • "dsttime" - type of dst correction

gmdate

(PHP 3, PHP 4 >= 4.0.0)

gmdate -- Format a GMT/CUT date/time

Description

string gmdate ( string format [, int timestamp])

Identical to the date() function except that the time returned is Greenwich Mean Time (GMT). For example, when run in Finland (GMT +0200), the first line below prints "Jan 01 1998 00:00:00", while the second prints "Dec 31 1997 22:00:00".

Przykład 1. gmdate() example

echo date ("M d Y H:i:s", mktime (0,0,0,1,1,1998));
echo gmdate ("M d Y H:i:s", mktime (0,0,0,1,1,1998));

See also date(), mktime(), gmmktime() and strftime()

gmmktime

(PHP 3, PHP 4 >= 4.0.0)

gmmktime -- Get UNIX timestamp for a GMT date

Description

int gmmktime ( int hour, int minute, int second, int month, int day, int year [, int is_dst])

Identical to mktime() except the passed parameters represents a GMT date.

gmstrftime

(PHP 3>= 3.0.12, PHP 4 >= 4.0.0)

gmstrftime --  Format a GMT/CUT time/date according to locale settings

Description

string gmstrftime ( string format [, int timestamp])

Behaves the same as strftime() except that the time returned is Greenwich Mean Time (GMT). For example, when run in Eastern Standard Time (GMT -0500), the first line below prints "Dec 31 1998 20:00:00", while the second prints "Jan 01 1999 01:00:00".

Przykład 1. gmstrftime() example

setlocale ('LC_TIME', 'en_US');
echo strftime ("%b %d %Y %H:%M:%S", mktime (20,0,0,12,31,98))."\n";
echo gmstrftime ("%b %d %Y %H:%M:%S", mktime (20,0,0,12,31,98))."\n";

See also strftime().

localtime

(PHP 4 >= 4.0.0)

localtime -- Get the local time

Description

array localtime ( [int timestamp [, bool is_associative]])

The localtime() function returns an array identical to that of the structure returned by the C function call. The first argument to localtime() is the timestamp, if this is not given the current time is used. The second argument to the localtime() is the is_associative, if this is set to 0 or not supplied than the array is returned as a regular, numerically indexed array. If the argument is set to 1 then localtime() is an associative array containing all the different elements of the structure returned by the C function call to localtime. The names of the different keys of the associative array are as follows:

  • "tm_sec" - seconds

  • "tm_min" - minutes

  • "tm_hour" - hour

  • "tm_mday" - day of the month

  • "tm_mon" - month of the year, 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

microtime

(PHP 3, PHP 4 >= 4.0.0)

microtime --  Return current UNIX timestamp with microseconds

Description

string microtime ( void)

Returns the string "msec sec" where sec is the current time measured in the number of seconds since the Unix Epoch (0:00:00 January 1, 1970 GMT), and msec is the microseconds part. This function is only available on operating systems that support the gettimeofday() system call.

Both portions of the string are returned in units of seconds.

Przykład 1. microtime() example

function getmicrotime(){ 
    list($usec, $sec) = explode(" ",microtime()); 
    return ((float)$usec + (float)$sec); 
    } 

$time_start = getmicrotime();
    
for ($i=0; $i < 1000; $i++){
    //do nothing, 1000 times
    }

$time_end = getmicrotime();
$time = $time_end - $time_start;

echo "Did nothing in $time seconds";

See also time().

mktime

(PHP 3, PHP 4 >= 4.0.0)

mktime -- Get UNIX timestamp for a date

Description

int mktime ( int hour, int minute, int second, int month, int day, int year [, int is_dst])

Warning: Note the strange order of arguments, which differs from the order of arguments in a regular UNIX mktime() call and which does not lend itself well to leaving out parameters from right to left (see below). It is a common error to mix these values up in a script.

Returns the Unix timestamp corresponding to the arguments given. This timestamp is a long integer containing the number of seconds between the Unix Epoch (January 1 1970) and the time specified.

Arguments may be left out in order from right to left; any arguments thus omitted will be set to the current value according to the local date and time.

Is_dst can be set to 1 if the time is during daylight savings time, 0 if it is not, or -1 (the default) if it is unknown whether the time is within daylight savings time or not.

Notatka: Is_dst was added in 3.0.10.

mktime() is useful for doing date arithmetic and validation, as it will automatically calculate the correct value for out-of-range input. For example, each of the following lines produces the string "Jan-01-1998".

Przykład 1. mktime() example

echo date ("M-d-Y", mktime (0,0,0,12,32,1997));
echo date ("M-d-Y", mktime (0,0,0,13,1,1997));
echo date ("M-d-Y", mktime (0,0,0,1,1,1998));
echo date ("M-d-Y", mktime (0,0,0,1,1,98));
Year may be a two or four digit value, with values between 0-69 mapping to 2000-2069 and 70-99 to 1970-1999 (on systems where time_t is a 32bit signed integer, as most common today, the valid range for year is somewhere between 1902 and 2037).

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".

Przykład 2. Last day of next month

$lastday = mktime (0,0,0,3,0,2000);
echo strftime ("Last day in Feb 2000 is: %d", $lastday);
     
$lastday = mktime (0,0,0,4,-31,2000);
echo strftime ("Last day in Feb 2000 is: %d", $lastday);

Date with year, month and day equal to zero is considered illegal (otherwise it what be regarded as 30.11.1999, which would be strange behavior).

See also date() and time().

strftime

(PHP 3, PHP 4 >= 4.0.0)

strftime --  Format a local time/date according to locale settings

Description

string strftime ( string format [, int timestamp])

Returns a string formatted according to the given format string using the given timestamp or the current local time if no timestamp is given. Month and weekday names and other language dependent strings respect the current locale set with setlocale().

The following conversion specifiers are recognized in the format string:

  • %a - abbreviated weekday name according to the current locale

  • %A - full weekday name according to the current locale

  • %b - abbreviated month name according to the current locale

  • %B - full month name according to the current locale

  • %c - preferred date and time representation for the current locale

  • %C - century number (the year divided by 100 and truncated to an integer, range 00 to 99)

  • %d - day of the month as a decimal number (range 01 to 31)

  • %D - same as %m/%d/%y

  • %e - day of the month as a decimal number, a single digit is preceded by a space (range ' 1' to '31')

  • %g - like %G, but without the century.

  • %G - The 4-digit year corresponding to the ISO week number (see %V). This has the same format and value as %Y, except that if the ISO week number belongs to the previous or next year, that year is used instead.

  • %h - same as %b

  • %H - hour as a decimal number using a 24-hour clock (range 00 to 23)

  • %I - hour as a decimal number using a 12-hour clock (range 01 to 12)

  • %j - day of the year as a decimal number (range 001 to 366)

  • %m - month as a decimal number (range 01 to 12)

  • %M - minute as a decimal number

  • %n - newline character

  • %p - either `am' or `pm' according to the given time value, or the corresponding strings for the current locale

  • %r - time in a.m. and p.m. notation

  • %R - time in 24 hour notation

  • %S - second as a decimal number

  • %t - tab character

  • %T - current time, equal to %H:%M:%S

  • %u - weekday as a decimal number [1,7], with 1 representing Monday

    Ostrze¿enie

    Sun Solaris seems to start with Sunday as 1 although ISO 9889:1999 (the current C standard) clearly specifies that it should be Monday.

  • %U - week number of the current year as a decimal number, starting with the first Sunday as the first day of the first week

  • %V - The ISO 8601:1988 week number of the current year as a decimal number, range 01 to 53, where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week. (Use %G or %g for the year component that corresponds to the week number for the specified timestamp.)

  • %W - week number of the current year as a decimal number, starting with the first Monday as the first day of the first week

  • %w - day of the week as a decimal, Sunday being 0

  • %x - preferred date representation for the current locale without the time

  • %X - preferred time representation for the current locale without the date

  • %y - year as a decimal number without a century (range 00 to 99)

  • %Y - year as a decimal number including the century

  • %Z - time zone or name or abbreviation

  • %% - a literal `%' character

Notatka: Not all conversion specifiers may be supported by your C library, in which case they will not be supported by PHP's strftime().

Przykład 1. strftime() example

setlocale (LC_TIME, "C");
print (strftime ("%A in Finnish is "));
setlocale (LC_TIME, "fi_FI");
print (strftime ("%A, in French "));
setlocale (LC_TIME, "fr_FR");
print (strftime ("%A and in German "));
setlocale (LC_TIME, "de_DE");
print (strftime ("%A.\n"));
This example works if you have the respective locales installed in your system.

See also setlocale() and mktime() and the Open Group specification of strftime().

time

(PHP 3, PHP 4 >= 4.0.0)

time -- Return current UNIX timestamp

Description

int time ( void)

Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

See also date().

strtotime

(PHP 3>= 3.0.12, PHP 4 >= 4.0.0)

strtotime --  Parse about any English textual datetime description into a UNIX timestamp

Description

int strtotime ( string time [, int now])

The function expects to be given a string containing an English date format and will try to parse that format into a UNIX timestamp relative to the timestamp given in now, or the current time if none is supplied. Upon failure, -1 is returned.

Because strtotime() behaves according to GNU date syntax, have a look at the GNU manual page titled Date Input Formats. Described there is valid syntax for the time parameter.

Przykład 1. strtotime() examples

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";

Przykład 2. Checking for failure

$str = 'Not Good';
if (($timestamp = strtotime($str)) === -1) {
    echo "The string ($str) is bogus";
} else {
    echo "$str == ". date('l dS of F Y h:i:s A',$timestamp);
}

Notatka: 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.)

XIX. dBase functions

These functions allow you to access records stored in dBase-format (dbf) databases. In order to use these functions, you must compile PHP with the --enable-dbase option.

There is no support for indexes or memo fields. There is no support for locking, too. Two concurrent webserver processes modifying the same dBase file will very likely ruin your database.

dBase files are simple sequential files of fixed length records. Records are appended to the end of the file and delete records are kept until you call dbase_pack().

We recommend that you do not use dBase files as your production database. Choose any real SQL server instead; MySQL or Postgres are common choices with PHP. dBase support is here to allow you to import and export data to and from your web database, because the file format is commonly understood by Windows spreadsheets and organizers.

Spis treści
dbase_create -- Creates a dBase database
dbase_open -- Opens a dBase database
dbase_close -- Close a dBase database
dbase_pack -- Packs a dBase database
dbase_add_record -- Add a record to a dBase database
dbase_replace_record -- Replace a record in a dBase database
dbase_delete_record -- Deletes a record from a dBase database
dbase_get_record -- Gets a record from a dBase database
dbase_get_record_with_names --  Gets a record from a dBase database as an associative array
dbase_numfields --  Find out how many fields are in a dBase database
dbase_numrecords --  Find out how many records are in a dBase database

dbase_create

(PHP 3, PHP 4 >= 4.0.0)

dbase_create -- Creates a dBase database

Description

int dbase_create ( string filename, array fields)

The fields parameter is an array of arrays, each array describing the format of one field in the database. Each field consists of a name, a character indicating the field type, a length, and a precision.

The types of fields available are:

L

Boolean. These do not have a length or precision.

M

Memo. (Note that these aren't supported by PHP.) These do not have a length or precision.

D

Date (stored as YYYYMMDD). These do not have a length or precision.

N

Number. These have both a length and a precision (the number of digits after the decimal point).

C

String.

If the database is successfully created, a dbase_identifier is returned, otherwise FALSE is returned.

Przykład 1. Creating a dBase database file

// "database" name
$dbname = "/tmp/test.dbf";

// database "definition"
$def =
    array(
        array("date",     "D"),
        array("name",     "C",  50),
        array("age",      "N",   3, 0),
        array("email",    "C", 128),
        array("ismember", "L")
    );

// creation
if (!dbase_create($dbname, $def))
    print "<strong>Error!</strong>";

dbase_open

(PHP 3, PHP 4 >= 4.0.0)

dbase_open -- Opens a dBase database

Description

int dbase_open ( string filename, int flags)

The flags correspond to those for the open() system call. (Typically 0 means read-only, 1 means write-only, and 2 means read and write.)

Returns a dbase_identifier for the opened database, or FALSE if the database couldn't be opened.

Notatka: Kiedy włączony jest tryb bezpieczny, PHP sprawdza, czy plik(i)/katalogi na których chcesz operować mają takie same UID jak skrypt, który jest aktualnie wykonywany.

dbase_close

(PHP 3, PHP 4 >= 4.0.0)

dbase_close -- Close a dBase database

Description

bool dbase_close ( int dbase_identifier)

Closes the database associated with dbase_identifier.

dbase_pack

(PHP 3, PHP 4 >= 4.0.0)

dbase_pack -- Packs a dBase database

Description

bool dbase_pack ( int dbase_identifier)

Packs the specified database (permanently deleting all records marked for deletion using dbase_delete_record()).

dbase_add_record

(PHP 3, PHP 4 >= 4.0.0)

dbase_add_record -- Add a record to a dBase database

Description

bool dbase_add_record ( int dbase_identifier, array record)

Adds the data in the record to the database. If the number of items in the supplied record isn't equal to the number of fields in the database, the operation will fail and FALSE will be returned.

dbase_replace_record

(PHP 3>= 3.0.11, PHP 4 >= 4.0.0)

dbase_replace_record -- Replace a record in a dBase database

Description

bool dbase_replace_record ( int dbase_identifier, array record, int dbase_record_number)

Replaces the data associated with the record record_number with the data in the record in the database. If the number of items in the supplied record is not equal to the number of fields in the database, the operation will fail and FALSE will be returned.

dbase_record_number is an integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).

dbase_delete_record

(PHP 3, PHP 4 >= 4.0.0)

dbase_delete_record -- Deletes a record from a dBase database

Description

bool dbase_delete_record ( int dbase_identifier, int record)

Marks record to be deleted from the database. To actually remove the record from the database, you must also call dbase_pack().

dbase_get_record

(PHP 3, PHP 4 >= 4.0.0)

dbase_get_record -- Gets a record from a dBase database

Description

array dbase_get_record ( int dbase_identifier, int record)

Returns the data from record in an array. The array is indexed starting at 0, and includes an associative member named 'deleted' which is set to 1 if the record has been marked for deletion (see dbase_delete_record().

Each field is converted to the appropriate PHP type, except:

  • Dates are left as strings

  • Integers that would have caused an overflow (> 32 bits) are returned as strings

dbase_get_record_with_names

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

dbase_get_record_with_names --  Gets a record from a dBase database as an associative array

Description

array dbase_get_record_with_names ( int dbase_identifier, int record)

Returns the data from record in an associative array. The array also includes an associative member named 'deleted' which is set to 1 if the record has been marked for deletion (see dbase_delete_record()).

Each field is converted to the appropriate PHP type, except:

  • Dates are left as strings

  • Integers that would have caused an overflow (> 32 bits) are returned as strings

dbase_numfields

(PHP 3, PHP 4 >= 4.0.0)

dbase_numfields --  Find out how many fields are in a dBase database

Description

int dbase_numfields ( int dbase_identifier)

Returns the number of fields (columns) in the specified database. Field numbers are between 0 and dbase_numfields($db)-1, while record numbers are between 1 and dbase_numrecords($db).

Przykład 1. Using dbase_numfields()

$rec = dbase_get_record($db, $recno);
$nf  = dbase_numfields($db);
for ($i=0; $i < $nf; $i++) {
    print $rec[$i]."<br>\n";
}

dbase_numrecords

(PHP 3, PHP 4 >= 4.0.0)

dbase_numrecords --  Find out how many records are in a dBase database

Description

int dbase_numrecords ( int dbase_identifier)

Returns the number of records (rows) in the specified database. Record numbers are between 1 and dbase_numrecords($db), while field numbers are between 0 and dbase_numfields($db)-1.

XX. DBM Functions

These functions allow you to store records stored in a dbm-style database. This type of database (supported by the Berkeley DB, GDBM, and some system libraries, as well as a built-in flatfile library) stores key/value pairs (as opposed to the full-blown records supported by relational databases).

Przykład 1. DBM example

$dbm = dbmopen ("lastseen", "w");
if (dbmexists ($dbm, $userid)) {
    $last_seen = dbmfetch ($dbm, $userid);
} else {
    dbminsert ($dbm, $userid, time());
}
do_stuff();
dbmreplace ($dbm, $userid, time());
dbmclose ($dbm);

Spis treści
dbmopen -- Opens a DBM database
dbmclose -- Closes a dbm database
dbmexists --  Tells if a value exists for a key in a DBM database
dbmfetch --  Fetches a value for a key from a DBM database
dbminsert --  Inserts a value for a key in a DBM database
dbmreplace --  Replaces the value for a key in a DBM database
dbmdelete --  Deletes the value for a key from a DBM database
dbmfirstkey --  Retrieves the first key from a DBM database
dbmnextkey --  Retrieves the next key from a DBM database
dblist --  Describes the DBM-compatible library being used

dbmopen

(PHP 3, PHP 4 >= 4.0.0)

dbmopen -- Opens a DBM database

Description

int dbmopen ( string filename, string flags)

The first argument is the full-path filename of the DBM file to be opened and the second is the file open mode which is one of "r", "n", "c" or "w" for read-only, new (implies read-write, and most likely will truncate an already-existing database of the same name), create (implies read-write, and will not truncate an already-existing database of the same name) and read-write respectively.

Returns an identifier to be passed to the other DBM functions on success, or FALSE on failure.

If NDBM support is used, NDBM will actually create filename.dir and filename.pag files. GDBM only uses one file, as does the internal flat-file support, and Berkeley DB creates a filename.db file. Note that PHP does its own file locking in addition to any file locking that may be done by the DBM library itself. PHP does not delete the .lck files it creates. It uses these files simply as fixed inodes on which to do the file locking. For more information on DBM files, see your Unix man pages, or obtain GNU's GDBM.

Notatka: Kiedy włączony jest tryb bezpieczny, PHP sprawdza, czy plik(i)/katalogi na których chcesz operować mają takie same UID jak skrypt, który jest aktualnie wykonywany.

dbmclose

(PHP 3, PHP 4 >= 4.0.0)

dbmclose -- Closes a dbm database

Description

bool dbmclose ( int dbm_identifier)

Unlocks and closes the specified database.

dbmexists

(PHP 3, PHP 4 >= 4.0.0)

dbmexists --  Tells if a value exists for a key in a DBM database

Description

bool dbmexists ( int dbm_identifier, string key)

Returns TRUE if there is a value associated with the key.

dbmfetch

(PHP 3, PHP 4 >= 4.0.0)

dbmfetch --  Fetches a value for a key from a DBM database

Description

string dbmfetch ( int dbm_identifier, string key)

Returns the value associated with key.

dbminsert

(PHP 3, PHP 4 >= 4.0.0)

dbminsert --  Inserts a value for a key in a DBM database

Description

int dbminsert ( int dbm_identifier, string key, string value)

Adds the value to the database with the specified key.

Returns -1 if the database was opened read-only, 0 if the insert was successful, and 1 if the specified key already exists. (To replace the value, use dbmreplace().)

dbmreplace

(PHP 3, PHP 4 >= 4.0.0)

dbmreplace --  Replaces the value for a key in a DBM database

Description

int dbmreplace ( int dbm_identifier, string key, string value)

Replaces the value for the specified key in the database.

This will also add the key to the database if it didn't already exist.

dbmdelete

(PHP 3, PHP 4 >= 4.0.0)

dbmdelete --  Deletes the value for a key from a DBM database

Description

bool dbmdelete ( int dbm_identifier, string key)

Deletes the value for key in the database.

Returns FALSE if the key didn't exist in the database.

dbmfirstkey

(PHP 3, PHP 4 >= 4.0.0)

dbmfirstkey --  Retrieves the first key from a DBM database

Description

string dbmfirstkey ( int dbm_identifier)

Returns the first key in the database. Note that no particular order is guaranteed since the database may be built using a hash-table, which doesn't guarantee any ordering.

dbmnextkey

(PHP 3, PHP 4 >= 4.0.0)

dbmnextkey --  Retrieves the next key from a DBM database

Description

string dbmnextkey ( int dbm_identifier, string key)

Returns the next key after key. By calling dbmfirstkey() followed by successive calls to dbmnextkey() it is possible to visit every key/value pair in the dbm database. For example:

Przykład 1. Visiting every key/value pair in a DBM database

$key = dbmfirstkey ($dbm_id);
while ($key) {
    echo "$key = " . dbmfetch ($dbm_id, $key) . "\n";
    $key = dbmnextkey ($dbm_id, $key);
}

dblist

(PHP 3, PHP 4 >= 4.0.0)

dblist --  Describes the DBM-compatible library being used

Description

string dblist ( void)

XXI. dbx functions

The dbx module is a database abstraction layer (db 'X', where 'X' is a supported database). The dbx functions allow you to access all supported databases using a single calling convention. In order to have these functions available, you must compile PHP with dbx support by using the --enable-dbx option and all options for the databases that will be used, e.g. for MySQL you must also specify --with-mysql. The dbx-functions themselves do not interface directly to the databases, but interface to the modules that are used to support these databases. To be able to use a database with the dbx-module, the module must be either linked or loaded into PHP, and the database module must be supported by the dbx-module. Currently, MySQL, PostgreSQL, Microsoft SQL Server, FrontBase and ODBC are supported, but others will follow (soon, I hope :-).

Documentation for adding additional database support to dbx can be found at http://www.guidance.nl/php/dbx/doc/.

Spis treści
dbx_close -- Close an open connection/database
dbx_connect -- Open a connection/database
dbx_error --  Report the error message of the latest function call in the module (not just in the connection)
dbx_query -- Send a query and fetch all results (if any)
dbx_sort --  Sort a result from a dbx_query by a custom sort function
dbx_compare -- Compare two rows for sorting purposes

dbx_close

(PHP 4 >= 4.0.6)

dbx_close -- Close an open connection/database

Description

bool dbx_close ( dbx_link_object link_identifier)

Returns TRUE on success, FALSE on error.

Przykład 1. dbx_close() example

<?php
$link = dbx_connect ("mysql", "localhost", "db", "username", "password")
    or die ("Could not connect");
print("Connected successfully");
dbx_close($link);
?>

Notatka: Always refer to the module-specific documentation as well.

See also: dbx_connect().

dbx_connect

(PHP 4 >= 4.0.6)

dbx_connect -- Open a connection/database

Description

dbx_link_object dbx_connect ( string module, string host, string database, string username, string password [, int persistent])

Returns: a dbx_link_object on success, FALSE on error. If a connection has been made but the database could not be selected, the connection is closed and FALSE is returned. The 'persistent' parameter can be set to DBX_PERSISTENT so a persistent connection will be created.

The module parameter can be either a string or a constant. The possible values are given below, but keep in mind that they only work if the module is actually loaded.

  • module DBX_MYSQL : "mysql"

  • module DBX_ODBC : "odbc"

  • module DBX_PGSQL : "pgsql"

  • module DBX_MSSQL : "mssql"

  • module DBX_FBSQL : "fbsql" (CVS only)

The dbx_link_object has three members, a 'handle', a 'module' and a 'database'. The 'database' member is the name of the currently selected database. The 'module' member is for internal use by dbx only, and is actually the module number mentioned above. The 'handle' member is a valid handle for the connected database, and as such can be used in module-specific functions (if required), e.g.

<?php
$link = dbx_connect ("mysql", "localhost", "db", "username", "password");
mysql_close ($link->handle); // dbx_close($link) would be better here
?>

Host, database, username and password parameters are expected, but not always used, depending on the connect-functions for the abstracted module.

Przykład 1. dbx_connect() example

<?php
$link = dbx_connect ("odbc", "", "db", "username", "password", DBX_PERSISTENT)
    or die ("Could not connect");
print ("Connected successfully");
dbx_close ($link);
?>

Notatka: Always refer to the module-specific documentation as well.

See also: dbx_close().

dbx_error

(PHP 4 >= 4.0.6)

dbx_error --  Report the error message of the latest function call in the module (not just in the connection)

Description

string dbx_error ( dbx_link_object link_identifier)

Returns a string containing the error-message from the last function call of the module (e.g. mysql-module). If there are multiple connections on the same module, just the last error is given. If there are connections on different modules, the latest error is returned for the specified module (specified by the link parameter, that is). Note that the ODBC-module doesn't support an error_reporting function at the moment.

Przykład 1. dbx_error() example

<?php
$link = dbx_connect ("mysql", "localhost", "db", "username", "password")
    or die ("Could not connect");
$result = dbx_query ($link, "select id from nonexistingtbl");
if ($result==0) {
    echo dbx_error ($link);
}
dbx_close ($link);
?>

Notatka: Always refer to the module-specific documentation as well.

The error-message for Microsoft SQL Server is actually the result of the mssql_get_last_message() function.

dbx_query

(PHP 4 >= 4.0.6)

dbx_query -- Send a query and fetch all results (if any)

Description

dbx_result_object dbx_query ( dbx_link_object link_identifier, string sql_statement [, long flags])

Returns a dbx_result_object or 1 on success (a result object is only returned for sql-statements that return results) or 0 on failure. The flags parameter is used to control the amount of information that is returned. It may be any combination of the constants DBX_RESULT_INFO, DBX_RESULT_INDEX, DBX_RESULT_ASSOC, OR-ed together. DBX_RESULT_INFO provides info about columns, such as field names and field types. DBX_RESULT_INDEX returns the results in a 2d indexed array (e.g. data[2][3], where 2 is the row (or record) number and 3 is the column (or field) number), where the first row and column are indexed at 0. DBX_RESULT_ASSOC associates the column indices with field names. Note that DBX_RESULT_INDEX is always returned, regardless of the flags parameter. If DBX_RESULT_ASSOC is specified, DBX_RESULT_INFO is also returned even if it wasn't specified. This means that effectively only the combinations DBX_RESULT_INDEX, DBX_RESULT_INDEX | DBX_RESULT_INFO and DBX_RESULT_INDEX | DBX_RESULT_INFO | DBX_RESULT_ASSOC are possible. This last combination is the default if the flags parameter isn't specified. Associated results are actual references to the indexed data, so if you modify data[0][0], then data[0]['fieldnameforfirstcolumn'] is modified as well.

A dbx_result_object has five members (possibly four depending on flags), 'handle', 'cols', 'rows', 'info' (optional) and 'data'. Handle is a valid result identifier for the specified module, and as such can be used in module-specific functions, as seen in the example:

$result = dbx_query ($link, "SELECT id FROM tbl");
mysql_field_len ($result->handle, 0);

The cols and rows members contain the number of columns (or fields) and rows (or records) respectively, e.g.

$result = dbx_query ($link, "SELECT id FROM tbl");
echo "result size: " . $result->rows . " x " . $result->cols . "<br>\n";

The info member is only returned if DBX_RESULT_INFO and/or DBX_RESULT_ASSOC are specified in the flags parameter. It is a 2d array, that has two named rows ("name" and "type") to retrieve column information, e.g.

$result = dbx_query ($link, "SELECT id FROM tbl");
echo "column name: " . $result->info["name"][0] . "<br>\n";
echo "column type: " . $result->info["type"][0] . "<br>\n";

The data member contains the actual resulting data, possibly associated with column names as well. If DBX_RESULT_ASSOC is set, it is possible to use $result->data[2]["fieldname"].

Przykład 1. dbx_query() example

<?php
$link = dbx_connect ("odbc", "", "db", "username", "password")
    or die ("Could not connect");
$result = dbx_query ($link, "SELECT id, parentid, description FROM tbl");
if ($result==0) echo "Query failed\n<br>";
elseif ($result==1) {
    echo "Query executed successfully\n<br>";
} else {
    $rows=$result->rows;
    $cols=$result->cols;
    echo "<p>table dimension: {$result->rows} x {$result->cols}<br><table border=1>\n";
    echo "<tr>";
    for ($col=0; $col<$cols; ++$col) {
        echo "<td>-{$result->info["name"][$col]}-<br>-{$result->info["type"][$col]}-</td>";
    }
    echo "</tr>\n";
    for ($row=0; $row<$rows; ++$row){
        echo "<tr>";
        for ($col=0; $col<$cols; ++$col) {
            echo "<td>-{$result->data[$row][$col]}-</td>";
        }
        echo "</tr>\n";
    }
    echo "</table><p>\n";
    echo "table dimension: {$result->rows} x id, parentid, description<br><table border=1>\n";
    for ($row=0; $row<$rows; ++$row) {
        echo "<tr>";
        echo "<td>-{$result->data[$row]["id"]}-</td>";
        echo "<td>-{$result->data[$row]["parentid"]}-</td>";
        echo "<td>-{$result->data[$row]["description"]}-</td>";
        echo "</tr>\n";
    }
    echo "</table><p>\n";
}
dbx_close($link);
?>

Notatka: Always refer to the module-specific documentation as well.

See also: dbx_connect().

dbx_sort

(PHP 4 >= 4.0.6)

dbx_sort --  Sort a result from a dbx_query by a custom sort function

Description

bool dbx_sort ( dbx_result_object result, string user_compare_function)

Returns TRUE on success, FALSE on error.

Przykład 1. dbx_sort() example

<?php
function user_re_order ($a, $b) {
    $rv = dbx_compare ($a, $b, "parentid", DBX_CMP_DESC);
    if (!$rv) $rv = dbx_compare ($a, $b, "id");
    return $rv;
}

$link = dbx_connect ("odbc", "", "db", "username", "password")
    or die ("Could not connect");
$result = dbx_query ($link, "SELECT id, parentid, description FROM tbl ORDER BY id");
echo "resulting data is now ordered by id<br>";
dbx_sort ($result, "user_re_order");
echo "resulting data is now ordered by parentid (descending), then by id<br>";
dbx_close ($link);
?>

See also dbx_compare().

dbx_compare

(PHP 4 >= 4.1.0)

dbx_compare -- Compare two rows for sorting purposes

Description

int dbx_compare ( array row_a, array row_b, string columnname_or_index [, int flags])

Returns 0 if row_a[$columnname_or_index] is equal to row_b[$columnname_or_index], 1 if it is greater and -1 if it is smaller (or vice versa if the DBX_CMP_DESC flag is set).

The flags can be set to specify comparison direction (whether sorting is ascending or descending) and comparison type (force string or numeric compare by converting the data). The constants for direction are DBX_CMP_ASC and DBX_CMP_DESC. The constants for comparison type are DBX_CMP_NATIVE (no conversion), DBX_CMP_TEXT and DBX_CMP_NUMBER. These constants can be OR-ed together. The default value for the flags parameter is DBX_CMP_ASC | DBX_CMP_NATIVE.

Przykład 1. dbx_compare() example

<?php
function user_re_order ($a, $b) {
    $rv = dbx_compare ($a, $b, "parentid", DBX_CMP_DESC);
    if (!$rv) { 
        $rv = dbx_compare ($a, $b, "id");
        return $rv;
    }
}

$link = dbx_connect ("odbc", "", "db", "username", "password")
    or die ("Could not connect");
$result = dbx_query ($link, "SELECT id, parentid, description FROM tbl ORDER BY id");
echo "resulting data is now ordered by id<br>";
dbx_sort ($result, "user_re_order");
echo "resulting data is now ordered by parentid (descending), then by id<br>";
dbx_close ($link);
?>

See also dbx_sort().

XXII. DB++ Functions

Ostrze¿enie

Ten moduł jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie tych funkcji, ich nazwy, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tego modułu na własne ryzyko.


DB++ Database Functions

db++, made by the german company Concept asa, is a relational database system with high performance and low memory and disk usage in mind. While providing SQL as an additional language interface it is not really a SQL database in the first place but provides its own AQL query language which is much more influenced by the relational algebra then SQL is.

Concept asa always had an interest in supporting open source languages, db++ has had Perl and Tcl call interfaces for years now and uses Tcl as its internal stored procedure language.


Requirements

You need the development libraries and header files included in every db++ installation archive. Concept asa provides additional documentation and Demo versions of db++ for Linux, some other UNIX versions and Windows95/NT.


Installation

Creation and installation of this extension requires the db++ client libraries and header files to be installed on your system. You have to run configure with option --with-dbplus to build this extension.

configure looks for the client libraries and header files under the default paths /usr/dbplus, /usr/local/dbplus and /opt/dblus. If you have installed db++ in a different place you have add the installation path to the configure option like this: --with-dbplus=/your/installation/path.


db++ error codes

Tabela 1. DB++ Error Codes

PHP Constantdb++ constantmeaning
DBPLUS_ERR_NOERRERR_NOERRNull error condition
DBPLUS_ERR_DUPLICATEERR_DUPLICATETried to insert a duplicate tuple
DBPLUS_ERR_EOSCANERR_EOSCANEnd of scan from rget()
DBPLUS_ERR_EMPTYERR_EMPTYRelation is empty (server)
DBPLUS_ERR_CLOSEERR_CLOSEThe server can't close
DBPLUS_ERR_WLOCKEDERR_WLOCKEDThe record is write locked
DBPLUS_ERR_LOCKEDERR_LOCKEDRelation was already locked
DBPLUS_ERR_NOLOCKERR_NOLOCKRelation cannot be locked
DBPLUS_ERR_READERR_READRead error on relation
DBPLUS_ERR_WRITEERR_WRITEWrite error on relation
DBPLUS_ERR_CREATEERR_CREATECreate() system call failed
DBPLUS_ERR_LSEEKERR_LSEEKLseek() system call failed
DBPLUS_ERR_LENGTHERR_LENGTHTuple exceeds maximum length
DBPLUS_ERR_OPENERR_OPENOpen() system call failed
DBPLUS_ERR_WOPENERR_WOPENRelation already opened for writing
DBPLUS_ERR_MAGICERR_MAGICFile is not a relation
DBPLUS_ERR_VERSIONERR_VERSIONFile is a very old relation
DBPLUS_ERR_PGSIZEERR_PGSIZERelation uses a different page size
DBPLUS_ERR_CRCERR_CRCInvalid crc in the superpage
DBPLUS_ERR_PIPEERR_PIPEPiped relation requires lseek()
DBPLUS_ERR_NIDXERR_NIDXToo many secondary indices
DBPLUS_ERR_MALLOCERR_MALLOCMalloc() call failed
DBPLUS_ERR_NUSERSERR_NUSERSError use of max users
DBPLUS_ERR_PREEXITERR_PREEXITCaused by invalid usage
DBPLUS_ERR_ONTRAPERR_ONTRAPCaused by a signal
DBPLUS_ERR_PREPROCERR_PREPROCError in the preprocessor
DBPLUS_ERR_DBPARSEERR_DBPARSEError in the parser
DBPLUS_ERR_DBRUNERRERR_DBRUNERRRun error in db
DBPLUS_ERR_DBPREEXITERR_DBPREEXITExit condition caused by prexit() * procedure
DBPLUS_ERR_WAITERR_WAITWait a little (Simple only)
DBPLUS_ERR_CORRUPT_TUPLEERR_CORRUPT_TUPLEA client sent a corrupt tuple
DBPLUS_ERR_WARNING0ERR_WARNING0 The Simple routines encountered a non fatal error which was corrected
DBPLUS_ERR_PANICERR_PANIC The server should not really die but after a disaster send ERR_PANIC to all its clients
DBPLUS_ERR_FIFOERR_FIFOCan't create a fifo
DBPLUS_ERR_PERMERR_PERMPermission denied
DBPLUS_ERR_TCLERR_TCLTCL_error
DBPLUS_ERR_RESTRICTEDERR_RESTRICTEDOnly two users
DBPLUS_ERR_USERERR_USER An error in the use of the library by an application programmer
DBPLUS_ERR_UNKNOWNERR_UNKNOWN 

Spis treści
dbplus_add -- Add a tuple to a relation
dbplus_aql -- Perform AQL query
dbplus_chdir -- Get/Set database virtual current directory
dbplus_close -- Close a relation
dbplus_curr -- Get current tuple from relation
dbplus_errcode --  Get error string for given errorcode or last error
dbplus_errno -- Get error code for last operation
dbplus_find -- Set a constraint on a relation
dbplus_first -- Get first tuple from relation
dbplus_flush -- Flush all changes made on a relation
dbplus_freealllocks -- Free all locks held by this client
dbplus_freelock -- Release write lock on tuple
dbplus_freerlocks -- Free all tuple locks on given relation
dbplus_getlock -- Get a write lock on a tuple
dbplus_getunique -- Get a id number unique to a relation
dbplus_info -- ???
dbplus_last -- Get last tuple from relation
dbplus_lockrel -- Request write lock on relation
dbplus_next -- Get next tuple from relation
dbplus_open -- Open relation file
dbplus_prev -- Get previous tuple from relation
dbplus_rchperm -- Change relation permissions
dbplus_rcreate -- Creates a new DB++ relation
dbplus_rcrtexact -- Creates an exact but empty copy of a relation including indices
dbplus_rcrtlike -- Creates an empty copy of a relation with default indices
dbplus_resolve -- Resolve host information for relation
dbplus_rkeys -- Specify new primary key for a relation
dbplus_restorepos -- ???
dbplus_ropen -- Open relation file local
dbplus_rquery -- Perform local (raw) AQL query
dbplus_rrename -- Rename a relation
dbplus_rsecindex --  Create a new secondary index for a relation
dbplus_runlink -- Remove relation from filesystem
dbplus_rzap -- Remove all tuples from relation
dbplus_savepos -- ???
dbplus_setindex -- ???
dbplus_setindexbynumber -- ???
dbplus_sql -- Perform SQL query
dbplus_tcl -- Execute TCL code on server side
dbplus_tremove -- Remove tuple and return new current tuple
dbplus_undo -- ???
dbplus_undoprepare -- ???
dbplus_unlockrel -- Give up write lock on relation
dbplus_unselect -- Remove a constraint from relation
dbplus_update -- Update specified tuple in relation
dbplus_xlockrel -- Request exclusive lock on relation
dbplus_xunlockrel -- Free exclusive lock on relation

dbplus_add

(PHP 4 >= 4.1.0)

dbplus_add -- Add a tuple to a relation

Description

int dbplus_add ( resource relation, array tuple)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

This function will add a tuple to a relation. The tuple data is an array of attribute/value pairs to be inserted into the given relation. After successful execution the tuple array will contain the complete data of the newly created tuple, including all implicitly set domain fields like sequences.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

dbplus_aql

(PHP 4 >= 4.1.0)

dbplus_aql -- Perform AQL query

Description

resource dbplus_aql ( string query [, string server [, string dbpath]])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_aql() will execute an AQL query on the given server and dbpath.

On success it will return a relation handle. The result data may be fetched from this relation by calling dbplus_next() and dbplus_current(). Other relation access functions will not work on a result relation.

Further information on the AQL A... Query Language is provided in the original db++ manual.

dbplus_chdir

(PHP 4 >= 4.1.0)

dbplus_chdir -- Get/Set database virtual current directory

Description

string dbplus_chdir ( [string newdir])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_chdir() will change the virtual current directory where relation files will be looked for by dbplus_open(). dbplus_chdir() will return the absolute path of the current directory. Calling dbplus_chdir() without giving any newdir may be used to query the current working directory.

dbplus_close

(PHP 4 >= 4.1.0)

dbplus_close -- Close a relation

Description

int dbplus_close ( resource relation)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Calling dbplus_close() will close a relation previously opened by dbplus_open().

dbplus_curr

(PHP 4 >= 4.1.0)

dbplus_curr -- Get current tuple from relation

Description

int dbplus_curr ( resource relation, array tuple)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_curr() will read the data for the current tuple for the given relation and will pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(), dbplus_prev(), dbplus_next(), and dbplus_last().

dbplus_errcode

(PHP 4 >= 4.1.0)

dbplus_errcode --  Get error string for given errorcode or last error

Description

string dbplus_errcode ( int errno)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_errcode() returns a cleartext error string for the error code passed as errno of for the result code of the last db++ operation if no parameter is given.

dbplus_errno

(PHP 4 >= 4.1.0)

dbplus_errno -- Get error code for last operation

Description

int dbplus_errno ( void)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_errno() will return the error code returned by the last db++ operation.

See also dbplus_errcode().

dbplus_find

(PHP 4 >= 4.1.0)

dbplus_find -- Set a constraint on a relation

Description

int dbplus_find ( resource relation, array constraints, mixed tuple)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_find() will place a constraint on the given relation. Further calls to functions like dbplus_curr() or dbplus_next() will only return tuples matching the given constraints.

Constraints are triplets of strings containing of a domain name, a comparison operator and a comparison value. The constraints parameter array may consist of a collection of string arrays, each of which contains a domain, an operator and a value, or of a single string array containing a multiple of three elements.

The comparison operator may be one of the following strings: '==', '>', '>=', '<', '<=', '!=', '~' for a regular expression match and 'BAND' or 'BOR' for bitwise operations.

See also dbplus_unselect().

dbplus_first

(PHP 4 >= 4.1.0)

dbplus_first -- Get first tuple from relation

Description

int dbplus_first ( resource relation, array tuple)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_curr() will read the data for the first tuple for the given relation, make it the current tuple and pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_curr(), dbplus_prev(), dbplus_next(), and dbplus_last().

dbplus_flush

(PHP 4 >= 4.1.0)

dbplus_flush -- Flush all changes made on a relation

Description

int dbplus_flush ( resource relation)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_flush() will write all changes applied to relation since the last flush to disk.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

dbplus_freealllocks

(PHP 4 >= 4.1.0)

dbplus_freealllocks -- Free all locks held by this client

Description

int dbplus_freealllocks ( void)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_freeaalllocks() will free all tuple locks held by this client.

See also dbplus_getlock(), dbplus_freelock(), and dbplus_freerlocks().

dbplus_freelock

(PHP 4 >= 4.1.0)

dbplus_freelock -- Release write lock on tuple

Description

int dbplus_freelock ( resource relation, string tname)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_freelock() will release a write lock on the given tuple previously obtained by dbplus_getlock().

See also dbplus_getlock(), dbplus_freerlocks(), and dbplus_freealllocks().

dbplus_freerlocks

(PHP 4 >= 4.1.0)

dbplus_freerlocks -- Free all tuple locks on given relation

Description

int dbplus_freerlocks ( resource relation)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_freerlocks() will free all tuple locks held on the given relation.

See also dbplus_getlock(), dbplus_freelock(), and dbplus_freealllocks().

dbplus_getlock

(PHP 4 >= 4.1.0)

dbplus_getlock -- Get a write lock on a tuple

Description

int dbplus_getlock ( resource relation, string tname)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_getlock() will request a write lock on the specified tuple. It will return zero on success or a non-zero error code, especially DBPLUS_ERR_WLOCKED, on failure.

See also dbplus_freelock(), dbplus_freerlocks(), and dbplus_freealllocks().

dbplus_getunique

(PHP 4 >= 4.1.0)

dbplus_getunique -- Get a id number unique to a relation

Description

int dbplus_getunique ( resource relation, int uniqueid)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_getunique() will obtain a number guaranteed to be unique for the given relation and will pass it back in the variable given as uniqueid.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

dbplus_info

(PHP 4 >= 4.1.0)

dbplus_info -- ???

Description

int dbplus_info ( resource relation, string key, array )

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Not implemented yet.

dbplus_last

(PHP 4 >= 4.1.0)

dbplus_last -- Get last tuple from relation

Description

int dbplus_last ( resource relation, array tuple)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_curr() will read the data for the last tuple for the given relation, make it the current tuple and pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(), dbplus_curr(), dbplus_prev(), and dbplus_next().

dbplus_lockrel

(unknown)

dbplus_lockrel -- Request write lock on relation

Description

int dbplus_lockrel ( resource relation)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_lockrel() will request a write lock on the given relation. Other clients may still query the relation, but can't alter it while it is locked.

dbplus_next

(PHP 4 >= 4.1.0)

dbplus_next -- Get next tuple from relation

Description

int dbplus_next ( resource relation, array )

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_curr() will read the data for the next tuple for the given relation, will make it the current tuple and will pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(), dbplus_curr(), dbplus_prev(), and dbplus_last().

dbplus_open

(PHP 4 >= 4.1.0)

dbplus_open -- Open relation file

Description

resource dbplus_open ( string name)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

The relation file name will be opened. name can be either a file name or a relative or absolute path name. This will be mapped in any case to an absolute relation file path on a specific host machine and server.

On success a relation file resource (cursor) is returned which must be used in any subsequent commands referencing the relation. Failure leads to a zero return value, the actual error code may be asked for by calling dbplus_errno().

dbplus_prev

(PHP 4 >= 4.1.0)

dbplus_prev -- Get previous tuple from relation

Description

int dbplus_prev ( resource relation, array tuple)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_curr() will read the data for the next tuple for the given relation, will make it the current tuple and will pass it back as an associative array in tuple.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(), dbplus_curr(), dbplus_next(), and dbplus_last().

dbplus_rchperm

(PHP 4 >= 4.1.0)

dbplus_rchperm -- Change relation permissions

Description

int dbplus_rchperm ( resource relation, int mask, string user, string group)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_rchperm() will change access permissions as specified by mask, user and group. The values for these are operating system specific.

dbplus_rcreate

(PHP 4 >= 4.1.0)

dbplus_rcreate -- Creates a new DB++ relation

Description

resource dbplus_rcreate ( string name, mixed domlist [, boolean overwrite])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_rcreate() will create a new relation named name. An existing relation by the same name will only be overwritten if the relation is currently not in use and overwrite is set to TRUE.

domlist should contain the domain specification for the new relation within an array of domain description strings. ( dbplus_rcreate() will also accept a string with space delimited domain description strings, but it is recommended to use an array). A domain description string consists of a domain name unique to this relation, a slash and a type specification character. See the db++ documentation, especially the dbcreate(1) manpage, for a description of available type specifiers and their meanings.

dbplus_rcrtexact

(PHP 4 >= 4.1.0)

dbplus_rcrtexact -- Creates an exact but empty copy of a relation including indices

Description

resource dbplus_rcrtexact ( string name, resource relation, boolean overwrite)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_rcrtexact() will create an exact but empty copy of the given relation under a new name. An existing relation by the same name will only be overwritten if overwrite is TRUE and no other process is currently using the relation.

dbplus_rcrtlike

(PHP 4 >= 4.1.0)

dbplus_rcrtlike -- Creates an empty copy of a relation with default indices

Description

resource dbplus_rcrtlike ( string name, resource relation, int flag)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_rcrtexact() will create an empty copy of the given relation under a new name, but with default indices. An existing relation by the same name will only be overwritten if overwrite is TRUE and no other process is currently using the relation.

dbplus_resolve

(PHP 4 >= 4.1.0)

dbplus_resolve -- Resolve host information for relation

Description

int dbplus_resolve ( string relation_name)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_resolve() will try to resolve the given relation_name and find out internal server id, real hostname and the database path on this host. The function will return an array containing these values under the keys 'sid', 'host' and 'host_path' or FALSE on error.

See also dbplus_tcl().

dbplus_rkeys

(PHP 4 >= 4.1.0)

dbplus_rkeys -- Specify new primary key for a relation

Description

resource dbplus_rkeys ( resource relation, mixed domlist)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_rkeys() will replace the current primary key for relation with the combination of domains specified by domlist.

domlist may be passed as a single domain name string or as an array of domain names.

dbplus_restorepos

(PHP 4 >= 4.1.0)

dbplus_restorepos -- ???

Description

int dbplus_restorepos ( resource relation, array tuple)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Not implemented yet.

dbplus_ropen

(PHP 4 >= 4.1.0)

dbplus_ropen -- Open relation file local

Description

resource dbplus_ropen ( string name)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_ropen() will open the relation file locally for quick access without any client/server overhead. Access is read only and only dbplus_current() and dbplus_next() may be applied to the returned relation.

dbplus_rquery

(PHP 4 >= 4.1.0)

dbplus_rquery -- Perform local (raw) AQL query

Description

int dbplus_rquery ( string query, string dbpath)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_rquery() performs a local (raw) AQL query using an AQL interpreter embedded into the db++ client library. dbplus_rquery() is faster than dbplus_aql() but will work on local data only.

dbplus_rrename

(PHP 4 >= 4.1.0)

dbplus_rrename -- Rename a relation

Description

int dbplus_rrename ( resource relation, string name)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_rrename() will change the name of relation to name.

dbplus_rsecindex

(PHP 4 >= 4.1.0)

dbplus_rsecindex --  Create a new secondary index for a relation

Description

resource dbplus_rsecindex ( resource relation, mixed domlist, int type)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_rsecindex() will create a new secondary index for relation with consists of the domains specified by domlist and is of type type

domlist may be passed as a single domain name string or as an array of domain names.

dbplus_runlink

(PHP 4 >= 4.1.0)

dbplus_runlink -- Remove relation from filesystem

Description

int dbplus_runlink ( resource relation)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_unlink() will close and remove the relation.

dbplus_rzap

(PHP 4 >= 4.1.0)

dbplus_rzap -- Remove all tuples from relation

Description

int dbplus_rzap ( resource relation)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_rzap() will remove all tuples from relation.

dbplus_savepos

(PHP 4 >= 4.1.0)

dbplus_savepos -- ???

Description

int dbplus_savepos ( resource relation)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Not implemented yet.

dbplus_setindex

(PHP 4 >= 4.1.0)

dbplus_setindex -- ???

Description

int dbplus_setindex ( resource relation, string idx_name)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Not implemented yet.

dbplus_setindexbynumber

(PHP 4 >= 4.1.0)

dbplus_setindexbynumber -- ???

Description

int dbplus_setindexbynumber ( resource relation, int idx_number)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Not implemented yet.

dbplus_sql

(PHP 4 >= 4.1.0)

dbplus_sql -- Perform SQL query

Description

resource dbplus_sql ( string query, string server, string dbpath)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Not implemented yet.

dbplus_tcl

(PHP 4 >= 4.1.0)

dbplus_tcl -- Execute TCL code on server side

Description

int dbplus_tcl ( int sid, string script)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

A db++ server will prepare a TCL interpreter for each client connection. This interpreter will enable the server to execute TCL code provided by the client as a sort of stored procedures to improve the performance of database operations by avoiding client/server data transfers and context switches.

dbplus_tcl() needs to pass the client connection id the TCL script code should be executed by. dbplus_resolve() will provide this connection id. The function will return whatever the TCL code returns or a TCL error message if the TCL code fails.

See also dbplus_resolve().

dbplus_tremove

(PHP 4 >= 4.1.0)

dbplus_tremove -- Remove tuple and return new current tuple

Description

int dbplus_tremove ( resource relation, array tuple [, array current])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_tremove() removes tuple from relation if it perfectly matches a tuple within the relation. current, if given, will contain the data of the new current tuple after calling dbplus_tremove().

dbplus_undo

(PHP 4 >= 4.1.0)

dbplus_undo -- ???

Description

int dbplus_undo ( resource relation)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Not implemented yet.

dbplus_undoprepare

(PHP 4 >= 4.1.0)

dbplus_undoprepare -- ???

Description

int dbplus_undoprepare ( resource relation)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Not implemented yet.

dbplus_unlockrel

(PHP 4 >= 4.1.0)

dbplus_unlockrel -- Give up write lock on relation

Description

int dbplus_unlockrel ( resource relation)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_unlockrel() will release a write lock previously obtained by dbplus_lockrel().

dbplus_unselect

(PHP 4 >= 4.1.0)

dbplus_unselect -- Remove a constraint from relation

Description

int dbplus_unselect ( resource relation)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Calling dbplus_unselect() will remove a constraint previously set by dbplus_find() on relation.

dbplus_update

(PHP 4 >= 4.1.0)

dbplus_update -- Update specified tuple in relation

Description

int dbplus_update ( resource relation, array old, array new)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_update() replaces the tuple given by old with the data from new if and only if old completely matches a tuple within relation.

dbplus_xlockrel

(PHP 4 >= 4.1.0)

dbplus_xlockrel -- Request exclusive lock on relation

Description

int dbplus_xlockrel ( resource relation)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_xlockrel() will request an exclusive lock on relation preventing even read access from other clients.

See also dbplus_xunlockrel().

dbplus_xunlockrel

(PHP 4 >= 4.1.0)

dbplus_xunlockrel -- Free exclusive lock on relation

Description

int dbplus_xunlockrel ( resource relation)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

dbplus_xunlockrel() will release an exclusive lock on relation previously obtained by dbplus_xlockrel().

XXIII. Direct IO functions

Direct I/O Functions

PHP supports the direct io functions as described in the Posix Standard (Section 6) for performing I/O functions at a lower level than the C-Language stream I/O functions (fopen, fread,..).


Installation

To get these functions to work, you have to configure PHP with --enable-dio.

Spis treści
dio_open --  Opens a new filename with specified permissions of flags and creation permissions of mode
dio_read --  Reads n bytes from fd and returns them, if n is not specified, reads 1k block
dio_write --  Writes data to fd with optional truncation at length
dio_truncate --  Truncates file descriptor fd to offset bytes
dio_stat --  Gets stat information about the file descriptor fd
dio_seek -- Seeks to pos on fd from whence
dio_fcntl -- Performs a c library fcntl on fd
dio_close -- Closes the file descriptor given by fd

dio_open

(PHP 4 CVS only)

dio_open --  Opens a new filename with specified permissions of flags and creation permissions of mode

Description

resource dio_open ( string filename, int flags [, int mode])

dio_open() opens a file and returns a new file descriptor for it, or -1 if any error occurred. If flags is O_CREAT, optional third parameter mode will set the mode of the file (creation permissions). The flags parameter can be one of the following options:

  • O_RDONLY - opens the file for read access

  • O_WRONLY - opens the file for write access

  • O_RDWR - opens the file for both reading and writing

The flags parameter can also include any combination of the following flags:

  • O_CREAT - creates the file, if it doesn't already exist

  • O_EXCL - if both, O_CREAT and O_EXCL are set, dio_open() fails, if file already exists

  • O_TRUNC - if file exists, and its opened for write access, file will be truncated to zero length.

  • O_APPEND - write operations write data at the end of file

  • O_NONBLOCK - sets non blocking mode

dio_read

(PHP 4 CVS only)

dio_read --  Reads n bytes from fd and returns them, if n is not specified, reads 1k block

Description

string dio_read ( resource fd [, int n])

The function dio_read() reads and returns n bytes from file with descriptor resource. If n is not specified, dio_read() reads 1K sized block and returns them.

dio_write

(PHP 4 CVS only)

dio_write --  Writes data to fd with optional truncation at length

Description

int dio_write ( resource fd, string data [, int len])

The function dio_write() writes up to len bytes from data to file fd. If len is not specified, dio_write() writes all data to the specified file. dio_write() returns the number of bytes written to fd.

dio_truncate

(PHP 4 CVS only)

dio_truncate --  Truncates file descriptor fd to offset bytes

Description

bool dio_truncate ( resource fd, int offset)

Function dio_truncate() causes the file referenced by fd to be truncated to at most offset bytes in size. If the file previously was larger than this size, the extra data is lost. If the file previously was shorter, it is unspecified whether the file is left unchanged or is extended. In the latter case the extended part reads as zero bytes. Returns 0 on success, otherwise -1.

dio_stat

(PHP 4 CVS only)

dio_stat --  Gets stat information about the file descriptor fd

Description

array dio_stat ( resource fd)

Function dio_stat() returns information about the file with file descriptor fd. dio_stat() returns an associative array with the following keys:

  • "device" - device

  • "inode" - inode

  • "mode" - mode

  • "nlink" - number of hard links

  • "uid" - user id

  • "gid" - group id

  • "device_type" - device type (if inode device)

  • "size" - total size in bytes

  • "blocksize" - blocksize

  • "blocks" - number of blocks allocated

  • "atime" - time of last access

  • "mtime" - time of last modification

  • "ctime" - time of last change

On error dio_stat() returns NULL.

dio_seek

(PHP 4 CVS only)

dio_seek -- Seeks to pos on fd from whence

Description

int dio_seek ( resource fd, int pos, int whence)

The function dio_seek() is used to change the file position of the file with descriptor resource. The parameter whence specifies how the position pos should be interpreted:

  • SEEK_SET - specifies that pos is specified from the beginning of the file

  • SEEK_CUR - Specifies that pos is a count of characters from the current file position. This count may be positive or negative

  • SEEK_END - Specifies that pos is a count of characters from the end of the file. A negative count specifies a position within the current extent of the file; a positive count specifies a position past the current end. If you set the position past the current end, and actually write data, you will extend the file with zeros up to that position

dio_fcntl

(PHP 4 CVS only)

dio_fcntl -- Performs a c library fcntl on fd

Description

mixed dio_fcntl ( resource fd, int cmd [, mixed arg])

The dio_fcntl() function performs the operation specified by cmd on the file descriptor fd. Some commands require additional arguments args to be supplied.

arg is an associative array, when cmd is F_SETLK or F_SETLLW, with the following keys:

  • "start" - offset where lock begins

  • "length" - size of locked area. zero means to end of file

  • "wenth" - Where l_start is relative to: can be SEEK_SET, SEEK_END and SEEK_CUR

  • "type" - type of lock: can be F_RDLCK (read lock), F_WRLCK (write lock) or F_UNLCK (unlock)

cmd can be one of the following operations:

  • F_SETLK - Lock is set or cleared. If the lock is held by someone else dio_fcntl() returns -1.

  • F_SETLKW - like F_SETLK, but in case the lock is held by someone else, dio_fcntl() waits until the lock is released.

  • F_GETLK - dio_fcntl() returns an associative array (as described above) if someone else prevents lock. If there is no obstruction key "type" will set to F_UNLCK.

  • F_DUPFD - finds the lowest numbered available file descriptor greater or equal than arg and returns them.

dio_close

(PHP 4 CVS only)

dio_close -- Closes the file descriptor given by fd

Description

void dio_close ( resource fd)

The function dio_close() closes the file descriptor resource.

XXIV. Directory functions

For related functions such as dirname(), is_dir(), mkdir(), and rmdir(), see the Filesystem section.

Spis treści
chroot -- change the root directory
chdir -- change directory
dir -- directory class
closedir -- close directory handle
getcwd -- gets the current working directory
opendir -- open directory handle
readdir -- read entry from directory handle
rewinddir -- rewind directory handle

chroot

(PHP 4 >= 4.0.5)

chroot -- change the root directory

Description

bool chroot ( string directory)

Changes the root directory of the current process to directory. Returns FALSE if unable to change the root directory, TRUE otherwise.

Notatka: It's not wise to use this function when running in a webserver environment, because it's not possible to reset the root directory to / again at the end of the request. This function will only function correct when running as CGI this way.

chdir

(PHP 3, PHP 4 >= 4.0.0)

chdir -- change directory

Description

bool chdir ( string directory)

Changes PHP's current directory to directory. Returns FALSE if unable to change directory, TRUE otherwise.

dir

(PHP 3, PHP 4 >= 4.0.0)

dir -- directory class

Description

 class dir {
dir(string directory);
string path;
string read();
void rewind();
void close();
}

A pseudo-object oriented mechanism for reading a directory. The given directory is opened. Two properties are available once the directory has been opened. The handle property can be used with other directory functions such as readdir(), rewinddir() and closedir(). The path property is set to path the directory that was opened. Three methods are available: read, rewind and close.

Przykład 1. dir() example

$d = dir("/etc");
echo "Handle: ".$d->handle."<br>\n";
echo "Path: ".$d->path."<br>\n";
while (false !== ($entry = $d->read())) {
    echo $entry."<br>\n";
}
$d->close();

Notatka: The order in which directory entries are returned by the read method is system-dependent.

closedir

(PHP 3, PHP 4 >= 4.0.0)

closedir -- close directory handle

Description

void closedir ( resource dir_handle)

Closes the directory stream indicated by dir_handle. The stream must have previously been opened by opendir().

getcwd

(PHP 4 >= 4.0.0)

getcwd -- gets the current working directory

Description

string getcwd ( void)

Returns the current working directory.

opendir

(PHP 3, PHP 4 >= 4.0.0)

opendir -- open directory handle

Description

resource opendir ( string path)

Returns a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls.

If path is not a valid directory or the directory can not be opened due to permission restrictions or filesystem errors, opendir() returns FALSE and generates a PHP error. You can suppress the error output of opendir() by prepending `@' to the front of the function name.

Przykład 1. opendir() example

<?php

if ($dir = @opendir("/tmp")) {
  while (($file = readdir($dir)) !== false) {
    echo "$file\n";
  }  
  closedir($dir);
}

?>

readdir

(PHP 3, PHP 4 >= 4.0.0)

readdir -- read entry from directory handle

Description

string readdir ( resource dir_handle)

Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem.

Please note the fashion in which readdir()'s return value is checked in the examples below. We are explicitly testing whether the return value is identical to (equal to and of the same type as--see Comparison Operators for more information) FALSE since otherwise, any directory entry whose name evaluates to FALSE will stop the loop.

Przykład 1. List all files in the current directory

// Note that !== did not exist until 4.0.0-RC2
<?php
$handle=opendir('.');
echo "Directory handle: $handle\n";
echo "Files:\n";

/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) { 
    echo "$file\n";
}

/* This is the WRONG way to loop over the directory. */
while ($file = readdir($handle)) { 
    echo "$file\n";
}

closedir($handle); 
?>

Note that readdir() will return the . and .. entries. If you don't want these, simply strip them out:

Przykład 2. List all files in the current directory and strip out . and ..

<?php 
$handle = opendir('.'); 
while (false !== ($file = readdir($handle))) { 
    if ($file != "." && $file != "..") { 
        echo "$file\n"; 
    } 
}
closedir($handle); 
?>

rewinddir

(PHP 3, PHP 4 >= 4.0.0)

rewinddir -- rewind directory handle

Description

void rewinddir ( resource dir_handle)

Resets the directory stream indicated by dir_handle to the beginning of the directory.

XXV. DOM XML functions

Ostrze¿enie

Ten moduł jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie tych funkcji, ich nazwy, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tego modułu na własne ryzyko.

This documentation is not finished yet. Don't start to translate it or use it as a programming reference (steinm@php.net).

These functions are only available if PHP was configured with --with-dom=[DIR], using the GNOME xml library. You will need at least libxml-2.2.7 These functions have been added in PHP 4.

The extension allows you to operate on an XML document with the DOM API. It also provides a function xmltree() to turn the complete XML document into a tree of PHP objects. Currently this tree should be considered read-only - you can modify it but this would not make any sense since dumpmem() cannot be applied to it. Therefore, if you want to read an XML file and write a modified version use the add_node(), set_attribute(), etc. and finally dumpmem() functions.

This module defines the following constants:

Tabela 1. XML constants

ConstantValueDescription
XML_ELEMENT_NODE1Node is an element
XML_ATTRIBUTE_NODE2Node is an attribute
XML_TEXT_NODE3Node is a piece of text
XML_CDATA_SECTION_NODE4 
XML_ENTITY_REF_NODE5 
XML_ENTITY_NODE6Node is an entity like &nbsp;
XML_PI_NODE7Node is a processing instruction
XML_COMMENT_NODE8Node is a comment
XML_DOCUMENT_NODE9Node is a document
XML_DOCUMENT_TYPE_NODE10 
XML_DOCUMENT_FRAG_NODE11 
XML_NOTATION_NODE12 
XML_GLOBAL_NAMESPACE1 
XML_LOCAL_NAMESPACE2 

Each function in this extension can be used in two ways. In a non-object oriented way by passing the object to apply the function to as a first argument, or in an object oriented way by calling the function as a method of an object. This documentation describes the non-object oriented functions, though you get the object methods by skipping the prefix "domxml_".

This module defines a number of classes, which are listed — including their properties and method — in the following table.

Tabela 2. DomDocument class (methods)

Method nameFunction nameDescription
rootdomxml_root() 
childrendomxml_children() 
add_rootdomxml_add_root() 
dtddomxml_intdtd() 
dumpmemdomxml() 
xpath_initxpath_init 
xpath_new_contextxpath_new_context 
xptr_new_contextxptr_new_context 

Tabela 3. DomDocument class (attributes)

NameTypeDescription
docclass DomDocumentThe object itself
namestring 
urlstring 
versionstringVersion of XML
encodingstring 
standalonelong1 if the file is a standalone version
typelongOne of the constants in table ...
compressionlong1 if the file is compressed
charsetlong 

Tabela 4. DomNode class (methods)

NamePHP nameDescription
lastchilddomxml_last_child() 
childrendomxml_children() 
parentdomxml_parent() 
new_childdomxml_new_child() 
get_attributedomxml_get_attribute() 
set_attributedomxml_set_attribute() 
attributesdomxml_attributes() 
nodedomxml_node() 
set_content()domxml_set_content 

Tabela 5. DomNode class (attributes)

NameTypeDescription
nodeclass DomNodeThe object itself
typelong 
tagnamestring 
contentstring 

Spis treści
xmldoc -- Creates a DOM object of an XML document
xmldocfile -- Creates a DOM object from XML file
xmltree --  Creates a tree of PHP objects from XML document
domxml_root --  Returns root element node
domxml_add_root --  Adds a further root node
domxml_dumpmem --  Dumps the internal XML tree back into a string
domxml_attributes --  Returns an array of attributes of a node
domxml_get_attribute --  Returns a certain attribute of a node
domxml_set_attribute -- 
domxml_children --  Returns children of a node or document
domxml_new_child --  Adds new child node
domxml_new_xmldoc --  Creates new empty XML document
xpath_new_context --  Creates new xpath context
xpath_eval --  Evaluates the XPath Location Path in the given string
domxml_node --  Creates node
domxml_node_set_content --  Sets content of a node
domxml_node_unlink_node --  Deletes node
xpath_eval_expression --  Evaluates the XPath Location Path in the given string
domxml_version --  Get XML library version
xptr_new_context --  Create new XPath Context
xptr_eval --  Evaluate the XPtr Location Path in the given string

xmldoc

(PHP 4 >= 4.0.0)

xmldoc -- Creates a DOM object of an XML document

Description

object xmldoc ( string str)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

The function parses the XML document in str and returns an object of class "Dom document", having the properties as listed above.

See also xmldocfile()

xmldocfile

(PHP 4 >= 4.0.0)

xmldocfile -- Creates a DOM object from XML file

Description

object xmldocfile ( string filename)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

The function parses the XML document in the file named filename and returns an object of class "Dom document", having the properties as listed above. The file is accessed read-only.

See also xmldoc()

xmltree

(PHP 4 >= 4.0.0)

xmltree --  Creates a tree of PHP objects from XML document

Description

object xmltree ( string str)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

The function parses the XML document in str and returns a tree PHP objects as the parsed document. This function is isolated from the other functions, which means you cannot access the tree with any of the other functions. Modifying it, for example by adding nodes, makes no sense since there is currently no way to dump it as an XML file. However this function may be valuable if you want to read a file and investigate the content.

domxml_root

(PHP 4 >= 4.0.0)

domxml_root --  Returns root element node

Description

object domxml_root ( object doc)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

domxml_root() takes one argument, an object of class "Dom document", and returns the root element node. There are actually other possible nodes like comments which are currently disregarded.

The following example returns just the element with name CHAPTER and prints it. The other root node -- the comment -- is not returned.

Przykład 1. Retrieving root element

<?php
$xmlstr = "<?xml version='1.0' standalone='yes'?>
<!DOCTYPE chapter SYSTEM '/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd'
[ <!ENTITY sp \"spanish\">
]>
<!-- lsfj  -->
<chapter language='en'><title language='en'>Title</title>
 <para language='ge'>
  &amp;sp;
  <!-- comment -->
  <informaltable language='&amp;sp;'>
   <tgroup cols='3'>
    <tbody>
     <row><entry>a1</entry><entry
morerows='1'>b1</entry><entry>c1</entry></row>
<row><entry>a2</entry><entry>c2</entry></row>
     <row><entry>a3</entry><entry>b3</entry><entry>c3</entry></row>
    </tbody>
   </tgroup>
  </informaltable>
 </para>
</chapter>";

if(!$dom = xmldoc($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->root();
/* or $root = domxml_root($dom); */
print_r($root);
?>

domxml_add_root

(PHP 4 >= 4.0.0)

domxml_add_root --  Adds a further root node

Description

resource domxml_add_root ( resource doc, string name)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Adds a root element node to a dom document and returns the new node. The element name is given in the second parameter.

Przykład 1. Creating a simple HTML document header

<?php
$doc = new_xmldoc("1.0");
$root = $doc->add_root("HTML");
$head = $root->new_child("HEAD", "");
$head->new_child("TITLE", "Hier der Titel");
echo $doc->dumpmem();
?>

domxml_dumpmem

(PHP 4 >= 4.0.0)

domxml_dumpmem --  Dumps the internal XML tree back into a string

Description

string domxml_dumpmem ( resource doc)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Creates an XML document from the dom representation. This function usually is called after a building a new dom document from scratch as in the example of domxml_add_root().

See also domxml_add_root()

domxml_attributes

(PHP 4 >= 4.0.0)

domxml_attributes --  Returns an array of attributes of a node

Description

array domxml_attributes ( resource node)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Returns all attributes of a node as array of objects of type "dom attribute".

domxml_get_attribute

(PHP 4 >= 4.0.5)

domxml_get_attribute --  Returns a certain attribute of a node

Description

object domxml_get_attribute ( resource node, string name)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Returns the attribute with name name of the given node.

See also domxml_set_attribute()

domxml_set_attribute

(PHP 4 >= 4.0.5)

domxml_set_attribute -- 

Description

object domxml_set_attribute ( resource node, string name, string value)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Sets an attribute with name name of the given node on a value.

If we take the example from domxml_add_root() it is simple to add an attribute to the HEAD element by the simply calling the set_attribute() function of the node class.

Przykład 1. Adding an attribute to an element

<?php
$doc = new_xmldoc("1.0");
$root = $doc->add_root("HTML");
$head = $root->new_child("HEAD", "");
$head->new_child("TITLE", "Hier der Titel");
$head->set_attribute("Language", "ge");
echo $doc->dumpmem();
?>

domxml_children

(PHP 4 >= 4.0.0)

domxml_children --  Returns children of a node or document

Description

array domxml_children ( object doc|node)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Returns all children of a node as an array of nodes.

In the following example the variable children will contain an array with one node of type XML_ELEMENT. This node is the TITLE element.

Przykład 1. Adding an attribute to an element

<?php
$doc = new_xmldoc("1.0");
$root = $doc->add_root("HTML");
$head = $root->new_child("HEAD", "");
$head->new_child("TITLE", "Hier der Titel");
$head->set_attribute("Language", "ge");
$children = $head->children();
?>

domxml_new_child

(PHP 4 >= 4.0.0)

domxml_new_child --  Adds new child node

Description

resource domxml_new_child ( string name, string content)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Adds a new child of type element to a node and returns it.

domxml_new_xmldoc

(PHP 4 >= 4.0.0)

domxml_new_xmldoc --  Creates new empty XML document

Description

object domxml_new_xmldoc ( string version)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Creates a new dom document from scratch and returns it.

See also domxml_add_root()

xpath_new_context

(PHP 4 >= 4.0.4)

xpath_new_context --  Creates new xpath context

Description

object xpath_new_context ( object dom document)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

See also xpath_eval()

xpath_eval

(PHP 4 >= 4.0.4)

xpath_eval --  Evaluates the XPath Location Path in the given string

Description

array xpath_eval ( object xpath context)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

See also xpath_new_context()

domxml_node

(PHP 4 >= 4.0.0)

domxml_node --  Creates node

Description

object domxml_node ( string name)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

domxml_node_set_content

(PHP 4 >= 4.1.0)

domxml_node_set_content --  Sets content of a node

Description

bool domxml_node_set_content ( string content)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

domxml_node_unlink_node

(PHP 4 >= 4.1.0)

domxml_node_unlink_node --  Deletes node

Description

object domxml_node_unlink_node ( void)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

xpath_eval_expression

(PHP 4 >= 4.0.4)

xpath_eval_expression --  Evaluates the XPath Location Path in the given string

Description

array xpath_eval_expression ( object xpath_context)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

See also xpath_eval()

domxml_version

(PHP 4 >= 4.1.0)

domxml_version --  Get XML library version

Description

string domxml_version ( void)

This function returns the version of the XML library version currently used.

xptr_new_context

(PHP 4 >= 4.0.4)

xptr_new_context --  Create new XPath Context

Description

string xptr_new_context ( [object doc_handle])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

xptr_eval

(PHP 4 >= 4.0.4)

xptr_eval --  Evaluate the XPtr Location Path in the given string

Description

int xptr_eval ( [object xpath_context, string eval_str])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

XXVI. .NET functions

Spis treści
dotnet_load -- Loads a DOTNET module

dotnet_load

(unknown)

dotnet_load -- Loads a DOTNET module

Description

int dotnet_load ( string assembly_name [, string datatype_name [, int codepage]])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

XXVII. Error Handling and Logging Functions

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.

Spis treści
error_log -- send an error message somewhere
error_reporting -- set which PHP errors are reported
restore_error_handler --  Restores the previous error handler function
set_error_handler --  Sets a user-defined error handler function.
trigger_error --  Generates a user-level error/warning/notice message
user_error --  Generates a user-level error/warning/notice message

error_log

(PHP 3, PHP 4 >= 4.0.0)

error_log -- send an error message somewhere

Description

int error_log ( string message [, int message_type [, string destination [, string extra_headers]]])

Sends an error message to the web server's error log, a TCP port or to a file. The first parameter, message, is the error message that should be logged. The second parameter, message_type says where the message should go:

Tabela 1. error_log() log types

0 message is sent to PHP's system logger, using the Operating System's system logging mechanism or a file, depending on what the error_log configuration directive is set to.
1 message is sent by email to the address in the destination parameter. This is the only message type where the fourth parameter, extra_headers is used. This message type uses the same internal function as mail() does.
2 message is sent through the PHP debugging connection. This option is only available if remote debugging has been enabled. In this case, the destination parameter specifies the host name or IP address and optionally, port number, of the socket receiving the debug information.
3 message is appended to the file destination.

Ostrze¿enie

Remote debugging via TCP/IP is a PHP 3 feature that is not available in PHP 4.

Przykład 1. error_log() examples

// Send notification through the server log if we can not
// connect to the database.
if (!Ora_Logon ($username, $password)) {
    error_log ("Oracle database not available!", 0);
}

// Notify administrator by email if we run out of FOO
if (!($foo = allocate_new_foo()) {
    error_log ("Big trouble, we're all out of FOOs!", 1,
               "operator@mydomain.com");
}

// other ways of calling error_log():
error_log ("You messed up!", 2, "127.0.0.1:7000");
error_log ("You messed up!", 2, "loghost");
error_log ("You messed up!", 3, "/var/tmp/my-errors.log");

error_reporting

(PHP 3, PHP 4 >= 4.0.0)

error_reporting -- set which PHP errors are reported

Description

int error_reporting ( [int level])

Sets PHP's error reporting level and returns the old level. The error reporting level is either a bitmask, or named constant. 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.

Przykład 1. Error Integer changes

error_reporting (55);   // PHP 3 equivalent to E_ALL ^ E_NOTICE

/* ...in PHP 4, '55' would mean (E_ERROR | E_WARNING | E_PARSE |
E_CORE_ERROR | E_CORE_WARNING) */

error_reporting (2039); // PHP 4 equivalent to E_ALL ^ E_NOTICE

error_reporting (E_ALL ^ E_NOTICE); // The same in both PHP 3 and 4
Follow the links for the internal values to get their meanings:

Tabela 1. error_reporting() bit values

constantvalue
1 E_ERROR
2 E_WARNING
4 E_PARSE
8 E_NOTICE
16 E_CORE_ERROR
32 E_CORE_WARNING
64 E_COMPILE_ERROR
128 E_COMPILE_WARNING
256 E_USER_ERROR
512 E_USER_WARNING
1024 E_USER_NOTICE

Przykład 2. error_reporting() examples

error_reporting(0);
/* Turn off all reporting */

error_reporting (7); // Old syntax, PHP 2/3
error_reporting  (E_ERROR | E_WARNING | E_PARSE); // New syntax for PHP 3/4
/* Good to use for simple running errors  */

error_reporting  (15); // Old syntax, PHP 2/3
error_reporting (E_ERROR | E_WARNING | E_PARSE | E_NOTICE); // New syntax for PHP 3/4
/*  good for code authoring to report uninitialized or (possibly mis-spelled) variables */

error_reporting (63); // Old syntax, PHP 2/3
error_reporting (E_ALL); // New syntax for PHP 3/4
/* report all PHP errors */

restore_error_handler

(PHP 4 )

restore_error_handler --  Restores the previous error handler function

Description

void 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)

See also error_reporting(), set_error_handler(), trigger_error(), user_error()

set_error_handler

(PHP 4 )

set_error_handler --  Sets a user-defined error handler function.

Description

string set_error_handler ( string error_handler)

Sets a user function (error_handler) to handle errors in a script. Returns the previously defined error handler (if any), or FALSE on error. 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())

The user function needs to accept 2 parameters: the error code, and a string describing the error. From PHP 4.0.2, an additional 3 optional parameters are 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 example below shows the handling of internal exceptions by triggering errors and handling them with a user defined function:

Przykład 1. Error handling with set_error_handler() and trigger_error()

<?php

// redefine the user error constants - PHP 4 only
define (FATAL,E_USER_ERROR);
define (ERROR,E_USER_WARNING);
define (WARNING,E_USER_NOTICE);

// set the error reporting level for this script
error_reporting (FATAL | ERROR | WARNING);

// error handler function
function myErrorHandler ($errno, $errstr, $errfile, $errline) {
  switch ($errno) {
  case FATAL:
    echo "<b>FATAL</b> [$errno] $errstr<br>\n";
    echo "  Fatal error in line ".$errline." of file ".$errfile;
    echo ", PHP ".PHP_VERSION." (".PHP_OS.")<br>\n";
    echo "Aborting...<br>\n";
    exit -1;
    break;
  case ERROR:
    echo "<b>ERROR</b> [$errno] $errstr<br>\n";
    break;
  case WARNING:
    echo "<b>WARNING</b> [$errno] $errstr<br>\n";
    break;
    default:
    echo "Unkown error type: [$errno] $errstr<br>\n";
    break;
  }
}

// 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",
      FATAL);
  if (!is_array($vect)) {
    trigger_error("Incorrect input vector, array of values expected", ERROR);
    return null;
  }
  for ($i=0; $i<count($vect); $i++) {
    if (!is_numeric($vect[$i]))
      trigger_error("Value at position $i is not a number, using 0 (zero)", 
        WARNING);
    $temp[$i] = log($scale) * $vect[$i];
  }
  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(2,3,"foo",5.5,43.3,21.11);
print_r($a);

// now generate second array, generating a warning
echo "----\nvector b - a warning (b = log(PI) * a)\n";
$b = scale_by_log($a, M_PI);
print_r($b);

// this is trouble, we pass a string instead of an array
echo "----\nvector c - an error\n";
$c = scale_by_log("not array",2.3);
var_dump($c);

// this is a critical error, log of zero or negative number is undefined
echo "----\nvector d - fatal error\n";
$d = scale_by_log($a, -2.5);

?>
And when you run this sample script, the output will be

vector a
Array
(
    [0] => 2
    [1] => 3
    [2] => foo
    [3] => 5.5
    [4] => 43.3
    [5] => 21.11
)
----
vector b - a warning (b = log(PI) * a)
<b>WARNING</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 - an error
<b>ERROR</b> [512] Incorrect input vector, array of values expected<br>
NULL
----
vector d - fatal error
<b>FATAL</b> [256] log(x) for x <= 0 is undefined, you used: scale = -2.5<br>
  Fatal error in line 36 of file trigger_error.php, PHP 4.0.2 (Linux)<br>
Aborting...<br>

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.

See also error_reporting(), restore_error_handler(), trigger_error(), user_error()

trigger_error

(PHP 4 )

trigger_error --  Generates a user-level error/warning/notice message

Description

void trigger_error ( string error_msg [, int error_type])

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()). It only works with the E_USER family of constants, and will default to E_USER_NOTICE.

This function is useful when you need to generate a particular response to an exception at runtime. For example:

if (assert ($divisor == 0))
   trigger_error ("Cannot divide by zero", E_USER_ERROR);

Notatka: See set_error_handler() for a more extensive example.

See also error_reporting(), set_error_handler(), restore_error_handler(), user_error()

user_error

(PHP 4 >= 4.0.0)

user_error --  Generates a user-level error/warning/notice message

Description

void user_error ( string error_msg [, int error_type])

This is an alias for the function trigger_error().

See also error_reporting(), set_error_handler(), restore_error_handler(), and trigger_error()

XXVIII. FrontBase Functions

These functions allow you to access FrontBase database servers. In order to have these functions available, you must compile php with fbsql support by using the --with-fbsql option. If you use this option without specifying the path to fbsql, php will search for the fbsql client libraries in the default installation location for the platform. Users who installed FrontBase in a non standard directory should always specify the path to fbsql: --with-fbsql=/path/to/fbsql. This will force php to use the client libraries installed by FrontBase, avoiding any conflicts.

More information about FrontBase can be found at http://www.frontbase.com/.

Documentation for FrontBase can be found at http://www.frontbase.com/cgi-bin/WebObjects/FrontBase.woa/wa/productsPage?currentPage=Documentation.

Frontbase support has been added to PHP 4.0.6.

Spis treści
fbsql_affected_rows --  Get number of affected rows in previous FrontBase operation
fbsql_autocommit -- Enable or disable autocommit.
fbsql_change_user --  Change logged in user of the active connection
fbsql_close -- Close FrontBase connection
fbsql_commit -- Commits a transaction to the database
fbsql_connect -- Open a connection to a FrontBase Server
fbsql_create_db -- Create a FrontBase database
fbsql_create_blob -- Create a BLOB
fbsql_create_clob -- Create a CLOB
fbsql_database_password --  Sets or retrieves the password for a FrontBase database
fbsql_data_seek -- Move internal result pointer
fbsql_db_query -- Send a FrontBase query
fbsql_db_status -- Get the status for a given database
fbsql_drop_db -- Drop (delete) a FrontBase database
fbsql_errno --  Returns the numerical value of the error message from previous FrontBase operation
fbsql_error --  Returns the text of the error message from previous FrontBase operation
fbsql_fetch_array --  Fetch a result row as an associative array, a numeric array, or both
fbsql_fetch_assoc --  Fetch a result row as an associative array
fbsql_fetch_field --  Get column information from a result and return as an object
fbsql_fetch_lengths --  Get the length of each output in a result
fbsql_fetch_object -- Fetch a result row as an object
fbsql_fetch_row -- Get a result row as an enumerated array
fbsql_field_flags --  Get the flags associated with the specified field in a result
fbsql_field_name --  Get the name of the specified field in a result
fbsql_field_len --  Returns the length of the specified field
fbsql_field_seek --  Set result pointer to a specified field offset
fbsql_field_table --  Get name of the table the specified field is in
fbsql_field_type --  Get the type of the specified field in a result
fbsql_free_result -- Free result memory
fbsql_insert_id --  Get the id generated from the previous INSERT operation
fbsql_list_dbs --  List databases available on a FrontBase server
fbsql_list_fields -- List FrontBase result fields
fbsql_list_tables -- List tables in a FrontBase database
fbsql_next_result --  Move the internal result pointer to the next result
fbsql_num_fields -- Get number of fields in result
fbsql_num_rows -- Get number of rows in result
fbsql_pconnect --  Open a persistent connection to a FrontBase Server
fbsql_query -- Send a FrontBase query
fbsql_read_blob -- Read a BLOB from the database
fbsql_read_clob -- Read a CLOB from the database
fbsql_result -- Get result data
fbsql_rollback -- Rollback a transaction to the database
fbsql_set_lob_mode --  Set the LOB retrieve mode for a FrontBase result set
fbsql_select_db -- Select a FrontBase database
fbsql_start_db -- Start a database on local or remote server
fbsql_stop_db -- Stop a database on local or remote server
fbsql_tablename -- Get table name of field
fbsql_warnings -- Enable or disable FrontBase warnings
fbsql_database -- Get or set the database name used with a connection
fbsql_get_autostart_info -- No description given yet
fbsql_hostname -- Get or set the host name used with a connection
fbsql_password -- Get or set the user password used with a connection
fbsql_set_transaction --  Set the transaction locking and isolation
fbsql_username -- Get or set the host user used with a connection

fbsql_affected_rows

(PHP 4 >= 4.0.6)

fbsql_affected_rows --  Get number of affected rows in previous FrontBase operation

Description

int fbsql_affected_rows ( [int link_identifier])

fbsql_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or DELETE query associated with link_identifier. If the link identifier isn't specified, the last link opened by fbsql_connect() is assumed.

Notatka: If you are using transactions, you need to call fbsql_affected_rows() after your INSERT, UPDATE, or DELETE query, not after the commit.

If the last query was a DELETE query with no WHERE clause, all of the records will have been deleted from the table but this function will return zero.

Notatka: When using UPDATE, FrontBase will not update columns where the new value is the same as the old value. This creates the possibility that fbsql_affected_rows() may not actually equal the number of rows matched, only the number of rows that were literally affected by the query.

If the last query failed, this function will return -1.

See also: fbsql_num_rows().

fbsql_autocommit

(PHP 4 >= 4.0.6)

fbsql_autocommit -- Enable or disable autocommit.

Description

bool fbsql_autocommit ( resource link_identifier [, bool OnOff])

fbsql_autocommit() returns the current autocommit status. if the optional OnOff parameter is given the auto commit status will be changed. With OnOff set to TRUE each statement will be committed automatically, if no errors was found. With OnOff set to FALSE the user must commit or rollback the transaction using either fbsql_commit() or fbsql_rollback().

See also: fbsql_commit() and fbsql_rollback()

fbsql_change_user

(unknown)

fbsql_change_user --  Change logged in user of the active connection

Description

resource fbsql_change_user ( string user, string password [, string database [, int link_identifier]])

fbsql_change_user() changes the logged in user of the current active connection, or the connection given by the optional parameter link_identifier. If a database is specified, this will default or current database after the user has been changed. If the new user and password authorization fails, the current connected user stays active.

fbsql_close

(PHP 4 >= 4.0.6)

fbsql_close -- Close FrontBase connection

Description

boolean fbsql_close ( [resource link_identifier])

Returns: TRUE on success, FALSE on error.

fbsql_close() closes the connection to the FrontBase server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is used.

Using fbsql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

Przykład 1. fbsql_close() example

<?php
    $link = fbsql_connect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    print ("Connected successfully");
    fbsql_close ($link);
?>

See also: fbsql_connect() and fbsql_pconnect().

fbsql_commit

(PHP 4 >= 4.0.6)

fbsql_commit -- Commits a transaction to the database

Description

bool fbsql_commit ( [resource link_identifier])

Returns: TRUE on success, FALSE on failure.

fbsql_commit() ends the current transaction by writing all inserts, updates and deletes to the disk and unlocking all row and table locks held by the transaction. This command is only needed if autocommit is set to false.

See also: fbsql_autocommit() and fbsql_rollback()

fbsql_connect

(PHP 4 >= 4.0.6)

fbsql_connect -- Open a connection to a FrontBase Server

Description

resource fbsql_connect ( [string hostname [, string username [, string password]]])

Returns a positive FrontBase link identifier on success, or an error message on failure.

fbsql_connect() establishes a connection to a FrontBase server. The following defaults are assumed for missing optional parameters: hostname = 'NULL', username = '_SYSTEM' and password = empty password.

If a second call is made to fbsql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling fbsql_close().

Przykład 1. fbsql_connect() example

<?php

    $link = fbsql_connect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    print ("Connected successfully");
    fbsql_close ($link);

?>

See also fbsql_pconnect() and fbsql_close().

fbsql_create_db

(PHP 4 >= 4.0.6)

fbsql_create_db -- Create a FrontBase database

Description

bool fbsql_create_db ( string database name [, resource link_identifier])

fbsql_create_db() attempts to create a new database on the server associated with the specified link identifier.

Przykład 1. fbsql_create_db() example

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    if (fbsql_create_db ("my_db")) {
        print("Database created successfully\n");
    } else {
        printf("Error creating database: %s\n", fbsql_error ());
    }
?>

See also: fbsql_drop_db().

fbsql_create_blob

(PHP 4 CVS only)

fbsql_create_blob -- Create a BLOB

Description

string fbsql_create_blob ( string blob_data [, resource link_identifier])

Returns: A resource handle to the newly created blob.

fbsql_create_blob() creates a blob from blob_data. The returned resource handle can be used with insert and update commands to store the blob in the database.

Przykład 1. fbsql_create_blob() example

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    $filename = "blobfile.bin";
    $fp = fopen($filename, "rb");
    $blobdata = fread($fp, filesize($filename));
    fclose($fp);
    
    $blobHandle = fbsql_create_blob($blobdata, $link);
    
    $sql = "INSERT INTO BLOB_TABLE (BLOB_COLUMN) VALUES ($blobHandle);";
    $rs = fbsql_query($sql, $link);
?>

See also: fbsql_create_clob(), fbsql_read_blob(), fbsql_read_clob(), and fbsql_set_lob_mode().

fbsql_create_clob

(PHP 4 CVS only)

fbsql_create_clob -- Create a CLOB

Description

string fbsql_create_clob ( string clob_data [, resource link_identifier])

Returns: A resource handle to the newly created CLOB.

fbsql_create_clob() creates a clob from clob_data. The returned resource handle can be used with insert and update commands to store the clob in the database.

Przykład 1. fbsql_create_clob() example

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    $filename = "clob_file.txt";
    $fp = fopen($filename, "rb");
    $clobdata = fread($fp, filesize($filename));
    fclose($fp);
    
    $clobHandle = fbsql_create_clob($clobdata, $link);
    
    $sql = "INSERT INTO CLOB_TABLE (CLOB_COLUMN) VALUES ($clobHandle);";
    $rs = fbsql_query($sql, $link);
?>

See also: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob(), and fbsql_set_lob_mode().

fbsql_database_password

(PHP 4 >= 4.0.6)

fbsql_database_password --  Sets or retrieves the password for a FrontBase database

Description

string fbsql_database_password ( resource link_identifier [, string database_password])

Returns: The database password associated with the link identifier.

fbsql_database_password() sets and retrieves the database password used by the connection. if a database is protected by a database password, the user must call this function before calling fbsql_select_db(). if the second optional parameter is given the function sets the database password for the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if fbsql_connect() was called, and use it.

This function does not change the database password in the database nor can it be used to retrive the database password for a database.

Przykład 1. fbsql_create_clob() example

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    fbsql_database_password($link, "secret db password");
    fbsql_select_db($database, $link);
?>

See also: fbsql_connect(), fbsql_pconnect() and fbsql_select_db().

fbsql_data_seek

(PHP 4 >= 4.0.6)

fbsql_data_seek -- Move internal result pointer

Description

bool fbsql_data_seek ( resource result_identifier, int row_number)

Returns: TRUE on success, FALSE on failure.

fbsql_data_seek() moves the internal row pointer of the FrontBase result associated with the specified result identifier to point to the specified row number. The next call to fbsql_fetch_row() would return that row.

Row_number starts at 0.

Przykład 1. fbsql_data_seek() example

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");

    fbsql_select_db ("samp_db")
        or die ("Could not select database");

    $query = "SELECT last_name, first_name FROM friends;";
    $result = fbsql_query ($query)
        or die ("Query failed");

    # fetch rows in reverse order

    for ($i = fbsql_num_rows ($result) - 1; $i >=0; $i--) {
        if (!fbsql_data_seek ($result, $i)) {
            printf ("Cannot seek to row %d\n", $i);
            continue;
        }

        if(!($row = fbsql_fetch_object ($result)))
            continue;

        printf("%s %s<BR>\n", $row->last_name, $row->first_name);
    }

    fbsql_free_result ($result);
?>

fbsql_db_query

(PHP 4 >= 4.0.6)

fbsql_db_query -- Send a FrontBase query

Description

resource fbsql_db_query ( string database, string query [, resource link_identifier])

Returns: A positive FrontBase result identifier to the query result, or FALSE on error.

fbsql_db_query() selects a database and executes a query on it. If the optional link identifier isn't specified, the function will try to find an open link to the FrontBase server and if no such link is found it'll try to create one as if fbsql_connect() was called with no arguments

See also fbsql_connect().

fbsql_db_status

(PHP 4 >= 4.1.0)

fbsql_db_status -- Get the status for a given database

Description

int fbsql_db_status ( string database_name [, resource link_identifier])

Returns: An integer value with the current status.

fbsql_db_status() requests the current status of the database specified by database_name. If the link_identifier is omitted the default link_identifier will be used.

The return value can be one of the following constants:

  • FALSE - The exec handler for the host was invalid. This error will occur when the link_identifier connects directly to a database by using a port number. FBExec can be available on the server but no connection has been made for it.

  • FBSQL_UNKNOWN - The Status is unknown.

  • FBSQL_STOPPED - The database is not running. Use fbsql_start_db() to start the database.

  • FBSQL_STARTING - The database is starting.

  • FBSQL_RUNNING - The database is running and can be used to perform SQL operations.

  • FBSQL_STOPPING - The database is stopping.

  • FBSQL_NOEXEC - FBExec is not running on the server and it is not possible to get the status of the database.

See also: fbsql_start_db() and fbsql_stop_db().

fbsql_drop_db

(PHP 4 >= 4.0.6)

fbsql_drop_db -- Drop (delete) a FrontBase database

Description

bool fbsql_drop_db ( string database_name [, resource link_identifier])

Returns: TRUE on success, FALSE on failure.

fbsql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier.

fbsql_errno

(PHP 4 >= 4.0.6)

fbsql_errno --  Returns the numerical value of the error message from previous FrontBase operation

Description

int fbsql_errno ( [resource link_identifier])

Returns the error number from the last fbsql function, or 0 (zero) if no error occurred.

Errors coming back from the fbsql database backend don't issue warnings. Instead, use fbsql_errno() to retrieve the error code. Note that this function only returns the error code from the most recently executed fbsql function (not including fbsql_error() and fbsql_errno()), so if you want to use it, make sure you check the value before calling another fbsql function.

<?php
fbsql_connect("marliesle");
echo fbsql_errno().": ".fbsql_error()."<BR>";
fbsql_select_db("nonexistentdb");
echo fbsql_errno().": ".fbsql_error()."<BR>";
$conn = fbsql_query("SELECT * FROM nonexistenttable;");
echo fbsql_errno().": ".fbsql_error()."<BR>";
?>

See also: fbsql_error() and fbsql_warnings().

fbsql_error

(PHP 4 >= 4.0.6)

fbsql_error --  Returns the text of the error message from previous FrontBase operation

Description

string fbsql_error ( [resource link_identifier])

Returns the error text from the last fbsql function, or '' (the empty string) if no error occurred.

Errors coming back from the fbsql database backend don't issue warnings. Instead, use fbsql_error() to retrieve the error text. Note that this function only returns the error text from the most recently executed fbsql function (not including fbsql_error() and fbsql_errno()), so if you want to use it, make sure you check the value before calling another fbsql function.

<?php
fbsql_connect("marliesle");
echo fbsql_errno().": ".fbsql_error()."<BR>";
fbsql_select_db("nonexistentdb");
echo fbsql_errno().": ".fbsql_error()."<BR>";
$conn = fbsql_query("SELECT * FROM nonexistenttable;");
echo fbsql_errno().": ".fbsql_error()."<BR>";
?>

See also: fbsql_errno() and fbsql_warnings().

fbsql_fetch_array

(PHP 4 >= 4.0.6)

fbsql_fetch_array --  Fetch a result row as an associative array, a numeric array, or both

Description

array fbsql_fetch_array ( resource result [, int result_type])

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

fbsql_fetch_array() is an extended version of fbsql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must the numeric index of the column or make an alias for the column.

select t1.f1 as foo t2.f1 as bar from t1, t2

An important thing to note is that using fbsql_fetch_array() is NOT significantly slower than using fbsql_fetch_row(), while it provides a significant added value.

The optional second argument result_type in fbsql_fetch_array() is a constant and can take the following values: FBSQL_ASSOC, FBSQL_NUM, and FBSQL_BOTH.

For further details, see also fbsql_fetch_row() and fbsql_fetch_assoc().

Przykład 1. fbsql_fetch_array() example

<?php 
fbsql_connect ($host, $user, $password);
$result = fbsql_db_query ("database","select user_id, fullname from table");
while ($row = fbsql_fetch_array ($result)) {
    echo "user_id: ".$row["user_id"]."<br>\n";
    echo "user_id: ".$row[0]."<br>\n";
    echo "fullname: ".$row["fullname"]."<br>\n";
    echo "fullname: ".$row[1]."<br>\n";
}
fbsql_free_result ($result);
?>

fbsql_fetch_assoc

(PHP 4 >= 4.0.6)

fbsql_fetch_assoc --  Fetch a result row as an associative array

Description

array fbsql_fetch_assoc ( resource result)

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

fbsql_fetch_assoc() is equivalent to calling fbsql_fetch_array() with FBSQL_ASSOC for the optional second parameter. It only returns an associative array. This is the way fbsql_fetch_array() originally worked. If you need the numeric indices as well as the associative, use fbsql_fetch_array().

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must use fbsql_fetch_array() and have it return the numeric indices as well.

An important thing to note is that using fbsql_fetch_assoc() is NOT significantly slower than using fbsql_fetch_row(), while it provides a significant added value.

For further details, see also fbsql_fetch_row() and fbsql_fetch_array().

Przykład 1. fbsql_fetch_assoc() example

<?php 
fbsql_connect ($host, $user, $password);
$result = fbsql_db_query ("database","select * from table");
while ($row = fbsql_fetch_assoc ($result)) {
    echo $row["user_id"];
    echo $row["fullname"];
}
fbsql_free_result ($result);
?>

fbsql_fetch_field

(PHP 4 >= 4.0.6)

fbsql_fetch_field --  Get column information from a result and return as an object

Description

object fbsql_fetch_field ( resource result [, int field_offset])

Returns an object containing field information.

fbsql_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by fbsql_fetch_field() is retrieved.

The properties of the object are:

  • name - column name

  • table - name of the table the column belongs to

  • max_length - maximum length of the column

  • not_null - 1 if the column cannot be NULL

  • type - the type of the column

Przykład 1. fbsql_fetch_field() example

<?php 
fbsql_connect ($host, $user, $password)
    or die ("Could not connect");
$result = fbsql_db_query ("database", "select * from table")
    or die ("Query failed");
# get column metadata
$i = 0;
while ($i < fbsql_num_fields ($result)) {
    echo "Information for column $i:<BR>\n";
    $meta = fbsql_fetch_field ($result);
    if (!$meta) {
        echo "No information available<BR>\n";
    }
    echo "<PRE>
max_length:   $meta->max_length
name:         $meta->name
not_null:     $meta->not_null
table:        $meta->table
type:         $meta->type
</PRE>";
    $i++;
}
fbsql_free_result ($result);
?>

See also fbsql_field_seek().

fbsql_fetch_lengths

(PHP 4 >= 4.0.6)

fbsql_fetch_lengths --  Get the length of each output in a result

Description

array fbsql_fetch_lengths ( [resource result])

Returns: An array that corresponds to the lengths of each field in the last row fetched by fbsql_fetch_row(), or FALSE on error.

fbsql_fetch_lengths() stores the lengths of each result column in the last row returned by fbsql_fetch_row(), fbsql_fetch_array() and fbsql_fetch_object() in an array, starting at offset 0.

See also: fbsql_fetch_row().

fbsql_fetch_object

(PHP 4 >= 4.0.6)

fbsql_fetch_object -- Fetch a result row as an object

Description

object fbsql_fetch_object ( resource result [, int result_type])

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

fbsql_fetch_object() is similar to fbsql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

The optional argument result_type is a constant and can take the following values: FBSQL_ASSOC, FBSQL_NUM, and FBSQL_BOTH.

Speed-wise, the function is identical to fbsql_fetch_array(), and almost as quick as fbsql_fetch_row() (the difference is insignificant).

Przykład 1. fbsql_fetch_object() example

<?php 
fbsql_connect ($host, $user, $password);
$result = fbsql_db_query ("database", "select * from table");
while ($row = fbsql_fetch_object ($result)) {
    echo $row->user_id;
    echo $row->fullname;
}
fbsql_free_result ($result);
?>

See also: fbsql_fetch_array() and fbsql_fetch_row().

fbsql_fetch_row

(PHP 4 >= 4.0.6)

fbsql_fetch_row -- Get a result row as an enumerated array

Description

array fbsql_fetch_row ( resource result)

Returns: An array that corresponds to the fetched row, or FALSE if there are no more rows.

fbsql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Subsequent call to fbsql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

See also: fbsql_fetch_array(), fbsql_fetch_object(), fbsql_data_seek(), fbsql_fetch_lengths(), and fbsql_result().

fbsql_field_flags

(PHP 4 >= 4.0.6)

fbsql_field_flags --  Get the flags associated with the specified field in a result

Description

string fbsql_field_flags ( resource result, int field_offset)

fbsql_field_flags() returns the field flags of the specified field. The flags are reported as a single word per flag separated by a single space, so that you can split the returned value using explode().

fbsql_field_name

(PHP 4 >= 4.0.6)

fbsql_field_name --  Get the name of the specified field in a result

Description

string fbsql_field_name ( resource result, int field_index)

fbsql_field_name() returns the name of the specified field index. result must be a valid result identifier and field_index is the numerical offset of the field.

Notatka: field_index starts at 0.

e.g. The index of the third field would actually be 2, the index of the fourth field would be 3 and so on.

Przykład 1. fbsql_field_name() example

// The users table consists of three fields: 
//   user_id
//   username
//   password.

$res = fbsql_db_query("users", "select * from users", $link);

echo fbsql_field_name($res, 0) . "\n";
echo fbsql_field_name($res, 2);

The above example would produce the following output:

user_id
password

fbsql_field_len

(PHP 4 >= 4.0.6)

fbsql_field_len --  Returns the length of the specified field

Description

int fbsql_field_len ( resource result, int field_offset)

fbsql_field_len() returns the length of the specified field.

fbsql_field_seek

(PHP 4 >= 4.0.6)

fbsql_field_seek --  Set result pointer to a specified field offset

Description

bool fbsql_field_seek ( resource result, int field_offset)

Seeks to the specified field offset. If the next call to fbsql_fetch_field() doesn't include a field offset, the field offset specified in fbsql_field_seek() will be returned.

See also: fbsql_fetch_field().

fbsql_field_table

(PHP 4 >= 4.0.6)

fbsql_field_table --  Get name of the table the specified field is in

Description

string fbsql_field_table ( resource result, int field_offset)

Returns the name of the table that the specified field is in.

fbsql_field_type

(PHP 4 >= 4.0.6)

fbsql_field_type --  Get the type of the specified field in a result

Description

string fbsql_field_type ( resource result, int field_offset)

fbsql_field_type() is similar to the fbsql_field_name() function. The arguments are identical, but the field type is returned instead. The field type will be one of "int", "real", "string", "blob", and others as detailed in the FrontBase documentation.

Przykład 1. fbsql_field_type() example

<?php 

fbsql_connect ("localhost", "_SYSTEM", "");
fbsql_select_db ("wisconsin");
$result = fbsql_query ("SELECT * FROM onek;");
$fields = fbsql_num_fields ($result);
$rows   = fbsql_num_rows ($result);
$i = 0;
$table = fbsql_field_table ($result, $i);
echo "Your '".$table."' table has ".$fields." fields and ".$rows." records <BR>";
echo "The table has the following fields <BR>"; 
while ($i < $fields) {
    $type  = fbsql_field_type  ($result, $i);
    $name  = fbsql_field_name  ($result, $i);
    $len   = fbsql_field_len   ($result, $i);
    $flags = fbsql_field_flags ($result, $i);
    echo $type." ".$name." ".$len." ".$flags."<BR>";
    $i++;
}
fbsql_close();

?>

fbsql_free_result

(PHP 4 >= 4.0.6)

fbsql_free_result -- Free result memory

Description

bool fbsql_free_result ( int result)

fbsql_free_result() will free all memory associated with the result identifier result.

fbsql_free_result() only needs to be called if you are concerned about how much memory is being used for queries that return large result sets. All associated result memory is automatically freed at the end of the script's execution.

fbsql_insert_id

(PHP 4 >= 4.0.6)

fbsql_insert_id --  Get the id generated from the previous INSERT operation

Description

int fbsql_insert_id ( [resource link_identifier])

fbsql_insert_id() returns the ID generated for an column defined as DEFAULT UNIQUE by the previous INSERT query using the given link_identifier. If link_identifier isn't specified, the last opened link is assumed.

fbsql_insert_id() returns 0 if the previous query does not generate an DEFAULT UNIQUE value. If you need to save the value for later, be sure to call fbsql_insert_id() immediately after the query that generates the value.

Notatka: The value of the FrontBase SQL function LAST_INSERT_ID() always contains the most recently generated DEFAULT UNIQUE value, and is not reset between queries.

fbsql_list_dbs

(PHP 4 >= 4.0.6)

fbsql_list_dbs --  List databases available on a FrontBase server

Description

resource fbsql_list_dbs ( [resource link_identifier])

fbsql_list_dbs() will return a result pointer containing the databases available from the current fbsql daemon. Use the fbsql_tablename() function to traverse this result pointer.

Przykład 1. fbsql_list_dbs() example

$link = fbsql_connect('localhost', 'myname', 'secret');
$db_list = fbsql_list_dbs($link);

while ($row = fbsql_fetch_object($db_list)) {
    echo $row->Database . "\n";
}

The above example would produce the following output:

database1
database2
database3
...

Notatka: The above code would just as easily work with fbsql_fetch_row() or other similar functions.

fbsql_list_fields

(PHP 4 >= 4.0.6)

fbsql_list_fields -- List FrontBase result fields

Description

resource fbsql_list_fields ( string database_name, string table_name [, resource link_identifier])

fbsql_list_fields() retrieves information about the given tablename. Arguments are the database name and the table name. A result pointer is returned which can be used with fbsql_field_flags(), fbsql_field_len(), fbsql_field_name(), and fbsql_field_type().

A result identifier is a positive integer. The function returns -1 if a error occurs. A string describing the error will be placed in $phperrmsg, and unless the function was called as @fbsql() then this error string will also be printed out.

Przykład 1. fbsql_list_fields() example

$link = fbsql_connect('localhost', 'myname', 'secret');

$fields = fbsql_list_fields("database1", "table1", $link);
$columns = fbsql_num_fields($fields);

for ($i = 0; $i < $columns; $i++) {
    echo fbsql_field_name($fields, $i) . "\n";;
}

The above example would produce the following output:

field1
field2
field3
...

fbsql_list_tables

(PHP 4 >= 4.0.6)

fbsql_list_tables -- List tables in a FrontBase database

Description

resource fbsql_list_tables ( string database [, resource link_identifier])

fbsql_list_tables() takes a database name and returns a result pointer much like the fbsql_db_query() function. The fbsql_tablename() function should be used to extract the actual table names from the result pointer.

fbsql_next_result

(PHP 4 >= 4.0.6)

fbsql_next_result --  Move the internal result pointer to the next result

Description

bool fbsql_next_result ( int result_id)

When sending more than one SQL statement to the server or executing a stored procedure with multiple results will cause the server to return multiple result sets. This function will test for additional results available form the server. If an additional result set exists it will free the existing result set and prepare to fetch the words from the new result set. The function will return TRUE if an additional result set was available or FALSE otherwise.

Przykład 1. fbsql_next_result() example

<?php
    $link = fbsql_connect ("localhost", "_SYSTEM", "secret");
    fbsql_select_db("MyDB", $link);
    $SQL = "Select * from table1; select * from table2;";
    $rs = fbsql_query($SQL, $link);
    do {
        while ($row = fbsql_fetch_row($rs)) {
        }
    } while (fbsql_next_result($rs));
    fbsql_free_result($rs);
    fbsql_close ($link);
?>

fbsql_num_fields

(PHP 4 >= 4.0.6)

fbsql_num_fields -- Get number of fields in result

Description

int fbsql_num_fields ( resource result)

fbsql_num_fields() returns the number of fields in a result set.

See also: fbsql_db_query(), fbsql_query(), fbsql_fetch_field(), and fbsql_num_rows().

fbsql_num_rows

(PHP 4 >= 4.0.6)

fbsql_num_rows -- Get number of rows in result

Description

int fbsql_num_rows ( resource result)

fbsql_num_rows() returns the number of rows in a result set. This command is only valid for SELECT statements. To retrieve the number of rows returned from a INSERT, UPDATE or DELETE query, use fbsql_affected_rows().

Przykład 1. fbsql_num_rows() example

<?php

$link = fbsql_connect("localhost", "username", "password"); 
fbsql_select_db("database", $link);

$result = fbsql_query("SELECT * FROM table1;", $link); 
$num_rows = fbsql_num_rows($result); 

echo "$num_rows Rows\n";

?>

See also: fbsql_affected_rows(), fbsql_connect(), fbsql_select_db(), and fbsql_query().

fbsql_pconnect

(PHP 4 >= 4.0.6)

fbsql_pconnect --  Open a persistent connection to a FrontBase Server

Description

resource fbsql_pconnect ( [string hostname [, string username [, string password]]])

Returns: A positive FrontBase persistent link identifier on success, or FALSE on error.

fbsql_pconnect() establishes a connection to a FrontBase server. The following defaults are assumed for missing optional parameters: host = 'localhost', username = "_SYSTEM" and password = empty password.

fbsql_pconnect() acts very much like fbsql_connect() with two major differences.

To set Frontbase server port number, use fbsql_select_db().

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use.

This type of links is therefore called 'persistent'.

fbsql_query

(PHP 4 >= 4.0.6)

fbsql_query -- Send a FrontBase query

Description

resource fbsql_query ( string query [, resource link_identifier])

fbsql_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if fbsql_connect() was called with no arguments, and use it.

Notatka: The query string shall always end with a semicolon.

fbsql_query() returns TRUE (non-zero) or FALSE to indicate whether or not the query succeeded. A return value of TRUE means that the query was legal and could be executed by the server. It does not indicate anything about the number of rows affected or returned. It is perfectly possible for a query to succeed but affect no rows or return no rows.

The following query is syntactically invalid, so fbsql_query() fails and returns FALSE:

Przykład 1. fbsql_query() example

<?php
$result = fbsql_query ("SELECT * WHERE 1=1")
    or die ("Invalid query");
?>

The following query is semantically invalid if my_col is not a column in the table my_tbl, so fbsql_query() fails and returns FALSE:

Przykład 2. fbsql_query() example

<?php
$result = fbsql_query ("SELECT my_col FROM my_tbl")
    or die ("Invalid query");
?>

fbsql_query() will also fail and return FALSE if you don't have permission to access the table(s) referenced by the query.

Assuming the query succeeds, you can call fbsql_num_rows() to find out how many rows were returned for a SELECT statement or fbsql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

For SELECT statements, fbsql_query() returns a new result identifier that you can pass to fbsql_result(). When you are done with the result set, you can free the resources associated with it by calling fbsql_free_result(). Although, the memory will automatically be freed at the end of the script's execution.

See also: fbsql_affected_rows(), fbsql_db_query(), fbsql_free_result(), fbsql_result(), fbsql_select_db(), and fbsql_connect().

fbsql_read_blob

(PHP 4 CVS only)

fbsql_read_blob -- Read a BLOB from the database

Description

string fbsql_read_blob ( string blob_handle [, resource link_identifier])

Returns: A string containing the BLOB specified by blob_handle.

fbsql_read_blob() reads BLOB data from the database. If a select statement contains BLOB and/or BLOB columns FrontBase will return the data directly when data is fetched. This default behavior can be changed with fbsql_set_lob_mode() so the fetch functions will return handles to BLOB and CLOB data. If a handle is fetched a user must call fbsql_read_blob() to get the actual BLOB data from the database.

Przykład 1. fbsql_read_blob() example

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    $sql = "SELECT BLOB_COLUMN FROM BLOB_TABLE;";
    $rs = fbsql_query($sql, $link);
    $row_data = fbsql_fetch_row($rs);
    // $row_data[0] will now contain the blob data for teh first row
    fbsql_free_result($rs);
    
    $rs = fbsql_query($sql, $link);
    fbsql_set_lob_mode($rs, FBSQL_LOB_HANDLE);
    $row_data = fbsql_fetch_row($rs);
    // $row_data[0] will now contain a handle to the BLOB data in the first row
    $blob_data = fbsql_read_blob($row_data[0]);
    fbsql_free_result($rs);
    
?>

See also: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob(), and fbsql_set_lob_mode().

fbsql_read_clob

(PHP 4 CVS only)

fbsql_read_clob -- Read a CLOB from the database

Description

string fbsql_read_clob ( string clob_handle [, resource link_identifier])

Returns: A string containing the CLOB specified by clob_handle.

fbsql_read_clob() reads CLOB data from the database. If a select statement contains BLOB and/or CLOB columns FrontBase will return the data directly when data is fetched. This default behavior can be changed with fbsql_set_lob_mode() so the fetch functions will return handles to BLOB and CLOB data. If a handle is fetched a user must call fbsql_read_clob() to get the actual CLOB data from the database.

Przykład 1. fbsql_read_clob() example

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    $sql = "SELECT CLOB_COLUMN FROM CLOB_TABLE;";
    $rs = fbsql_query($sql, $link);
    $row_data = fbsql_fetch_row($rs);
    // $row_data[0] will now contain the clob data for teh first row
    fbsql_free_result($rs);
    
    $rs = fbsql_query($sql, $link);
    fbsql_set_lob_mode($rs, FBSQL_LOB_HANDLE);
    $row_data = fbsql_fetch_row($rs);
    // $row_data[0] will now contain a handle to the CLOB data in the first row
    $clob_data = fbsql_read_clob($row_data[0]);
    fbsql_free_result($rs);
    
?>

See also: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob(), and fbsql_set_lob_mode().

fbsql_result

(PHP 4 >= 4.0.6)

fbsql_result -- Get result data

Description

mixed fbsql_result ( resource result, int row [, mixed field])

fbsql_result() returns the contents of one cell from a FrontBase result set. The field argument can be the field's offset, or the field's name, or the field's table dot field's name (tabledname.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than fbsql_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Calls to fbsql_result() should not be mixed with calls to other functions that deal with the result set.

Recommended high-performance alternatives: fbsql_fetch_row(), fbsql_fetch_array(), and fbsql_fetch_object().

fbsql_rollback

(PHP 4 >= 4.0.6)

fbsql_rollback -- Rollback a transaction to the database

Description

bool fbsql_rollback ( [resource link_identifier])

Returns: TRUE on success, FALSE on failure.

fbsql_rollback() ends the current transaction by rolling back all statements issued since last commit. This command is only needed if autocommit is set to false.

See also: fbsql_autocommit() and fbsql_commit()

fbsql_set_lob_mode

(PHP 4 CVS only)

fbsql_set_lob_mode --  Set the LOB retrieve mode for a FrontBase result set

Description

bool fbsql_set_lob_mode ( resource result, string database_name)

Returns: TRUE on success, FALSE on error.

fbsql_set_lob_mode() sets the mode for retrieving LOB data from the database. When BLOB and CLOB data is stored in FrontBase it can be stored direct or indirect. Direct stored LOB data will always be fetched no matter the setting of the lob mode. If the LOB data is less than 512 bytes it will always be stored directly.

  • FBSQL_LOB_DIRECT - LOB data is retrieved directly. When data is fetched from the database with fbsql_fetch_row(), and other fetch functions, all CLOB and BLOB columns will be returned as ordinary columns. This is the default value on a new FrontBase result.

  • FBSQL_LOB_HANDLE - LOB data is retrieved as handles to the data. When data is fetched from the database with fbsql_fetch_row (), and other fetch functions, LOB data will be returned as a handle to the data if the data is stored indirect or the data if it is stored direct. If a handle is returned it will be a 27 byte string formatted as "@'000000000000000000000000'".

See also: fbsql_create_blob(), fbsql_create_clob(), fbsql_read_blob(), and fbsql_read_clob().

fbsql_select_db

(PHP 4 >= 4.0.6)

fbsql_select_db -- Select a FrontBase database

Description

bool fbsql_select_db ( string database_name [, resource link_identifier])

Returns: TRUE on success, FALSE on error.

fbsql_select_db() sets the current active database on the server that's associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if fbsql_connect() was called, and use it.

The client contacts FBExec to obtain the port number to use for the connection to the database. If the database name is a number the system will use that as a port number and it will not ask FBExec for the port number. The FrontBase server can be stared as FRontBase -FBExec=No -port=<port number> <database name>.

Every subsequent call to fbsql_query() will be made on the active database.

if the database is protected with a database password, the user must call fbsql_database_password() before selecting the database.

See also: fbsql_connect(), fbsql_pconnect(), fbsql_database_password() and fbsql_query().

fbsql_start_db

(PHP 4 >= 4.0.6)

fbsql_start_db -- Start a database on local or remote server

Description

bool fbsql_start_db ( string database_name [, resource link_identifier])

Returns: TRUE on success, FALSE on failure.

fbsql_start_db()

See also: fbsql_db_status() and fbsql_stop_db().

fbsql_stop_db

(PHP 4 >= 4.0.6)

fbsql_stop_db -- Stop a database on local or remote server

Description

bool fbsql_stop_db ( string database_name [, resource link_identifier])

Returns: TRUE on success, FALSE on failure.

fbsql_stop_db()

See also: fbsql_db_status() and fbsql_start_db().

fbsql_tablename

(PHP 4 CVS only)

fbsql_tablename -- Get table name of field

Description

string fbsql_tablename ( resource result, int i)

fbsql_tablename() takes a result pointer returned by the fbsql_list_tables() function as well as an integer index and returns the name of a table. The fbsql_num_rows() function may be used to determine the number of tables in the result pointer.

Przykład 1. fbsql_tablename() example

<?php 
fbsql_connect ("localhost", "_SYSTEM", "");
$result = fbsql_list_tables ("wisconsin");
$i = 0;
while ($i < fbsql_num_rows ($result)) {
    $tb_names[$i] = fbsql_tablename ($result, $i);
    echo $tb_names[$i] . "<BR>";
    $i++;
}
?>

fbsql_warnings

(PHP 4 >= 4.0.6)

fbsql_warnings -- Enable or disable FrontBase warnings

Description

bool fbsql_warnings ( [bool OnOff])

Returns TRUE if warnings is turned on otherwise FALSE.

fbsql_warnings() enables or disables FrontBase warnings.

fbsql_database

(PHP 4 >= 4.0.6)

fbsql_database -- Get or set the database name used with a connection

Description

string fbsql_database ( resource link_identifier [, string database])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

fbsql_get_autostart_info

(PHP 4 >= 4.1.0)

fbsql_get_autostart_info -- No description given yet

Description

array fbsql_get_autostart_info ( [resource link_identifier])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

fbsql_hostname

(PHP 4 >= 4.0.6)

fbsql_hostname -- Get or set the host name used with a connection

Description

string fbsql_hostname ( resource link_identifier [, string host_name])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

fbsql_password

(PHP 4 >= 4.0.6)

fbsql_password -- Get or set the user password used with a connection

Description

string fbsql_password ( resource link_identifier [, string password])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

fbsql_set_transaction

(PHP 4 CVS only)

fbsql_set_transaction --  Set the transaction locking and isolation

Description

void fbsql_set_transaction ( resource link_identifier, int Locking, int Isolation)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

fbsql_username

(PHP 4 >= 4.0.6)

fbsql_username -- Get or set the host user used with a connection

Description

string fbsql_username ( resource link_identifier [, string username])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

XXIX. filePro functions

These functions allow read-only access to data stored in filePro databases.

filePro is a registered trademark of fP Technologies, Inc. You can find more information about filePro at http://www.fptech.com/.

Spis treści
filepro -- read and verify the map file
filepro_fieldname -- gets the name of a field
filepro_fieldtype -- gets the type of a field
filepro_fieldwidth -- gets the width of a field
filepro_retrieve -- retrieves data from a filePro database
filepro_fieldcount -- find out how many fields are in a filePro database
filepro_rowcount -- find out how many rows are in a filePro database

filepro

(PHP 3, PHP 4 >= 4.0.0)

filepro -- read and verify the map file

Description

bool filepro ( string directory)

This reads and verifies the map file, storing the field count and info.

No locking is done, so you should avoid modifying your filePro database while it may be opened in PHP.

Notatka: Kiedy włączony jest tryb bezpieczny, PHP sprawdza, czy plik(i)/katalogi na których chcesz operować mają takie same UID jak skrypt, który jest aktualnie wykonywany.

filepro_fieldname

(PHP 3, PHP 4 >= 4.0.0)

filepro_fieldname -- gets the name of a field

Description

string filepro_fieldname ( int field_number)

Returns the name of the field corresponding to field_number.

filepro_fieldtype

(PHP 3, PHP 4 >= 4.0.0)

filepro_fieldtype -- gets the type of a field

Description

string filepro_fieldtype ( int field_number)

Returns the edit type of the field corresponding to field_number.

filepro_fieldwidth

(PHP 3, PHP 4 >= 4.0.0)

filepro_fieldwidth -- gets the width of a field

Description

int filepro_fieldwidth ( int field_number)

Returns the width of the field corresponding to field_number.

filepro_retrieve

(PHP 3, PHP 4 >= 4.0.0)

filepro_retrieve -- retrieves data from a filePro database

Description

string filepro_retrieve ( int row_number, int field_number)

Returns the data from the specified location in the database.

Notatka: Kiedy włączony jest tryb bezpieczny, PHP sprawdza, czy plik(i)/katalogi na których chcesz operować mają takie same UID jak skrypt, który jest aktualnie wykonywany.

filepro_fieldcount

(PHP 3, PHP 4 >= 4.0.0)

filepro_fieldcount -- find out how many fields are in a filePro database

Description

int filepro_fieldcount ( void)

Returns the number of fields (columns) in the opened filePro database.

See also filepro().

filepro_rowcount

(PHP 3, PHP 4 >= 4.0.0)

filepro_rowcount -- find out how many rows are in a filePro database

Description

int filepro_rowcount ( void)

Returns the number of rows in the opened filePro database.

Notatka: Kiedy włączony jest tryb bezpieczny, PHP sprawdza, czy plik(i)/katalogi na których chcesz operować mają takie same UID jak skrypt, który jest aktualnie wykonywany.

See also filepro().

XXX. System plików

Spis treści
basename --  Zwraca nazwę pliku, będącego składową ścieżki
chgrp -- Zmienia grupę pliku
chmod -- Zmienia prawa dostępu do pliku
chown -- Zmienia właściciela pliku
clearstatcache -- Czyści cache statystki pliku
copy -- Kopiuje plik
delete -- Ślepy wpis
dirname -- Zwraca nazwę katalogu, będącego składową ścieżki
disk_free_space -- Zwraca ilość wolnego miejsca w katalogu
diskfreespace -- Alias do disk_free_space()
disk_total_space -- Zwraca całkowity rozmiar katalogu
fclose -- Zamyka otwarty wskaźnik pliku
feof -- Sprawdza czy wskaźnik pliku jest na końcu pliku (EOF)
fflush -- Flushes the output to a file
fgetc -- Pobiera znak ze wskaźnika pliku
fgetcsv --  Pobiera linię ze wskanika pliku i przetwarza na pola CSV
fgets -- Pobiera linię ze wskaźnika pliku
fgetss --  Pobiera linię ze wskaźnika pliku i usuwa tagi HTML
file -- Czyta całą zawartość pliku do tablicy
file_exists -- Sprawdza czy plik istnieje
fileatime -- Pobiera ostatni czas dostępu do pliku
filectime -- Gets inode change time of file
filegroup -- Pobiera grupę pliku
fileinode -- Pobiera i-węzeł pliku
filemtime -- Pobiera czas ostatniej modyfikacji pliku
fileowner -- Pobiera właściciela pliku
fileperms -- Pobiera prawa dostępu pliku
filesize -- Pobiera rozmiar pliku
filetype -- Pobiera typ pliku
flock -- Portable advisory file locking
fopen -- Otwiera plik lub URL
fpassthru --  Output all remaining data on a file pointer
fputs -- Zapisuje do wskaźnika pliku
fread -- Odczyt plików binarnie bezpieczny
fscanf -- Przetwarza dane z pliku według formatu
fseek -- Seeks on a file pointer
fstat --  Pobiera informacje o pliku używając otwartego wskaźnika pliku
ftell -- Tells file pointer read/write position
ftruncate --  Przycina plik do podanej długości.
fwrite -- Binary-safe file write
set_file_buffer --  Sets file buffering on the given file pointer
is_dir -- Mówi czy nazwa_pliku jest katalogiem
is_executable -- Mówi czy plik jest wykonywalny
is_file --  Mówi czy nazwa_pliku jest zwykłym plikiem
is_link --  Mówi czy nazwa_pliku jest dowiązaniem symbolicznym
is_readable --  Tells whether the filename is readable
is_writable -- Tells whether the filename is writable
is_writeable -- Tells whether the filename is writable
is_uploaded_file -- Mówi czy plik został przysłany przez HTTP POST.
link -- Create a hard link
linkinfo -- Gets information about a link
mkdir -- Makes directory
move_uploaded_file -- Moves an uploaded file to a new location.
parse_ini_file -- Parse a configuration file
pathinfo -- Returns information about a file path
pclose -- Closes process file pointer
popen -- Opens process file pointer
readfile -- Outputs a file
readlink -- Returns the target of a symbolic link
rename -- Renames a file
rewind -- Rewind the position of a file pointer
rmdir -- Removes directory
stat -- Gives information about a file
lstat --  Gives information about a file or symbolic link
realpath -- Returns canonicalized absolute pathname
symlink -- Creates a symbolic link
tempnam -- Create file with unique file name
tmpfile -- Tworzy plik tymczasowy
touch -- Ustawia czas modyfikacji pliku
umask -- Changes the current umask
unlink -- Kasowanie pliku

basename

(PHP 3, PHP 4 >= 4.0.0)

basename --  Zwraca nazwę pliku, będącego składową ścieżki

Opis

string basename ( string ścieżka [, string przyrostek])

Z podanego łańcucha zawierającego ścieżkę do pliku, funkcja zwraca samą nazwę pliku. Jeśli koniec nazwy pliku pasuje do parametru przyrostek to zostanie on także obcięty.

W Windows jako separator ścieżki używany jest znak slash (/) i backslash (\). W innych środowiskach jest to slash (/).

Przykład 1. basename() przykład

$path = "/home/httpd/html/index.php";
$file = basename ($path);        // $file zawiera "index.php"
$file = basename ($path,".php"); // $file zawiera "index"

Notatka: Parametr przyrostek został dodany w PHP 4.1.0.

Patrz także: dirname()

chgrp

(PHP 3, PHP 4 >= 4.0.0)

chgrp -- Zmienia grupę pliku

Opis

int chgrp ( string nazwa_pliku, mixed grupa)

Dokonuje zmiany grupy pliku podanego w parametrze nazwa_pliku na wybraną parametrem grupa (określoną przez nazwę lub numer). Tylko super użytkownik może zmienić dowolnie grupę pliku; inni użytkownicy mogą zmienić grupę pliku na dowolną grupę, której członkiem jest ten użytkownik.

Zwraca TRUE gdy sukces; w przeciwnym wypadku zwraca FALSE.

Patrz także chown() i chmod().

Notatka: Ta funkcja nie jest dostępna na platformie Windows.

chmod

(PHP 3, PHP 4 >= 4.0.0)

chmod -- Zmienia prawa dostępu do pliku

Opis

int chmod ( string nazwa_pliku, int prawa)

Dokonuje zmiany praw pliku podanego w parametrze nazwa_pliku na podane w prawa.

Pamiętaj, że parametr prawa nie jest automatycznie zastępowany wartością oktalną, więc łańcuchy (takie jak "g+w") nie będą poprawnie interpretowane. Aby zapewnić poprawność operacji musisz parametr prawa poprzedzić prefixem zero (0):

chmod ("/katalog/plik", 755);   // dziesiętnie; prawdopodobnie nieprawidłowo
chmod ("/katalog/plik", "u+rwx,go+rx"); // łańcuch; nieprawidłowo
chmod ("/katalog/plik", 0755);  // ósemkowo; poprawna wartość dla praw

Zwraca TRUE gdy sukces i FALSE w przeciwnym wypadku.

Patrz także chown() i chgrp().

Notatka: Ta funkcja nie jest dostępna na platformie Windows.

chown

(PHP 3, PHP 4 >= 4.0.0)

chown -- Zmienia właściciela pliku

Opis

int chown ( string nazwa_pliku, mixed użytkownik)

Dokonuje zmiany właściciela pliku nazwa_pliku na użytkownika podanego w parametrze użytkownik (określonego przez nazwę lub numer). Tylko super użytkownik może zmienić właściciela pliku.

Zwraca TRUE gdy sukces; w przeciwnym wypadku zwraca FALSE.

Patrz także chown() i chmod().

Notatka: Ta funkcja nie jest dostępna na platformie Windows.

clearstatcache

(PHP 3, PHP 4 >= 4.0.0)

clearstatcache -- Czyści cache statystki pliku

Opis

void clearstatcache ( void)

Wywoływanie systemowych stat lub lstat w większości systemów jest zbyt kosztowne. Dlatego, wynik ostatniego wywołania każdej z funkcji statusowej (przedstawionej poniżej) jest przechowywany do wykorzystania go przy następnym wywołaniu funkcji z tą samą nazwą pliku. Jeśli chcesz wymusić ponowne sprawdzenie statusu, pliku który jest sprawdzany wielokrotnie i mógł się zmienić lub zniknąć, użyj tej funkcji aby wyczyścić wyniki ostatniego wywołania tych funkcji z pamięci.

Te wartości są cachowane tylko przez czas działania pojedynczego wywołania.

Dotyczy funkcji stat(), lstat(), file_exists(), is_writable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype() i fileperms().

copy

(PHP 3, PHP 4 >= 4.0.0)

copy -- Kopiuje plik

Opis

int copy ( string źródło, string przeznaczenie)

Tworzy kopię pliku. Zwraca TRUE jeśli kopiowanie powiodło się, FALSE w przeciwnym przypadku.

Przykład 1. copy() przykład

if (!copy($file, $file.'.bak')) {
    print ("Kopiowanie pliku nie powiodło się...<br>\n");
}

Ostrze¿enie

Jeśli docelowy plik istnieje to zostanie nadpisany.

Patrz także: move_uploaded_file(), rename(), i część podręcznika dotycząca obsługi uploadowanych plików.

delete

(unknown)

delete -- Ślepy wpis

Opis

void delete ( string plik)

To jest ślepy wpis aby zadowolić ludzi którzy szukają unlink() lub unset() w nie właściwym miejscu.

Patrz także: unlink() do kasowania plików, unset() do kasowania zmiennych.

dirname

(PHP 3, PHP 4 >= 4.0.0)

dirname -- Zwraca nazwę katalogu, będącego składową ścieżki

Opis

string dirname ( string ścieżka)

Z podanego łańcucha zawierającego ścieżkę do pliku, funkcja ta zwróci nazwę katalogu.

W Windows jako separator ścieżki używany jest znak slash (/) i backslash (\). W innych środowiskach jest to slash (/).

Przykład 1. dirname() przykład

$path = "/etc/passwd";
$file = dirname ($path); // $file zawiera "/etc"

Patrz także: basename()

disk_free_space

(PHP 4 >= 4.1.0)

disk_free_space -- Zwraca ilość wolnego miejsca w katalogu

Opis

float disk_free_space ( string katalog)

Podając łańcuch zawierający katalog, funkcja zwróci ilość wolnego miejsca (w bajtach) w odpowiadającym mu systemie plików lub partycji dysku.

Przykład 1. disk_free_space() przykład

$df = disk_free_space("/"); // $df zawiera ilość wolnego (w bajtach) miejsca
                          // w "/"

diskfreespace

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

diskfreespace -- Alias do disk_free_space()

Opis

float diskfreespace ( string katalog)

To jest odradzany alias do disk_free_space(). Użyj tej funkcji zamiast niego.

disk_total_space

(PHP 4 >= 4.1.0)

disk_total_space -- Zwraca całkowity rozmiar katalogu

Opis

float disk_total_space ( string katalog)

Podając łańcuch zawierający katalog, funkcja ta zwróci całkowity rozmiar (w bajtach) w odpowiadającym mu systemie plików lub partycji dysku.

Przykład 1. disk_total_space() przykład

$df = disk_total_space("/"); // $df zawiera całkowitą liczbę bajtów
                             // dostępną w "/"

fclose

(PHP 3, PHP 4 >= 4.0.0)

fclose -- Zamyka otwarty wskaźnik pliku

Opis

bool fclose ( int fp)

Wskaźnik pliku fp jest zamykany.

Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.

Wskaźnik pliku musi być poprawny i musi wskazywać na plik poprawnie otwarty przez fopen() lub fsockopen().

feof

(PHP 3, PHP 4 >= 4.0.0)

feof -- Sprawdza czy wskaźnik pliku jest na końcu pliku (EOF)

Opis

int feof ( int fp)

Zwraca TRUE jeśli wskaźnik pliku jest na EOF lub gdy zdarzy się błąd; w przeciwnym wypadku zwraca FALSE.

Wskaźnik pliku musi być poprawny i musi wskazywać na plik poprawnie otwarty przez fopen(), popen() lub fsockopen().

fflush

(PHP 4 )

fflush -- Flushes the output to a file

Description

int fflush ( int fp)

This function forces a write of all buffered output to the to the resource pointed to by the file handle fp. Returns TRUE if succesful, FALSE otherwise.

The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen().

fgetc

(PHP 3, PHP 4 >= 4.0.0)

fgetc -- Pobiera znak ze wskaźnika pliku

Opis

string fgetc ( int fp)

Zwraca łańcuch zawierający pojedynczy znak odczytany z pliku wskazanego przez fp. Zwraca FALSE gdy EOF (koniec pliku).

Wskaźnik pliku musi być poprawny i musi wskazywać na plik poprawnie otwarty przez fopen() lub fsockopen().

Patrz także fread(), fopen(), popen(), fsockopen() i fgets().

fgetcsv

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

fgetcsv --  Pobiera linię ze wskanika pliku i przetwarza na pola CSV

Opis

array fgetcsv ( int fp, int długość [, string delimiter])

Działa podobnie do fgets() tylko, że fgetcsv() przetwarza odczytaną linię na pola w formacie CSV i zwraca tablicę zawierającą odczytane pola. Delimiterem pól jest przecinek, chyba że określisz inny delimiter w opcjonalnym 3 parametrze.

Fp musi być poprawnym wskaźnikiem do pliku poprawnie otworzonym przez fopen() lub fsockopen().

Długość musi być większa niż najdłuższa linia znajdująca się w pliku CSV (wliczając w to znaki końca linii).

fgetcsv() zwraca FALSE gdy wystąpi błąd, włączając w to koniec pliku.

Nota bene. Pusta linia w pliku CSV zostanie zwrócona jako tablica składająca się z pojedynczego pola NULL i nie zostanie potraktowana jako błąd.

Przykład 1. fgetcsv() przykład - Odczyt i wyświetlenie całej zawartości pliku CSV

$row = 1;
$fp = fopen ("test.csv","r");
while ($data = fgetcsv ($fp, 1000, ",")) {
    $num = count ($data);
    print "<p> $num pola w linii $row: <br>";
    $row++;
    for ($c=0; $c < $num; $c++) {
        print $data[$c] . "<br>";
    }
}
fclose ($fp);

fgets

(PHP 3, PHP 4 >= 4.0.0)

fgets -- Pobiera linię ze wskaźnika pliku

Opis

string fgets ( int fp [, int długość])

Zwraca łańcuch o długości - 1 bajtów odczytany z pliku wskazanego przez fp. Czytanie kończy się kiedy przeczytano długość - 1 bajtów lub gdy wystąpi znak nowej linii (jest on dołączany do zwracanego wyniku) lub gdy wystąpi znak końca pliku EOF (którykolwiek przypadek zdarzy się pierwszy). Jeśli nie została określona długość, domyślnie przyjmuje 1k (1024 bajty).

W przypadku błędu, zwraca FALSE.

Główna pułapka:

Osoby używające semantyki 'C' z fgets powinni zauważyć różnicę w sposobie zwracania EOF.

Wskaźnik pliku musi być poprawny i musi wskazywać na plik poprawnie otwarty przez fopen(), popen() lub fsockopen().

Prosty przykład:

Przykład 1. Czytanie pliku linia po linii

$fd = fopen ("/tmp/inputfile.txt", "r");
while (!feof ($fd)) {
    $buffer = fgets($fd, 4096);
    echo $buffer;
}
fclose ($fd);

Patrz także fread(), fopen(), popen(), fgetc(), fsockopen() i socket_set_timeout().

fgetss

(PHP 3, PHP 4 >= 4.0.0)

fgetss --  Pobiera linię ze wskaźnika pliku i usuwa tagi HTML

Opis

string fgetss ( int fp, int długość [, string dozwolone_tagi])

Działa identycznie jak fgets(), tylko że fgetss dokonuje usunięcia wszystkich tagów HTML i PHP z tektu, który przeczyta.

Możesz określić opcjonalny 3 parametr aby wyszczególnić tagi, które nie powinny zostać usunięte.

Notatka: dozwolone_tagi został dodany w PHP 3.0.13, PHP4B3.

Patrz także fgets(), fopen(), fsockopen(), popen() i strip_tags().

file

(PHP 3, PHP 4 >= 4.0.0)

file -- Czyta całą zawartość pliku do tablicy

Opis

array file ( string nazwa_pliku [, int użyj_include_path])

Działa identycznie jak readfile(), tylko że file() zwraca plik w tablicy. Każdy element tablicy odpowiada linii w pliku. Elementy tablicy zawierają znak nowej linii.

Notatka: Każda linia w wynikowej tabeli zawiera znak nowej lini, jeśli chcesz się ich pozbyć to musisz użyć trim().

Możesz użyć opcjonalnego 2 parametru i ustawić go na "1", jeśli chcesz szukać pliku także w include_path.

<?php
// pobiera stronę WWW do tablicy i wyświetla ją
$fcontents = file ('http://www.php.net/');
while (list ($line_num, $line) = each ($fcontents)) {
    echo "<b>Linia $line_num:</b>; ", htmlspecialchars ($line), "<br>\n";
}

// pobiera stronę WWW i zapisuje do łańcucha
$fcontents = join ('', file ('http://www.php.net/'));
?>

Ostrze¿enie

Ta funkcja nie jest (jeszcze) bezpieczna dla danych binarnych!

Podpowiedź: Jeśli włączona jest funkcja "fopen wrapper", możliwe jest podanie jako nazwy pliku adresu URL. Zobacz fopen() by uzyskać więcej informacji.

Patrz także readfile(), fopen(), fsockopen() i popen().

file_exists

(PHP 3, PHP 4 >= 4.0.0)

file_exists -- Sprawdza czy plik istnieje

Opis

bool file_exists ( string nazwa_pliku)

Zwraca TRUE jeśli podany plik w parametrze nazwa_pliku istnieje; FALSE w przeciwnym wypadku.

Ta funkcja nie działa na zdalnych plikach; sprawdzany plik musi być dostępny przez system plików serwera.

Wyniki tej funkcji są cachowane. Zobacz clearstatcache() aby uzyskać więcej szczegółów.

fileatime

(PHP 3, PHP 4 >= 4.0.0)

fileatime -- Pobiera ostatni czas dostępu do pliku

Opis

int fileatime ( string nazwa_pliku)

Zwraca czas, kiedy nastąpił ostatni dostęp do pliku lub FALSE w przypadku błędu. Czas jest zwracany w postaci unix'owego znacznika czasu.

Wyniki tej funkcji są cachowane. Zobacz clearstatcache() aby uzyskać więcej szczegółów.

Notka: Czas dostępu do pliku przypuszczalnie zmienia się zawsze kiedy bloki danych pliku są odczytywane. To może kosztować utratę wydajności aplikacji, która regularnie korzystają z wielu plików lub katalogów. Niektóre unix'owe systemy plików mogą być montowane z wyłączonym uaktualnianiem czasu dostępu, aby podnieść wydajność takich aplikacji; USENETowy katalog roboczy wiadomości są powszechnym przykładem. Na takich systemach plików ta funkcja będzie bezużyteczna.

Ta funkcja nie działa na zdalnych plikach; sprawdzany plik musi być dostępny przez system plików serwera.

filectime

(PHP 3, PHP 4 >= 4.0.0)

filectime -- Gets inode change time of file

Description

int filectime ( string filename)

Returns the time the file was last changed, or FALSE in case of an error. The time is returned as a Unix timestamp.

The results of this function are cached. See clearstatcache() for more details.

Note: In most Unix filesystems, a file is considered changed when its inode data is changed; that is, when the permissions, owner, group, or other metadata from the inode is updated. See also filemtime() (which is what you want to use when you want to create "Last Modified" footers on web pages) and fileatime().

Note also that in some Unix texts the ctime of a file is referred to as being the creation time of the file. This is wrong. There is no creation time for Unix files in most Unix filesystems.

This function will not work on remote files; the file to be examined must be accessible via the server's filesystem.

filegroup

(PHP 3, PHP 4 >= 4.0.0)

filegroup -- Pobiera grupę pliku

Opis

int filegroup ( string nazwa_pliku)

Zwraca identyfikator grupy do której należy właściciel pliku lub FALSE w przypadku błędu. Identyfikator grupy zwracany jest w postaci numerycznej, użyj posix_getgrgid() aby rozwinąć go w nazwę grupy.

Wyniki tej funkcji są cachowane. Zobacz clearstatcache() aby uzyskać więcej szczegółów.

Notatka: Ta funkcja nie jest dostępna na platformie Windows.

Ta funkcja nie działa na zdalnych plikach; sprawdzany plik musi być dostępny przez system plików serwera.

fileinode

(PHP 3, PHP 4 >= 4.0.0)

fileinode -- Pobiera i-węzeł pliku

Opis

int fileinode ( string nazwa_pliku)

Zwraca numer i-węzła pliku lub FALSE w przypadku błędu.

Wyniki tej funkcji są cachowane. Zobacz clearstatcache() aby uzyskać więcej szczegółów.

Ta funkcja nie działa na zdalnych plikach; sprawdzany plik musi być dostępny przez system plików serwera.

Notatka: Ta funkcja nie jest dostępna na platformie Windows.

filemtime

(PHP 3, PHP 4 >= 4.0.0)

filemtime -- Pobiera czas ostatniej modyfikacji pliku

Opis

int filemtime ( string nazwa_pliku)

Zwraca czas, kiedy plik był ostatnio modyfikowany lub FALSE w przypadku błędu. Czas jest zwracany w postaci unix'owego znacznika czasu.

Wyniki tej funkcji są cachowane. Zobacz clearstatcache() aby uzyskać więcej szczegółów.

Ta funkcja nie działa na zdalnych plikach; sprawdzany plik musi być dostępny przez system plików serwera.

Notka: Ta funkcja zwraca czas kiedy bloki danych pliku zostały zapisane, to jest, czas kiedy zawartość pliku została zmieniona. Użyj date() na wyniku tej funkcji aby otrzymać czytelną datę modyfikacji do użycia jej w stopkach stron.

fileowner

(PHP 3, PHP 4 >= 4.0.0)

fileowner -- Pobiera właściciela pliku

Opis

int fileowner ( string nazwa_pliku)

Zwraca identyfikator użytkownika, który jest właścicielem pliku, lub FALSE w przypadku błędu. Identyfikator użytkownika zwracany jest w postaci numerycznej, użyj posix_getpwuid() aby rozwinąć go w nazwę użytkownika.

Wyniki tej funkcji są cachowane. Zobacz clearstatcache() aby uzyskać więcej szczegółów.

Ta funkcja nie działa na zdalnych plikach; sprawdzany plik musi być dostępny przez system plików serwera.

Notatka: Ta funkcja nie jest dostępna na platformie Windows.

fileperms

(PHP 3, PHP 4 >= 4.0.0)

fileperms -- Pobiera prawa dostępu pliku

Opis

int fileperms ( string nazwa_pliku)

Zwraca prawa dostępu pliku, lub FALSE w przypadku błędu.

Ta funkcja nie działa na zdalnych plikach; sprawdzany plik musi być dostępny przez system plików serwera.

Wyniki tej funkcji są cachowane. Zobacz clearstatcache() aby uzyskać więcej szczegółów.

filesize

(PHP 3, PHP 4 >= 4.0.0)

filesize -- Pobiera rozmiar pliku

Opis

int filesize ( string nazwa_pliku)

Zwraca rozmiar pliku w bajtach, lub FALSE w przypadku błędu.

Wyniki tej funkcji są cachowane. Zobacz clearstatcache() aby uzyskać więcej szczegółów.

Ta funkcja nie działa na zdalnych plikach; sprawdzany plik musi być dostępny przez system plików serwera.

filetype

(PHP 3, PHP 4 >= 4.0.0)

filetype -- Pobiera typ pliku

Opis

string filetype ( string nazwa_pliku)

Zwraca typ pliku. Możliwe wartości to fifo, char, dir, block, link, file, and unknown.

Zwraca FALSE w przypadku błędu.

Wyniki tej funkcji są cachowane. Zobacz clearstatcache() aby uzyskać więcej szczegółów.

Ta funkcja nie działa na zdalnych plikach; sprawdzany plik musi być dostępny przez system plików serwera.

flock

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

flock -- Portable advisory file locking

Description

bool flock ( int fp, int operation [, int wouldblock])

PHP supports a portable way of locking complete files in an advisory way (which means all accessing programs have to use the same way of locking or it will not work).

flock() operates on fp which must be an open file pointer. operation is one of the following values:

  • To acquire a shared lock (reader), set operation to LOCK_SH (set to 1 prior to PHP 4.0.1).

  • To acquire an exclusive lock (writer), set operation to LOCK_EX (set to 2 prior to PHP 4.0.1).

  • To release a lock (shared or exclusive), set operation to LOCK_UN (set to 3 prior to PHP 4.0.1).

  • If you don't want flock() to block while locking, add LOCK_NB (4 prior to PHP 4.0.1) to operation.

flock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unix derivatives and even Windows). The optional third argument is set to TRUE if the lock would block (EWOULDBLOCK errno condition)

flock() returns TRUE on success and FALSE on error (e.g. when a lock could not be acquired).

Notatka: Because flock() requires a file pointer, you may have to use a special lock file to protect access to a file that you intend to truncate by opening it in write mode (with a "w" or "w+" argument to fopen()).

Ostrze¿enie

flock() will not work on NFS and many other networked file systems. Check your operating system documentation for more details.

On some operating systems flock() is implemented at the process level. When using a multithreaded server API like ISAPI you may not be able to rely on flock() to protect files against other PHP scripts running in parallel threads of the same server instance!

fopen

(PHP 3, PHP 4 >= 4.0.0)

fopen -- Otwiera plik lub URL

Opis

int fopen ( string nazwa_pliku, string tryb [, int użyj_include_path])

Jeśli nazwa_pliku zaczyna się od "http://" (nie jest rozróżniana wielość liter), jest otwierane połączenie HTTP 1.0 do wybranego serwera, strona jest żądana używając metody HTTP GET i wskaźnik pliku jest ustawiany na początku ciała odpowiedzi. Nagłówek 'Host:' jest wysyłany z żądaniem pozwalającym uchwycić oparte o nazwę wirtualne hosty.

Zauważ, że wskaźnik pliku pozwala tobie wydobyć tylko ciało odpowiedzi; Nie możesz dostać się do nagłówka HTTP używając tej funkcji.

Wersje przed PHP 4.0.5 nie obsługują przekierowań HTTP. Z tego powodu katalogi muszą zawierać kończące slashe.

Jeśli nazwa_pliku zaczyna się od "ftp://" (nie jest rozróżniana wielkość znaków), jest otwierane połączenie ftp do podanego serwera i zwracany jest wskaźnik do żądanego pliku. jeśli serwer nie obsługuje trybu pasywnego ftp, ta funkcja zawiedzie. Możesz otwierać pliki albo do odczytu lub zapisu przez ftp (ale nie oba tryby równocześnie).

Jeśli nazwa_pliku jest jedną z możliwości "php://stdin", "php://stdout" lub "php://stderr" zostanie otworzony odpowiedni strumień stdio. (To zostało wprowadzone w PHP 3.0.13; w wcześniejszych wersjach, aby dostać się do strumienia stdio nazwa_pliku musi mieć postać "/dev/stdin" lub "/dev/fd/0".)

Jeśli nazwa_pliku zaczyna się czymkolwiek innym zostanie otworzony plik z systemu plików i zostanie zwrócony wskaźnik pliku.

Jeśli otwieranie zwiedzie, funkcja zwróci FALSE.

tryb może być dowolny z poniższych:

  • 'r' - Otwórz tylko do odczytu; ustawia wskaźnik pliku na początku pliku.

  • 'r+' - Otwórz do odczytu i zapisu; ustawia wskaźnik pliku na początku pliku.

  • 'w' - Otwórz tylko do zapisu; ustawia wskaźnik pliku na początku pliku i obcina plik (zeruje) do 0 długości. Jeśli plik nie istnieje to próbuje go utworzyć.

  • 'w+' - Otwórz do odczytu i zapisu; ustawia wskaźnik pliku na początku pliku i obcina plik (zeruje) do 0 długości. Jeśli plik nie istnieje to próbuje go utworzyć.

  • 'a' - Otwórz tylko do zapisu; ustawia wskaźnik pliku na końcu pliku. Jeśli plik nie istnieje to próbuje go utworzyć.

  • 'a+' - Otwórz do odczytu i zapisu; ustawia wskaźnik pliku na końcu pliku. Jeśli plik nie istnieje to próbuje go utworzyć.

Notatka: Parametr tryb może zawierać literę 'b'. To jest użyteczne tylko na systemach, które rozróżniają pliki pomiędzy binarne i tekstowe (np. Windows. To jest bezużyteczne na Unixach) Jeśli nie potrzebne zostanie zignorowane.

Możesz użyć opcjonalnego 3 parametru i ustawić go na "1", jeśli chcesz szukać pliku także w include_path.

Przykład 1. fopen() przykład

$fp = fopen ("/home/rasmus/file.txt", "r");
$fp = fopen ("/home/rasmus/file.gif", "wb");
$fp = fopen ("http://www.php.net/", "r");
$fp = fopen ("ftp://user:password@example.com/", "w");

Jeśli doświadczasz problemów z czytaniem i zapisywaniem do plików i używasz PHP jako moduł serwera, pamiętaj, że pliki i katalogi które używasz muszą być osiągalne dla procesu serwera.

Na platformach Windows, uważaj na zastosowanie znaków ucieczki dla wszystkich użytych w ścieżce do pliku backslashy, lub użyj slash'y.

$fp = fopen ("c:\\data\\info.txt", "r");

Patrz także fclose(), fsockopen(), socket_set_timeout() i popen().

fpassthru

(PHP 3, PHP 4 >= 4.0.0)

fpassthru --  Output all remaining data on a file pointer

Description

int fpassthru ( int fp)

Reads to EOF on the given file pointer from the current position and writes the results to standard output.

If an error occurs, fpassthru() returns FALSE.

The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen(). You may need to call rewind() to reset the file pointer to the beginning of the file if you have already written data to the file. The file is closed when fpassthru() is done reading it (leaving fp useless).

If you just want to dump the contents of a file to stdout you may want to use the readfile(), which saves you the fopen() call.

Notatka: When using fpassthru() on a binary file on Windows systems, you should make sure to open the file in binary mode by appending a b to the mode used in the call to fopen().

See also readfile(), fopen(), popen(), and fsockopen()

fputs

(PHP 3, PHP 4 >= 4.0.0)

fputs -- Zapisuje do wskaźnika pliku

Opis

int fputs ( int fp, string str [, int długość])

fputs() jest aliasem do fwrite(), i jest identyczna w każdym przypadku. Zauważ, że parametr długość jest opcjonalny i jeśli go nie podasz to cały łańcuch zostanie zapisany.

fread

(PHP 3, PHP 4 >= 4.0.0)

fread -- Odczyt plików binarnie bezpieczny

Opis

string fread ( int fp, int długość)

fread() odczytuje do długość bajtów ze wskaźnika pliku fp. Czytanie kończy się gdy odczytano już długość bajtów lub osiągnięto EOF, cokolwiek nastąpi pierwsze.

// pobierz zawartość pliku do łańcucha
$filename = "/usr/local/something.txt";
$fd = fopen ($filename, "r");
$contents = fread ($fd, filesize ($filename));
fclose ($fd);

Notatka: W systemach, które rozróżniają pliki na binarne i tekstowe (np. Windows) plik musi zostać otworzony z 'b' włączonym do parametru tryb funkcji fopen().

$filename = "c:\\files\\somepic.gif";
$fd = fopen ($filename, "rb");
$contents = fread ($fd, filesize ($filename));
fclose ($fd);

Patrz także fwrite(), fopen(), fsockopen(), popen(), fgets(), fgetss(), fscanf(), file() i fpassthru().

fscanf

(PHP 4 )

fscanf -- Przetwarza dane z pliku według formatu

Opis

mixed fscanf ( int uchwyt, string format [, string war1])

Funkcja fscanf() jest podobna do sscanf(), ale pobiera dane wejściowe z pliku skojarzonego z uchwytem i interpretuje je zgodnie z podanych formatem. Jeśli tylko dwa parametry zostaną podane do funkcji, przetworzone wartości zostaną zwrócone w tablicy. W przeciwnym razie, jeśli opcjonalne parametry zostaną podane, funkcja zwróci numer przypisany do wartości. Opcjonalny parametr musi być podawany przez referencje.

Przykład 1. fscanf() Przykład

$fp = fopen ("users.txt","r");
while ($userinfo = fscanf ($fp, "%s\t%s\t%s\n")) {
    list ($name, $profession, $countrycode) = $userinfo;
    //... zrób coś z wartościami
}
fclose($fp);

Przykład 2. users.txt

javier  argonaut        pe
hiroshi sculptor        jp
robert  slacker us
luigi   florist it

Patrz także fread(), fgets(), fgetss(), sscanf(), printf() i sprintf().

fseek

(PHP 3, PHP 4 >= 4.0.0)

fseek -- Seeks on a file pointer

Description

int fseek ( int fp, int offset [, int whence])

Sets the file position indicator for the file referenced by fp.The new position, measured in bytes from the beginning of the file, is obtained by adding offset to the position specified by whence, whose values are defined as follows:

SEEK_SET - Set position equal to offset bytes.
SEEK_CUR - Set position to current location plus offset.
SEEK_END - Set position to end-of-file plus offset. (To move to a position before the end-of-file, you need to pass a negative value in offset.)

If whence is not specified, it is assumed to be SEEK_SET.

Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.

May not be used on file pointers returned by fopen() if they use the "http://" or "ftp://" formats.

Notatka: The whence argument was added after PHP 4.0 RC1.

See also ftell() and rewind().

fstat

(PHP 4 >= 4.0.0)

fstat --  Pobiera informacje o pliku używając otwartego wskaźnika pliku

Opis

array fstat ( int fp)

Zbiera statystyki otwartego pliku przez wskaźnik pliku fp. Ta funkcja jest podobna do funkcji stat() z wyjątkiem tego, że operuje na otwartym wskaźniku pliku zamiast na nazwię pliku.

Zwraca tablicę ze statystyką pliku z następującymi elementami:

  1. urządzenie

  2. i-węzeł

  3. liczba dowiązań

  4. identyfikator właściciela

  5. identyfikator grupy właściciela

  6. typ urządzenia (jeśli urządzenie inode)*

  7. rozmiar w bajtach

  8. czas ostatniego dostępu

  9. czas ostatniej modyfikacji

  10. czas ostatniej zmiany

  11. rozmiar bloku w systemie plików I/O *

  12. liczba przydzielonych bloków

* - poprawny tylko w systemach obsługujących type st_blksize -- inne systemy (np. Windows) zwracają -1

Wyniki tej funkcji są cachowane. Zobacz clearstatcache() aby uzyskać więcej szczegółów.

ftell

(PHP 3, PHP 4 >= 4.0.0)

ftell -- Tells file pointer read/write position

Description

int ftell ( int fp)

Returns the position of the file pointer referenced by fp; i.e., its offset into the file stream.

If an error occurs, returns FALSE.

The file pointer must be valid, and must point to a file successfully opened by fopen() or popen().

See also fopen(), popen(), fseek() and rewind().

ftruncate

(PHP 4 >= 4.0.0)

ftruncate --  Przycina plik do podanej długości.

Opis

int ftruncate ( int fp, int rozmiar)

Pobiera wskaźnik pliku, fp, i przycina plik do długości, rozmiar.

Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.

fwrite

(PHP 3, PHP 4 >= 4.0.0)

fwrite -- Binary-safe file write

Description

int fwrite ( int fp, string string [, int length])

fwrite() writes the contents of string to the file stream pointed to by fp. If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.

Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.

Notatka: On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.

See also fread(), fopen(), fsockopen(), popen(), and fputs().

set_file_buffer

(PHP 3>= 3.0.8, PHP 4 )

set_file_buffer --  Sets file buffering on the given file pointer

Description

int set_file_buffer ( int fp, int buffer)

Output using fwrite() is normally buffered at 8K. This means that if there are two processess wanting to write to the same output stream (a file), each is paused after 8K of data to allow the other to write. set_file_buffer() sets the buffering for write operations on the given filepointer fp to buffer bytes. If buffer is 0 then write operations are unbuffered. This ensures that all writes with fwrite() are completed before other processes are allowed to write to that output stream.

The function returns 0 on success, or EOF if the request cannot be honored.

The following example demonstrates how to use set_file_buffer() to create an unbuffered stream.

Przykład 1. set_file_buffer() example

$fp=fopen($file, "w");
if($fp){
  set_file_buffer($fp, 0);
  fputs($fp, $output);
  fclose($fp);
}

See also fopen(), fwrite().

is_dir

(PHP 3, PHP 4 >= 4.0.0)

is_dir -- Mówi czy nazwa_pliku jest katalogiem

Opis

bool is_dir ( string nazwa_pliku)

Zwraca TRUE jeśli nazwa_pliku istnieje i jest katalogiem.

Wyniki tej funkcji są cachowane. Zobacz clearstatcache() aby uzyskać więcej szczegółów.

Ta funkcja nie działa na zdalnych plikach; sprawdzany plik musi być dostępny przez system plików serwera.

Patrz także is_file() i is_link().

is_executable

(PHP 3, PHP 4 >= 4.0.0)

is_executable -- Mówi czy plik jest wykonywalny

Opis

bool is_executable ( string nazwa_pliku)

Zwraca TRUE jeśli plik istnieje i jest wykonywalny.

Wyniki tej funkcji są cachowane. Zobacz clearstatcache() aby uzyskać więcej szczegółów.

Ta funkcja nie działa na zdalnych plikach; sprawdzany plik musi być dostępny przez system plików serwera.

Patrz także is_file() i is_link().

is_file

(PHP 3, PHP 4 >= 4.0.0)

is_file --  Mówi czy nazwa_pliku jest zwykłym plikiem

Opis

bool is_file ( string nazwa_pliku)

Zwraca TRUE jesli nazwa_pliku istnieje i jest zwykłym plikiem.

Wyniki tej funkcji są cachowane. Zobacz clearstatcache() aby uzyskać więcej szczegółów.

Patrz także is_dir() i is_link().

is_link

(PHP 3, PHP 4 >= 4.0.0)

is_link --  Mówi czy nazwa_pliku jest dowiązaniem symbolicznym

Opis

bool is_link ( string nazwa_pliku)

Zwraca TRUE jeśli nazwa_pliku istnieje i jest dowiązaniem symbolicznym.

Wyniki tej funkcji są cachowane. Zobacz clearstatcache() aby uzyskać więcej szczegółów.

Patrz także is_dir(), is_file() i readlink().

Ta funkcja nie działa na zdalnych plikach; sprawdzany plik musi być dostępny przez system plików serwera.

Notatka: Ta funkcja nie jest dostępna na platformie Windows.

is_readable

(PHP 3, PHP 4 >= 4.0.0)

is_readable --  Tells whether the filename is readable

Description

bool is_readable ( string filename)

Returns TRUE if the filename exists and is readable.

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account.

The results of this function are cached. See clearstatcache() for more details.

This function will not work on remote files; the file to be examined must be accessible via the server's filesystem.

See also is_writable().

is_writable

(PHP 4 >= 4.0.0)

is_writable -- Tells whether the filename is writable

Description

bool is_writable ( string filename)

Returns TRUE if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writeable.

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account.

The results of this function are cached. See clearstatcache() for more details.

This function will not work on remote files; the file to be examined must be accessible via the server's filesystem.

See also is_readable().

is_writeable

(PHP 3, PHP 4 >= 4.0.0)

is_writeable -- Tells whether the filename is writable

Description

bool is_writeable ( string filename)

This is an alias for is_writable()

is_uploaded_file

(PHP 3>= 3.0.17, PHP 4 >= 4.0.3)

is_uploaded_file -- Mówi czy plik został przysłany przez HTTP POST.

Description

bool is_uploaded_file ( string nazwa_pliku)

Ta funkcja jest dostępna tylko w wersjach PHP 3 późniejszych od 3.0.16 i w wersjach PHP 4 późniejszych od 4.0.2.

Zwraca TRUE jeśli plik o nazwie nazwa_pliku został przysłany (upload) przez HTTP POST. To pomaga upewnić się, czy złośliwy użytkownik nie próbuje oszukać skryptu pracującego na plikach, tak aby działał on na plikach na których nie powinien -- na przykład /etc/passwd.

Ten rodzaj testów jest szczególnie ważny jeśli istnieje szansa, że cokolwiek robimy z przysłanymi plikami może zdradzić ich treść użytkownikowi lub nawet innym użytkownikom tego samego systemu.

Patrz także move_uploaded_file() i sekcję Handling file uploads aby zobaczyć przykładowe skrypty.

link

(PHP 3, PHP 4 >= 4.0.0)

link -- Create a hard link

Description

int link ( string target, string link)

link() creates a hard link.

See also the symlink() to create soft links, and readlink() along with linkinfo().

Notatka: Ta funkcja nie jest dostępna na platformie Windows.

linkinfo

(PHP 3, PHP 4 >= 4.0.0)

linkinfo -- Gets information about a link

Description

int linkinfo ( string path)

linkinfo() returns the st_dev field of the UNIX C stat structure returned by the lstat system call. This function is used to verify if a link (pointed to by path) really exists (using the same method as the S_ISLNK macro defined in stat.h). Returns 0 or FALSE in case of error.

See also symlink(), link(), and readlink().

Notatka: Ta funkcja nie jest dostępna na platformie Windows.

mkdir

(PHP 3, PHP 4 >= 4.0.0)

mkdir -- Makes directory

Description

int mkdir ( string pathname, int mode)

Attempts to create the directory specified by pathname.

Note that you probably want to specify the mode as an octal number, which means it should have a leading zero. The mode is also modified by the current umask, which you can change using umask().

mkdir ("/path/to/my/dir", 0700);

Returns TRUE on success and FALSE on failure.

See also rmdir().

move_uploaded_file

(PHP 4 >= 4.0.3)

move_uploaded_file -- Moves an uploaded file to a new location.

Description

bool move_uploaded_file ( string filename, string destination)

This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.

If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.

If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.

Notatka: Kiedy włączony jest tryb bezpieczny, PHP sprawdza, czy plik(i)/katalogi na których chcesz operować mają takie same UID jak skrypt, który jest aktualnie wykonywany.

Ostrze¿enie

If the destination file already exists, it will be overwritten.

See also is_uploaded_file(), and the section Handling file uploads for a simple usage example.

parse_ini_file

(PHP 4 >= 4.0.0)

parse_ini_file -- Parse a configuration file

Description

array parse_ini_file ( string filename [, bool process_sections])

parse_ini_file() loads in the ini file specified in filename, and returns the settings in it in an associative array. By setting the last process_sections parameter to TRUE, you get a multidimensional array, with the section names and settings included. The default for process_sections is FALSE

Notatka: This function has nothing to do with the php.ini file. It is already processed, the time you run your script. This function can be used to read in your own application's configuration files.

The structure of the ini file is similar to that of the php.ini's.

Przykład 1. Contents of sample.ini

; This is a sample configuration file
; Comments start with ';', as in php.ini

[first_section]
one = 1
five = 5

[second_section]
path = /usr/local/bin

Przykład 2. parse_ini_file() example

<?php

// Parse without sections
$ini_array = parse_ini_file("sample.ini");
print_r($ini_array);

// Parse with sections
$ini_array = parse_ini_file("sample.ini", TRUE);
print_r($ini_array);

?>

Would produce:

Array
(
    [one] => 1
    [five] => 5
    [path] => /usr/local/bin
)
Array
(
    [first_section] => Array
        (
            [one] => 1
            [five] => 5
        )

    [second_section] => Array
        (
            [path] => /usr/local/bin
        )

)

pathinfo

(PHP 4 >= 4.0.3)

pathinfo -- Returns information about a file path

Description

array pathinfo ( string path)

pathinfo() returns an associative array containing information about path. The following array elements are returned: dirname, basename and extension.

Przykład 1. pathinfo() Example

<?php

$path_parts = pathinfo("/www/htdocs/index.html");

echo $path_parts["dirname"] . "\n";
echo $path_parts["basename"] . "\n";
echo $path_parts["extension"] . "\n";

?>

Would produce:

/www/htdocs
index.html
html

See also dirname(), basename(), parse_url() and realpath().

pclose

(PHP 3, PHP 4 >= 4.0.0)

pclose -- Closes process file pointer

Description

int pclose ( int fp)

Closes a file pointer to a pipe opened by popen().

The file pointer must be valid, and must have been returned by a successful call to popen().

Returns the termination status of the process that was run.

See also popen().

popen

(PHP 3, PHP 4 >= 4.0.0)

popen -- Opens process file pointer

Description

int popen ( string command, string mode)

Opens a pipe to a process executed by forking the command given by command.

Returns a file pointer identical to that returned by fopen(), except that it is unidirectional (may only be used for reading or writing) and must be closed with pclose(). This pointer may be used with fgets(), fgetss(), and fputs().

If an error occurs, returns FALSE.

$fp = popen ("/bin/ls", "r");

See also pclose().

readfile

(PHP 3, PHP 4 >= 4.0.0)

readfile -- Outputs a file

Description

int readfile ( string filename [, int use_include_path])

Reads a file and writes it to standard output.

Returns the number of bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readfile, an error message is printed.

If filename begins with "http://" (not case sensitive), an HTTP 1.0 connection is opened to the specified server and the text of the response is written to standard output.

Versions prior to PHP 4.0.5 do not handle HTTP redirects. Because of this, directories must include trailing slashes.

If filename begins with "ftp://" (not case sensitive), an ftp connection to the specified server is opened and the requested file is written to standard output. If the server does not support passive mode ftp, this will fail.

If filename begins with neither of these strings, the file will be opened from the filesystem and its contents written to standard output.

You can use the optional second parameter and set it to "1", if you want to search for the file in the include_path, too.

See also fpassthru(), file(), fopen(), include(), require(), and virtual().

readlink

(PHP 3, PHP 4 >= 4.0.0)

readlink -- Returns the target of a symbolic link

Description

string readlink ( string path)

readlink() does the same as the readlink C function and returns the contents of the symbolic link path or 0 in case of error.

See also is_link(), symlink() and linkinfo().

Notatka: Ta funkcja nie jest dostępna na platformie Windows.

rename

(PHP 3, PHP 4 >= 4.0.0)

rename -- Renames a file

Description

int rename ( string oldname, string newname)

Attempts to rename oldname to newname.

Returns TRUE on success and FALSE on failure.

rewind

(PHP 3, PHP 4 >= 4.0.0)

rewind -- Rewind the position of a file pointer

Description

int rewind ( int fp)

Sets the file position indicator for fp to the beginning of the file stream.

If an error occurs, returns 0.

The file pointer must be valid, and must point to a file successfully opened by fopen().

Notatka: If you have opened the file in append ("a") mode, any data you write to the file will always be appended, regardless of the file position.

See also fseek() and ftell().

rmdir

(PHP 3, PHP 4 >= 4.0.0)

rmdir -- Removes directory

Description

int rmdir ( string dirname)

Attempts to remove the directory named by pathname. The directory must be empty, and the relevant permissions must permit. this.

If an error occurs, returns 0.

See also mkdir().

stat

(PHP 3, PHP 4 >= 4.0.0)

stat -- Gives information about a file

Description

array stat ( string filename)

Gathers the statistics of the file named by filename.

Returns an array with the statistics of the file with the following elements:

  1. device

  2. inode

  3. inode protection mode

  4. number of links

  5. user id of owner

  6. group id owner

  7. device type if inode device *

  8. size in bytes

  9. time of last access

  10. time of last modification

  11. time of last change

  12. blocksize for filesystem I/O *

  13. number of blocks allocated

* - only valid on systems supporting the st_blksize type--other systems (i.e. Windows) return -1.

Returns FALSE in case of error.

stat() doesn't handle URL as does fopen().

The results of this function are cached. See clearstatcache() for more details.

lstat

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

lstat --  Gives information about a file or symbolic link

Description

array lstat ( string filename)

Gathers the statistics of the file or symbolic link named by filename. This function is identical to the stat() function except that if the filename parameter is a symbolic link, the status of the symbolic link is returned, not the status of the file pointed to by the symbolic link.

Returns an array with the statistics of the file with the following elements:

  1. device

  2. inode

  3. inode protection mode

  4. number of links

  5. user id of owner

  6. group id owner

  7. device type if inode device *

  8. size in bytes

  9. time of last access

  10. time of last modification

  11. time of last change

  12. blocksize for filesystem I/O *

  13. number of blocks allocated

* - only valid on systems supporting the st_blksize type--other systems (i.e. Windows) return -1

The results of this function are cached. See clearstatcache() for more details.

realpath

(PHP 4 >= 4.0.0)

realpath -- Returns canonicalized absolute pathname

Description

string realpath ( string path)

realpath() expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the input path and return the canonicalized absolute pathname. The resulting path will have no symbolic link, '/./' or '/../' components.

Przykład 1. realpath() example

$real_path = realpath ("../../index.php");

symlink

(PHP 3, PHP 4 >= 4.0.0)

symlink -- Creates a symbolic link

Description

int symlink ( string target, string link)

symlink() creates a symbolic link from the existing target with the specified name link.

See also link() to create hard links, and readlink() along with linkinfo().

Notatka: Ta funkcja nie jest dostępna na platformie Windows.

tempnam

(PHP 3, PHP 4 >= 4.0.0)

tempnam -- Create file with unique file name

Description

string tempnam ( string dir, string prefix)

Creates a file with a unique filename in the specified directory. If the directory does not exist, tempnam() may generate a file in the system's temporary directory, and return the name of that.

Prior to PHP 4.0.6, the behaviour of the tempnam() function was system dependent. On Windows the TMP environment variable will override the dir parameter, on Linux the TMPDIR environment variable has precedence, while SVR4 will always use your dir parameter if the directory it points to exists. Consult your system documentation on the tempnam(3) function if in doubt.

Returns the new temporary filename, or the FALSE string on failure.

Przykład 1. tempnam() example

$tmpfname = tempnam ("/tmp", "FOO");

$fp = fopen($tmpfname, "w");
fwrite($fp, "writing to tempfile");
fclose($fp);

// do here something

unlink($tmpfname);

Notatka: This function's behavior changed in 4.0.3. The temporary file is also created to avoid a race condition where the file might appear in the filesystem between the time the string was generated and before the the script gets around to creating the file. Note, that you need to remove the file in case you need it no more, it is not done automatically.

See also tmpfile(), unlink().

tmpfile

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

tmpfile -- Tworzy plik tymczasowy

Opis

int tmpfile ( void)

Tworzy plik tymczasowy o unikalnej nazwie i otwiera go w trybie d zapisu, zwraca uchwyt pliku, podobnie jak fopen(). Plik jest automatycznie kasowany przy zamykaniu (po użyciu fclose()), lub gdy skrypt się zakończy.

Jeśli chcesz uzyskać więcej szczegółów, zajrzyj do dokumentacji twojego systemu dotyczącej funkcji tmpfile(3), albo do pliku nagłówkowego stdio.h.

Przykład 1. tmpfile() przykład

$temp = tmpfile();
fwrite($temp, "zapisywanie do pliku tymczasowego");
fclose($temp); // to kasuje plik

Patrz także tempnam().

touch

(PHP 3, PHP 4 >= 4.0.0)

touch -- Ustawia czas modyfikacji pliku

Opis

int touch ( string nazwa_pliku [, int czas])

Próbuje ustawić czas modyfikacji pliku o nazwie nazwa_pliku na wartość podaną przez czas. Jeśli opcja czas nie jest podana, używa czasu bieżącego.

Jeśli plik nie istnieje, to zostanie utworzony.

Zwraca TRUE gdy sukces i FALSE w przeciwnym wypadku.

Przykład 1. touch() przykład

if (touch ($FileName)) {
    print "$FileName czas modyfikacji został
           zmieniony na obecną date i czas";
} else {
    print "Przykro mi ale Nie Mogę zmienić czasu modyfikacji pliku $FileName";
}

umask

(PHP 3, PHP 4 >= 4.0.0)

umask -- Changes the current umask

Description

int umask ( int mask)

umask() sets PHP's umask to mask & 0777 and returns the old umask. When PHP is being used as a server module, the umask is restored when each request is finished.

umask() without arguments simply returns the current umask.

Notatka: Ta funkcja nie jest dostępna na platformie Windows.

unlink

(PHP 3, PHP 4 >= 4.0.0)

unlink -- Kasowanie pliku

Opis

int unlink ( string nazwa_pliku)

Kasuje nazwa_pliku. Podobnie do funkcji unlink() z Unix'owego C.

Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.

Patrz także rmdir() do kasowania katalogów.

XXXI. Forms Data Format functions

Forms Data Format (FDF) is a format for handling forms within PDF documents. You should read the documentation at http://partners.adobe.com/asn/developer/acrosdk/forms.html for more information on what FDF is and how it is used in general.

Notatka: If you run into problems configuring php with fdftk support, check whether the header file FdfTk.h and the library libFdfTk.so are at the right place. They should be in fdftk-dir/include and fdftk-dir/lib. This will not be the case if you just unpack the FdfTk distribution.

The general idea of FDF is similar to HTML forms. The difference is basically the format how data is transmitted to the server when the submit button is pressed (this is actually the Form Data Format) and the format of the form itself (which is the Portable Document Format, PDF). Processing the FDF data is one of the features provided by the fdf functions. But there is more. One may as well take an existing PDF form and populated the input fields with data without modifying the form itself. In such a case one would create a FDF document (fdf_create()) set the values of each input field (fdf_set_value()) and associate it with a PDF form (fdf_set_file()). Finally it has to be sent to the browser with MimeType application/vnd.fdf. The Acrobat reader plugin of your browser recognizes the MimeType, reads the associated PDF form and fills in the data from the FDF document.

If you look at an FDF-document with a text editor you will find a catalogue object with the name FDF. Such an object may contain a number of entries like Fields, F, Status etc.. The most commonly used entries are Fields which points to a list of input fields, and F which contains the filename of the PDF-document this data belongs to. Those entries are referred to in the FDF documentation as /F-Key or /Status-Key. Modifying this entries is done by functions like fdf_set_file() and fdf_set_status(). Fields are modified with fdf_set_value(), fdf_set_opt() etc..

The following examples shows just the evaluation of form data.

Przykład 1. Evaluating a FDF document

<?php
// Save the FDF data into a temp file
$fdffp = fopen("test.fdf", "w");
fwrite($fdffp, $HTTP_FDF_DATA, strlen($HTTP_FDF_DATA));
fclose($fdffp);

// Open temp file and evaluate data
// The pdf form contained several input text fields with the names
// volume, date, comment, publisher, preparer, and two checkboxes
// show_publisher and show_preparer.
$fdf = fdf_open("test.fdf");
$volume = fdf_get_value($fdf, "volume");
echo "The volume field has the value '<B>$volume</B>'<BR>";

$date = fdf_get_value($fdf, "date");
echo "The date field has the value '<B>$date</B>'<BR>";

$comment = fdf_get_value($fdf, "comment");
echo "The comment field has the value '<B>$comment</B>'<BR>";

if(fdf_get_value($fdf, "show_publisher") == "On") {
  $publisher = fdf_get_value($fdf, "publisher");
  echo "The publisher field has the value '<B>$publisher</B>'<BR>";
} else
  echo "Publisher shall not be shown.<BR>";

if(fdf_get_value($fdf, "show_preparer") == "On") {
  $preparer = fdf_get_value($fdf, "preparer");
  echo "The preparer field has the value '<B>$preparer</B>'<BR>";
} else
  echo "Preparer shall not be shown.<BR>";
fdf_close($fdf);
?>
Spis treści
fdf_open -- Open a FDF document
fdf_close -- Close an FDF document
fdf_create -- Create a new FDF document
fdf_save -- Save a FDF document
fdf_get_value -- Get the value of a field
fdf_set_value -- Set the value of a field
fdf_next_field_name -- Get the next field name
fdf_set_ap -- Set the appearance of a field
fdf_set_status -- Set the value of the /STATUS key
fdf_get_status -- Get the value of the /STATUS key
fdf_set_file -- Set the value of the /F key
fdf_get_file -- Get the value of the /F key
fdf_set_flags -- Sets a flag of a field
fdf_set_opt -- Sets an option of a field
fdf_set_submit_form_action -- Sets a submit form action of a field
fdf_set_javascript_action -- Sets an javascript action of a field
fdf_set_encoding -- Sets FDF character encoding
fdf_add_template -- Adds a template into the FDF document

fdf_open

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

fdf_open -- Open a FDF document

Description

int fdf_open ( string filename)

The fdf_open() function opens a file with form data. This file must contain the data as returned from a PDF form. Currently, the file has to be created 'manually' by using fopen() and writing the content of HTTP_FDF_DATA with fwrite() into it. A mechanism like for HTML form data where for each input field a variable is created does not exist.

Przykład 1. Accessing the form data

<?php
// Save the FDF data into a temp file
$fdffp = fopen("test.fdf", "w");
fwrite($fdffp, $HTTP_FDF_DATA, strlen($HTTP_FDF_DATA));
fclose($fdffp);

// Open temp file and evaluate data
$fdf = fdf_open("test.fdf");
...
fdf_close($fdf);
?>

See also fdf_close().

fdf_close

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

fdf_close -- Close an FDF document

Description

bool fdf_close ( int fdf_document)

The fdf_close() function closes the FDF document.

See also fdf_open().

fdf_create

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

fdf_create -- Create a new FDF document

Description

int fdf_create ( void)

The fdf_create() creates a new FDF document. This function is needed if one would like to populate input fields in a PDF document with data.

Przykład 1. Populating a PDF document

<?php
$outfdf = fdf_create();
fdf_set_value($outfdf, "volume", $volume, 0);

fdf_set_file($outfdf, "http:/testfdf/resultlabel.pdf");
fdf_save($outfdf, "outtest.fdf");
fdf_close($outfdf);
Header("Content-type: application/vnd.fdf");
$fp = fopen("outtest.fdf", "r");
fpassthru($fp);
unlink("outtest.fdf");
?>

See also fdf_close(), fdf_save(), fdf_open().

fdf_save

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

fdf_save -- Save a FDF document

Description

int fdf_save ( string filename)

The fdf_save() function saves a FDF document. The FDF Toolkit provides a way to output the document to stdout if the parameter filename is '.'. This does not work if PHP is used as an apache module. In such a case one will have to write to a file and use e.g. fpassthru() to output it.

See also fdf_close() and example for fdf_create().

fdf_get_value

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

fdf_get_value -- Get the value of a field

Description

string fdf_get_value ( int fdf_document, string fieldname)

The fdf_get_value() function returns the value of a field.

See also fdf_set_value().

fdf_set_value

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

fdf_set_value -- Set the value of a field

Description

bool fdf_set_value ( int fdf_document, string fieldname, string value, int isName)

The fdf_set_value() function sets the value of a field. The last parameter determines if the field value is to be converted to a PDF Name (isName = 1) or set to a PDF String (isName = 0).

See also fdf_get_value().

fdf_next_field_name

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

fdf_next_field_name -- Get the next field name

Description

string fdf_next_field_name ( int fdf_document [, string fieldname])

The fdf_next_field_name() function returns the name of the field after the field in fieldname or the field name of the first field if the second parameter is NULL.

See also fdf_set_value(), fdf_get_value().

fdf_set_ap

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

fdf_set_ap -- Set the appearance of a field

Description

bool fdf_set_ap ( int fdf_document, string field_name, int face, string filename, int page_number)

The fdf_set_ap() function sets the appearance of a field (i.e. the value of the /AP key). The possible values of face are 1=FDFNormalAP, 2=FDFRolloverAP, 3=FDFDownAP.

fdf_set_status

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

fdf_set_status -- Set the value of the /STATUS key

Description

bool fdf_set_status ( int fdf_document, string status)

The fdf_set_status() sets the value of the /STATUS key.

See also fdf_get_status().

fdf_get_status

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

fdf_get_status -- Get the value of the /STATUS key

Description

string fdf_get_status ( int fdf_document)

The fdf_get_status() returns the value of the /STATUS key.

See also fdf_set_status().

fdf_set_file

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

fdf_set_file -- Set the value of the /F key

Description

bool fdf_set_file ( int fdf_document, string filename)

The fdf_set_file() sets the value of the /F key. The /F key is just a reference to a PDF form which is to be populated with data. In a web environment it is a URL (e.g. http:/testfdf/resultlabel.pdf).

See also fdf_get_file() and example for fdf_create().

fdf_get_file

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

fdf_get_file -- Get the value of the /F key

Description

string fdf_get_file ( int fdf_document)

The fdf_set_file() returns the value of the /F key.

See also fdf_set_file().

fdf_set_flags

(PHP 4 >= 4.0.2)

fdf_set_flags -- Sets a flag of a field

Description

bool fdf_set_flags ( int fdf_document, string fieldname, int whichFlags, int newFlags)

The fdf_set_flags() sets certain flags of the given field fieldname.

See also fdf_set_opt().

fdf_set_opt

(PHP 4 >= 4.0.2)

fdf_set_opt -- Sets an option of a field

Description

bool fdf_set_opt ( int fdf_document, string fieldname, int element, string str1, string str2)

The fdf_set_opt() sets options of the given field fieldname.

See also fdf_set_flags().

fdf_set_submit_form_action

(PHP 4 >= 4.0.2)

fdf_set_submit_form_action -- Sets a submit form action of a field

Description

bool fdf_set_submit_form_action ( int fdf_document, string fieldname, int trigger, string script, int flags)

The fdf_set_submit_form_action() sets a submit form action for the given field fieldname.

See also fdf_set_javascript_action().

fdf_set_javascript_action

(PHP 4 >= 4.0.2)

fdf_set_javascript_action -- Sets an javascript action of a field

Description

bool fdf_set_javascript_action ( int fdf_document, string fieldname, int trigger, string script)

fdf_set_javascript_action() sets a javascript action for the given field fieldname.

See also fdf_set_submit_form_action().

fdf_set_encoding

(PHP 4 >= 4.1.0)

fdf_set_encoding -- Sets FDF character encoding

Description

bool fdf_set_encoding ( int fdf_document, string encoding)

fdf_set_encoding() sets the character encoding in FDF document fdf_document. encoding should be the valid encoding name. The valid encoding name in Acrobat 5.0 are "Shift-JIS", "UHC", "GBK","BigFive".

The fdf_set_encoding() is available in PHP 4.1.0 or later.

fdf_add_template

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

fdf_add_template -- Adds a template into the FDF document

Description

bool fdf_add_template ( int fdfdoc, int newpage, string filename, string template, int rename)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

XXXII. FriBiDi functions

Spis treści
fribidi_log2vis -- Convert a logical string to a visual one

fribidi_log2vis

(PHP 4 >= 4.0.4)

fribidi_log2vis -- Convert a logical string to a visual one

Description

string fribidi_log2vis ( string str, string direction, int charset)

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

XXXIII. FTP

Funkcje z tego rozszerzenia implementują kliencki dostęp do plików serwera rozpoznającego File Transfer Protocol FTP opisanego w http://www.faqs.org/rfcs/rfc959.html.

Poniższe stałe są zdefiniowane podczas pracy z modułem FTP: FTP_ASCII i FTP_BINARY.

Aby móc skorzystać z funkcji FTP, powinno się dodać opcję --enable-ftp przy instalacji PHP 4 lub --with-ftp używając PHP 3.

Przykład 1. Przykład ftp()

<?php
// ustaw podstawowe połączenie
$conn_id = ftp_connect("$ftp_server"); 

// zaloguj się nazwą użytkownika i hasłem
$login_result = ftp_login($conn_id, "$ftp_user_name", "$ftp_user_pass"); 

// sprawdź połączenie
if ((!$conn_id) || (!$login_result)) { 
        echo "Połączenie FTP się nie powiodło!";
        echo "Próbowano połączyć się do $ftp_server jako użytkownik";
           . $ftp_user_name;
        die; 
    } else {
        echo "Połączony z $ftp_server jako użytkownik $ftp_user_name";
    }

// prześlij plik
$upload = ftp_put($conn_id, "$plik_docelowy", "$plik_zrodlowy", FTP_BINARY); 

// sprawdź stan operacji
if (!$upload) { 
        echo "Ftp upload has failed!";
    } else {
        echo "Przesłano $plik_zrodlowy na $ftp_server jako $plik_docelowy";
    }

// zamknij strumień FTP
ftp_quit($conn_id); 
?>

Spis treści
ftp_connect -- Otwiera połączenie FTP
ftp_login -- Loguje się w połączeniu FTP
ftp_pwd -- Zwraca nazwę bieżącego katalogu
ftp_cdup -- Zmienia bieżący katalog na nadrzędny
ftp_chdir -- Zmienia katalog na serwerze FTP
ftp_mkdir -- Tworzy katalog
ftp_rmdir -- Usuwa katalog
ftp_nlist -- Zwraca listę plików w podanym katalogu.
ftp_rawlist --  Zwraca szczegółową listę plików w podanym katalogu.
ftp_systype --  Zwraca identyfikator systemu dla zdalnego serwera FTP.
ftp_pasv -- Włącza/wyłącza tryb pasywny.
ftp_get -- Pobiera plik z serwera FTP.
ftp_fget --  Pobiera plik z serwera FTP i zapisuje go do otwartego pliku.
ftp_put -- Umieszcza plik na serwerze FTP.
ftp_fput -- Umieszcza dane z otwartego pliku na serwerze FTP.
ftp_size -- Zwraca rozmiar podanego pliku.
ftp_mdtm -- Zwraca czas ostaniej modyfikacji podanego pliku.
ftp_rename -- Zmienia nazwę pliku na serwerze FTP.
ftp_delete -- Usuwa plik z serwera FTP.
ftp_site -- Wysyła serwerowi polecenie SITE.
ftp_quit -- Zamyka połączenie FTP

ftp_connect

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ftp_connect -- Otwiera połączenie FTP

Opis

int ftp_connect ( string host [, int port])

Zwraca strumień FTP w przypadku sukcesu, lub wartość FALSE w przypadku porażki.

ftp_connect() otwiera połączenie z hostem podanym w parametrze host. Paremetr port określa alternatywny port połączenia. Jeśli jest on pominięty lub równy zero, użyty będzie domyślny port FTP, czyli 21.

ftp_login

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ftp_login -- Loguje się w połączeniu FTP

Opis

int ftp_login ( int strumien_ftp, string nazwa_uzytkownika, string haslo)

Loguje się do podanego strumienia FTP.

Zwraca wartość TRUE w przypadku sukcesu lub FALSE w przypadku napotkania błędu.

ftp_pwd

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ftp_pwd -- Zwraca nazwę bieżącego katalogu

Opis

string ftp_pwd ( int strumien_ftp)

Zwraca nazwę bieżącego katalogu lub FALSE w przypadku napotkania błędu.

ftp_cdup

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ftp_cdup -- Zmienia bieżący katalog na nadrzędny

Opis

int ftp_cdup ( int strumien_ftp)

Zmienia bieżący katalog na nadrzędny.

Zwraca wartość TRUE w przypadku sukcesu lub FALSE w przypadku napotkania błędu.

ftp_chdir

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ftp_chdir -- Zmienia katalog na serwerze FTP

Opis

int ftp_chdir ( int strumien_ftp, string katalog)

Zmienia bieżący katalog na ten określony w parametrze katalog.

Zwraca wartość TRUE w przypadku sukcesu lub FALSE w przypadku napotkania błędu.

ftp_mkdir

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ftp_mkdir -- Tworzy katalog

Opis

string ftp_mkdir ( int strumien_ftp, string katalog)

Tworzy podany katalog.

W przypadku sukcesu zwraca nazwę nowo utworzonego katalogu, lub wartość FALSE w przypadku napotkania błędu.

ftp_rmdir

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ftp_rmdir -- Usuwa katalog

Opis

int ftp_rmdir ( int strumien_ftp, string katalog)

Tworzy podany katalog.

Zwraca wartość TRUE w przypadku sukcesu lub FALSE w przypadku napotkania błędu.

ftp_nlist

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ftp_nlist -- Zwraca listę plików w podanym katalogu.

Opis

array ftp_nlist ( int strumien_ftp, string katalog)

W przypadku sukcesu zwracana jest tablica z nazwami plików lub wartość FALSE w przypadku napotkania błędu.

ftp_rawlist

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ftp_rawlist --  Zwraca szczegółową listę plików w podanym katalogu.

Opis

array ftp_rawlist ( int strumien_ftp, string katalog)

ftp_rawlist() wykonuje polecenie FTP LIST i zwraca wynik tego polecenia jako tablicę. Każdy element odpowiada jednej linii tekstu. Wyjście nie jest parsowane w jakikolwiek sposób. Identyfikator systemu, zwracany przez ftp_systype(), może być użyty do interpretacji wyników.

ftp_systype

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ftp_systype --  Zwraca identyfikator systemu dla zdalnego serwera FTP.

Opis

string ftp_systype ( int strumien_ftp)

Zwraca typ zdalnego systemu lub FALSE w przypadku napotkania błędu.

ftp_pasv

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ftp_pasv -- Włącza/wyłącza tryb pasywny.

Opis

int ftp_pasv ( int strumien_ftp, int pasywny)

ftp_pasv() włącza tryb pasywny jeśli parametr pasywny ma wartość TRUE (wyłącza tryb pasywyny jeśli parametr pasywny ma wartość FALSE.) W trybie pasywnym, połączenia danych są inicjowane przez klienta a nie przez serwer.

Zwraca wartość TRUE w przypadku sukcesu lub FALSE w przypadku napotkania błędu.

ftp_get

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ftp_get -- Pobiera plik z serwera FTP.

Opis

int ftp_get ( int strumien_ftp, string plik_lokalny, string plik_zdalny, int tryb)

ftp_get() pobiera plik_zdalny z serwera FTP i zapisuje go lokalnie jako plik_lokalny . tryb połączenia musi być podany jako FTP_ASCII lub FTP_BINARY.

Zwraca wartość TRUE w przypadku sukcesu lub FALSE w przypadku napotkania błędu.

ftp_fget

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ftp_fget --  Pobiera plik z serwera FTP i zapisuje go do otwartego pliku.

Opis

int ftp_fget ( int strumien_ftp, int fp, string plik_zdalny, int tryb)

ftp_fget() pobiera plik_zdalny z serwera FTP i zapisuje go do podanego wskaźnika, fp. tryb musi być podany jako FTP_ASCII lub FTP_BINARY.

Zwraca wartość TRUE w przypadku sukcesu lub FALSE w przypadku napotkania błędu.

ftp_put

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ftp_put -- Umieszcza plik na serwerze FTP.

Opis

int ftp_put ( int strumien_ftp, string plik_zdalny, string plik_lokalny, int tryb)

ftp_put() umieszcza plik_lokalny na serwerze jako plik_zdalny. tryb połączenia musi być określony jako FTP_ASCII lub FTP_BINARY.

Zwraca wartość TRUE w przypadku sukcesu lub FALSE w przypadku napotkania błędu.

Przykład 1. Przykład ftp_put()

$upload = ftp_put ($conn_id, "$plik_docelowy", "$plik_zrodlowy", FTP_ASCII);

ftp_fput

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ftp_fput -- Umieszcza dane z otwartego pliku na serwerze FTP.

Opis

int ftp_fput ( int strumien_ftp, string plik_zdalny, int fp, int tryb)

ftp_fput() umieszcza na serwerze dane pobrane ze wskaźnika fp do końca pliku. tryb połączenia musi być określony jako FTP_ASCII lub FTP_BINARY

Zwraca wartość TRUE w przypadku sukcesu lub FALSE w przypadku napotkania błędu.

ftp_size

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ftp_size -- Zwraca rozmiar podanego pliku.

Opis

int ftp_size ( int strumien_ftp, string plik_zdalny)

ftp_size() zwraca rozmiar zdalnego pliku. Jeśli napotkany zostanie błąd lub plik nie istnieje, zwracana jest wartość -1. Nie wszystkie serwery obsługują tą opcję.

W przypadku sukcesu zwraca rozmiar podanego pliku lub -1 w przypadku napotkania błędu.

ftp_mdtm

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ftp_mdtm -- Zwraca czas ostaniej modyfikacji podanego pliku.

Opis

int ftp_mdtm ( int strumien_ftp, string plik_zdalny)

ftp_mdtm() sprawdza czas ostatniej modyfikacji podanego pliku i zwraca to jako UNIX timestamp (ilość sekund od 1.1.1970). Jeśli napotkany zostanie błąd lub plik nie istnieje, zwracana jest wartość -1. Zauważ, że nie wszystkie serwery obsługują tą opcję.

W przypadku sukcesu zwraca UNIX timestamp lub -1 w przypadku napotkania błędu.

Notatka: ftp_mdtm() nie działa dla katalogów.

ftp_rename

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ftp_rename -- Zmienia nazwę pliku na serwerze FTP.

Opis

boolean ftp_rename ( resource strumien_ftp, string z, string na)

ftp_rename() zmienia nazwę pliku lub katalogu o aktualnej nazwie z na nową nazwę na, na strumieniu FTP strumien_ftp.

Zwraca wartość TRUE w przypadku sukcesu lub FALSE w przypadku napotkania błędu.

ftp_delete

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ftp_delete -- Usuwa plik z serwera FTP.

Opis

int ftp_delete ( int strumien_ftp, string sciezka)

ftp_delete() usuwa plik określony przez parametr ściezka z serwera FTP.

Zwraca wartość TRUE w przypadku sukcesu lub FALSE w przypadku napotkania błędu.

ftp_site

(PHP 3>= 3.0.15, PHP 4 >= 4.0.0)

ftp_site -- Wysyła serwerowi polecenie SITE.

Opis

int ftp_site ( int strumien_ftp, string cmd)

ftp_site() wysyła do serwera FTP komendę określoną przez parametr cmd. Komendy SITE nie są ustandaryzowane i mogą się różnić między serwerami. Są one przydatne przy obsłudze takich rzeczy jak prawa dostępu do plików i członkostwo w grupach.

Zwraca wartość TRUE w przypadku sukcesu lub FALSE w przypadku napotkania błędu.

ftp_quit

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ftp_quit -- Zamyka połączenie FTP

Opis

int ftp_quit ( int strumien_ftp)

ftp_quit() zamyka strumien_ftp.

XXXIV. Function Handling functions

These functions all handle various operations involved in working with functions.

Spis treści
call_user_func_array --  Call a user function given with an array of parameters
call_user_func --  Call a user function given by the first parameter
create_function -- Create an anonymous (lambda-style) function
func_get_arg -- Return an item from the argument list
func_get_args --  Returns an array comprising a function's argument list
func_num_args --  Returns the number of arguments passed to the function
function_exists --  Return TRUE if the given function has been defined
get_defined_functions --  Returns an array of all defined functions
register_shutdown_function --  Register a function for execution on shutdown
register_tick_function --  Register a function for execution on each tick
unregister_tick_function --  De-register a function for execution on each tick

call_user_func_array

(PHP 4 >= 4.0.4)

call_user_func_array --  Call a user function given with an array of parameters

Description

mixed call_user_func_array ( string function_name [, array paramarr])

Call a user defined function given by function_name, with the parameters in paramarr. For example:

function debug($var, $val)
    echo "***DEBUGGING\nVARIABLE: $var\nVALUE:";
    if (is_array($val) || is_object($val) || is_resource($val))
        print_r($val);
    else
        echo "\n$val\n";
    echo "***\n";
}

$c = mysql_connect();
$host = $HTTP_SERVER_VARS["SERVER_NAME"];

call_user_func_array ('debug', array("host", $host));
call_user_func_array ('debug', array("c", $c));
call_user_func_array ('debug', array("HTTP_POST_VARS", $HTTP_POST_VARS));

See also: call_user_func(), call_user_method(), call_user_method_array().

Notatka: This function was added to the CVS code after release of PHP 4.0.4pl1

call_user_func

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

call_user_func --  Call a user function given by the first parameter

Description

mixed call_user_func ( string function_name [, mixed parameter [, mixed ...]])

Call a user defined function given by the function_name parameter. Take the following:

function barber ($type) {
    print "You wanted a $type haircut, no problem";
}
call_user_func ('barber', "mushroom");
call_user_func ('barber', "shave");

See also: call_user_func_array(), call_user_method(), call_user_method_array().

create_function

(PHP 4 )

create_function -- Create an anonymous (lambda-style) function

Description

string create_function ( string args, string code)

Creates an anonymous function from the parameters passed, and returns a unique name for it. Usually the args will be passed as a single quote delimited string, and this is also recommended for the code. 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. \$avar.

You can use this function, to (for example) create a function from information gathered at run time:

Przykład 1. Creating an anonymous function with create_function()

$newfunc = create_function('$a,$b','return "ln($a) + ln($b) = ".log($a * $b);');
echo "New anonymous function: $newfunc\n";
echo $newfunc(2,M_E)."\n";
// outputs
// New anonymous function: lambda_1
// ln(2) + ln(2.718281828459) = 1.6931471805599
Or, perhaps to have general handler function that can apply a set of operations to a list of parameters:

Przykład 2. Making a general processing function with create_function()

function process($var1, $var2, $farr) {
    for ($f=0; $f < count($farr); $f++)
    echo $farr[$f]($var1,$var2)."\n";
}

// create a bunch of math functions
$f1 = 'if ($a >=0) {return "b*a^2 = ".$b*sqrt($a);} else {return false;}';
$f2 = "return \"min(b^2+a, a^2,b) = \".min(\$a*\$a+\$b,\$b*\$b+\$a);";
$f3 = 'if ($a > 0 && $b != 0) {return "ln(a)/b = ".log($a)/$b; } else { return false; }';
$farr = array(
    create_function('$x,$y', 'return "some trig: ".(sin($x) + $x*cos($y));'),
    create_function('$x,$y', 'return "a hypotenuse: ".sqrt($x*$x + $y*$y);'),
    create_function('$a,$b', $f1),
    create_function('$a,$b', $f2),
    create_function('$a,$b', $f3)
    );

echo "\nUsing the first array of anonymous functions\n";
echo "parameters: 2.3445, M_PI\n";
process(2.3445, M_PI, $farr);

// now make a bunch of string processing functions
$garr = array(
    create_function('$b,$a','if (strncmp($a,$b,3) == 0) return "** \"$a\" '.
    'and \"$b\"\n** Look the same to me! (looking at the first 3 chars)";'),
    create_function('$a,$b','; return "CRCs: ".crc32($a)." , ".crc32(b);'),
    create_function('$a,$b','; return "similar(a,b) = ".similar_text($a,$b,&$p)."($p%)";')
    );
echo "\nUsing the second array of anonymous functions\n";
process("Twas brilling and the slithy toves", "Twas the night", $garr);
and when you run the code above, the output will be:

Using the first array of anonymous functions
parameters: 2.3445, M_PI
some trig: -1.6291725057799
a hypotenuse: 3.9199852871011
b*a^2 = 4.8103313314525
min(b^2+a, a^2,b) = 8.6382729035898
ln(a/b) = 0.27122299212594

Using the second array of anonymous functions
** "Twas the night" and "Twas brilling and the slithy toves"
** Look the same to me! (looking at the first 3 chars)
CRCs: -725381282 , 1908338681
similar(a,b) = 11(45.833333333333%)

But perhaps the most common use for of lambda-style (anonymous) functions is to create callback functions, for example when using array_walk() or usort()

Przykład 3. Using anonymous functions as callback functions

$av = array("the ","a ","that ","this ");
array_walk($av, create_function('&$v,$k','$v = $v."mango";'));
print_r($av);  // for PHP 3 use var_dump()
// outputs:
// Array
// (
//   [0] => the mango
//   [1] => a mango
//   [2] => that mango
//   [3] => this mango
// )

// an array of strings ordered from shorter to longer
$sv = array("small","larger","a big string","it is a string thing");
print_r($sv);
// outputs:
// Array
// (
//   [0] => small
//   [1] => larger
//   [2] => a big string
//   [3] => it is a string thing
// )

// sort it from longer to shorter
usort($sv, create_function('$a,$b','return strlen($b) - strlen($a);'));
print_r($sv);
// outputs:
// Array
// (
//   [0] => it is a string thing
//   [1] => a big string
//   [2] => larger
//   [3] => small
// )

func_get_arg

(PHP 4 >= 4.0.0)

func_get_arg -- Return an item from the argument list

Description

mixed func_get_arg ( int arg_num)

Returns the argument which is at the arg_num'th offset into a user-defined function's argument list. Function arguments are counted starting from zero. func_get_arg() will generate a warning if called from outside of a function definition.

If arg_num is greater than the number of arguments actually passed, a warning will be generated and func_get_arg() will return FALSE.

<?php
function foo() {
     $numargs = func_num_args();
     echo "Number of arguments: $numargs<br>\n";
     if ($numargs >= 2) {
     echo "Second argument is: " . func_get_arg (1) . "<br>\n";
     }
} 

foo (1, 2, 3);
?>

func_get_arg() may be used in conjunction with func_num_args() and func_get_args() to allow user-defined functions to accept variable-length argument lists.

Notatka: This function was added in PHP 4.

func_get_args

(PHP 4 >= 4.0.0)

func_get_args --  Returns an array comprising a function's argument list

Description

array func_get_args ( void)

Returns an array in which each element is the corresponding member of the current user-defined function's argument list. func_get_args() will generate a warning if called from outside of a function definition.

<?php
function foo() {
    $numargs = func_num_args();
    echo "Number of arguments: $numargs<br>\n";
    if ($numargs >= 2) {
    echo "Second argument is: " . func_get_arg (1) . "<br>\n";
    }
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
    echo "Argument $i is: " . $arg_list[$i] . "<br>\n";
    }
} 

foo (1, 2, 3);
?>

func_get_args() may be used in conjunction with func_num_args() and func_get_arg() to allow user-defined functions to accept variable-length argument lists.

Notatka: This function was added in PHP 4.

func_num_args

(PHP 4 >= 4.0.0)

func_num_args --  Returns the number of arguments passed to the function

Description

int func_num_args ( void)

Returns the number of arguments passed into the current user-defined function. func_num_args() will generate a warning if called from outside of a user-defined function.

<?php
function foo() {
    $numargs = func_num_args();
    echo "Number of arguments: $numargs\n";
} 

foo (1, 2, 3);    // Prints 'Number of arguments: 3'
?>

func_num_args() may be used in conjunction with func_get_arg() and func_get_args() to allow user-defined functions to accept variable-length argument lists.

function_exists

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

function_exists --  Return TRUE if the given function has been defined

Description

bool function_exists ( string function_name)

Checks the list of defined functions for function_name. Returns TRUE if the given function name was found, FALSE otherwise.

if (function_exists('imap_open')) {
    echo "IMAP functions are available.<br>\n";
} else {
    echo "IMAP functions are not available.<br>\n";
}

Note that a function name may exist, even if the function itself is unusable due to configuration or compiling options.

See also method_exists().

get_defined_functions

(PHP 4 >= 4.0.4)

get_defined_functions --  Returns an array of all defined functions

Description

array get_defined_functions ( void)

This function returns an multidimensional array containing a list of all defined functions, both built-in (internal) and user-defined. The internal functions will be accessible via $arr["internal"], and the user defined ones using $arr["user"] (see example below).

function myrow($id, $data) {
    return "<tr><th>$id</th><td>$data</td></tr>\n";
}

$arr = get_defined_functions();

print_r($arr);

Will output something along the lines of:

Array
(
    [internal] => Array
        (
            [0] => zend_version
            [1] => func_num_args
            [2] => func_get_arg
            [3] => func_get_args
            [4] => strlen
            [5] => strcmp
            [6] => strncmp
            ...
            [750] => bcscale
            [751] => bccomp
        )

    [user] => Array
        (
            [0] => myrow
        )

)

See also get_defined_vars().

register_shutdown_function

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

register_shutdown_function --  Register a function for execution on shutdown

Description

int register_shutdown_function ( string func)

Registers the function named by func to be executed when script processing is complete.

Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered. If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called.

The registered shutdown functions are called after the request has been completed (including sending any output buffers), so it is not possible to send output to the browser using echo() or print(), or retrieve the contents of any output buffers using ob_get_contents().

Notatka: Zamiast nazwy funkcji może zostać przekazana

register_tick_function

(PHP 4 >= 4.0.3)

register_tick_function --  Register a function for execution on each tick

Description

void register_tick_function ( string func [, mixed arg])

Registers the function named by func to be executed when a tick is called.

unregister_tick_function

(PHP 4 >= 4.0.3)

unregister_tick_function --  De-register a function for execution on each tick

Description

void unregister_tick_function ( string func [, mixed arg])

De-registers the function named by func so it is no longer executed when a tick is called.

XXXV. Gettext

The gettext functions implement a NLS (Native Language Support) API which can be used to internationalize your PHP applications. Please see the gettext documentation from your system for a thorough explanation of these functions.

Spis treści
bindtextdomain -- Sets the path for a domain
bind_textdomain_codeset --  Specify the character encoding in which the messages from the DOMAIN message catalog will be re turned
dcgettext -- Overrides the domain for a single lookup
dcngettext -- Plural version of dcgettext() Plural version of dcgettext
dgettext -- Override the current domain
dngettext -- Plural version of dcgettext() Plural version of dgettext
gettext -- Lookup a message in the current domain
ngettext -- Plural version of gettext
textdomain -- Sets the default domain

bindtextdomain

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

bindtextdomain -- Sets the path for a domain

Description

string bindtextdomain ( string domain, string directory)

The bindtextdomain() function sets the path for a domain.

bind_textdomain_codeset

(PHP 4 CVS only)

bind_textdomain_codeset --  Specify the character encoding in which the messages from the DOMAIN message catalog will be re turned

Description

string bind_textdomain_codeset ( string domain, string codeset)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

dcgettext

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

dcgettext -- Overrides the domain for a single lookup

Description

string dcgettext ( string domain, string message, int category)

This function allows you to override the current domain for a single message lookup. It also allows you to specify a category.

dcngettext

(PHP 4 CVS only)

dcngettext -- Plural version of dcgettext() Plural version of dcgettext

Description

string dcngettext ( string domain, string msgid1, string msgid2, int n, int category)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

dgettext

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

dgettext -- Override the current domain

Description

string dgettext ( string domain, string message)

The dgettext() function allows you to override the current domain for a single message lookup.

dngettext

(PHP 4 CVS only)

dngettext -- Plural version of dcgettext() Plural version of dgettext

Description

string dngettext ( string domain, string msgid1, string msgid2, int n)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

gettext

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

gettext -- Lookup a message in the current domain

Description

string gettext ( string message)

This function returns a translated string if one is found in the translation table, or the submitted message if not found. You may use an underscore character as an alias to this function.

Przykład 1. gettext()-check

<?php
// Set language to German
putenv ("LANG=de");

// Specify location of translation tables
bindtextdomain ("myPHPApp", "./locale");

// Choose domain
textdomain ("myPHPApp");

// Print a test message
print (gettext ("Welcome to My PHP Application"));
?>

ngettext

(PHP 4 CVS only)

ngettext -- Plural version of gettext

Description

string ngettext ( string msgid1, string msgid2, int n)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

textdomain

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

textdomain -- Sets the default domain

Description

string textdomain ( string text_domain)

This function sets the domain to search within when calls are made to gettext(), usually the named after an application. The previous default domain is returned. Call it with NULL as parameter to get the current setting without changing it.

XXXVI. GMP functions

These functions allow you to work with arbitrary-length integers using the GNU MP library. In order to have these functions available, you must compile PHP with GMP support by using the --with-gmp option.

You can download the GMP library from http://www.swox.com/gmp/. This site also has the GMP manual available.

You will need GMP version 2 or better to use these functions. Some functions may require more recent version of the GMP library.

These functions have been added in PHP 4.0.4.

Notatka: Most GMP functions accept GMP number arguments, defined as resource below. However, most of these functions will also accept numeric and string arguments, given that it is possible to convert the latter to a number. Also, if there is a faster function that can operate on integer arguments, it would be used instead of the slower function when the supplied arguments are integers. This is done transparently, so the bottom line is that you can use integers in every function that expects GMP number. See also the gmp_init() function.

Ostrze¿enie

If you want to explicitly specify a large integer, specify it as a string. If you don't do that, PHP will interpret the integer-literal first, possibly resulting in loss of precision, even before GMP comes into play.

Przykład 1. Factorial function using GMP

<?php
function fact ($x) {
    if ($x <= 1) 
        return 1;
    else
        return gmp_mul ($x, fact ($x-1));
}

print gmp_strval (fact (1000)) . "\n";
?>

This will calculate factorial of 1000 (pretty big number) very fast.

Spis treści
gmp_init -- Create GMP number
gmp_intval -- Convert GMP number to integer
gmp_strval -- Convert GMP number to string
gmp_add -- Add numbers
gmp_sub -- Subtract numbers
gmp_mul -- Multiply numbers
gmp_div_q -- Divide numbers
gmp_div_r -- Remainder of the division of numbers
gmp_div_qr -- Divide numbers and get quotient and remainder
gmp_div -- Divide numbers
gmp_mod -- Modulo operation
gmp_divexact -- Exact division of numbers
gmp_cmp -- Compare numbers
gmp_neg -- Negate number
gmp_com --  Calculates one's complement of a
gmp_abs -- Absolute value
gmp_sign -- Sign of number
gmp_fact -- Factorial
gmp_sqrt -- Square root
gmp_sqrtrm -- Square root with remainder
gmp_perfect_square -- Perfect square check
gmp_pow -- Raise number into power
gmp_powm -- Raise number into power with modulo
gmp_prob_prime -- Check if number is "probably prime"
gmp_gcd -- Calculate GCD
gmp_gcdext -- Calculate GCD and multipliers
gmp_invert -- Inverse by modulo
gmp_legendre -- Legendre symbol
gmp_jacobi -- Jacobi symbol
gmp_random -- Random number
gmp_and -- Logical AND
gmp_or -- Logical OR
gmp_xor -- Logical XOR
gmp_setbit -- Set bit
gmp_clrbit -- Clear bit
gmp_scan0 -- Scan for 0
gmp_scan1 -- Scan for 1
gmp_popcount -- Population count
gmp_hamdist -- Hamming distance

gmp_init

(PHP 4 >= 4.0.4)

gmp_init -- Create GMP number

Description

resource gmp_init ( mixed number)

Creates a GMP number from an integer or string. String representation can be decimal or hexadecimal. In the latter case, the string should start with 0x.

Przykład 1. Creating GMP number

<?php
    $a = gmp_init (123456);
    $b = gmp_init ("0xFFFFDEBACDFEDF7200");
?>

Notatka: It is not necessary to call this function if you want to use integer or string in place of GMP number in GMP functions, like gmp_add(). Function arguments are automatically converted to GMP numbers, if such conversion is possible and needed, using the same rules as gmp_init().

gmp_intval

(PHP 4 >= 4.0.4)

gmp_intval -- Convert GMP number to integer

Description

int gmp_intval ( resource gmpnumber)

This function allows to convert GMP number to integer.

Ostrze¿enie

This function returns a useful result only if the number actually fits the PHP integer (i.e., signed long type). If you want just to print the GMP number, use gmp_strval().

gmp_strval

(PHP 4 >= 4.0.4)

gmp_strval -- Convert GMP number to string

Description

string gmp_strval ( resource gmpnumber [, int base])

Convert GMP number to string representation in base base. The default base is 10. Allowed values for the base are from 2 to 36.

Przykład 1. Converting a GMP number to a string

<?php
    $a = gmp_init("0x41682179fbf5");
    printf ("Decimal: %s, 36-based: %s", gmp_strval($a), gmp_strval($a,36));
?>

gmp_add

(PHP 4 >= 4.0.4)

gmp_add -- Add numbers

Description

resource gmp_add ( resource a, resource b)

Add two GMP numbers. The result will be a GMP number representing the sum of the arguments.

gmp_sub

(PHP 4 >= 4.0.4)

gmp_sub -- Subtract numbers

Description

resource gmp_sub ( resource a, resource b)

Subtracts b from a and returns the result.

gmp_mul

(PHP 4 >= 4.0.4)

gmp_mul -- Multiply numbers

Description

resource gmp_mul ( resource a, resource b)

Multiplies a by b and returns the result.

gmp_div_q

(PHP 4 >= 4.0.4)

gmp_div_q -- Divide numbers

Description

resource gmp_div_q ( resource a, resource b [, int round])

Divides a by b and returns the integer result. The result rounding is defined by the round, which can have the following values:

  • GMP_ROUND_ZERO: The result is truncated towards 0.

  • GMP_ROUND_PLUSINF: The result is rounded towards +infinity.

  • GMP_ROUND_MINUSINF: The result is rounded towards -infinity.

This function can also be called as gmp_div().

See also gmp_div_r(), gmp_div_qr()

gmp_div_r

(PHP 4 >= 4.0.4)

gmp_div_r -- Remainder of the division of numbers

Description

resource gmp_div_r ( resource n, resource d [, int round])

Calculates remainder of the integer division of n by d. The remainder has the sign of the n argument, if not zero.

See the gmp_div_q() function for description of the round argument.

See also gmp_div_q(), gmp_div_qr()

gmp_div_qr

(PHP 4 >= 4.0.4)

gmp_div_qr -- Divide numbers and get quotient and remainder

Description

array gmp_div_qr ( resource n, resource d [, int round])

The function divides n by d and returns array, with the first element being [n/d] (the integer result of the division) and the second being (n - [n/d] * d) (the remainder of the division).

See the gmp_div_q() function for description of the round argument.

Przykład 1. Division of GMP numbers

<?php
    $a = gmp_init ("0x41682179fbf5");
    $res = gmp_div_qr ($a, "0xDEFE75");
    printf("Result is: q - %s, r - %s", 
            gmp_strval ($res[0]), gmp_strval ($res[1]));
?>

See also gmp_div_q(), gmp_div_r().

gmp_div

(PHP 4 >= 4.0.4)

gmp_div -- Divide numbers

Description

resource gmp_div ( resource a, resource b)

This function is an alias to gmp_div_q().

gmp_mod

(PHP 4 >= 4.0.4)

gmp_mod -- Modulo operation

Description

resource gmp_mod ( resource n, resource d)

Calculates n modulo d. The result is always non-negative, the sign of d is ignored.

gmp_divexact

(PHP 4 >= 4.0.4)

gmp_divexact -- Exact division of numbers

Description

resource gmp_divexact ( resource n, resource d)

Divides n by d, using fast "exact division" algorithm. This function produces correct results only when it is known in advance that d divides n.

gmp_cmp

(PHP 4 >= 4.0.4)

gmp_cmp -- Compare numbers

Description

int gmp_cmp ( resource a, resource b)

Returns a positive value if a > b, zero if a = b and negative value if a < b.

gmp_neg

(PHP 4 >= 4.0.4)

gmp_neg -- Negate number

Description

resource gmp_neg ( resource a)

Returns -a.

gmp_com

(PHP 4 >= 4.0.4)

gmp_com --  Calculates one's complement of a

Description

resource gmp_com ( resource a)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

gmp_abs

(PHP 4 >= 4.0.4)

gmp_abs -- Absolute value

Description

resource gmp_abs ( resource a)

Returns absolute value of a.

gmp_sign

(PHP 4 >= 4.0.4)

gmp_sign -- Sign of number

Description

int gmp_sign ( resource a)

Return sign of a - 1 if a is positive and -1 if it's negative.

gmp_fact

(PHP 4 >= 4.0.4)

gmp_fact -- Factorial

Description

resource gmp_fact ( int a)

Calculates factorial (a!) of a.

gmp_sqrt

(PHP 4 >= 4.0.4)

gmp_sqrt -- Square root

Description

resource gmp_sqrt ( resource a)

Calculates square root of a.

gmp_sqrtrm

(unknown)

gmp_sqrtrm -- Square root with remainder

Description

array gmp_sqrtrm ( resource a)

Returns array where first element is the integer square root of a (see also gmp_sqrt()), and the second is the remainder (i.e., the difference between a and the first element squared).

gmp_perfect_square

(PHP 4 >= 4.0.4)

gmp_perfect_square -- Perfect square check

Description

bool gmp_perfect_square ( resource a)

Returns TRUE if a is a perfect square, FALSE otherwise.

See also: gmp_sqrt(), gmp_sqrtrm().

gmp_pow

(PHP 4 >= 4.0.4)

gmp_pow -- Raise number into power

Description

resource gmp_pow ( resource base, int exp)

Raise base into power exp. The case of 0^0 yields 1. exp cannot be negative.

gmp_powm

(PHP 4 >= 4.0.4)

gmp_powm -- Raise number into power with modulo

Description

resource gmp_powm ( resource base, resource exp, resource mod)

Calculate (base raised into power exp) modulo mod. If exp is negative, result is undefined.

gmp_prob_prime

(PHP 4 >= 4.0.4)

gmp_prob_prime -- Check if number is "probably prime"

Description

int gmp_prob_prime ( resource a [, int reps])

If this function returns 0, a is definitely not prime. If it returns 1, then a is "probably" prime. If it returns 2, then a is surely prime. Reasonable values of reps vary from 5 to 10 (default being 10); a higher value lowers the probability for a non-prime to pass as a "probable" prime.

The function uses Miller-Rabin's probabilistic test.

gmp_gcd

(PHP 4 >= 4.0.4)

gmp_gcd -- Calculate GCD

Description

resource gmp_gcd ( resource a, resource b)

Calculate greatest common divisor of a and b. The result is always positive even if either of, or both, input operands are negative.

gmp_gcdext

(PHP 4 >= 4.0.4)

gmp_gcdext -- Calculate GCD and multipliers

Description

array gmp_gcdext ( resource a, resource b)

Calculates g, s, and t, such that a*s + b*t = g = gcd(a,b), where gcd is the greatest common divisor. Returns an array with respective elements g, s and t.

gmp_invert

(PHP 4 >= 4.0.4)

gmp_invert -- Inverse by modulo

Description

resource gmp_invert ( resource a, resource b)

Computes the inverse of a modulo b. Returns FALSE if an inverse does not exist.

gmp_legendre

(PHP 4 >= 4.0.4)

gmp_legendre -- Legendre symbol

Description

int gmp_legendre ( resource a, resource p)

Compute the Legendre symbol of a and p. p should be odd and must be positive.

gmp_jacobi

(PHP 4 >= 4.0.4)

gmp_jacobi -- Jacobi symbol

Description

int gmp_jacobi ( resource a, resource p)

Computes Jacobi symbol of a and p. p should be odd and must be positive.

gmp_random

(PHP 4 >= 4.0.4)

gmp_random -- Random number

Description

resource gmp_random ( int limiter)

Generate a random number. The number will be between limiter and zero in value. If limiter is negative, negative numbers are generated.

gmp_and

(PHP 4 >= 4.0.4)

gmp_and -- Logical AND

Description

resource gmp_and ( resource a, resource b)

Calculates logical AND of two GMP numbers.

gmp_or

(PHP 4 >= 4.0.4)

gmp_or -- Logical OR

Description

resource gmp_or ( resource a, resource b)

Calculates logical inclusive OR of two GMP numbers.

gmp_xor

(PHP 4 >= 4.0.4)

gmp_xor -- Logical XOR

Description

resource gmp_xor ( resource a, resource b)

Calculates logical exclusive OR (XOR) of two GMP numbers.

gmp_setbit

(PHP 4 >= 4.0.4)

gmp_setbit -- Set bit

Description

resource gmp_setbit ( resource &a, int index [, bool set_clear])

Sets bit index in a. set_clear defines if the bit is set to 0 or 1. By default the bit is set to 1.

gmp_clrbit

(PHP 4 >= 4.0.4)

gmp_clrbit -- Clear bit

Description

resource gmp_clrbit ( resource &a, int index)

Clears (sets to 0) bit index in a.

gmp_scan0

(PHP 4 >= 4.0.4)

gmp_scan0 -- Scan for 0

Description

int gmp_scan0 ( resource a, int start)

Scans a, starting with bit start, towards more significant bits, until the first clear bit is found. Returns the index of the found bit.

gmp_scan1

(PHP 4 >= 4.0.4)

gmp_scan1 -- Scan for 1

Description

int gmp_scan1 ( resource a, int start)

Scans a, starting with bit start, towards more significant bits, until the first set bit is found. Returns the index of the found bit.

gmp_popcount

(PHP 4 >= 4.0.4)

gmp_popcount -- Population count

Description

int gmp_popcount ( resource a)

Return the population count of a.

gmp_hamdist

(PHP 4 >= 4.0.4)

gmp_hamdist -- Hamming distance

Description

int gmp_hamdist ( resource a, resource b)

Returns the hamming distance between a and b. Both operands should be non-negative.

XXXVII. HTTP

Te funkcje pozwalają ci operować na danych wysyłanych do przeglądarki internetowej na poziomie protokołu HTTP.

Spis treści
header -- Wysyła surowy nagłowek HTTP
headers_sent -- Zwraca TRUE jeśli nagłówki zostały już wysłane
setcookie -- Wysyła ciasteczko

header

(PHP 3, PHP 4 >= 4.0.0)

header -- Wysyła surowy nagłowek HTTP

Opis

int header ( string treść_nagłówka [, bool zamień])

header() służy do wysłania surowego nagłówka HTTP. Zajrzyj do Specyfikacji HTTP 1.1 aby dowiedzieć się więcej na temat nagłówków HTTP.

Opcjonalny agrument zamień określa, czy funkcja ma zastąpić nagłówek tego samego typu przygotowany przez serwer, czy dodać jeszcze jeden. Domyślnie, oryginalny nagłówek zostanie zastąpiony, ale jeśli ustawisz ten argument na FALSE, to nowy nagłówek zostanie dodany do już istniejących. Na przykład:

header('WWW-Authenticate: Negociate');
header('WWW-Authenticate: NTLM',false);

W PHP są dwa specjalne wywołania header(). Pierwszym z nich jest "Location". To wywołanie nie tylko wysyła ten nagłówek do przeglądarki, ale także wysyła do przeglądarki status przekierowania REDIRECT (302).

header("Location: http://www.php.net/"); /* Przekieruj przeglądarkę 
                                            na stronę główną PHP */
exit;                 /* Upewnij się, że kod poniżej nie zostanie wykonany 
                         po przekierowaniu. */

Notatka: Protokół HTTP 1.1 wymaga bezwzględnego URI w nagłówku Location: włącznie z określeniem protokołu, nazwy hosta i bezwzględnej scieżki dostępu, ale niektóre klienty akceptują względne URI. Zwykle używa się $HTTP_SERVER_VARS['HTTP_HOST'], $HTTP_SERVER_VARS['PHP_SELF'] i funkcji dirname() by wygenerować bezwględnego URI:

header("Location: http://".$HTTP_SERVER_VARS['HTTP_HOST']
                       ."/".dirname($HTTP_SERVER_VARS['PHP_SELF'])
                       ."/".$relative_url);

Drugim specjalnym wywołaniem funkcji jest każdy nagłówek zaczynający się od ciągu znaków "HTTP/" (wielkość liter nie gra roli), którego używa się do określenia, jaki kod statusu HTTP ma zostać wysłany. Na przykład, jeśli skonfigurowałeś Apache'a tak, że skrypt PHP obsługuje zapytania do nieistniejących plików (za pomocą dyrektywy ErrorDocument), powinieneś zwrócić uwagę, aby skrypt generował właściwy kod statusu zapytania HTTP.

header("HTTP/1.0 404 Not Found");

Notatka: W PHP 3 działa to tylko wtedy, kiedy PHP jest skompilowane jako moduł serwera Apache. Taki sam efekt można osiągnąć za pomocą nagłówka Status.

header("Status: 404 Not Found");

Skrypty PHP często służą do generowania dynamiczej treści, która nie może być buforowana przez klienta czy serwer proxy. Pamięć cache (bufor) w większości tych urządzeń da się wyłączyć dzięki:

header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");    // data w przeszłości
header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
                                                      // ciągle modyfikowany
header("Cache-Control: no-store, no-cache, must-revalidate");  // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");                          // HTTP/1.0

Notatka: Możesz zaobserwować, że strony nie są buforowane, nawet jeśli nie użyłeś wszystkich ww. nagłówków. Jest wiele sposobów, w jakie użytkownicy mogą skonfigurować swoje przeglądarki, aby zmienić standardowy sposób buforowania. Przez wysłanie powyższych nagłówków, powinno się udać ominąć jakiekolwiek ustawienia pozwalające na zbuforowanie wyniku pracy twojego skryptu.

Dodatkowo, session_cache_limiter() i dyrektywa konfiguracyjna session.cache_limiter służą do automatycznego generowania nagłówków związanych z bufurowaniem, kiedy sesje są w użyciu.

Pamiętaj, że header() może być wywoływana jedynie do momentu nim zostanie wysłana jakakolwiek treść, tzn. znaczniki HTML, puste linie lub wynik pracy PHP. Jest to bardzo częsty błąd, gdzie skrypty z funkcjami include(), require() itp. mają spacje albo puste linie przed wywołaniem funkcji header(). Problem ten pojawia się również w skryptach opartych na pojedynczym pliku PHP/HTML.

&lt;?php require("user_logging.inc") ?&gt;


&lt;?php header ("Content-Type: audio/x-pn-realaudio"); ?&gt;
// skrypt nie działa - zauważ puste linie pomiędzy instrukcjami

Notatka: W PHP 4 można użyć buforowania wyjścia aby ominąć ten problem. Wszystko, co skrypt wyśle do przeglądarki zostanie zatrzymane na serwerze do momentu, kiedy pojawi się instrukcja wysłania danych. Można to zrobić za pomocą funkcji ob_start() i ob_end_flush(), lub ustawiając dyrektywę kofiguracyjną output_buffering w pliku php.ini lub w plikach konfiguracyjnych serwera.

Aby użytkownik został monitowany o zapisanie wysyłanych danych, takich jak np. wygenerowany plik PDF, można użyć nagłówka Content-Disposition aby podać zalecaną nazwę pliku i zmusić przeglądarkę do wyświetlenia okienka Zapisz jako.

&lt;?php
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=downloaded.pdf");

/* ... treść pliku pdf ... */

Notatka: W Microsoft Internet Explorer 4.01 jest błąd, który uniemożliwia wykorzystanie tego mechanizmu. Nie ma na to rozwiązania. Błąd, który zahacza o ten mechanizm, jest także w Microsoft Internet Explorer 5.5, jednak da się go ominąć aktualizując przeglądarkę poprzez Service Pack 2 lub późniejszy.

Zobacz też headers_sent(), setcookie(), i rozdział Autoryzacja HTTP.

headers_sent

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

headers_sent -- Zwraca TRUE jeśli nagłówki zostały już wysłane

Opis

bool headers_sent ( void)

headers_sent() zwraca TRUE jeśli nagłówki HTTP już zostały wysłane, lub FALSE w przeciwnym wypadku.

Zobacz też header()

setcookie

(PHP 3, PHP 4 >= 4.0.0)

setcookie -- Wysyła ciasteczko

Opis

int setcookie ( string nazwa [, string wartość [, int data_ważności [, string ścieżka [, string domena [, int bezpieczne]]]]])

setcookie() określa ciasteczko (ang. cookie) do wysłania z nagłówkami HTTP. Ciasteczko musi być wysłane zanim jakiekolwiek inne nagłówki zostaną wysłane (to jest ograniczenie ciasteczek, nie PHP). To wymaga od ciebie umieszczenia wywołań tej funkcji przed znacznikami <html> czy <head>.

Wszystkie argumenty poza nazwa są opcjonalne. Jeśli tylko argument nazwa jest obecny, ciasteczko o takie nazwie zostanie usunięte z klienta. Możesz też opuścić argumenty za pomocą pustego łańcucha (""). Argumenty data_ważności i bezpieczne są liczbami całkowitymi i nie można ich opuścić wstawiając pusty łańcuch. Zamiast niego użyj liczby zero (0). Argument data_ważności jest regularnym uniksowym znacznikiem czasu, takim jak zwracany przez funkcje time() lub mktime (). Argument bezpieczne oznacza, że ciasteczko może być przekazywane tylko poprzez bezpieczne połączenie HTTPS.

Częste pułapki:

  • Ciasteczka nie będą widziane do następnego przeładowania strony dla której mają być widoczne.

  • Ciasteczko może być usunięte tylko z tymi parametrami, z jakimi je ustawiono.

W PHP 3, wielokrotne wywołania setcookie() w jednym skrypcie wykonywane były w odwrotnej kolejności. Jeśli chcesz usunąć jedno ciastko przed wprowadzeniem kolejnego, powinieneś umieścić wprowadzenie nowego przed usunęciem starego. W PHP 4, wielokrotne wywołania setcookie() wykonywane są we właściwej kolejności.

Parę przykładów - jak wysyłać ciasteczka:

Przykład 1. setcookie() wysyła przykładowe ciasteczka

setcookie ("TestCookie", $value);
setcookie ("TestCookie", $value,time()+3600);  /* traci ważność za godzinę */
setcookie ("TestCookie", $value,time()+3600, "/~rasmus/", ".utoronto.ca", 1);

Aby skasować ciasteczko, należy ustawić datę ważności na datę w przeszłości, co uruchomi w przeglądarce mechanizm kasowania ciasteczek. A teraz, jak usunąć ciasteczka z poprzedniego przykładu:

Przykład 2. Kasowanie ciasteczek

setcookie ("TestCookie");
// ustaw datę ważności na godzinę wstecz
setcookie ("TestCookie", "", time() - 3600);
setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", ".utoronto.ca", 1);

Proszę zwrócić uwagę, że zawartość ciasteczka jest automatycznie kodowana do formatu URL przy wysyłaniu, a po odebraniu automatycznie dekodowana i przypisywana do zmiennej o tej samej nazwie co ciasteczko. Aby poznać zawartość przykładowego ciasteczka ze skryptu, należy zastosować poniższy przykład:

echo $TestCookie;
echo $HTTP_COOKIE_VARS["TestCookie"];

Można też tworzyć tablice złożone z ciasteczek za pomocą zapisu tablicowego w nazwie ciasteczka. Powoduje to utworzenie tylu ciasteczek, ile jest elemetów tablicy, a po otrzymaniu takiego ciasteczka, jego wartości umieszczane są w tablicy o nazwie takiej jak ciasteczko.

setcookie ("cookie[three]", "cookiethree");
setcookie ("cookie[two]", "cookietwo");
setcookie ("cookie[one]", "cookieone");
if (isset ($cookie)) {
    while (list ($name, $value) = each ($cookie)) {
        echo "$name == $value&lt;br>\n";
    }
}

Więcej informacji na temat ciasteczek znajduje się w specyfikacji Netscape'a, na stronie http://www.netscape.com/newsref/std/cookie_spec.html.

Microsoft Internet Explorer 4 z zainstalowanym Service Pack 1 nie radzi sobie poprawnie z ciasteczkami, które mają ustawiony parametr ścieżka.

Netscape Communicator 4.05 i Microsoft Internet Explorer 3.x niepoprawnie obsługują ciasteczka, w których ścieżka i data_ważności nie są ustawione.

XXXVIII. Hyperwave functions

Introduction

Hyperwave has been developed at IICM in Graz. It started with the name Hyper-G and changed to Hyperwave when it was commercialised (If I remember properly it was in 1996).

Hyperwave is not free software. The current version, 4.1, is available at www.hyperwave.com. A time limited version can be ordered for free (30 days).

Hyperwave is an information system similar to a database (HIS, Hyperwave Information Server). Its focus is the storage and management of documents. A document can be any possible piece of data that may as well be stored in file. Each document is accompanied by its object record. The object record contains meta data for the document. The meta data is a list of attributes which can be extended by the user. Certain attributes are always set by the Hyperwave server, other may be modified by the user. An attribute is a name/value pair of the form name=value. The complete object record contains as many of those pairs as the user likes. The name of an attribute does not have to be unique, e.g. a title may appear several times within an object record. This makes sense if you want to specify a title in several languages. In such a case there is a convention, that each title value is preceded by the two letter language abbreviation followed by a colon, e.g. 'en:Title in English' or 'ge:Titel in deutsch'. Other attributes like a description or keywords are potential candidates. You may also replace the language abbreviation by any other string as long as it separated by colon from the rest of the attribute value.

Each object record has native a string representation with each name/value pair separated by a newline. The Hyperwave extension also knows a second representation which is an associated array with the attribute name being the key. Multilingual attribute values itself form another associated array with the key being the language abbreviation. Actually any multiple attribute forms an associated array with the string left to the colon in the attribute value being the key. (This is not fully implemented. Only the attributes Title, Description and Keyword are treated properly yet.)

Besides the documents, all hyper links contained in a document are stored as object records as well. Hyper links which are in a document will be removed from it and stored as individual objects, when the document is inserted into the database. The object record of the link contains information about where it starts and where it ends. In order to gain the original document you will have to retrieve the plain document without the links and the list of links and reinsert them (The functions hw_pipedocument() and hw_gettext() do this for you. The advantage of separating links from the document is obvious. Once a document to which a link is pointing to changes its name, the link can easily be modified accordingly. The document containing the link is not affected at all. You may even add a link to a document without modifying the document itself.

Saying that hw_pipedocument() and hw_gettext() do the link insertion automatically is not as simple as it sounds. Inserting links implies a certain hierarchy of the documents. On a web server this is given by the file system, but Hyperwave has its own hierarchy and names do not reflect the position of an object in that hierarchy. Therefore creation of links first of all requires a mapping from the Hyperwave hierarchy and namespace into a web hierarchy respective web namespace. The fundamental difference between Hyperwave and the web is the clear distinction between names and hierarchy in Hyperwave. The name does not contain any information about the objects position in the hierarchy. In the web the name also contains the information on where the object is located in the hierarchy. This leads to two possibles ways of mapping. Either the Hyperwave hierarchy and name of the Hyperwave object is reflected in the URL or the name only. To make things simple the second approach is used. Hyperwave object with name 'my_object' is mapped to 'http://host/my_object' disregarding where it resides in the Hyperwave hierarchy. An object with name 'parent/my_object' could be the child of 'my_object' in the Hyperwave hierarchy, though in a web namespace it appears to be just the opposite and the user might get confused. This can only be prevented by selecting reasonable object names.

Having made this decision a second problem arises. How do you involve PHP? The URL http://host/my_object will not call any PHP script unless you tell your web server to rewrite it to e.g. 'http://host/php3_script/my_object' and the script 'php3_script' evaluates the $PATH_INFO variable and retrieves the object with name 'my_object' from the Hyperwave server. Their is just one little drawback which can be fixed easily. Rewriting any URL would not allow any access to other document on the web server. A PHP script for searching in the Hyperwave server would be impossible. Therefore you will need at least a second rewriting rule to exclude certain URLS like all e.g. starting with http://host/Hyperwave. This is basically sharing of a namespace by the web and Hyperwave server.

Based on the above mechanism links are insert into documents.

It gets more complicated if PHP is not run as a server module or CGI script but as a standalone application e.g. to dump the content of the Hyperwave server on a CD-ROM. In such a case it makes sense to retain the Hyperwave hierarchy and map in onto the file system. This conflicts with the object names if they reflect its own hierarchy (e.g. by choosing names including '/'). Therefore '/' has to be replaced by another character, e.g. '_'. to be continued.

The network protocol to communicate with the Hyperwave server is called HG-CSP (Hyper-G Client/Server Protocol). It is based on messages to initiate certain actions, e.g. get object record. In early versions of the Hyperwave Server two native clients (Harmony, Amadeus) were provided for communication with the server. Those two disappeared when Hyperwave was commercialised. As a replacement a so called wavemaster was provided. The wavemaster is like a protocol converter from HTTP to HG-CSP. The idea is to do all the administration of the database and visualisation of documents by a web interface. The wavemaster implements a set of placeholders for certain actions to customise the interface. This set of placeholders is called the PLACE Language. PLACE lacks a lot of features of a real programming language and any extension to it only enlarges the list of placeholders. This has led to the use of JavaScript which IMO does not make life easier.

Adding Hyperwave support to PHP should fill in the gap of a missing programming language for interface customisation. It implements all the messages as defined by the HG-CSP but also provides more powerful commands to e.g. retrieve complete documents.

Hyperwave has its own terminology to name certain pieces of information. This has widely been taken over and extended. Almost all functions operate on one of the following data types.

  • object ID: An unique integer value for each object in the Hyperwave server. It is also one of the attributes of the object record (ObjectID). Object ids are often used as an input parameter to specify an object.

  • object record: A string with attribute-value pairs of the form attribute=value. The pairs are separated by a carriage return from each other. An object record can easily be converted into an object array with hw_object2array(). Several functions return object records. The names of those functions end with obj.

  • object array: An associated array with all attributes of an object. The key is the attribute name. If an attribute occurs more than once in an object record it will result in another indexed or associated array. Attributes which are language depended (like the title, keyword, description) will form an associated array with the key set to the language abbreviation. All other multiple attributes will form an indexed array. PHP functions never return object arrays.

  • hw_document: This is a complete new data type which holds the actual document, e.g. HTML, PDF etc. It is somewhat optimised for HTML documents but may be used for any format.

Several functions which return an array of object records do also return an associated array with statistical information about them. The array is the last element of the object record array. The statistical array contains the following entries:

Hidden

Number of object records with attribute PresentationHints set to Hidden.

CollectionHead

Number of object records with attribute PresentationHints set to CollectionHead.

FullCollectionHead

Number of object records with attribute PresentationHints set to FullCollectionHead.

CollectionHeadNr

Index in array of object records with attribute PresentationHints set to CollectionHead.

FullCollectionHeadNr

Index in array of object records with attribute PresentationHints set to FullCollectionHead.

Total

Total: Number of object records.


Integration with Apache

The Hyperwave extension is best used when PHP is compiled as an Apache module. In such a case the underlying Hyperwave server can be hidden from users almost completely if Apache uses its rewriting engine. The following instructions will explain this.

Since PHP with Hyperwave support built into Apache is intended to replace the native Hyperwave solution based on Wavemaster I will assume that the Apache server will only serve as a Hyperwave web interface. This is not necessary but it simplifies the configuration. The concept is quite simple. First of all you need a PHP script which evaluates the PATH_INFO variable and treats its value as the name of a Hyperwave object. Let's call this script 'Hyperwave'. The URL http://your.hostname/Hyperwave/name_of_object would than return the Hyperwave object with the name 'name_of_object'. Depending on the type of the object the script has to react accordingly. If it is a collection, it will probably return a list of children. If it is a document it will return the mime type and the content. A slight improvement can be achieved if the Apache rewriting engine is used. From the users point of view it would be more straight forward if the URL http://your.hostname/name_of_object would return the object. The rewriting rule is quite easy:

RewriteRule ^/(.*) /usr/local/apache/htdocs/HyperWave/$1 [L]

Now every URL relates to an object in the Hyperwave server. This causes a simple to solve problem. There is no way to execute a different script, e.g. for searching, than the 'Hyperwave' script. This can be fixed with another rewriting rule like the following:

RewriteRule ^/hw/(.*) /usr/local/apache/htdocs/hw/$1 [L]

This will reserve the directory /usr/local/apache/htdocs/hw for additional scripts and other files. Just make sure this rule is evaluated before the one above. There is just a little drawback: all Hyperwave objects whose name starts with 'hw/' will be shadowed. So, make sure you don't use such names. If you need more directories, e.g. for images just add more rules or place them all in one directory. Finally, don't forget to turn on the rewriting engine with

RewriteEngine on

My experiences have shown that you will need the following scripts:

  • to return the object itself

  • to allow searching

  • to identify yourself

  • to set your profile

  • one for each additional function like to show the object attributes, to show information about users, to show the status of the server, etc.


Todo

There are still some things todo:

  • The hw_InsertDocument has to be split into hw_insertobject() and hw_putdocument().

  • The names of several functions are not fixed, yet.

  • Most functions require the current connection as its first parameter. This leads to a lot of typing, which is quite often not necessary if there is just one open connection. A default connection will improve this.

  • Conversion form object record into object array needs to handle any multiple attribute.

Spis treści
hw_Array2Objrec -- convert attributes from object array to object record
hw_Children -- object ids of children
hw_ChildrenObj -- object records of children
hw_Close -- closes the Hyperwave connection
hw_Connect -- opens a connection
hw_Cp -- copies objects
hw_Deleteobject -- deletes object
hw_DocByAnchor -- object id object belonging to anchor
hw_DocByAnchorObj -- object record object belonging to anchor
hw_Document_Attributes -- object record of hw_document
hw_Document_BodyTag -- body tag of hw_document
hw_Document_Content -- returns content of hw_document
hw_Document_SetContent -- sets/replaces content of hw_document
hw_Document_Size -- size of hw_document
hw_ErrorMsg -- returns error message
hw_EditText -- retrieve text document
hw_Error -- error number
hw_Free_Document -- frees hw_document
hw_GetParents -- object ids of parents
hw_GetParentsObj -- object records of parents
hw_GetChildColl -- object ids of child collections
hw_GetChildCollObj -- object records of child collections
hw_GetRemote -- Gets a remote document
hw_GetRemoteChildren -- Gets children of remote document
hw_GetSrcByDestObj -- Returns anchors pointing at object
hw_GetObject -- object record
hw_GetAndLock -- return bject record and lock object
hw_GetText -- retrieve text document
hw_GetObjectByQuery -- search object
hw_GetObjectByQueryObj -- search object
hw_GetObjectByQueryColl -- search object in collection
hw_GetObjectByQueryCollObj -- search object in collection
hw_GetChildDocColl -- object ids of child documents of collection
hw_GetChildDocCollObj -- object records of child documents of collection
hw_GetAnchors -- object ids of anchors of document
hw_GetAnchorsObj -- object records of anchors of document
hw_Mv -- moves objects
hw_Identify -- identifies as user
hw_InCollections -- check if object ids in collections
hw_Info -- info about connection
hw_InsColl -- insert collection
hw_InsDoc -- insert document
hw_InsertDocument -- upload any document
hw_InsertObject -- inserts an object record
hw_mapid -- Maps global id on virtual local id
hw_Modifyobject -- modifies object record
hw_New_Document -- create new document
hw_Objrec2Array -- convert attributes from object record to object array
hw_Output_Document -- prints hw_document
hw_pConnect -- make a persistent database connection
hw_PipeDocument -- retrieve any document
hw_Root -- root object id
hw_Unlock -- unlock object
hw_Who -- List of currently logged in users
hw_getusername -- name of currently logged in user
hw_stat --  Returns status string
hw_setlinkroot --  Set the id to which links are calculated
hw_connection_info --  Prints information about the connection to Hyperwave server
hw_dummy --  Hyperwave dummy function
hw_insertanchors --  Inserts only anchors into text
hw_getrellink --  Get link from source to dest relative to rootid
hw_changeobject --  Changes attributes of an object (obsolete)

hw_Array2Objrec

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

hw_Array2Objrec -- convert attributes from object array to object record

Description

strin hw_array2objrec ( array object_array)

Converts an object_array into an object record. Multiple attributes like 'Title' in different languages are treated properly.

See also hw_objrec2array().

hw_Children

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_Children -- object ids of children

Description

array hw_children ( int connection, int objectID)

Returns an array of object ids. Each id belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.

hw_ChildrenObj

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_ChildrenObj -- object records of children

Description

array hw_childrenobj ( int connection, int objectID)

Returns an array of object records. Each object record belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.

hw_Close

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_Close -- closes the Hyperwave connection

Description

int hw_close ( int connection)

Returns FALSE if connection is not a valid connection index, otherwise TRUE. Closes down the connection to a Hyperwave server with the given connection index.

hw_Connect

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_Connect -- opens a connection

Description

int hw_connect ( string host, int port, string username, string password)

Opens a connection to a Hyperwave server and returns a connection index on success, or FALSE if the connection could not be made. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple connections open at once. Keep in mind, that the password is not encrypted.

See also hw_pconnect().

hw_Cp

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_Cp -- copies objects

Description

int hw_cp ( int connection, array object_id_array, int destination id)

Copies the objects with object ids as specified in the second parameter to the collection with the id destination id.

The value return is the number of copied objects.

See also hw_mv().

hw_Deleteobject

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_Deleteobject -- deletes object

Description

int hw_deleteobject ( int connection, int object_to_delete)

Deletes the object with the given object id in the second parameter. It will delete all instances of the object.

Returns TRUE if no error occurs otherwise FALSE.

See also hw_mv().

hw_DocByAnchor

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_DocByAnchor -- object id object belonging to anchor

Description

int hw_docbyanchor ( int connection, int anchorID)

Returns an th object id of the document to which anchorID belongs.

hw_DocByAnchorObj

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_DocByAnchorObj -- object record object belonging to anchor

Description

string hw_docbyanchorobj ( int connection, int anchorID)

Returns an th object record of the document to which anchorID belongs.

hw_Document_Attributes

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_Document_Attributes -- object record of hw_document

Description

string hw_document_attributes ( int hw_document)

Returns the object record of the document.

For backward compatibility, hw_documentattributes() is also accepted. This is deprecated, however.

See also hw_document_bodytag(), and hw_document_size().

hw_Document_BodyTag

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_Document_BodyTag -- body tag of hw_document

Description

string hw_document_bodytag ( int hw_document)

Returns the BODY tag of the document. If the document is an HTML document the BODY tag should be printed before the document.

See also hw_document_attributes(), and hw_document_size().

For backward compatibility, hw_documentbodytag() is also accepted. This is deprecated, however.

hw_Document_Content

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_Document_Content -- returns content of hw_document

Description

string hw_document_content ( int hw_document)

Returns the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record.

See also hw_document_attributes(), hw_document_size(), and hw_document_setcontent().

hw_Document_SetContent

(PHP 4 >= 4.0.0)

hw_Document_SetContent -- sets/replaces content of hw_document

Description

string hw_document_setcontent ( int hw_document, string content)

Sets or replaces the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record. If you provide this information in the content of the document too, the Hyperwave server will change the object record accordingly when the document is inserted. Probably not a very good idea. If this functions fails the document will retain its old content.

See also hw_document_attributes(), hw_document_size(), and hw_document_content().

hw_Document_Size

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_Document_Size -- size of hw_document

Description

int hw_document_size ( int hw_document)

Returns the size in bytes of the document.

See also hw_document_bodytag(), and hw_document_attributes().

For backward compatibility, hw_documentsize() is also accepted. This is deprecated, however.

hw_ErrorMsg

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_ErrorMsg -- returns error message

Description

string hw_errormsg ( int connection)

Returns a string containing the last error message or 'No Error'. If FALSE is returned, this function failed. The message relates to the last command.

hw_EditText

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_EditText -- retrieve text document

Description

int hw_edittext ( int connection, int hw_document)

Uploads the text document to the server. The object record of the document may not be modified while the document is edited. This function will only works for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.

See also hw_pipedocument(), hw_free_document(), hw_document_bodytag(), hw_document_size(), hw_output_document(), hw_gettext().

hw_Error

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_Error -- error number

Description

int hw_error ( int connection)

Returns the last error number. If the return value is 0 no error has occurred. The error relates to the last command.

hw_Free_Document

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_Free_Document -- frees hw_document

Description

int hw_free_document ( int hw_document)

Frees the memory occupied by the Hyperwave document.

hw_GetParents

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_GetParents -- object ids of parents

Description

array hw_getparents ( int connection, int objectID)

Returns an indexed array of object ids. Each object id belongs to a parent of the object with ID objectID.

hw_GetParentsObj

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_GetParentsObj -- object records of parents

Description

array hw_getparentsobj ( int connection, int objectID)

Returns an indexed array of object records plus an associated array with statistical information about the object records. The associated array is the last entry of the returned array. Each object record belongs to a parent of the object with ID objectID.

hw_GetChildColl

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_GetChildColl -- object ids of child collections

Description

array hw_getchildcoll ( int connection, int objectID)

Returns an array of object ids. Each object ID belongs to a child collection of the collection with ID objectID. The function will not return child documents.

See also hw_children(), and hw_getchilddoccoll().

hw_GetChildCollObj

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_GetChildCollObj -- object records of child collections

Description

array hw_getchildcollobj ( int connection, int objectID)

Returns an array of object records. Each object records belongs to a child collection of the collection with ID objectID. The function will not return child documents.

See also hw_childrenobj(), and hw_getchilddoccollobj().

hw_GetRemote

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_GetRemote -- Gets a remote document

Description

int hw_getremote ( int connection, int objectID)

Returns a remote document. Remote documents in Hyperwave notation are documents retrieved from an external source. Common remote documents are for example external web pages or queries in a database. In order to be able to access external sources throught remote documents Hyperwave introduces the HGI (Hyperwave Gateway Interface) which is similar to the CGI. Currently, only ftp, http-servers and some databases can be accessed by the HGI. Calling hw_getremote() returns the document from the external source. If you want to use this function you should be very familiar with HGIs. You should also consider to use PHP instead of Hyperwave to access external sources. Adding database support by a Hyperwave gateway should be more difficult than doing it in PHP.

See also hw_getremotechildren().

hw_GetRemoteChildren

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_GetRemoteChildren -- Gets children of remote document

Description

int hw_getremotechildren ( int connection, string object record)

Returns the children of a remote document. Children of a remote document are remote documents itself. This makes sense if a database query has to be narrowed and is explained in Hyperwave Programmers' Guide. If the number of children is 1 the function will return the document itself formated by the Hyperwave Gateway Interface (HGI). If the number of children is greater than 1 it will return an array of object record with each maybe the input value for another call to hw_getremotechildren(). Those object records are virtual and do not exist in the Hyperwave server, therefore they do not have a valid object ID. How exactely such an object record looks like is up to the HGI. If you want to use this function you should be very familiar with HGIs. You should also consider to use PHP instead of Hyperwave to access external sources. Adding database support by a Hyperwave gateway should be more difficult than doing it in PHP.

See also hw_getremote().

hw_GetSrcByDestObj

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_GetSrcByDestObj -- Returns anchors pointing at object

Description

array hw_getsrcbydestobj ( int connection, int objectID)

Returns the object records of all anchors pointing to the object with ID objectID. The object can either be a document or an anchor of type destination.

See also hw_getanchors().

hw_GetObject

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_GetObject -- object record

Description

array hw_getobject ( int connection, [int|array] objectID, string query)

Returns the object record for the object with ID objectID if the second parameter is an integer. If the second parameter is an array of integer the function will return an array of object records. In such a case the last parameter is also evaluated which is a query string.

The query string has the following syntax:

<expr> ::= "(" <expr> ")" |

"!" <expr> | /* NOT */

<expr> "||" <expr> | /* OR */

<expr> "&&" <expr> | /* AND */

<attribute> <operator> <value>

<attribute> ::= /* any attribute name (Title, Author, DocumentType ...) */

<operator> ::= "=" | /* equal */

"<" | /* less than (string compare) */

">" | /* greater than (string compare) */

"~" /* regular expression matching */

The query allows to further select certain objects from the list of given objects. Unlike the other query functions, this query may use not indexed attributes. How many object records are returned depends on the query and if access to the object is allowed.

See also hw_getandlock(), and hw_getobjectbyquery().

hw_GetAndLock

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_GetAndLock -- return bject record and lock object

Description

string hw_getandlock ( int connection, int objectID)

Returns the object record for the object with ID objectID. It will also lock the object, so other users cannot access it until it is unlocked.

See also hw_unlock(), and hw_getobject().

hw_GetText

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_GetText -- retrieve text document

Description

int hw_gettext ( int connection, int objectID [, mixed rootID/prefix])

Returns the document with object ID objectID. If the document has anchors which can be inserted, they will be inserted already. The optional parameter rootID/prefix can be a string or an integer. If it is an integer it determines how links are inserted into the document. The default is 0 and will result in links that are constructed from the name of the link's destination object. This is useful for web applications. If a link points to an object with name 'internet_movie' the HTML link will be <A HREF="/internet_movie">. The actual location of the source and destination object in the document hierachy is disregarded. You will have to set up your web browser, to rewrite that URL to for example '/my_script.php3/internet_movie'. 'my_script.php3' will have to evaluate $PATH_INFO and retrieve the document. All links will have the prefix '/my_script.php3/'. If you do not want this you can set the optional parameter rootID/prefix to any prefix which is used instead. Is this case it has to be a string.

If rootID/prefix is an integer and unequal to 0 the link is constructed from all the names starting at the object with the id rootID/prefix separated by a slash relative to the current object. If for example the above document 'internet_movie' is located at 'a-b-c-internet_movie' with '-' being the seperator between hierachy levels on the Hyperwave server and the source document is located at 'a-b-d-source' the resulting HTML link would be: <A HREF="../c/internet_movie">. This is useful if you want to download the whole server content onto disk and map the document hierachy onto the file system.

This function will only work for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.

See also hw_pipedocument(), hw_free_document(), hw_document_bodytag(), hw_document_size(), and hw_output_document().

hw_GetObjectByQuery

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_GetObjectByQuery -- search object

Description

array hw_getobjectbyquery ( int connection, string query, int max_hits)

Searches for objects on the whole server and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyqueryobj().

hw_GetObjectByQueryObj

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_GetObjectByQueryObj -- search object

Description

array hw_getobjectbyqueryobj ( int connection, string query, int max_hits)

Searches for objects on the whole server and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyquery().

hw_GetObjectByQueryColl

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_GetObjectByQueryColl -- search object in collection

Description

array hw_getobjectbyquerycoll ( int connection, int objectID, string query, int max_hits)

Searches for objects in collection with ID objectID and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyquerycollobj().

hw_GetObjectByQueryCollObj

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_GetObjectByQueryCollObj -- search object in collection

Description

array hw_getobjectbyquerycollobj ( int connection, int objectID, string query, int max_hits)

Searches for objects in collection with ID objectID and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyquerycoll().

hw_GetChildDocColl

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_GetChildDocColl -- object ids of child documents of collection

Description

array hw_getchilddoccoll ( int connection, int objectID)

Returns array of object ids for child documents of a collection.

See also hw_children(), and hw_getchildcoll().

hw_GetChildDocCollObj

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_GetChildDocCollObj -- object records of child documents of collection

Description

array hw_getchilddoccollobj ( int connection, int objectID)

Returns an array of object records for child documents of a collection.

See also hw_childrenobj(), and hw_getchildcollobj().

hw_GetAnchors

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_GetAnchors -- object ids of anchors of document

Description

array hw_getanchors ( int connection, int objectID)

Returns an array of object ids with anchors of the document with object ID objectID.

hw_GetAnchorsObj

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_GetAnchorsObj -- object records of anchors of document

Description

array hw_getanchorsobj ( int connection, int objectID)

Returns an array of object records with anchors of the document with object ID objectID.

hw_Mv

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_Mv -- moves objects

Description

int hw_mv ( int connection, array object id array, int source id, int destination id)

Moves the objects with object ids as specified in the second parameter from the collection with id source id to the collection with the id destination id. If the destination id is 0 the objects will be unlinked from the source collection. If this is the last instance of that object it will be deleted. If you want to delete all instances at once, use hw_deleteobject().

The value return is the number of moved objects.

See also hw_cp(), and hw_deleteobject().

hw_Identify

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_Identify -- identifies as user

Description

int hw_identify ( string username, string password)

Identifies as user with username and password. Identification is only valid for the current session. I do not thing this function will be needed very often. In most cases it will be easier to identify with the opening of the connection.

See also hw_connect().

hw_InCollections

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_InCollections -- check if object ids in collections

Description

array hw_incollections ( int connection, array object_id_array, array collection_id_array, int return_collections)

Checks whether a set of objects (documents or collections) specified by the object_id_array is part of the collections listed in collection_id_array. When the fourth parameter return_collections is 0, the subset of object ids that is part of the collections (i.e., the documents or collections that are children of one or more collections of collection ids or their subcollections, recursively) is returned as an array. When the fourth parameter is 1, however, the set of collections that have one or more objects of this subset as children are returned as an array. This option allows a client to, e.g., highlight the part of the collection hierarchy that contains the matches of a previous query, in a graphical overview.

hw_Info

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_Info -- info about connection

Description

string hw_info ( int connection)

Returns information about the current connection. The returned string has the following format: <Serverstring>, <Host>, <Port>, <Username>, <Port of Client>, <Byte swapping>

hw_InsColl

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_InsColl -- insert collection

Description

int hw_inscoll ( int connection, int objectID, array object_array)

Inserts a new collection with attributes as in object_array into collection with object ID objectID.

hw_InsDoc

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_InsDoc -- insert document

Description

int hw_insdoc ( int connection, int parentID, string object_record, string text)

Inserts a new document with attributes as in object_record into collection with object ID parentID. This function inserts either an object record only or an object record and a pure ascii text in text if text is given. If you want to insert a general document of any kind use hw_insertdocument() instead.

See also hw_insertdocument(), and hw_inscoll().

hw_InsertDocument

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_InsertDocument -- upload any document

Description

int hw_insertdocument ( int connection, int parent_id, int hw_document)

Uploads a document into the collection with parent_id. The document has to be created before with hw_new_document(). Make sure that the object record of the new document contains at least the attributes: Type, DocumentType, Title and Name. Possibly you also want to set the MimeType. The functions returns the object id of the new document or FALSE.

See also hw_pipedocument().

hw_InsertObject

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_InsertObject -- inserts an object record

Description

int hw_insertobject ( int connection, string object rec, string parameter)

Inserts an object into the server. The object can be any valid hyperwave object. See the HG-CSP documentation for a detailed information on how the parameters have to be.

Note: If you want to insert an Anchor, the attribute Position has always been set either to a start/end value or to 'invisible'. Invisible positions are needed if the annotation has no correspondig link in the annotation text.

See also hw_pipedocument(), hw_insertdocument(), hw_insdoc(), and hw_inscoll().

hw_mapid

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

hw_mapid -- Maps global id on virtual local id

Description

int hw_mapid ( int connection, int server id, int object id)

Maps a global object id on any hyperwave server, even those you did not connect to with hw_connect(), onto a virtual object id. This virtual object id can then be used as any other object id, e.g. to obtain the object record with hw_getobject(). The server id is the first part of the global object id (GOid) of the object which is actually the IP number as an integer.

Note: In order to use this function you will have to set the F_DISTRIBUTED flag, which can currently only be set at compile time in hg_comm.c. It is not set by default. Read the comment at the beginning of hg_comm.c

hw_Modifyobject

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

hw_Modifyobject -- modifies object record

Description

int hw_modifyobject ( int connection, int object_to_change, array remove, array add, int mode)

This command allows to remove, add, or modify individual attributes of an object record. The object is specified by the Object ID object_to_change. The first array remove is a list of attributes to remove. The second array add is a list of attributes to add. In order to modify an attribute one will have to remove the old one and add a new one. hw_modifyobject() will always remove the attributes before it adds attributes unless the value of the attribute to remove is not a string or array.

The last parameter determines if the modification is performed recursively. 1 means recurive modification. If some of the objects cannot be modified they will be skiped without notice. hw_error() may not indicate an error though some of the objects could not be modified.

The keys of both arrays are the attributes name. The value of each array element can either be an array, a string or anything else. If it is an array each attribute value is constructed by the key of each element plus a colon and the value of each element. If it is a string it is taken as the attribute value. An empty string will result in a complete removal of that attribute. If the value is neither a string nor an array but something else, e.g. an integer, no operation at all will be performed on the attribute. This is neccessary if you want to to add a completely new attribute not just a new value for an existing attribute. If the remove array contained an empty string for that attribute, the attribute would be tried to be removed which would fail since it doesn't exist. The following addition of a new value for that attribute would also fail. Setting the value for that attribute to e.g. 0 would not even try to remove it and the addition will work.

If you would like to change the attribute 'Name' with the current value 'books' into 'articles' you will have to create two arrays and call hw_modifyobject().

Przykład 1. modifying an attribute

// $connect is an existing connection to the Hyperwave server
       // $objid is the ID of the object to modify
       $remarr = array("Name" => "books");
       $addarr = array("Name" => "articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
In order to delete/add a name=value pair from/to the object record just pass the remove/add array and set the last/third parameter to an empty array. If the attribute is the first one with that name to add, set attribute value in the remove array to an integer.

Przykład 2. adding a completely new attribute

// $connect is an existing connection to the Hyperwave server
       // $objid is the ID of the object to modify
       $remarr = array("Name" => 0);
       $addarr = array("Name" => "articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);

Notatka: Multilingual attributes, e.g. 'Title', can be modified in two ways. Either by providing the attributes value in its native form 'language':'title' or by providing an array with elements for each language as described above. The above example would than be:

Przykład 3. modifying Title attribute

$remarr = array("Title" => "en:Books");
       $addarr = array("Title" => "en:Articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
or

Przykład 4. modifying Title attribute

$remarr = array("Title" => array("en" => "Books"));
       $addarr = array("Title" => array("en" => "Articles", "ge"=>"Artikel"));
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
This removes the english title 'Books' and adds the english title 'Articles' and the german title 'Artikel'.

Przykład 5. removing attribute

$remarr = array("Title" => "");
       $addarr = array("Title" => "en:Articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);

Notatka: This will remove all attributes with the name 'Title' and adds a new 'Title' attribute. This comes in handy if you want to remove attributes recursively.

Notatka: If you need to delete all attributes with a certain name you will have to pass an empty string as the attribute value.

Notatka: Only the attributes 'Title', 'Description' and 'Keyword' will properly handle the language prefix. If those attributes don't carry a language prefix, the prefix 'xx' will be assigned.

Notatka: The 'Name' attribute is somewhat special. In some cases it cannot be complete removed. You will get an error message 'Change of base attribute' (not clear when this happens). Therefore you will always have to add a new Name first and than remove the old one.

Notatka: You may not suround this function by calls to hw_getandlock() and hw_unlock(). hw_modifyobject() does this internally.

Returns TRUE if no error occurs otherwise FALSE.

hw_New_Document

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_New_Document -- create new document

Description

int hw_new_document ( string object_record, string document_data, int document_size)

Returns a new Hyperwave document with document data set to document_data and object record set to object_record. The length of the document_data has to passed in document_sizeThis function does not insert the document into the Hyperwave server.

See also hw_free_document(), hw_document_size(), hw_document_bodytag(), hw_output_document(), and hw_insertdocument().

hw_Objrec2Array

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_Objrec2Array -- convert attributes from object record to object array

Description

array hw_objrec2array ( string object_record [, array format])

Converts an object_record into an object array. The keys of the resulting array are the attributes names. Multi-value attributes like 'Title' in different languages form its own array. The keys of this array are the left part to the colon of the attribute value. This left part must be two characters long. Other multi-value attributes without a prefix form an indexed array. If the optional parameter is missing the attributes 'Title', 'Description' and 'Keyword' are treated as language attributes and the attributes 'Group', 'Parent' and 'HtmlAttr' as non-prefixed multi-value attributes. By passing an array holding the type for each attribute you can alter this behaviour. The array is an associated array with the attribute name as its key and the value being one of HW_ATTR_LANG or HW_ATTR_NONE

See also hw_array2objrec().

hw_Output_Document

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_Output_Document -- prints hw_document

Description

int hw_output_document ( int hw_document)

Prints the document without the BODY tag.

For backward compatibility, hw_outputdocument() is also accepted. This is deprecated, however.

hw_pConnect

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_pConnect -- make a persistent database connection

Description

int hw_pconnect ( string host, int port, string username, string password)

Returns a connection index on success, or FALSE if the connection could not be made. Opens a persistent connection to a Hyperwave server. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple persistent connections open at once.

See also hw_connect().

hw_PipeDocument

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_PipeDocument -- retrieve any document

Description

int hw_pipedocument ( int connection, int objectID)

Returns the Hyperwave document with object ID objectID. If the document has anchors which can be inserted, they will have been inserted already. The document will be transfered via a special data connection which does not block the control connection.

See also hw_gettext() for more on link insertion, hw_free_document(), hw_document_size(), hw_document_bodytag(), and hw_output_document().

hw_Root

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_Root -- root object id

Description

int hw_root ( )

Returns the object ID of the hyperroot collection. Currently this is always 0. The child collection of the hyperroot is the root collection of the connected server.

hw_Unlock

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_Unlock -- unlock object

Description

int hw_unlock ( int connection, int objectID)

Unlocks a document, so other users regain access.

See also hw_getandlock().

hw_Who

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_Who -- List of currently logged in users

Description

int hw_who ( int connection)

Returns an array of users currently logged into the Hyperwave server. Each entry in this array is an array itself containing the elements id, name, system, onSinceDate, onSinceTime, TotalTime and self. 'self' is 1 if this entry belongs to the user who initianted the request.

hw_getusername

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_getusername -- name of currently logged in user

Description

string hw_getusername ( int connection)

Returns the username of the connection.

hw_stat

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_stat --  Returns status string

Description

string hw_stat ( int link)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

hw_setlinkroot

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_setlinkroot --  Set the id to which links are calculated

Description

void hw_setlinkroot ( int link, int rootid)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

hw_connection_info

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_connection_info --  Prints information about the connection to Hyperwave server

Description

void hw_connection_info ( int link)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

hw_dummy

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_dummy --  Hyperwave dummy function

Description

string hw_dummy ( int link, int id, int msgid)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

hw_insertanchors

(PHP 4 >= 4.0.4)

hw_insertanchors --  Inserts only anchors into text

Description

string hw_insertanchors ( int hwdoc, array anchorecs, array dest [, array urlprefixes])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

hw_getrellink

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_getrellink --  Get link from source to dest relative to rootid

Description

string hw_getrellink ( int link, int rootid, int sourceid, int destid)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

hw_changeobject

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

hw_changeobject --  Changes attributes of an object (obsolete)

Description

void hw_changeobject ( int link, int objid, array attributes)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

XXXIX. ICAP Functions [deprecated]

To get these functions to work, you have to compile PHP with --with-icap. That requires the icap library to be installed, which is not longer supported and available.

Notatka: Icap will be removed in near future. Neither this module, nor those versions of icap library are supported any longer. If you want to use calendar capabilities in php, use mcal instead.

Spis treści
icap_open -- Opens up an ICAP connection
icap_close -- Close an ICAP stream
icap_fetch_event -- Fetches an event from the calendar stream/
icap_list_events --  Return a list of events between two given datetimes
icap_store_event -- Store an event into an ICAP calendar
icap_delete_event -- Delete an event from an ICAP calendar
icap_snooze -- Snooze an alarm
icap_list_alarms --  Return a list of events that has an alarm triggered at the given datetime
icap_create_calendar --  Create a new calendar
icap_rename_calendar --  Rename a calendar
icap_delete_calendar --  Delete a calendar
icap_reopen --  Reopen ICAP stream to new calendar

icap_open

(PHP 4 >= 4.0.0)

icap_open -- Opens up an ICAP connection

Description

stream icap_open ( string calendar, string username, string password, string options)

Returns an ICAP stream on success, FALSE on error.

icap_open() opens up an ICAP connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also.

icap_close

(unknown)

icap_close -- Close an ICAP stream

Description

int icap_close ( int icap_stream [, int flags])

Closes the given icap stream.

icap_fetch_event

(PHP 4 >= 4.0.0)

icap_fetch_event -- Fetches an event from the calendar stream/

Description

int icap_fetch_event ( int stream_id, int event_id [, int options])

icap_fetch_event() fetches an event from the calendar stream specified by event_id.

Returns an event object consisting of:

  • int id - ID of that event.

  • int public - TRUE if the event if public, FALSE if it is private.

  • string category - Category string of the event.

  • string title - Title string of the event.

  • string description - Description string of the event.

  • int alarm - number of minutes before the event to send an alarm/reminder.

  • object start - Object containing a datetime entry.

  • object end - Object containing a datetime entry.

All datetime entries consist of an object that contains:

  • int year - year

  • int month - month

  • int mday - day of month

  • int hour - hour

  • int min - minutes

  • int sec - seconds

icap_list_events

(PHP 4 >= 4.0.0)

icap_list_events --  Return a list of events between two given datetimes

Description

array icap_list_events ( int stream_id, int begin_date [, int end_date])

Returns an array of event ID's that are between the two given datetimes.

icap_list_events() function takes in a beginning datetime and an end datetime for a calendar stream. An array of event id's that are between the given datetimes are returned.

All datetime entries consist of an object that contains:

  • int year - year

  • int month - month

  • int mday - day of month

  • int hour - hour

  • int min - minutes

  • int sec - seconds

icap_store_event

(PHP 4 >= 4.0.0)

icap_store_event -- Store an event into an ICAP calendar

Description

string icap_store_event ( int stream_id, object event)

icap_store_event() Stores an event into an ICAP calendar. An event object consists of:

  • int public - 1 if public, 0 if private;

  • string category - Category string of the event.

  • string title - Title string of the event.

  • string description - Description string of the event.

  • int alarm - Number of minutes before the event to sned out an alarm.

  • datetime start - datetime object of the start of the event.

  • datetime end - datetime object of the end of the event.

All datetime entries consist of an object that contains:

  • int year - year

  • int month - month

  • int mday - day of month

  • int hour - hour

  • int min - minutes

  • int sec - seconds

Returns TRUE on success and FALSE on error.

icap_delete_event

(PHP 4 >= 4.0.0)

icap_delete_event -- Delete an event from an ICAP calendar

Description

string icap_delete_event ( int stream_id, int uid)

icap_delete_event() deletes the calendar event specified by the uid.

Returns TRUE.

icap_snooze

(PHP 4 >= 4.0.0)

icap_snooze -- Snooze an alarm

Description

string icap_snooze ( int stream_id, int uid)

icap_snooze() turns on an alarm for a calendar event specified by the uid.

Returns TRUE.

icap_list_alarms

(PHP 4 >= 4.0.0)

icap_list_alarms --  Return a list of events that has an alarm triggered at the given datetime

Description

int icap_list_alarms ( int stream_id, array date, array time)

Returns an array of event ID's that has an alarm going off at the given datetime.

icap_list_alarms() function takes in a datetime for a calendar stream. An array of event id's that has an alarm should be going off at the datetime are returned.

All datetime entries consist of an object that contains:

  • int year - year

  • int month - month

  • int mday - day of month

  • int hour - hour

  • int min - minutes

  • int sec - seconds

icap_create_calendar

(PHP 4 >= 4.0.0)

icap_create_calendar --  Create a new calendar

Description

string icap_create_calendar ( int stream_id, string calendar)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

icap_rename_calendar

(PHP 4 >= 4.0.0)

icap_rename_calendar --  Rename a calendar

Description

string icap_rename_calendar ( int stream_id, string old_name, string new_name)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

icap_delete_calendar

(PHP 4 >= 4.0.0)

icap_delete_calendar --  Delete a calendar

Description

string icap_delete_calendar ( int stream_id, string calendar)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

icap_reopen

(PHP 4 >= 4.0.0)

icap_reopen --  Reopen ICAP stream to new calendar

Description

int icap_reopen ( int stream_id, string calendar [, int options])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

XL. iconv

Ten moduł zawiera interferjs do korzystania z funkcji biblioteki iconv. Aby móc używać funkcji opisanych w tym module, trzeba skompilować interpreter PHP z opcją --with-iconv. Należy przy tym dysponować funkcją iconv() w standardowej bibliotece C lub mieć zainstalowaną w systemie bibliotekę libiconv. Biblioteka libiconv jest dostępna pod adresem http://www.gnu.org/software/libiconv/.

Funkcja biblioteki iconv służy do konwersji plików pomiędzy różnymi zestawami znaków. Od implementacji iconv() w twoim systemie zależy, jakie zestawy znaków funkcja będzie obsługiwać. Proszę pamiętać, że funkcja iconv()w niektórych systemach nie działa zgodnie z oczekiwaniami. Należy wtedy zainstalować bibliotekę libiconv, aby usunąć ten problem.

Spis treści
iconv -- Konwertuje łańcuch znaków do innego zestawu znaków
iconv_get_encoding --  Pobiera aktualne ustawienia dla konwersji zestawu znaków
iconv_set_encoding --  Ustawia aktualne ustawienia dla konwersji zestawu znaków
ob_iconv_handler --  Konwertuje kodowanie znaków jako uchwyt buforu wyjścia

iconv

(PHP 4 >= 4.0.5)

iconv -- Konwertuje łańcuch znaków do innego zestawu znaków

Opis

string iconv ( string zestaw_wejściowy, string zestaw_docelowy, string łańcuch)

Konwertuje łańcuch znaków łańcuch, zakodowany w zestaw_wejściowy na łańcuch znaków zakodowany w zestaw_docelowy. Zwraca skonwertowany łańcuch lub FALSE, jeśli konwersja się nie uda.

Przykład 1. przykład iconv():

echo iconv("ISO-8859-1","UTF-8","To jest test.");
echo iconv("ISO-8859-2","UTF-8","Zażółć gęślą jaźń");

iconv_get_encoding

(PHP 4 >= 4.0.5)

iconv_get_encoding --  Pobiera aktualne ustawienia dla konwersji zestawu znaków

Opis

array iconv_get_encoding ( [string typ])

Zwraca aktualne ustawienia funkcji ob_iconv_handler() jako tablicę, lub FALSE jeśli się nie uda.

Zobacz też: iconv_set_encoding() i ob_iconv_handler().

iconv_set_encoding

(PHP 4 >= 4.0.5)

iconv_set_encoding --  Ustawia aktualne ustawienia dla konwersji zestawu znaków

Opis

array iconv_set_encoding ( string typ, string zestaw_znaków)

Zmienia wartość zmiennej typ na zestaw_znaków i zwraca TRUE jeśli zmiana się powiedzie, lub FALSE w przeciwnym razie.

Przykład 1. przykład iconv_set_encoding():

iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");

Zobacz też: iconv_get_encoding() i ob_iconv_handler().

ob_iconv_handler

(PHP 4 >= 4.0.5)

ob_iconv_handler --  Konwertuje kodowanie znaków jako uchwyt buforu wyjścia

Opis

array ob_iconv_handler ( string zawartość, int status)

Konwertuje łańcuch zapisany w internal_encoding do output_encoding.

internal_encoding i output_encoding powinny zostać zdefiniowane przez iconv_set_encoding() lub w pliku konfiguracyjnym.

Przykład 1. przykład ob_iconv_handler():

ob_start("ob_iconv_handler"); // rozpocznij buforowanie wyjścia

Zobacz też: iconv_get_encoding() i iconv_set_encoding().

XLI. Image functions

You can use the image functions in PHP to get the size of JPEG, GIF, PNG, and SWF images, and if you have the GD library (available at http://www.boutell.com/gd/) you will also be able to create and manipulate images.

The format of images you are able to manipulate depend on the version of gd you install, and any other libraries gd might need to access those image formats. Versions of gd older than gd-1.6 support gif format images, and do not support png, where versions greater than gd-1.6 support png, not gif.

In order to read and write images in jpeg format, you will need to obtain and install jpeg-6b (available at ftp://ftp.uu.net/graphics/jpeg/), and then recompile gd to make use of jpeg-6b. You will also have to compile PHP with --with-jpeg-dir=/path/to/jpeg-6b.

To add support for Type 1 fonts, you can install t1lib (available at ftp://sunsite.unc.edu/pub/Linux/libs/graphics/), and then add --with-t1lib[=dir].

Spis treści
GetImageSize -- Get the size of an image
Image2WBMP -- Output image to browser or file
ImageAlphaBlending -- Set the blending mode for an image
ImageArc -- Draw a partial ellipse
ImageFilledArc -- Draw a partial ellipse and fill it
ImageEllipse -- Draw an ellipse
ImageFilledEllipse -- Draw a filled ellipse
ImageChar -- Draw a character horizontally
ImageCharUp -- Draw a character vertically
ImageColorAllocate -- Allocate a color for an image
ImageColorDeAllocate --  De-allocate a color for an image
ImageColorAt -- Get the index of the color of a pixel
ImageColorClosest --  Get the index of the closest color to the specified color
ImageColorClosestAlpha --  Get the index of the closest color to the specified color + alpha
ImageColorClosestThwb --  Get the index of the color which has the hue, white and blackness nearest to the given color
ImageColorExact -- Get the index of the specified color
ImageColorExactAlpha -- Get the index of the specified color + alpha
ImageColorResolve --  Get the index of the specified color or its closest possible alternative
ImageColorResolveAlpha --  Get the index of the specified color + alpha or its closest possible alternative
ImageGammaCorrect --  Apply a gamma correction to a GD image
ImageColorSet --  Set the color for the specified palette index
ImageColorsForIndex -- Get the colors for an index
ImageColorsTotal --  Find out the number of colors in an image's palette
ImageColorTransparent -- Define a color as transparent
ImageCopy --  Copy part of an image
ImageCopyMerge --  Copy and merge part of an image
ImageCopyMergeGray --  Copy and merge part of an image with gray scale
ImageCopyResized -- Copy and resize part of an image
ImageCopyResampled -- Copy and resize part of an image with resampling
ImageCreate -- Create a new palette based image
ImageCreateTrueColor -- Create a new TRUE color image
ImageTrueColorToPalette -- Convert a TRUE color image to a palette image
ImageCreateFromGD --  Create a new image from GD file or URL
ImageCreateFromGD2 --  Create a new image from GD2 file or URL
ImageCreateFromGD2Part --  Create a new image from a given part of GD2 file or URL
ImageCreateFromGIF -- Create a new image from file or URL
ImageCreateFromJPEG -- Create a new image from file or URL
ImageCreateFromPNG -- Create a new image from file or URL
ImageCreateFromWBMP -- Create a new image from file or URL
ImageCreateFromString -- Create a new image from the image stream in the string
ImageCreateFromXBM -- Create a new image from file or URL
ImageCreateFromXPM -- Create a new image from file or URL
ImageDashedLine -- Draw a dashed line
ImageDestroy -- Destroy an image
ImageFill -- Flood fill
ImageFilledPolygon -- Draw a filled polygon
ImageFilledRectangle -- Draw a filled rectangle
ImageFillToBorder -- Flood fill to specific color
ImageFontHeight -- Get font height
ImageFontWidth -- Get font width
ImageGD --  Output GD image to browser or file
ImageGD2 --  Output GD2 image to browser or file
ImageGIF -- Output image to browser or file
ImagePNG --  Output a PNG image to either the browser or a file
ImageJPEG -- Output image to browser or file
ImageWBMP -- Output image to browser or file
ImageInterlace -- Enable or disable interlace
ImageLine -- Draw a line
ImageLoadFont -- Load a new font
ImagePaletteCopy -- Copy the palette from one image to another
ImagePolygon -- Draw a polygon
ImagePSBBox --  Give the bounding box of a text rectangle using PostScript Type1 fonts
ImagePSEncodeFont --  Change the character encoding vector of a font
ImagePSFreeFont -- Free memory used by a PostScript Type 1 font
ImagePSLoadFont -- Load a PostScript Type 1 font from file
ImagePsExtendFont --  Extend or condense a font
ImagePsSlantFont --  Slant a font
ImagePSText --  To draw a text string over an image using PostScript Type1 fonts
ImageRectangle -- Draw a rectangle
ImageSetPixel -- Set a single pixel
ImageSetBrush -- Set the brush image for line drawing
ImageSetStyle -- Set the style for line drawing
ImageSetTile -- Set the tile image for filling
ImageSetThickness -- Set the thickness for line drawing
ImageString -- Draw a string horizontally
ImageStringUp -- Draw a string vertically
ImageSX -- Get image width
ImageSY -- Get image height
ImageTTFBBox --  Give the bounding box of a text using TrueType fonts
ImageFtBBox --  Give the bounding box of a text using fonts via freetype2
ImageTTFText --  Write text to the image using TrueType fonts
ImageFtText --  Write text to the image using fonts using FreeType 2
ImageTypes --  Return the image types supported by this PHP build
JPEG2WBMP --  Convert JPEG image file to WBMP image file
PNG2WBMP --  Convert PNG image file to WBMP image file
read_exif_data -- Read the EXIF headers from a JPEG
iptcembed --  Embed binary IPTC data into a JPEG image.

GetImageSize

(PHP 3, PHP 4 >= 4.0.0)

GetImageSize -- Get the size of an image

Description

array getimagesize ( string filename [, array imageinfo])

The GetImageSize() function will determine the size of any GIF, JPG, PNG, SWF, PSD or BMP image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML IMG tag.

Returns an array with 4 elements. Index 0 contains the width of the image in pixels. Index 1 contains the height. Index 2 a flag indicating the type of the image. 1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP. Index 3 is a text string with the correct "height=xxx width=xxx" string that can be used directly in an IMG tag.

Przykład 1. GetImageSize (file)

<?php $size = GetImageSize ("img/flag.jpg"); ?>
<IMG SRC="img/flag.jpg" <?php echo $size[3]; ?>

Przykład 2. GetImageSize (URL)

<?php $size = GetImageSize ("http://www.php.net/gifs/logo.gif"); ?>

With JPG images, two extras index are returned : channel and bits. channel will be 3 for RGB pictures, and 4 for CMYK pictures. bits is the number of bits for each color.

If accessing the filename image is impossible, or if it isn't a valid picture, getimagesize() will return NULL and generate a warning.

The optional imageinfo parameter allows you to extract some extended information from the image file. Currently this will return the different JPG APP markers in an associative Array. Some Programs use these APP markers to embedd text information in images. A very common one in to embed IPTC http://www.iptc.org/ information in the APP13 marker. You can use the iptcparse() function to parse the binary APP13 marker into something readable.

Przykład 3. GetImageSize returning IPTC

<?php
    $size = GetImageSize ("testimg.jpg",&$info);
    if (isset ($info["APP13"])) {
        $iptc = iptcparse ($info["APP13"]);
        var_dump ($iptc);
    }
?>

Notatka: This function does not require the GD image library.

Notatka: URL support was added in PHP 4.0.5

Image2WBMP

(PHP 4 >= 4.0.5)

Image2WBMP -- Output image to browser or file

Description

int image2WBMP ( int im [, string filename [, int threshold]])

Image2WBMP() creates the WBMP file in filename from the image im. The im argument is the return from ImageCreate().

The filename argument is optional, and if left off, the raw image stream will be output directly. By sending an image/vnd.wap.wbmp content-type using header(), you can create a PHP script that outputs WBMP images directly.

Notatka: WBMP support is only available if PHP was compiled against GD-1.8 or later.

See also ImageWBMP().

ImageAlphaBlending

(PHP 4 >= 4.0.6)

ImageAlphaBlending -- Set the blending mode for an image

Description

int imagealphablending ( resource im, bool blendmode)

ImageAlphaBlending() allows for two different modes of drawing on truecolor images. In blending mode, the alpha channel component of the color supplied to all drawing function, such as ImageSetPixel() determines how much of the underlying color should be allowed to shine through. As a result, gd automatically blends the existing color at that point with the drawing color, and stores the result in the image. The resulting pixel is opaque. In non-blending mode, the drawing color is copied literally with its alpha channel information, replacing the destination pixel. Blending mode is not available when drawing on palette images. If blendmode is TRUE, then blending mode is enabled, otherwise disabled.

Notatka: This function was added in PHP 4.0.6 and requires GD 2.0.1

ImageArc

(PHP 3, PHP 4 >= 4.0.0)

ImageArc -- Draw a partial ellipse

Description

int imagearc ( int im, int cx, int cy, int w, int h, int s, int e, int col)

ImageArc() draws a partial ellipse centered at cx, cy (top left is 0, 0) in the image represented by im. W and h specifies the ellipse's width and height respectively while the start and end points are specified in degrees indicated by the s and e arguments. 0° is located at the three-o'clock position, and the arc is drawn counter-clockwise.

See also ImageEllipse(), ImageFilledEllipse(), and ImageFilledArc().

ImageFilledArc

(PHP 4 >= 4.0.6)

ImageFilledArc -- Draw a partial ellipse and fill it

Description

int imagefilledarc ( int im, int cx, int cy, int w, int h, int s, int e, int col, int style)

ImageFilledArc() draws a partial ellipse centered at cx, cy (top left is 0, 0) in the image represented by im. W and h specifies the ellipse's width and height respectively while the start and end points are specified in degrees indicated by the s and e arguments. style is a bitwise OR of the following possibilities:

  1. IMG_ARC_PIE

  2. IMG_ARC_CHORD

  3. IMG_ARC_NOFILL

  4. IMG_ARC_EDGED

IMG_ARC_PIE and IMG_ARC_CHORD are mutually exclusive; IMG_ARC_CHORD just connects the starting and ending angles with a straight line, while IMG_ARC_PIE produces a rounded edge. IMG_ARC_NOFILL indicates that the arc or chord should be outlined, not filled. IMG_ARC_EDGED, used together with IMG_ARC_NOFILL, indicates that the beginning and ending angles should be connected to the center - this is a good way to outline (rather than fill) a 'pie slice'.

Notatka: This function was added in PHP 4.0.6 and requires GD 2.0.1

ImageEllipse

(PHP 4 >= 4.0.6)

ImageEllipse -- Draw an ellipse

Description

int imageellipse ( resource im, int cx, int cy, int w, int h, int col)

ImageEllipse() draws an ellipse centered at cx, cy (top left is 0, 0) in the image represented by im. W and h specifies the ellipse's width and height respectively. The color of the ellipse is specified by color.

Notatka: This function was added in PHP 4.0.6 and requires GD 2.0.2 or later

See also ImageArc().

ImageFilledEllipse

(PHP 4 >= 4.0.6)

ImageFilledEllipse -- Draw a filled ellipse

Description

int imagefilledellipse ( resource im, int cx, int cy, int w, int h, int col)

ImageFilledEllipse() draws an ellipse centered at cx, cy (top left is 0, 0) in the image represented by im. W and h specifies the ellipse's width and height respectively. The ellipse is filled using color

Notatka: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

See also ImageFilledArc().

ImageChar

(PHP 3, PHP 4 >= 4.0.0)

ImageChar -- Draw a character horizontally

Description

int imagechar ( int im, int font, int x, int y, string c, int col)

ImageChar() draws the first character of c in the image identified by id with its upper-left at x,y (top left is 0, 0) with the color col. If font is 1, 2, 3, 4 or 5, a built-in font is used (with higher numbers corresponding to larger fonts).

See also imageloadfont().

ImageCharUp

(PHP 3, PHP 4 >= 4.0.0)

ImageCharUp -- Draw a character vertically

Description

int imagecharup ( int im, int font, int x, int y, string c, int col)

ImageCharUp() draws the character c vertically in the image identified by im at coordinates x, y (top left is 0, 0) with the color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.

See also imageloadfont().

ImageColorAllocate

(PHP 3, PHP 4 >= 4.0.0)

ImageColorAllocate -- Allocate a color for an image

Description

int imagecolorallocate ( int im, int red, int green, int blue)

ImageColorAllocate() returns a color identifier representing the color composed of the given RGB components. The im argument is the return from the imagecreate() function. Red, green and blue are the values of the red, green and blue component of the requested color respectively. These parameters are integers between 0 and 255. ImageColorAllocate() must be called to create each color that is to be used in the image represented by im.

$white = ImageColorAllocate ($im, 255, 255, 255);
$black = ImageColorAllocate ($im, 0, 0, 0);

Returns -1 if the allocation failed.

ImageColorDeAllocate

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

ImageColorDeAllocate --  De-allocate a color for an image

Description

int imagecolordeallocate ( int im, int index)

The ImageColorDeAllocate() function de-allocates a color previously allocated with the ImageColorAllocate() function.

$white = ImageColorAllocate($im, 255, 255, 255);
ImageColorDeAllocate($im, $white);

ImageColorAt

(PHP 3, PHP 4 >= 4.0.0)

ImageColorAt -- Get the index of the color of a pixel

Description

int imagecolorat ( int im, int x, int y)

Returns the index of the color of the pixel at the specified location in the image.

See also imagecolorset() and imagecolorsforindex().

ImageColorClosest

(PHP 3, PHP 4 >= 4.0.0)

ImageColorClosest --  Get the index of the closest color to the specified color

Description

int imagecolorclosest ( int im, int red, int green, int blue)

Returns the index of the color in the palette of the image which is "closest" to the specified RGB value.

The "distance" between the desired color and each color in the palette is calculated as if the RGB values represented points in three-dimensional space.

See also imagecolorexact().

ImageColorClosestAlpha

(PHP 4 >= 4.0.6)

ImageColorClosestAlpha --  Get the index of the closest color to the specified color + alpha

Description

int imagecolorclosestalpha ( resource im, int red, int green, int blue, int alpha)

Returns the index of the color in the palette of the image which is "closest" to the specified RGB value and alpha level.

See also imagecolorexactalpha().

Notatka: This function was added in PHP 4.0.6 and requires GD 2.0.1

ImageColorClosestThwb

(unknown)

ImageColorClosestThwb --  Get the index of the color which has the hue, white and blackness nearest to the given color

Description

int imagecolorclosesthwb ( int im, int red, int green, int blue)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ImageColorExact

(PHP 3, PHP 4 >= 4.0.0)

ImageColorExact -- Get the index of the specified color

Description

int imagecolorexact ( int im, int red, int green, int blue)

Returns the index of the specified color in the palette of the image.

If the color does not exist in the image's palette, -1 is returned.

See also imagecolorclosest().

ImageColorExactAlpha

(PHP 4 >= 4.0.6)

ImageColorExactAlpha -- Get the index of the specified color + alpha

Description

int imagecolorexactalpha ( resource im, int red, int green, int blue, int alpha)

Returns the index of the specified color+alpha in the palette of the image.

If the color does not exist in the image's palette, -1 is returned.

See also imagecolorclosestalpha().

Notatka: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

ImageColorResolve

(PHP 3>= 3.0.2, PHP 4 >= 4.0.0)

ImageColorResolve --  Get the index of the specified color or its closest possible alternative

Description

int imagecolorresolve ( int im, int red, int green, int blue)

This function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.

See also imagecolorclosest().

ImageColorResolveAlpha

(PHP 4 >= 4.0.6)

ImageColorResolveAlpha --  Get the index of the specified color + alpha or its closest possible alternative

Description

int imagecolorresolvealpha ( resource im, int red, int green, int blue, int alpha)

This function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.

See also imagecolorclosestalpha().

Notatka: This function was added in PHP 4.0.6 and requires GD 2.0.1

ImageGammaCorrect

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ImageGammaCorrect --  Apply a gamma correction to a GD image

Description

int imagegammacorrect ( int im, float inputgamma, float outputgamma)

The ImageGammaCorrect() function applies gamma correction to a gd image stream (im) given an input gamma, the parameter inputgamma and an output gamma, the parameter outputgamma.

ImageColorSet

(PHP 3, PHP 4 >= 4.0.0)

ImageColorSet --  Set the color for the specified palette index

Description

bool imagecolorset ( int im, int index, int red, int green, int blue)

This sets the specified index in the palette to the specified color. This is useful for creating flood-fill-like effects in paletted images without the overhead of performing the actual flood-fill.

See also imagecolorat().

ImageColorsForIndex

(PHP 3, PHP 4 >= 4.0.0)

ImageColorsForIndex -- Get the colors for an index

Description

array imagecolorsforindex ( int im, int index)

This returns an associative array with red, green, and blue keys that contain the appropriate values for the specified color index.

See also imagecolorat() and imagecolorexact().

ImageColorsTotal

(PHP 3, PHP 4 >= 4.0.0)

ImageColorsTotal --  Find out the number of colors in an image's palette

Description

int imagecolorstotal ( int im)

This returns the number of colors in the specified image's palette.

See also imagecolorat() and imagecolorsforindex().

ImageColorTransparent

(PHP 3, PHP 4 >= 4.0.0)

ImageColorTransparent -- Define a color as transparent

Description

int imagecolortransparent ( int im [, int col])

ImageColorTransparent() sets the transparent color in the im image to col. im is the image identifier returned by ImageCreate() and col is a color identifier returned by ImageColorAllocate().

Notatka: The transparent color is a property of the image, transparency is not a property of the color. Once you have a set a color to be the transparent color, any regions of the image in that color that were drawn previously will be transparent.

The identifier of the new (or current, if none is specified) transparent color is returned.

ImageCopy

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

ImageCopy --  Copy part of an image

Description

int ImageCopy ( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h)

Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y.

ImageCopyMerge

(PHP 4 )

ImageCopyMerge --  Copy and merge part of an image

Description

int ImageCopyMerge ( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct)

Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y. The two images will be merged according to pct which can range from 0 to 100. When pct = 0, no action is taken, when 100 this function behaves identically to ImageCopy().

Notatka: This function was added in PHP 4.0.6

ImageCopyMergeGray

(PHP 4 >= 4.0.6)

ImageCopyMergeGray --  Copy and merge part of an image with gray scale

Description

int ImageCopyMergeGray ( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct)

ImageCopyMergeGray() copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y. The two images will be merged according to pct which can range from 0 to 100. When pct = 0, no action is taken, when 100 this function behaves identically to ImageCopy().

This function is identical to ImageCopyMerge() except that when merging it preservese the hue of the source by converting the destination pixels to gray scale before the copy operation.

Notatka: This function was added in PHP 4.0.6

ImageCopyResized

(PHP 3, PHP 4 >= 4.0.0)

ImageCopyResized -- Copy and resize part of an image

Description

int imagecopyresized ( resource dst_im, resource src_im, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH)

ImageCopyResized() copies a rectangular portion of one image to another image. Dst_im is the destination image, src_im is the source image identifier. If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_im is the same as src_im) but if the regions overlap the results will be unpredictable.

See also ImageCopyResampled().

ImageCopyResampled

(PHP 4 >= 4.0.6)

ImageCopyResampled -- Copy and resize part of an image with resampling

Description

int imagecopyresampled ( resource dst_im, resource src_im, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH)

ImageCopyResampled() copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity. Dst_im is the destination image, src_im is the source image identifier. If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_im is the same as src_im) but if the regions overlap the results will be unpredictable.

See also ImageCopyResized().

Notatka: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

ImageCreate

(PHP 3, PHP 4 >= 4.0.0)

ImageCreate -- Create a new palette based image

Description

int imagecreate ( int x_size, int y_size)

ImageCreate() returns an image identifier representing a blank image of size x_size by y_size.

Przykład 1. Creating a new GD image stream and outputting an image.

<?php
header ("Content-type: image/png");
$im = @ImageCreate (50, 100)
    or die ("Cannot Initialize new GD image stream");
$background_color = ImageColorAllocate ($im, 255, 255, 255);
$text_color = ImageColorAllocate ($im, 233, 14, 91);
ImageString ($im, 1, 5, 5,  "A Simple Text String", $text_color);
ImagePng ($im);
?>

ImageCreateTrueColor

(PHP 4 >= 4.0.6)

ImageCreateTrueColor -- Create a new TRUE color image

Description

resource imagecreatetruecolor ( int x_size, int y_size)

ImageCreateTrueColor() returns an image identifier representing a black image of size x_size by y_size.

Notatka: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

ImageTrueColorToPalette

(PHP 4 >= 4.0.6)

ImageTrueColorToPalette -- Convert a TRUE color image to a palette image

Description

void imagetruecolortopalette ( resource im, bool dither, int ncolors)

ImageTrueColorToPalette() converts a truecolor image to a palette image. The code for this function was originally drawn from the Independent JPEG Group library code, which is excellent. The code has been modified to preserve as much alpha channel information as possible in the resulting palette, in addition to preserving colors as well as possible. This does not work as well as might be hoped. It is usually best to simply produce a truecolor output image instead, which guarantees the highest output quality.

dither indicates if the image should be dithered - if it is TRUE then dithering will be used which will result in a more speckled image but with better color approximation.

ncolors sets the maximum number of colors that should be retained in the palette.

Notatka: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

ImageCreateFromGD

(PHP 4 >= 4.1.0)

ImageCreateFromGD --  Create a new image from GD file or URL

Description

int imagecreatefromgd ( string filename)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ImageCreateFromGD2

(PHP 4 >= 4.1.0)

ImageCreateFromGD2 --  Create a new image from GD2 file or URL

Description

int imagecreatefromgd2 ( string filename)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ImageCreateFromGD2Part

(PHP 4 >= 4.1.0)

ImageCreateFromGD2Part --  Create a new image from a given part of GD2 file or URL

Description

int imagecreatefromgd2part ( string filename, int srcX, int srcY, int width, int height)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ImageCreateFromGIF

(PHP 3, PHP 4 >= 4.0.0)

ImageCreateFromGIF -- Create a new image from file or URL

Description

int imagecreatefromgif ( string filename)

ImageCreateFromGif() returns an image identifier representing the image obtained from the given filename.

ImageCreateFromGif() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error GIF:

Przykład 1. Example to handle an error during creation (courtesy vic@zymsys.com)

function LoadGif ($imgname) {
    $im = @ImageCreateFromGIF ($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im = ImageCreate (150, 30); /* Create a blank image */
        $bgc = ImageColorAllocate ($im, 255, 255, 255);
        $tc  = ImageColorAllocate ($im, 0, 0, 0);
        ImageFilledRectangle ($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        ImageString($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}

Notatka: Since all GIF support was removed from the GD library in version 1.6, this function is not available if you are using that version of the GD library.

ImageCreateFromJPEG

(PHP 3>= 3.0.16, PHP 4 >= 4.0.0)

ImageCreateFromJPEG -- Create a new image from file or URL

Description

int imagecreatefromjpeg ( string filename)

ImageCreateFromJPEG() returns an image identifier representing the image obtained from the given filename.

ImagecreateFromJPEG() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error JPEG:

Przykład 1. Example to handle an error during creation (courtesy vic@zymsys.com )

function LoadJpeg ($imgname) {
    $im = @ImageCreateFromJPEG ($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im = ImageCreate (150, 30); /* Create a blank image */
        $bgc = ImageColorAllocate ($im, 255, 255, 255);
        $tc  = ImageColorAllocate ($im, 0, 0, 0);
        ImageFilledRectangle ($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        ImageString ($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}

ImageCreateFromPNG

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ImageCreateFromPNG -- Create a new image from file or URL

Description

int imagecreatefrompng ( string filename)

ImageCreateFromPNG() returns an image identifier representing the image obtained from the given filename.

ImageCreateFromPNG() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error PNG:

Przykład 1. Example to handle an error during creation (courtesy vic@zymsys.com)

function LoadPNG ($imgname) {
    $im = @ImageCreateFromPNG ($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im  = ImageCreate (150, 30); /* Create a blank image */
        $bgc = ImageColorAllocate ($im, 255, 255, 255);
        $tc  = ImageColorAllocate ($im, 0, 0, 0);
        ImageFilledRectangle ($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        ImageString ($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}

ImageCreateFromWBMP

(PHP 4 )

ImageCreateFromWBMP -- Create a new image from file or URL

Description

int imagecreatefromwbmp ( string filename)

ImageCreateFromWBMP() returns an image identifier representing the image obtained from the given filename.

ImageCreateFromWBMP() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error WBMP:

Przykład 1. Example to handle an error during creation (courtesy vic@zymsys.com)

function LoadWBMP ($imgname) {
    $im = @ImageCreateFromWBMP ($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im  = ImageCreate (20, 20); /* Create a blank image */
        $bgc = ImageColorAllocate ($im, 255, 255, 255);
        $tc  = ImageColorAllocate ($im, 0, 0, 0);
        ImageFilledRectangle ($im, 0, 0, 10, 10, $bgc);
        /* Output an errmsg */
        ImageString ($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}

Notatka: WBMP support is only available if PHP was compiled against GD-1.8 or later.

ImageCreateFromString

(PHP 4 >= 4.0.4)

ImageCreateFromString -- Create a new image from the image stream in the string

Description

int imagecreatefromstring ( string image)

ImageCreateFromString() returns an image identifier representing the image obtained from the given string.

ImageCreateFromXBM

(PHP 4 )

ImageCreateFromXBM -- Create a new image from file or URL

Description

int imagecreatefromxbm ( string filename)

ImageCreateFromXBM() returns an image identifier representing the image obtained from the given filename.

ImageCreateFromXPM

(PHP 4 )

ImageCreateFromXPM -- Create a new image from file or URL

Description

int imagecreatefromxpm ( string filename)

ImageCreateFromXPM() returns an image identifier representing the image obtained from the given filename.

ImageDashedLine

(PHP 3, PHP 4 >= 4.0.0)

ImageDashedLine -- Draw a dashed line

Description

int imagedashedline ( int im, int x1, int y1, int x2, int y2, int col)

This function is deprecated. Use combination of ImageSetStyle() and ImageLine() instead.

ImageDestroy

(PHP 3, PHP 4 >= 4.0.0)

ImageDestroy -- Destroy an image

Description

int imagedestroy ( int im)

ImageDestroy() frees any memory associated with image im. Im is the image identifier returned by the ImageCreate() function.

ImageFill

(PHP 3, PHP 4 >= 4.0.0)

ImageFill -- Flood fill

Description

int imagefill ( int im, int x, int y, int col)

ImageFill() performs a flood fill starting at coordinate x, y (top left is 0, 0) with color col in the image im.

ImageFilledPolygon

(PHP 3, PHP 4 >= 4.0.0)

ImageFilledPolygon -- Draw a filled polygon

Description

int imagefilledpolygon ( int im, array points, int num_points, int col)

ImageFilledPolygon() creates a filled polygon in image im. Points is a PHP array containing the polygon's vertices, ie. points[0] = x0, points[1] = y0, points[2] = x1, points[3] = y1, etc. Num_points is the total number of vertices.

ImageFilledRectangle

(PHP 3, PHP 4 >= 4.0.0)

ImageFilledRectangle -- Draw a filled rectangle

Description

int imagefilledrectangle ( int im, int x1, int y1, int x2, int y2, int col)

ImageFilledRectangle() creates a filled rectangle of color col in image im starting at upper left coordinates x1, y1 and ending at bottom right coordinates x2, y2. 0, 0 is the top left corner of the image.

ImageFillToBorder

(PHP 3, PHP 4 >= 4.0.0)

ImageFillToBorder -- Flood fill to specific color

Description

int imagefilltoborder ( int im, int x, int y, int border, int col)

ImageFillToBorder() performs a flood fill whose border color is defined by border. The starting point for the fill is x, y (top left is 0, 0) and the region is filled with color col.

ImageFontHeight

(PHP 3, PHP 4 >= 4.0.0)

ImageFontHeight -- Get font height

Description

int imagefontheight ( int font)

Returns the pixel height of a character in the specified font.

See also ImageFontWidth() and ImageLoadFont().

ImageFontWidth

(PHP 3, PHP 4 >= 4.0.0)

ImageFontWidth -- Get font width

Description

int imagefontwidth ( int font)

Returns the pixel width of a character in font.

See also ImageFontHeight() and ImageLoadFont().

ImageGD

(PHP 4 >= 4.1.0)

ImageGD --  Output GD image to browser or file

Description

int imagegd ( int im [, string filename])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ImageGD2

(PHP 4 >= 4.1.0)

ImageGD2 --  Output GD2 image to browser or file

Description

int imagegd2 ( int im [, string filename])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ImageGIF

(PHP 3, PHP 4 >= 4.0.0)

ImageGIF -- Output image to browser or file

Description

int imagegif ( int im [, string filename])

ImageGIF() creates the GIF file in filename from the image im. The im argument is the return from the imagecreate() function.

The image format will be GIF87a unless the image has been made transparent with ImageColorTransparent(), in which case the image format will be GIF89a.

The filename argument is optional, and if left off, the raw image stream will be output directly. By sending an image/gif content-type using header(), you can create a PHP script that outputs GIF images directly.

Notatka: Since all GIF support was removed from the GD library in version 1.6, this function is not available if you are using that version of the GD library.

The following code snippet allows you to write more portable PHP applications by auto-detecting the type of GD support which is available. Replace the sequence Header("Content-type: image/gif"); ImageGIF($im); by the more flexible sequence:

<?php
  if (function_exists("imagegif")) {
    Header("Content-type: image/gif");
    ImageGIF($im);
  }
  elseif (function_exists("imagejpeg")) {
    Header("Content-type: image/jpeg");
    ImageJPEG($im, "", 0.5);
  }
  elseif (function_exists("imagepng")) {
    Header("Content-type: image/png");
    ImagePNG($im);
  }
  elseif (function_exists("imagewbmp")) {
    Header("Content-type: image/vnd.wap.wbmp");
    ImageWBMP($im);
  }
  else
    die("No image support in this PHP server");
?>

Notatka: As of version 3.0.18 and 4.0.2 you can use the function imagetypes() in place of function_exists() for checking the presence of the various supported image formats:

if (ImageTypes() & IMG_GIF) {
    Header("Content-type: image/gif");
    ImageGif($im);
}
elseif (ImageTypes() & IMG_JPG) {
        ... etc.

See also ImagePNG(), ImageWBMP(), ImageJPEG(), ImageTypes().

ImagePNG

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

ImagePNG --  Output a PNG image to either the browser or a file

Description

int imagepng ( int im [, string filename])

The ImagePNG() outputs a GD image stream (im) in PNG format to standard output (usually the browser) or, if a filename is given by the filename it outputs the image to the file.

<?php
$im = ImageCreateFromPng("test.png");
ImagePng($im);
?>

See also ImageGIF(), ImageWBMP(), ImageJPEG(), ImageTypes().

ImageJPEG

(PHP 3>= 3.0.16, PHP 4 >= 4.0.0)

ImageJPEG -- Output image to browser or file

Description

int imagejpeg ( int im [, string filename [, int quality]])

ImageJPEG() creates the JPEG file in filename from the image im. The im argument is the return from the ImageCreate() function.

The filename argument is optional, and if left off, the raw image stream will be output directly. To skip the filename argument in order to provide a quality argument just use an empty string (''). By sending an image/jpeg content-type using header(), you can create a PHP script that outputs JPEG images directly.

Notatka: JPEG support is only available if PHP was compiled against GD-1.8 or later.

quality is optional, and ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75).

If you want to output Progressive JPEGs, you need to set interlacing on with ImageInterlace().

See also ImagePNG(), ImageGIF(), ImageWBMP(), ImageInterlace() and ImageTypes().

ImageWBMP

(PHP 3>= 3.0.15, PHP 4 )

ImageWBMP -- Output image to browser or file

Description

int imageWBMP ( int im [, string filename [, int foreground]])

ImageWBMP() creates the WBMP file in filename from the image im. The im argument is the return from the ImageCreate() function.

The filename argument is optional, and if left off, the raw image stream will be output directly. By sending an image/vnd.wap.wbmp content-type using header(), you can create a PHP script that outputs WBMP images directly.

Notatka: WBMP support is only available if PHP was compiled against GD-1.8 or later.

Using the optional foreground parameter, you can set the foreground color. Use an identifier obtained from imagecolorallocate(). The default foreground color is black.

See also image2WBMP(), ImagePNG(), ImageGIF(), ImageJPEG(), ImageTypes().

ImageInterlace

(PHP 3, PHP 4 >= 4.0.0)

ImageInterlace -- Enable or disable interlace

Description

int imageinterlace ( int im [, int interlace])

ImageInterlace() turns the interlace bit on or off. If interlace is 1 the im image will be interlaced, and if interlace is 0 the interlace bit is turned off.

If the interlace bit is set and the image is used as a JPEG image, the image is created as a progressive JPEG.

This function returns whether the interlace bit is set for the image.

ImageLine

(PHP 3, PHP 4 >= 4.0.0)

ImageLine -- Draw a line

Description

int imageline ( int im, int x1, int y1, int x2, int y2, int col)

ImageLine() draws a line from x1, y1 to x2, y2 (top left is 0, 0) in image im of color col.

See also ImageCreate() and ImageColorAllocate().

ImageLoadFont

(PHP 3, PHP 4 >= 4.0.0)

ImageLoadFont -- Load a new font

Description

int imageloadfont ( string file)

ImageLoadFont() loads a user-defined bitmap font and returns an identifier for the font (that is always greater than 5, so it will not conflict with the built-in fonts).

The font file format is currently binary and architecture dependent. This means you should generate the font files on the same type of CPU as the machine you are running PHP on.

Tabela 1. Font file format

byte positionC data typedescription
byte 0-3intnumber of characters in the font
byte 4-7int value of first character in the font (often 32 for space)
byte 8-11intpixel width of each character
byte 12-15intpixel height of each character
byte 16-char array with character data, one byte per pixel in each character, for a total of (nchars*width*height) bytes.

See also ImageFontWidth() and ImageFontHeight().

ImagePaletteCopy

(PHP 4 )

ImagePaletteCopy -- Copy the palette from one image to another

Description

int imagepalettecopy ( resource destination, resource source)

imagepalettecopy() copies the palette from the source image to the destination image.

ImagePolygon

(PHP 3, PHP 4 >= 4.0.0)

ImagePolygon -- Draw a polygon

Description

int imagepolygon ( int im, array points, int num_points, int col)

ImagePolygon() creates a polygon in image id. Points is a PHP array containing the polygon's vertices, ie. points[0] = x0, points[1] = y0, points[2] = x1, points[3] = y1, etc. Num_points is the total number of vertices.

See also imagecreate().

ImagePSBBox

(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)

ImagePSBBox --  Give the bounding box of a text rectangle using PostScript Type1 fonts

Description

array imagepsbbox ( string text, int font, int size [, int space [, int tightness [, float angle]]])

Size is expressed in pixels.

Space allows you to change the default value of a space in a font. This amount is added to the normal value and can also be negative.

Tightness allows you to control the amount of white space between characters. This amount is added to the normal character width and can also be negative.

Angle is in degrees.

Parameters space and tightness are expressed in character space units, where 1 unit is 1/1000th of an em-square.

Parameters space, tightness, and angle are optional.

The bounding box is calculated using information available from character metrics, and unfortunately tends to differ slightly from the results achieved by actually rasterizing the text. If the angle is 0 degrees, you can expect the text to need 1 pixel more to every direction.

This function returns an array containing the following elements:

0lower left x-coordinate
1lower left y-coordinate
2upper right x-coordinate
3upper right y-coordinate

See also imagepstext().

ImagePSEncodeFont

(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)

ImagePSEncodeFont --  Change the character encoding vector of a font

Description

int imagepsencodefont ( int font_index, string encodingfile)

Loads a character encoding vector from from a file and changes the fonts encoding vector to it. As a PostScript fonts default vector lacks most of the character positions above 127, you'll definitely want to change this if you use an other language than english. The exact format of this file is described in T1libs documentation. T1lib comes with two ready-to-use files, IsoLatin1.enc and IsoLatin2.enc.

If you find yourself using this function all the time, a much better way to define the encoding is to set ps.default_encoding in the configuration file to point to the right encoding file and all fonts you load will automatically have the right encoding.

ImagePSFreeFont

(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)

ImagePSFreeFont -- Free memory used by a PostScript Type 1 font

Description

void imagepsfreefont ( int fontindex)

See also ImagePSLoadFont().

ImagePSLoadFont

(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)

ImagePSLoadFont -- Load a PostScript Type 1 font from file

Description

int imagepsloadfont ( string filename)

In the case everything went right, a valid font index will be returned and can be used for further purposes. Otherwise the function returns FALSE and prints a message describing what went wrong, which you cannot read directly, while the output type is image.

<?php
Header ("Content-type: image/jpeg");
$im = ImageCreate (350, 45);
$black = ImageColorAllocate ($im, 0, 0, 0);
$white = ImageColorAllocate ($im, 255, 255, 255);
$font=ImagePsLoadFont("bchbi.pfb");
// or locate your .pfb files on your machine
ImagePsText($im, "Testing... It worked!",
$font, 32, $white, $black, 32, 32);
ImagePsFreeFont($font); 
ImageJpeg($im, "", 100);//for best quality... your mileage may vary
ImageDestroy ($im);
?>

See also ImagePSFreeFont().

ImagePsExtendFont

(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)

ImagePsExtendFont --  Extend or condense a font

Description

bool imagepsextendfont ( int font_index, float extend)

Extend or condense a font (font_index), if the value of the extend parameter is less than one you will be condensing the font.

ImagePsSlantFont

(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)

ImagePsSlantFont --  Slant a font

Description

bool imagepsslantfont ( int font_index, float slant)

Slant a font given by the font_index parameter with a slant of the value of the slant parameter.

ImagePSText

(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)

ImagePSText --  To draw a text string over an image using PostScript Type1 fonts

Description

array imagepstext ( int image, string text, int font, int size, int foreground, int background, int x, int y [, int space [, int tightness [, float angle [, int antialias_steps]]]])

Size is expressed in pixels.

Foreground is the color in which the text will be painted. Background is the color to which the text will try to fade in with antialiasing. No pixels with the color background are actually painted, so the background image does not need to be of solid color.

The coordinates given by x, y will define the origin (or reference point) of the first character (roughly the lower-left corner of the character). This is different from the ImageString(), where x, y define the upper-right corner of the first character. Refer to PostScipt documentation about fonts and their measuring system if you have trouble understanding how this works.

Space allows you to change the default value of a space in a font. This amount is added to the normal value and can also be negative.

Tightness allows you to control the amount of white space between characters. This amount is added to the normal character width and can also be negative.

Angle is in degrees.

Antialias_steps allows you to control the number of colours used for antialiasing text. Allowed values are 4 and 16. The higher value is recommended for text sizes lower than 20, where the effect in text quality is quite visible. With bigger sizes, use 4. It's less computationally intensive.

Parameters space and tightness are expressed in character space units, where 1 unit is 1/1000th of an em-square.

Parameters space, tightness, angle and antialias are optional.

This function returns an array containing the following elements:

0lower left x-coordinate
1lower left y-coordinate
2upper right x-coordinate
3upper right y-coordinate

See also imagepsbbox().

ImageRectangle

(PHP 3, PHP 4 >= 4.0.0)

ImageRectangle -- Draw a rectangle

Description

int imagerectangle ( int im, int x1, int y1, int x2, int y2, int col)

ImageRectangle() creates a rectangle of color col in image im starting at upper left coordinate x1, y1 and ending at bottom right coordinate x2, y2. 0, 0 is the top left corner of the image.

ImageSetPixel

(PHP 3, PHP 4 >= 4.0.0)

ImageSetPixel -- Set a single pixel

Description

int imagesetpixel ( int im, int x, int y, int col)

ImageSetPixel() draws a pixel at x, y (top left is 0, 0) in image im of color col.

See also ImageCreate() and ImageColorAllocate().

ImageSetBrush

(PHP 4 >= 4.0.6)

ImageSetBrush -- Set the brush image for line drawing

Description

int imagesetbrush ( resource im, resource brush)

ImageSetBrush() sets the brush image to be used by all line drawing functions (such as ImageLine() and ImagePolygon()) when drawing with the special colors IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED.

Notatka: You need not take special action when you are finished with a brush, but if you destroy the brush image, you must not use the IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED colors until you have set a new brush image!

Notatka: This function was added in PHP 4.0.6

ImageSetStyle

(PHP 4 >= 4.0.6)

ImageSetStyle -- Set the style for line drawing

Description

int imagesetstyle ( resource im, array style)

ImageSetStyle() sets the style to be used by all line drawing functions (such as ImageLine() and ImagePolygon()) when drawing with the special color IMG_COLOR_STYLED or lines of images with color IMG_COLOR_STYLEDBRUSHED.

The style parameter is an array of pixels. Following example script draws a dashed line from upper left to lower right corner of the canvas:

Przykład 1. ImageSetStyle

<?php
Header ("Content-type: image/png");
$im  = imagecreate (100, 100);
$w   = ImageColorAllocate ($im, 255, 255, 255);
$red = ImageColorAllocate ($im, 255, 0, 0);
     
/* Draw a dashed line, 5 red pixels, 5 white pixels */
$style=array($red,$red,$red,$red,$red,$w,$w,$w,$w,$w);
ImageSetStyle($im, $style);
ImageLine($im, 0, 0, 100, 100, IMG_COLOR_STYLED);

/* Draw a line of happy faces using ImageSetBrush() with ImageSetStyle */
$style=array($w,$w,$w,$w,$w,$w,$w,$w,$w,$w,$w,$w,$red);
ImageSetStyle($im, $style);

$brush=ImageCreateFromPng("http://www.libpng.org/pub/png/images/smile.happy.png");
ImageColorTransparent($brush, $w);
ImageSetBrush($im, $brush);
ImageLine($im, 100, 0, 0, 100, IMG_COLOR_STYLEDBRUSHED);

ImagePng($im);
ImageDestroy ($im);
?>

See also ImageSetBrush(), ImageLine().

Notatka: This function was added in PHP 4.0.6

ImageSetTile

(PHP 4 >= 4.0.6)

ImageSetTile -- Set the tile image for filling

Description

int imagesettile ( resource im, resource tile)

ImageSetTile() sets the tile image to be used by all region filling functions (such as ImageFill() and ImageFilledPolygon()) when filling with the special color IMG_COLOR_TILED.

A tile is an image used to fill an area with a repeated pattern. Any GD image can be used as a tile, and by setting the transparent color index of the tile image with ImageColorTransparent(), a tile allows certain parts of the underlying area to shine through can be created.

Notatka: You need not take special action when you are finished with a tile, but if you destroy the tile image, you must not use the IMG_COLOR_TILED color until you have set a new tile image!

Notatka: This function was added in PHP 4.0.6

ImageSetThickness

(PHP 4 >= 4.0.6)

ImageSetThickness -- Set the thickness for line drawing

Description

void imagesetthickness ( resource im, int thickness)

ImageSetThickness() sets the thickness of the lines drawn when drawing rectangles, polygons, ellipses etc. etc. to thickness pixels.

Notatka: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

ImageString

(PHP 3, PHP 4 >= 4.0.0)

ImageString -- Draw a string horizontally

Description

int imagestring ( int im, int font, int x, int y, string s, int col)

ImageString() draws the string s in the image identified by im at coordinates x, y (top left is 0, 0) in color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.

See also ImageLoadFont().

ImageStringUp

(PHP 3, PHP 4 >= 4.0.0)

ImageStringUp -- Draw a string vertically

Description

int imagestringup ( int im, int font, int x, int y, string s, int col)

ImageStringUp() draws the string s vertically in the image identified by im at coordinates x, y (top left is 0, 0) in color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.

See also ImageLoadFont().

ImageSX

(PHP 3, PHP 4 >= 4.0.0)

ImageSX -- Get image width

Description

int imagesx ( int im)

ImageSX() returns the width of the image identified by im.

See also ImageCreate() and ImageSY().

ImageSY

(PHP 3, PHP 4 >= 4.0.0)

ImageSY -- Get image height

Description

int imagesy ( int im)

ImageSY() returns the height of the image identified by im.

See also ImageCreate() and ImageSX().

ImageTTFBBox

(PHP 3>= 3.0.1, PHP 4 >= 4.0.0)

ImageTTFBBox --  Give the bounding box of a text using TrueType fonts

Description

array imagettfbbox ( int size, int angle, string fontfile, string text)

This function calculates and returns the bounding box in pixels for a TrueType text.

text

The string to be measured.

size

The font size in pixels.

fontfile

The name of the TrueType font file. (Can also be an URL.) Depending on which version of the GD library that PHP is using, it may attempt to search for files that do not begin with a leading '/' by appending '.ttf' to the filename and searching along a library-defined font path.

angle

Angle in degrees in which text will be measured.

ImageTTFBBox() returns an array with 8 elements representing four points making the bounding box of the text:

0lower left corner, X position
1lower left corner, Y position
2lower right corner, X position
3lower right corner, Y position
4upper right corner, X position
5upper right corner, Y position
6upper left corner, X position
7upper left corner, Y position

The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner seeing the text horizontallty.

This function requires both the GD library and the FreeType library.

See also ImageTTFText().

ImageFtBBox

(PHP 4 >= 4.1.0)

ImageFtBBox --  Give the bounding box of a text using fonts via freetype2

Description

array imageftbbox ( int size, int angle, string font_file, string text [, array extrainfo])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ImageTTFText

(PHP 3, PHP 4 >= 4.0.0)

ImageTTFText --  Write text to the image using TrueType fonts

Description

array imagettftext ( int im, int size, int angle, int x, int y, int col, string fontfile, string text)

ImageTTFText() draws the string text in the image identified by im, starting at coordinates x, y (top left is 0, 0), at an angle of angle in color col, using the TrueType font file identified by fontfile. Depending on which version of the GD library that PHP is using, when fontfile does not begin with a leading '/', '.ttf' will be appended to the filename and the the library will attempt to search for that filename along a library-defined font path.

The coordinates given by x, y will define the basepoint of the first character (roughly the lower-left corner of the character). This is different from the ImageString(), where x, y define the upper-right corner of the first character.

Angle is in degrees, with 0 degrees being left-to-right reading text (3 o'clock direction), and higher values representing a counter-clockwise rotation. (i.e., a value of 90 would result in bottom-to-top reading text).

Fontfile is the path to the TrueType font you wish to use.

Text is the text string which may include UTF-8 character sequences (of the form: &#123;) to access characters in a font beyond the first 255.

Col is the color index. Using the negative of a color index has the effect of turning off antialiasing.

ImageTTFText() returns an array with 8 elements representing four points making the bounding box of the text. The order of the points is lower left, lower right, upper right, upper left. The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner when you see the text horizontallty.

This example script will produce a black GIF 400x30 pixels, with the words "Testing..." in white in the font Arial.

Przykład 1. ImageTTFText

<?php
Header ("Content-type: image/gif");
$im = imagecreate (400, 30);
$black = ImageColorAllocate ($im, 0, 0, 0);
$white = ImageColorAllocate ($im, 255, 255, 255);
ImageTTFText ($im, 20, 0, 10, 20, $white, "/path/arial.ttf",
              "Testing... Omega: &#937;");
ImageGif ($im);
ImageDestroy ($im);
?>

This function requires both the GD library and the FreeType library.

See also ImageTTFBBox().

ImageFtText

(PHP 4 >= 4.1.0)

ImageFtText --  Write text to the image using fonts using FreeType 2

Description

array imagefttext ( int im, int size, int angle, int x, int y, int col, string font_file, string text [, array extrainfo])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ImageTypes

(PHP 3 CVS only, PHP 4 >= 4.0.2)

ImageTypes --  Return the image types supported by this PHP build

Description

int imagetypes ( void)

This function returns a bit-field corresponding to the image formats supported by the version of GD linked into PHP. The following bits are returned, IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP. To check for PNG support, for example, do this:

Przykład 1. ImageTypes

<?php
if (ImageTypes() & IMG_PNG) {
    echo "PNG Support is enabled";
}
?>

JPEG2WBMP

(PHP 4 >= 4.0.5)

JPEG2WBMP --  Convert JPEG image file to WBMP image file

Description

int jpeg2wbmp ( string jpegname, string wbmpname, int d_height, int d_width, int threshold)

Converts the jpegname JPEG file to WBMP format, and saves it as wbmpname. With the d_height and d_width you specify the height and width of the destination image.

Notatka: WBMP support is only available if PHP was compiled against GD-1.8 or later.

See also png2wbmp().

PNG2WBMP

(PHP 4 >= 4.0.5)

PNG2WBMP --  Convert PNG image file to WBMP image file

Description

int png2wbmp ( string pngname, string wbmpname, int d_height, int d_width, int threshold)

Converts the pngname PNG file to WBMP format, and saves it as wbmpname. With the d_height and d_width you specify the height and width of the destination image.

Notatka: WBMP support is only available if PHP was compiled against GD-1.8 or later.

See also jpeg2wbmp().

read_exif_data

(PHP 4 )

read_exif_data -- Read the EXIF headers from a JPEG

Description

array read_exif_data ( string filename)

The read_exif_data() function reads the EXIF headers from a JPEG image file. It returns an associative array where the indexes are the Exif header names and the values are the values associated with those Exif headers. Exif headers tend to be present in JPEG images generated by digital cameras, but unfortunately each digital camera maker has a different idea of how to actually tag their images, so you can't always rely on a specific Exif header being present.

Przykład 1. read_exif_data

<?php
 $exif = read_exif_data ('p0001807.jpg');
 while(list($k,$v)=each($exif)) {
   echo "$k: $v<br>\n";
 }
?>

Output:
FileName: p0001807.jpg
FileDateTime: 929353056
FileSize: 378599
CameraMake: Eastman Kodak Company
CameraModel: KODAK DC265 ZOOM DIGITAL CAMERA (V01.00)
DateTime: 1999:06:14 01:37:36
Height: 1024
Width: 1536
IsColor: 1
FlashUsed: 0
FocalLength:  8.0mm
RawFocalLength: 8
ExposureTime:  0.004 s (1/250)
RawExposureTime: 0.0040000001899898
ApertureFNumber: f/ 9.5
RawApertureFNumber: 9.5100002288818
FocusDistance: 16.66m
RawFocusDistance: 16.659999847412
Orientation: 1
ExifVersion: 0200

Notatka: This function is only available in PHP 4 compiled using --enable-exif

This function does not require the GD image library.

iptcembed

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

iptcembed --  Embed binary IPTC data into a JPEG image.

Description

array iptcembed ( string iptcdata, string jpeg_file_name [, int spool])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

XLII. IMAP, POP3 and NNTP functions

To get these functions to work, you have to compile PHP with --with-imap. That requires the c-client library to be installed. Grab the latest version from ftp://ftp.cac.washington.edu/imap/ and compile it. Then copy c-client/c-client.a to /usr/local/lib/libc-client.a or some other directory on your link path and copy c-client/rfc822.h, mail.h and linkage.h to /usr/local/include or some other directory in your include path.

Note that these functions are not limited to the IMAP protocol, despite their name. The underlying c-client library also supports NNTP, POP3 and local mailbox access methods.

This document can't go into detail on all the topics touched by the provided functions. Further information is provided by the documentation of the c-client library source (docs/internal.txt). and the following RFC documents:

  • RFC2821: Simple Mail Transfer Protocol (SMTP).

  • RFC2822: Standard for ARPA internet text messages.

  • RFC2060: Internet Message Access Protocol (IMAP) Version 4rev1.

  • RFC1939: Post Office Protocol Version 3 (POP3).

  • RFC977: Network News Transfer Protocol (NNTP).

  • RFC2076: Common Internet Message Headers.

  • RFC2045 , RFC2046 , RFC2047 , RFC2048 & RFC2049: Multipurpose Internet Mail Extensions (MIME).

A detailed overview is also available in the books Programming Internet Email by David Wood and Managing IMAP by Dianna Mullet & Kevin Mullet.

Spis treści
imap_8bit --  Convert an 8bit string to a quoted-printable string
imap_alerts --  This function returns all IMAP alert messages (if any) that have occurred during this page request or since the alert stack was reset
imap_append --  Append a string message to a specified mailbox
imap_base64 -- Decode BASE64 encoded text
imap_binary --  Convert an 8bit string to a base64 string
imap_body -- Read the message body
imap_bodystruct --  Read the structure of a specified body section of a specific message
imap_check -- Check current mailbox
imap_clearflag_full -- Clears flags on messages
imap_close -- Close an IMAP stream
imap_createmailbox -- Create a new mailbox
imap_delete --  Mark a messge for deletion from current mailbox
imap_deletemailbox -- Delete a mailbox
imap_errors --  This function returns all of the IMAP errors (if any) that have occurred during this page request or since the error stack was reset.
imap_expunge -- Delete all messages marked for deletion
imap_fetch_overview --  Read an overview of the information in the headers of the given message
imap_fetchbody --  Fetch a particular section of the body of the message
imap_fetchheader -- Returns header for a message
imap_fetchstructure --  Read the structure of a particular message
imap_get_quota --  Retrieve the quota level settings, and usage statics per mailbox
imap_getmailboxes --  Read the list of mailboxes, returning detailed information on each one
imap_getsubscribed -- List all the subscribed mailboxes
imap_header -- Read the header of the message
imap_headerinfo -- Read the header of the message
imap_headers --  Returns headers for all messages in a mailbox
imap_last_error --  This function returns the last IMAP error (if any) that occurred during this page request
imap_listmailbox -- Read the list of mailboxes
imap_listsubscribed -- List all the subscribed mailboxes
imap_mail --  Send an email message
imap_mail_compose --  Create a MIME message based on given envelope and body sections
imap_mail_copy -- Copy specified messages to a mailbox
imap_mail_move -- Move specified messages to a mailbox
imap_mailboxmsginfo -- Get information about the current mailbox
imap_mime_header_decode -- Decode MIME header elements
imap_msgno --  This function returns the message sequence number for the given UID
imap_num_msg --  Gives the number of messages in the current mailbox
imap_num_recent -- Gives the number of recent messages in current mailbox
imap_open -- Open an IMAP stream to a mailbox
imap_ping -- Check if the IMAP stream is still active
imap_popen --  Open a persistant IMAP stream to a mailbox
imap_qprint -- Convert a quoted-printable string to an 8 bit string
imap_renamemailbox -- Rename an old mailbox to new mailbox
imap_reopen -- Reopen IMAP stream to new mailbox
imap_rfc822_parse_adrlist -- Parses an address string
imap_rfc822_parse_headers -- Parse mail headers from a string
imap_rfc822_write_address --  Returns a properly formatted email address given the mailbox, host, and personal info.
imap_scanmailbox --  Read the list of mailboxes, takes a string to search for in the text of the mailbox
imap_search --  This function returns an array of messages matching the given search criteria
imap_setacl --  Sets the ACL for a giving mailbox
imap_set_quota -- Sets a quota for a given mailbox
imap_setflag_full -- Sets flags on messages
imap_sort -- Sort an array of message headers
imap_status --  This function returns status information on a mailbox other than the current one
imap_subscribe -- Subscribe to a mailbox
imap_uid --  This function returns the UID for the given message sequence number
imap_undelete --  Unmark the message which is marked deleted
imap_unsubscribe -- Unsubscribe from a mailbox
imap_utf7_decode --  Decodes a modified UTF-7 encoded string.
imap_utf7_encode --  Converts 8bit data to modified UTF-7 text.
imap_utf8 --  Converts text to UTF8
imap_thread --  Return threaded by REFERENCES tree

imap_8bit

(PHP 3, PHP 4 >= 4.0.0)

imap_8bit --  Convert an 8bit string to a quoted-printable string

Description

string imap_8bit ( string string)

Convert an 8bit string to a quoted-printable string (according to RFC2045, section 6.7).

Returns a quoted-printable string.

See also imap_qprint().

imap_alerts

(PHP 3>= 3.0.12, PHP 4 >= 4.0.0)

imap_alerts --  This function returns all IMAP alert messages (if any) that have occurred during this page request or since the alert stack was reset

Description

array imap_alerts ( void)

This function returns an array of all of the IMAP alert messages generated since the last imap_alerts() call, or the beginning of the page. When imap_alerts() is called, the alert stack is subsequently cleared. The IMAP specification requires that these messages be passed to the user.

imap_append

(PHP 3, PHP 4 >= 4.0.0)

imap_append --  Append a string message to a specified mailbox

Description

int imap_append ( int imap_stream, string mbox, string message [, string flags])

Returns TRUE on sucess, FALSE on error.

imap_append() appends a string message to the specified mailbox mbox. If the optional flags is specified, writes the flags to that mailbox also.

When talking to the Cyrus IMAP server, you must use "\r\n" as your end-of-line terminator instead of "\n" or the operation will fail.

Przykład 1. imap_append() example

$stream = imap_open("{your.imap.host}INBOX.Drafts","username", "password");

$check = imap_check($stream);
print "Msg Count before append: ". $check->Nmsgs."\n";

imap_append($stream,"{your.imap.host}INBOX.Drafts"
                   ,"From: me@my.host\r\n"
                   ."To: you@your.host\r\n"
                   ."Subject: test\r\n"
                   ."\r\n"
                   ."this is a test message, please ignore\r\n"
                   );

$check = imap_check($stream);
print "Msg Count after append : ". $check->Nmsgs."\n";

imap_close($stream);

imap_base64

(PHP 3, PHP 4 >= 4.0.0)

imap_base64 -- Decode BASE64 encoded text

Description

string imap_base64 ( string text)

imap_base64() function decodes BASE-64 encoded text (see RFC2045, Section 6.8). The decoded message is returned as a string.

See also imap_binary().

imap_binary

(PHP 3>= 3.0.2, PHP 4 >= 4.0.0)

imap_binary --  Convert an 8bit string to a base64 string

Description

string imap_binary ( string string)

Convert an 8bit string to a base64 string (according to RFC2045, Section 6.8).

Returns a base64 string.

See also imap_base64().

imap_body

(PHP 3, PHP 4 >= 4.0.0)

imap_body -- Read the message body

Description

string imap_body ( int imap_stream, int msg_number [, int flags])

imap_body() returns the body of the message, numbered msg_number in the current mailbox. The optional flags are a bit mask with one or more of the following:

  • FT_UID - The msgno is a UID

  • FT_PEEK - Do not set the \Seen flag if not already set

  • FT_INTERNAL - The return string is in internal format, will not canonicalize to CRLF.

imap_body() will only return a verbatim copy of the message body. To extract single parts of a multipart MIME-encoded message you have to use imap_fetchstructure() to analyze its structure and imap_fetchbody() to extract a copy of a single body component.

imap_bodystruct

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

imap_bodystruct --  Read the structure of a specified body section of a specific message

Description

object imap_bodystruct ( int stream_id, int msg_no, int section)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

imap_check

(PHP 3, PHP 4 >= 4.0.0)

imap_check -- Check current mailbox

Description

object imap_check ( int imap_stream)

Returns information about the current mailbox. Returns FALSE on failure.

The imap_check() function checks the current mailbox status on the server and returns the information in an object with following properties:

  • Date - last change of mailbox contents

  • Driver - protocol used to access this mailbox: POP3, IMAP, NNTP

  • Mailbox - the mailbox name

  • Nmsgs - number of messages in the mailbox

  • Recent - number of recent messages in the mailbox

imap_clearflag_full

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

imap_clearflag_full -- Clears flags on messages

Description

string imap_clearflag_full ( int stream, string sequence, string flag, string options)

This function causes a store to delete the specified flag to the flags set for the messages in the specified sequence. The flags which you can unset are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", "\\Draft", and "\\Recent" (as defined by RFC2060).

The options are a bit mask with one or more of the following:


ST_UID          The sequence argument contains UIDs instead of
                sequence numbers
      

imap_close

(PHP 3, PHP 4 >= 4.0.0)

imap_close -- Close an IMAP stream

Description

int imap_close ( int imap_stream [, int flags])

Close the imap stream. Takes an optional flag CL_EXPUNGE, which will silently expunge the mailbox before closing, removing all messages marked for deletion.

imap_createmailbox

(PHP 3, PHP 4 >= 4.0.0)

imap_createmailbox -- Create a new mailbox

Description

int imap_createmailbox ( int imap_stream, string mbox)

imap_createmailbox() creates a new mailbox specified by mbox. Names containing international characters should be encoded by imap_utf7_encode()

Returns TRUE on success and FALSE on error.

See also imap_renamemailbox(), imap_deletemailbox() and imap_open() for the format of mbox names.

Przykład 1. imap_createmailbox() example

$mbox = imap_open("{your.imap.host}","username","password",OP_HALFOPEN)
     or die("can't connect: ".imap_last_error());

$name1 = "phpnewbox";
$name2 = imap_utf7_encode("phpnewb&ouml;x");

$newname = $name1;

echo "Newname will be '$name1'<br>\n";

# we will now create a new mailbox "phptestbox" in your inbox folder,
# check its status after creation and finaly remove it to restore
# your inbox to its initial state 
if(@imap_createmailbox($mbox,imap_utf7_encode("{your.imap.host}INBOX.$newname"))) {
  $status = @imap_status($mbox,"{your.imap.host}INBOX.$newname",SA_ALL);
  if($status) {
    print("your new mailbox '$name1' has the following status:<br>\n");
    print("Messages:   ". $status->messages   )."<br>\n";
    print("Recent:     ". $status->recent     )."<br>\n";
    print("Unseen:     ". $status->unseen     )."<br>\n";
    print("UIDnext:    ". $status->uidnext    )."<br>\n";
    print("UIDvalidity:". $status->uidvalidity)."<br>\n";
    
    if(imap_renamemailbox($mbox,"{your.imap.host}INBOX.$newname","{your.imap.host}INBOX.$name2")) {
      echo "renamed new mailbox from '$name1' to '$name2'<br>\n";
      $newname=$name2;
    } else {
      print "imap_renamemailbox on new mailbox failed: ".imap_last_error()."<br>\n";
    }
  } else {
    print  "imap_status on new mailbox failed: ".imap_last_error()."<br>\n";
  }
  if(@imap_deletemailbox($mbox,"{your.imap.host}INBOX.$newname")) {
    print "new mailbox removed to restore initial state<br>\n";
  } else {
    print  "imap_deletemailbox on new mailbox failed: ".implode("<br>\n",imap_errors())."<br>\n";
  }
  
} else {
  print  "could not create new mailbox: ".implode("<br>\n",imap_errors())."<br>\n";
}

imap_close($mbox);

imap_delete

(PHP 3, PHP 4 >= 4.0.0)

imap_delete --  Mark a messge for deletion from current mailbox

Description

int imap_delete ( int imap_stream, int msg_number [, int flags])

Returns TRUE.

imap_delete() marks messages listed in msg_number for deletion. The optional flags parameter only has a single option, FT_UID, which tells the function to treat the msg_number argument as a UID. Messages marked for deletion will stay in the mailbox until either imap_expunge() is called or imap_close() is called with the optional parameter CL_EXPUNGE.

Notatka: POP3 mailboxes do not have their message flags saved between connections, so imap_expunge() must be called during the same connection in order for messages marked for deletion to actually be purged.

Przykład 1. imap_delete() Beispiel

$mbox = imap_open ("{your.imap.host}INBOX", "username", "password")
    or die ("can't connect: " . imap_last_error());

$check = imap_mailboxmsginfo ($mbox);
print "Messages before delete: " . $check->Nmsgs . "<br>\n" ;
imap_delete ($mbox, 1);
$check = imap_mailboxmsginfo ($mbox);
print "Messages after  delete: " . $check->Nmsgs . "<br>\n" ;
imap_expunge ($mbox);
$check = imap_mailboxmsginfo ($mbox);
print "Messages after expunge: " . $check->Nmsgs . "<br>\n" ;
imap_close ($mbox);

imap_deletemailbox

(PHP 3, PHP 4 >= 4.0.0)

imap_deletemailbox -- Delete a mailbox

Description

int imap_deletemailbox ( int imap_stream, string mbox)

imap_deletemailbox() deletes the specified mailbox (see imap_open() for the format of mbox names).

Returns TRUE on success and FALSE on error.

See also imap_createmailbox(), imap_renamemailbox(), and imap_open() for the format of mbox.

imap_errors

(PHP 3>= 3.0.12, PHP 4 >= 4.0.0)

imap_errors --  This function returns all of the IMAP errors (if any) that have occurred during this page request or since the error stack was reset.

Description

array imap_errors ( void)

This function returns an array of all of the IMAP error messages generated since the last imap_errors() call, or the beginning of the page. When imap_errors() is called, the error stack is subsequently cleared.

imap_expunge

(PHP 3, PHP 4 >= 4.0.0)

imap_expunge -- Delete all messages marked for deletion

Description

int imap_expunge ( int imap_stream)

imap_expunge() deletes all the messages marked for deletion by imap_delete(), imap_mail_move(), or imap_setflag_full().

Returns TRUE.

imap_fetch_overview

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

imap_fetch_overview --  Read an overview of the information in the headers of the given message

Description

array imap_fetch_overview ( int imap_stream, string sequence [, int flags])

This function fetches mail headers for the given sequence and returns an overview of their contents. sequence will contain a sequence of message indices or UIDs, if flags contains FT_UID. The returned value is an array of objects describing one message header each:

  • subject - the messages subject

  • from - who sent it

  • date - when was it sent

  • message_id - Message-ID

  • references - is a reference to this message id

  • size - size in bytes

  • uid - UID the message has in the mailbox

  • msgno - message sequence number in the maibox

  • recent - this message is flagged as recent

  • flagged - this message is flagged

  • answered - this message is flagged as answered

  • deleted - this message is flagged for deletion

  • seen - this message is flagged as already read

  • draft - this message is flagged as being a draft

Przykład 1. imap_fetch_overview() example

$mbox = imap_open("{your.imap.host:143}","username","password")
     or die("can't connect: ".imap_last_error());
 
$overview = imap_fetch_overview($mbox,"2,4:6",0);
 
if(is_array($overview)) {
        reset($overview);
        while( list($key,$val) = each($overview)) {
                print     $val->msgno
                . " - " . $val->date
                . " - " . $val->subject
                . "\n";
        }
}
 
imap_close($mbox);

imap_fetchbody

(PHP 3, PHP 4 >= 4.0.0)

imap_fetchbody --  Fetch a particular section of the body of the message

Description

string imap_fetchbody ( int imap_stream, int msg_number, string part_number [, flags flags])

This function causes a fetch of a particular section of the body of the specified messages as a text string and returns that text string. The section specification is a string of integers delimited by period which index into a body part list as per the IMAP4 specification. Body parts are not decoded by this function.

The options for imap_fetchbody() is a bitmask with one or more of the following:

  • FT_UID - The msg_number is a UID

  • FT_PEEK - Do not set the \Seen flag if not already set

  • FT_INTERNAL - The return string is in "internal" format, without any attempt to canonicalize CRLF.

See also: imap_fetchstructure().

imap_fetchheader

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

imap_fetchheader -- Returns header for a message

Description

string imap_fetchheader ( int imap_stream, int msgno, int flags)

This function causes a fetch of the complete, unfiltered RFC2822 format header of the specified message as a text string and returns that text string.

The options are:


FT_UID          The msgno argument is a UID 
FT_INTERNAL     The return string is in "internal" format,
                without any attempt to canonicalize to CRLF
                newlines
FT_PREFETCHTEXT The RFC822.TEXT should be pre-fetched at the
                same time.  This avoids an extra RTT on an
                IMAP connection if a full message text is
                desired (e.g. in a "save to local file"
                operation)
      

imap_fetchstructure

(PHP 3, PHP 4 >= 4.0.0)

imap_fetchstructure --  Read the structure of a particular message

Description

object imap_fetchstructure ( int imap_stream, int msg_number [, int flags])

This function fetches all the structured information for a given message. The optional flags parameter only has a single option, FT_UID, which tells the function to treat the msg_number argument as a UID. The returned object includes the envelope, internal date, size, flags and body structure along with a similar object for each mime attachement. The structure of the returned objects is as follows:

Tabela 1. Returned Objects for imap_fetchstructure()

typePrimary body type
encodingBody transfer encoding
ifsubtypeTRUE if there is a subtype string
subtypeMIME subtype
ifdescriptionTRUE if there is a description string
descriptionContent description string
ifidTRUE if there is an identification string
idIdentification string
linesNumber of lines
bytesNumber of bytes
ifdispositionTRUE if there is a disposition string
dispositionDisposition string
ifdparametersTRUE if the dparameters array exists
dparametersAn array of objects where each object has an "attribute" and a "value" property corresponding to the parameters on the Content-disposition MIMEheader.
ifparametersTRUE if the parameters array exists
parametersAn array of objects where each object has an "attribute" and a "value" property.
partsAn array of objects identical in structure to the top-level object, each of which corresponds to a MIME body part.

Tabela 2. Primary body type

0text
1multipart
2message
3application
4audio
5image
6video
7other

Tabela 3. Transfer encodings

07BIT
18BIT
2BINARY
3BASE64
4QUOTED-PRINTABLE
5OTHER

See also: imap_fetchbody().

imap_get_quota

(PHP 4 >= 4.0.5)

imap_get_quota --  Retrieve the quota level settings, and usage statics per mailbox

Description

array imap_get_quota ( int imap_stream, string quota_root)

Returns an array with integer values limit and usage for the given mailbox. The value of limit represents the total amount of space allowed for this mailbox. The usage value represents the mailboxes current level of capacity. Will return FALSE in the case of failure.

This function is currently only available to users of the c-client2000 library.

imap_stream should be the value returned from an imap_status() call. This stream is required to be opened as the mail admin user for the quota function to work. quota_root should normally be in the form of user.name where name is the mailbox you wish to retrieve information about.

Przykład 1. imap_get_quota() example

$mbox = imap_open("{your.imap.host}","mailadmin","password",OP_HALFOPEN)
      or die("can't connect: ".imap_last_error());
 
$quota_value = imap_get_quota($mbox, "user.kalowsky");
if(is_array($quota_value)) {
    print "Usage level is: " . $quota_value['usage'];
    print "Limit level is: " . $quota_value['limit'];
} 
 
imap_close($mbox);

See also imap_open(), imap_set_quota().

imap_getmailboxes

(PHP 3>= 3.0.12, PHP 4 >= 4.0.0)

imap_getmailboxes --  Read the list of mailboxes, returning detailed information on each one

Description

array imap_getmailboxes ( int imap_stream, string ref, string pattern)

Returns an array of objects containing mailbox information. Each object has the attributes name, specifying the full name of the mailbox; delimiter, which is the hierarchy delimiter for the part of the hierarchy this mailbox is in; and attributes. Attributes is a bitmask that can be tested against:

  • LATT_NOINFERIORS - This mailbox has no "children" (there are no mailboxes below this one).

  • LATT_NOSELECT - This is only a container, not a mailbox - you cannot open it.

  • LATT_MARKED - This mailbox is marked. Only used by UW-IMAPD.

  • LATT_UNMARKED - This mailbox is not marked. Only used by UW-IMAPD.

Mailbox names containing international Characters outside the printable ASCII range will be encoded and may be decoded by imap_utf7_decode().

ref should normally be just the server specification as described in imap_open(), and pattern specifies where in the mailbox hierarchy to start searching. If you want all mailboxes, pass '*' for pattern.

There are two special characters you can pass as part of the pattern: '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

Przykład 1. imap_getmailboxes() example

$mbox = imap_open("{your.imap.host}","username","password",OP_HALFOPEN)
      or die("can't connect: ".imap_last_error());
 
$list = imap_getmailboxes($mbox,"{your.imap.host}","*");
if(is_array($list)) {
  reset($list);
  while (list($key, $val) = each($list))
  {
    print "($key) ";
    print imap_utf7_decode($val->name).",";
    print "'".$val->delimiter."',";
    print $val->attributes."<br>\n";
  }
} else
  print "imap_getmailboxes failed: ".imap_last_error()."\n";
 
imap_close($mbox);

See also imap_getsubscribed().

imap_getsubscribed

(PHP 3>= 3.0.12, PHP 4 >= 4.0.0)

imap_getsubscribed -- List all the subscribed mailboxes

Description

array imap_getsubscribed ( int imap_stream, string ref, string pattern)

This function is identical to imap_getmailboxes(), except that it only returns mailboxes that the user is subscribed to.

imap_header

(PHP 3, PHP 4 >= 4.0.0)

imap_header -- Read the header of the message

Description

object imap_header ( int imap_stream, int msg_number [, int fromlength [, int subjectlength [, string defaulthost]]])

This is an alias to imap_headerinfo() and is identical to this in any way.

imap_headerinfo

(PHP 3, PHP 4 >= 4.0.0)

imap_headerinfo -- Read the header of the message

Description

object imap_headerinfo ( int imap_stream, int msg_number [, int fromlength [, int subjectlength [, string defaulthost]]])

This function returns an object of various header elements.


       remail, date, Date, subject, Subject, in_reply_to, message_id,
       newsgroups, followup_to, references

message flags:
   Recent -  'R' if recent and seen, 
             'N' if recent and not seen, 
             ' ' if not recent
   Unseen -  'U' if not seen AND not recent, 
             ' ' if seen OR not seen and recent
   Answered -'A' if answered, 
             ' ' if unanswered
   Deleted - 'D' if deleted, 
             ' ' if not deleted
   Draft -   'X' if draft, 
             ' ' if not draft
   Flagged - 'F' if flagged, 
             ' ' if not flagged

NOTE that the Recent/Unseen behavior is a little odd. If you want to
know if a message is Unseen, you must check for

Unseen == 'U' || Recent == 'N'

toaddress (full to: line, up to 1024 characters)

to[] (returns an array of objects from the To line, containing):
   personal
   adl
   mailbox
   host

fromaddress (full from: line, up to 1024 characters)

from[] (returns an array of objects from the From line, containing):
   personal
   adl
   mailbox
   host

ccaddress (full cc: line, up to 1024 characters)
cc[] (returns an array of objects from the Cc line, containing):
   personal
   adl
   mailbox
   host

bccaddress (full bcc line, up to 1024 characters)
bcc[] (returns an array of objects from the Bcc line, containing):
   personal
   adl
   mailbox
   host

reply_toaddress (full reply_to: line, up to 1024 characters)
reply_to[] (returns an array of objects from the Reply_to line,
containing):
   personal
   adl
   mailbox
   host

senderaddress (full sender: line, up to 1024 characters)
sender[] (returns an array of objects from the sender line, containing):
   personal
   adl
   mailbox
   host

return_path (full return-path: line, up to 1024 characters)
return_path[] (returns an array of objects from the return_path line,
containing):
   personal
   adl
   mailbox
   host

udate (mail message date in unix time)

fetchfrom (from line formatted to fit fromlength 
characters)

fetchsubject (subject line formatted to fit subjectlength characters)
      

imap_headers

(PHP 3, PHP 4 >= 4.0.0)

imap_headers --  Returns headers for all messages in a mailbox

Description

array imap_headers ( int imap_stream)

Returns an array of string formatted with header info. One element per mail message.

imap_last_error

(PHP 3>= 3.0.12, PHP 4 >= 4.0.0)

imap_last_error --  This function returns the last IMAP error (if any) that occurred during this page request

Description

string imap_last_error ( void)

This function returns the full text of the last IMAP error message that occurred on the current page. The error stack is untouched; calling imap_last_error() subsequently, with no intervening errors, will return the same error.

imap_listmailbox

(PHP 3, PHP 4 >= 4.0.0)

imap_listmailbox -- Read the list of mailboxes

Description

array imap_listmailbox ( int imap_stream, string ref, string pattern)

Returns an array containing the names of the mailboxes. See imap_getmailboxes() for a description of ref and pattern.

Przykład 1. imap_listmailbox() example

$mbox = imap_open("{your.imap.host}","username","password",OP_HALFOPEN)
      or die("can't connect: ".imap_last_error());
 
$list = imap_listmailbox($mbox,"{your.imap.host}","*");
if(is_array($list)) {
  reset($list);
  while (list($key, $val) = each($list))
    print imap_utf7_decode($val)."<br>\n";
} else
  print "imap_listmailbox failed: ".imap_last_error()."\n";
 
imap_close($mbox);

imap_listsubscribed

(PHP 3, PHP 4 >= 4.0.0)

imap_listsubscribed -- List all the subscribed mailboxes

Description

array imap_listsubscribed ( int imap_stream, string ref, string pattern)

Returns an array of all the mailboxes that you have subscribed. This is almost identical to imap_listmailbox(), but will only return mailboxes the user you logged in as has subscribed.

imap_mail

(PHP 3>= 3.0.14, PHP 4 >= 4.0.0)

imap_mail --  Send an email message

Description

string imap_mail ( string to, string subject, string message [, string additional_headers [, string cc [, string bcc [, string rpath]]]])

This function allows sending of emails with correct handling of Cc and Bcc receivers. The parameters to, cc and bcc are all strings and are all parsed as rfc822 address lists. The receivers specified in bcc will get the mail, but are excluded from the headers. Use the rpath parameter to specify return path. This is useful when using php as a mail client for multiple users.

imap_mail_compose

(PHP 3>= 3.0.5, PHP 4 >= 4.0.0)

imap_mail_compose --  Create a MIME message based on given envelope and body sections

Description

string imap_mail_compose ( array envelope, array body)

Przykład 1. imap_mail_compose() example

<?php

$envelope["from"]="musone@afterfive.com";
$envelope["to"]="musone@darkstar";
$envelope["cc"]="musone@edgeglobal.com";

$part1["type"]=TYPEMULTIPART;
$part1["subtype"]="mixed";

$filename="/tmp/imap.c.gz";
$fp=fopen($filename,"r");
$contents=fread($fp,filesize($filename));
fclose($fp);

$part2["type"]=TYPEAPPLICATION;
$part2["encoding"]=ENCBINARY;
$part2["subtype"]="octet-stream";
$part2["description"]=basename($filename);
$part2["contents.data"]=$contents;

$part3["type"]=TYPETEXT;
$part3["subtype"]="plain";
$part3["description"]="description3";
$part3["contents.data"]="contents.data3\n\n\n\t";

$body[1]=$part1;
$body[2]=$part2;
$body[3]=$part3;

echo nl2br(imap_mail_compose($envelope,$body));

?>

imap_mail_copy

(PHP 3, PHP 4 >= 4.0.0)

imap_mail_copy -- Copy specified messages to a mailbox

Description

int imap_mail_copy ( int imap_stream, string msglist, string mbox [, int flags])

Returns TRUE on success and FALSE on error.

Copies mail messages specified by msglist to specified mailbox. msglist is a range not just message numbers (as described in RFC2060).

Flags is a bitmask of one or more of

  • CP_UID - the sequence numbers contain UIDS

  • CP_MOVE - Delete the messages from the current mailbox after copying

imap_mail_move

(PHP 3, PHP 4 >= 4.0.0)

imap_mail_move -- Move specified messages to a mailbox

Description

int imap_mail_move ( int imap_stream, string msglist, string mbox [, int flags])

Moves mail messages specified by msglist to specified mailbox. msglist is a range not just message numbers (as described in RFC2060).

Flags is a bitmask and may contain the single option

  • CP_UID - the sequence numbers contain UIDS

Returns TRUE on success and FALSE on error.

imap_mailboxmsginfo

(PHP 3>= 3.0.2, PHP 4 >= 4.0.0)

imap_mailboxmsginfo -- Get information about the current mailbox

Description

object imap_mailboxmsginfo ( int imap_stream)

Returns information about the current mailbox. Returns FALSE on failure.

The imap_mailboxmsginfo() function checks the current mailbox status on the server. It is similar to imap_status(), but will additionally sum up the size of all messages in the mailbox, which will take some additional time to execute. It returns the information in an object with following properties.

Tabela 1. Mailbox properties

Datedate of last change
Driverdriver
Mailboxname of the mailbox
Nmsgsnumber of messages
Recentnumber of recent messages
Unreadnumber of unread messages
Deletednumber of deleted messages
Sizemailbox size

Przykład 1. imap_mailboxmsginfo() example

<?php

$mbox = imap_open("{your.imap.host}INBOX","username", "password")
      or die("can't connect: ".imap_last_error());
 
$check = imap_mailboxmsginfo($mbox);
 
if($check) {
    print "Date: "    . $check->Date    ."<br>\n" ;
    print "Driver: "  . $check->Driver  ."<br>\n" ;
    print "Mailbox: " . $check->Mailbox ."<br>\n" ;
    print "Messages: ". $check->Nmsgs   ."<br>\n" ;
    print "Recent: "  . $check->Recent  ."<br>\n" ;
    print "Unread: "  . $check->Unread  ."<br>\n" ;
    print "Deleted: " . $check->Deleted ."<br>\n" ;
    print "Size: "    . $check->Size    ."<br>\n" ;
} else {
    print "imap_check() failed: ".imap_last_error(). "<br>\n";
}
 
imap_close($mbox);

?>

imap_mime_header_decode

(PHP 3>= 3.0.17, PHP 4 >= 4.0.0)

imap_mime_header_decode -- Decode MIME header elements

Description

array imap_mime_header_decode ( string text)

imap_mime_header_decode() function decodes MIME message header extensions that are non ASCII text (see RFC2047) The decoded elements are returned in an array of objects, where each object has two properties, "charset" & "text". If the element hasn't been encoded, and in other words is in plain US-ASCII,the "charset" property of that element is set to "default".

Przykład 1. imap_mime_header_decode() example

$text="=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@dkuug.dk>";

$elements=imap_mime_header_decode($text);
for($i=0;$i<count($elements);$i++) {
    echo "Charset: {$elements[$i]->charset}\n";
    echo "Text: {$elements[$i]->text}\n\n";
}

In the above example we would have two elements, whereas the first element had previously been encoded with ISO-8859-1, and the second element would be plain US-ASCII.

imap_msgno

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

imap_msgno --  This function returns the message sequence number for the given UID

Description

int imap_msgno ( int imap_stream, int uid)

This function returns the message sequence number for the given UID. It is the inverse of imap_uid().

imap_num_msg

(PHP 3, PHP 4 >= 4.0.0)

imap_num_msg --  Gives the number of messages in the current mailbox

Description

int imap_num_msg ( int imap_stream)

Return the number of messages in the current mailbox.

See also: imap_num_recent() and imap_status().

imap_num_recent

(PHP 3, PHP 4 >= 4.0.0)

imap_num_recent -- Gives the number of recent messages in current mailbox

Description

int imap_num_recent ( int imap_stream)

Returns the number of recent messages in the current mailbox.

See also: imap_num_msg() and imap_status().

imap_open

(PHP 3, PHP 4 >= 4.0.0)

imap_open -- Open an IMAP stream to a mailbox

Description

int imap_open ( string mailbox, string username, string password [, int flags])

Returns an IMAP stream on success and FALSE on error. This function can also be used to open streams to POP3 and NNTP servers, but some functions and features are not available on IMAP servers.

A mailbox name consists of a server part and a mailbox path on this server. The special name INBOX stands for the current users personal mailbox. The server part, which is enclosed in '{' and '}', consists of the servers name or ip address, an optional port (prefixed by ':'), and an optional protocol specification (prefixed by '/'). The server part is mandatory in all mailbox parameters. Mailbox names that contain international characters besides those in the printable ASCII space have to be encoded with imap_utf7_encode().

The options are a bit mask with one or more of the following:

  • OP_READONLY - Open mailbox read-only

  • OP_ANONYMOUS - Dont use or update a .newsrc for news (NNTP only)

  • OP_HALFOPEN - For IMAP and NNTP names, open a connection but dont open a mailbox

  • CL_EXPUNGE - Expunge mailbox automatically upon mailbox close

To connect to an IMAP server running on port 143 on the local machine, do the following:

$mbox = imap_open ("{localhost:143}INBOX", "user_id", "password");

To connect to a POP3 server on port 110 on the local server, use:

$mbox = imap_open ("{localhost:110/pop3}INBOX", "user_id", "password");

To connect to an SSL IMAP or POP3 server, add /ssl after the protocol specification:

$mbox = imap_open ("{localhost:993/imap/ssl}INBOX", "user_id", "password");

To connect to an SSL IMAP or POP3 server with a self-signed certificate, add /ssl/novalidate-cert after the protocol specification:

$mbox = imap_open ("{localhost:995/pop3/ssl/novalidate-cert}", "user_id", "password");

To connect to an NNTP server on port 119 on the local server, use:

$nntp = imap_open ("{localhost:119/nntp}comp.test", "", "");

To connect to a remote server replace "localhost" with the name or the IP address of the server you want to connect to.

Przykład 1. imap_open() example

$mbox = imap_open ("{your.imap.host:143}", "username", "password");

echo "<p><h1>Mailboxes</h1>\n";
$folders = imap_listmailbox ($mbox, "{your.imap.host:143}", "*");

if ($folders == false) {
    echo "Call failed<br>\n";
} else {
    while (list ($key, $val) = each ($folders)) {
        echo $val."<br>\n";
    }
}

echo "<p><h1>Headers in INBOX</h1>\n";
$headers = imap_headers ($mbox);

if ($headers == false) {
    echo "Call failed<br>\n";
} else {
    while (list ($key,$val) = each ($headers)) {
        echo $val."<br>\n";
    }
}

imap_close($mbox);

imap_ping

(PHP 3, PHP 4 >= 4.0.0)

imap_ping -- Check if the IMAP stream is still active

Description

int imap_ping ( int imap_stream)

Returns TRUE if the stream is still alive, FALSE otherwise.

imap_ping() function pings the stream to see it is still active. It may discover new mail; this is the preferred method for a periodic "new mail check" as well as a "keep alive" for servers which have inactivity timeout. (As PHP scripts do not tend to run that long, i can hardly imagine that this function will be usefull to anyone.)

imap_popen

(PHP 3>= 3.0.12, PHP 4 >= 4.0.0)

imap_popen --  Open a persistant IMAP stream to a mailbox

Description

int imap_popen ( string mailbox, string user, string password [, int options])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

imap_qprint

(PHP 3, PHP 4 >= 4.0.0)

imap_qprint -- Convert a quoted-printable string to an 8 bit string

Description

string imap_qprint ( string string)

Convert a quoted-printable string to an 8 bit string (according to RFC2045, section 6.7).

Returns an 8 bit (binary) string.

See also imap_8bit().

imap_renamemailbox

(PHP 3, PHP 4 >= 4.0.0)

imap_renamemailbox -- Rename an old mailbox to new mailbox

Description

int imap_renamemailbox ( int imap_stream, string old_mbox, string new_mbox)

This function renames on old mailbox to new mailbox (see imap_open() for the format of mbox names).

Returns TRUE on success and FALSE on error.

See also imap_createmailbox(), imap_deletemailbox(), and imap_open() for the format of mbox.

imap_reopen

(PHP 3, PHP 4 >= 4.0.0)

imap_reopen -- Reopen IMAP stream to new mailbox

Description

int imap_reopen ( int imap_stream, string mailbox [, string flags])

This function reopens the specified stream to a new mailbox on an IMAP or NNTP server.

The options are a bit mask with one or more of the following:

  • OP_READONLY - Open mailbox read-only

  • OP_ANONYMOUS - Dont use or update a .newsrc for news (NNTP only)

  • OP_HALFOPEN - For IMAP and NNTP names, open a connection but dont open a mailbox.

  • CL_EXPUNGE - Expunge mailbox automatically upon mailbox close (see also imap_delete() and imap_expunge())

Returns TRUE on success and FALSE on error.

imap_rfc822_parse_adrlist

(PHP 3>= 3.0.2, PHP 4 >= 4.0.0)

imap_rfc822_parse_adrlist -- Parses an address string

Description

array imap_rfc822_parse_adrlist ( string address, string default_host)

This function parses the address string as defined in RFC2822 and for each address, returns an array of objects. The objects properties are:

  • mailbox - the mailbox name (username)

  • host - the host name

  • personal - the personal name

  • adl - at domain source route

Przykład 1. imap_rfc822_parse_adrlist() example

$address_string = "Hartmut Holzgraefe <hartmut@cvs.php.net>, postmaster@somedomain.net, root";
$address_array  = imap_rfc822_parse_adrlist($address_string,"somedomain.net");
if(! is_array($address_array)) die("somethings wrong\n");
 
reset($address_array);
while(list($key,$val)=each($address_array)){
  print "mailbox : ".$val->mailbox."<br>\n";
  print "host    : ".$val->host."<br>\n";
  print "personal: ".$val->personal."<br>\n";
  print "adl     : ".$val->adl."<p>\n";
}

imap_rfc822_parse_headers

(PHP 4 >= 4.0.0)

imap_rfc822_parse_headers -- Parse mail headers from a string

Description

object imap_rfc822_parse_headers ( string headers [, string defaulthost])

This function returns an object of various header elements, similar to imap_header(), except without the flags and other elements that come from the IMAP server.

imap_rfc822_write_address

(PHP 3>= 3.0.2, PHP 4 >= 4.0.0)

imap_rfc822_write_address --  Returns a properly formatted email address given the mailbox, host, and personal info.

Description

string imap_rfc822_write_address ( string mailbox, string host, string personal)

Returns a properly formatted email address as defined in RFC2822 given the mailbox, host, and personal info.

Przykład 1. imap_rfc822_write_address() example

print imap_rfc822_write_address("hartmut","cvs.php.net","Hartmut Holzgraefe")."\n";

imap_scanmailbox

(PHP 3, PHP 4 >= 4.0.0)

imap_scanmailbox --  Read the list of mailboxes, takes a string to search for in the text of the mailbox

Description

array imap_scanmailbox ( int imap_stream, string ref, string pattern, string content)

Returns an array containing the names of the mailboxes that have content in the text of the mailbox. This function is similar to imap_listmailbox(), but it will additionally check for the presence of the string content inside the mailbox data. See imap_getmailboxes() for a description of ref and pattern.

imap_search

(PHP 3>= 3.0.12, PHP 4 >= 4.0.0)

imap_search --  This function returns an array of messages matching the given search criteria

Description

array imap_search ( int imap_stream, string criteria, int flags)

This function performs a search on the mailbox currently opened in the given imap stream. criteria is a string, delimited by spaces, in which the following keywords are allowed. Any multi-word arguments (eg. FROM "joey smith") must be quoted.

  • ALL - return all messages matching the rest of the criteria

  • ANSWERED - match messages with the \\ANSWERED flag set

  • BCC "string" - match messages with "string" in the Bcc: field

  • BEFORE "date" - match messages with Date: before "date"

  • BODY "string" - match messages with "string" in the body of the message

  • CC "string" - match messages with "string" in the Cc: field

  • DELETED - match deleted messages

  • FLAGGED - match messages with the \\FLAGGED (sometimes referred to as Important or Urgent) flag set

  • FROM "string" - match messages with "string" in the From: field

  • KEYWORD "string" - match messages with "string" as a keyword

  • NEW - match new messages

  • OLD - match old messages

  • ON "date" - match messages with Date: matching "date"

  • RECENT - match messages with the \\RECENT flag set

  • SEEN - match messages that have been read (the \\SEEN flag is set)

  • SINCE "date" - match messages with Date: after "date"

  • SUBJECT "string" - match messages with "string" in the Subject:

  • TEXT "string" - match messages with text "string"

  • TO "string" - match messages with "string" in the To:

  • UNANSWERED - match messages that have not been answered

  • UNDELETED - match messages that are not deleted

  • UNFLAGGED - match messages that are not flagged

  • UNKEYWORD "string" - match messages that do not have the keyword "string"

  • UNSEEN - match messages which have not been read yet

For example, to match all unanswered messages sent by Mom, you'd use: "UNANSWERED FROM mom". Searches appear to be case insensitive. This list of criteria is from a reading of the UW c-client source code and may be uncomplete or inaccurate (see also RFC2060, section 6.4.4).

Valid values for flags are SE_UID, which causes the returned array to contain UIDs instead of messages sequence numbers.

imap_setacl

(PHP 4 >= 4.1.0)

imap_setacl --  Sets the ACL for a giving mailbox

Description

int imap_setacl ( int stream_id, string mailbox, string id, string rights)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

imap_set_quota

(PHP 4 >= 4.0.5)

imap_set_quota -- Sets a quota for a given mailbox

Description

int imap_set_quota ( int imap_stream, string quota_root, int quota_limit)

Sets an upper limit quota on a per mailbox basis. This function requires the imap_stream to have been opened as the mail administrator account. It will not work if opened as any other user.

This function is currently only available to users of the c-client2000 library.

imap_stream is the stream pointer returned from a imap_open() call. This stream must be opened as the mail administrator, other wise this function will fail. quota_root is the mailbox to have a quota set. This should follow the IMAP standard format for a mailbox, 'user.name'. quota_limit is the maximum size (in KB) for the quota_root.

Returns TRUE on success and FALSE on error.

Przykład 1. imap_set_quota() example

$mbox = imap_open ("{your.imap.host:143}", "mailadmin", "password");

if(!imap_set_quota($mbox, "user.kalowsky", 3000)) {
    print "Error in setting quota\n";
    return;
}

imap_close($mbox);

See also imap_open(), imap_set_quota().

imap_setflag_full

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

imap_setflag_full -- Sets flags on messages

Description

string imap_setflag_full ( int stream, string sequence, string flag, string options)

This function causes a store to add the specified flag to the flags set for the messages in the specified sequence.

The flags which you can set are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", "\\Draft", and "\\Recent" (as defined by RFC2060).

The options are a bit mask with one or more of the following:


ST_UID          The sequence argument contains UIDs instead of
                sequence numbers
      

Przykład 1. imap_setflag_full() example

$mbox = imap_open("{your.imap.host:143}","username","password")
     or die("can't connect: ".imap_last_error());
 
$status = imap_setflag_full($mbox,"2,5","\\Seen \\Flagged");
 
print gettype($status)."\n";
print $status."\n";
 
imap_close($mbox);

imap_sort

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

imap_sort -- Sort an array of message headers

Description

array imap_sort ( int stream, int criteria, int reverse, int options)

Returns an array of message numbers sorted by the given parameters.

Reverse is 1 for reverse-sorting.

Criteria can be one (and only one) of the following:


SORTDATE        message Date
SORTARRIVAL     arrival date
SORTFROM        mailbox in first From address
SORTSUBJECT     message Subject
SORTTO          mailbox in first To address 
SORTCC          mailbox in first cc address 
SORTSIZE        size of message in octets
      

The flags are a bitmask of one or more of the following:


SE_UID          Return UIDs instead of sequence numbers
SE_NOPREFETCH   Don't prefetch searched messages.
      

imap_status

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

imap_status --  This function returns status information on a mailbox other than the current one

Description

object imap_status ( int imap_stream, string mailbox, int options)

This function returns an object containing status information. Valid flags are:

  • SA_MESSAGES - set status->messages to the number of messages in the mailbox

  • SA_RECENT - set status->recent to the number of recent messages in the mailbox

  • SA_UNSEEN - set status->unseen to the number of unseen (new) messages in the mailbox

  • SA_UIDNEXT - set status->uidnext to the next uid to be used in the mailbox

  • SA_UIDVALIDITY - set status->uidvalidity to a constant that changes when uids for the mailbox may no longer be valid

  • SA_ALL - set all of the above

status->flags is also set, which contains a bitmask which can be checked against any of the above constants.

Przykład 1. imap_status() example

$mbox = imap_open("{your.imap.host}","username","password",OP_HALFOPEN)
      or die("can't connect: ".imap_last_error());
 
$status = imap_status($mbox,"{your.imap.host}INBOX",SA_ALL);
if($status) {
  print("Messages:   ". $status->messages   )."<br>\n";
  print("Recent:     ". $status->recent     )."<br>\n";
  print("Unseen:     ". $status->unseen     )."<br>\n";
  print("UIDnext:    ". $status->uidnext    )."<br>\n";
  print("UIDvalidity:". $status->uidvalidity)."<br>\n"; 
} else
  print "imap_status failed: ".imap_last_error()."\n";
 
imap_close($mbox);

imap_subscribe

(PHP 3, PHP 4 >= 4.0.0)

imap_subscribe -- Subscribe to a mailbox

Description

int imap_subscribe ( int imap_stream, string mbox)

Subscribe to a new mailbox.

Returns TRUE on success and FALSE on error.

imap_uid

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

imap_uid --  This function returns the UID for the given message sequence number

Description

int imap_uid ( int imap_stream, int msgno)

This function returns the UID for the given message sequence number. An UID is an unique identifier that will not change over time while a message sequence number may change whenever the content of the mailbox changes. This function is the inverse of imap_msgno().

Notatka: This is not supported by POP3 mailboxes.

imap_undelete

(PHP 3, PHP 4 >= 4.0.0)

imap_undelete --  Unmark the message which is marked deleted

Description

int imap_undelete ( int imap_stream, int msg_number)

This function removes the deletion flag for a specified message, which is set by imap_delete() or imap_mail_move().

Returns TRUE on success and FALSE on error.

imap_unsubscribe

(PHP 3, PHP 4 >= 4.0.0)

imap_unsubscribe -- Unsubscribe from a mailbox

Description

int imap_unsubscribe ( int imap_stream, string mbox)

Unsubscribe from a specified mailbox.

Returns TRUE on success and FALSE on error.

imap_utf7_decode

(PHP 3>= 3.0.15, PHP 4 >= 4.0.0)

imap_utf7_decode --  Decodes a modified UTF-7 encoded string.

Description

string imap_utf7_decode ( string text)

Decodes modified UTF-7 text into 8bit data.

Returns the decoded 8bit data, or FALSE if the input string was not valid modified UTF-7. This function is needed to decode mailbox names that contain international characters outside of the printable ASCII range. The modified UTF-7 encoding is defined in RFC 2060, section 5.1.3 (original UTF-7 was defned in RFC1642).

imap_utf7_encode

(PHP 3>= 3.0.15, PHP 4 >= 4.0.0)

imap_utf7_encode --  Converts 8bit data to modified UTF-7 text.

Description

string imap_utf7_encode ( string data)

Converts 8bit data to modified UTF-7 text. This is needed to encode mailbox names that contain international characters outside of the printable ASCII range. The modified UTF-7 encoding is defined in RFC 2060, section 5.1.3 (original UTF-7 was defned in RFC1642).

Returns the modified UTF-7 text.

imap_utf8

(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)

imap_utf8 --  Converts text to UTF8

Description

string imap_utf8 ( string text)

Converts the given text to UTF8 (as defined in RFC2044).

imap_thread

(PHP 4 >= 4.1.0)

imap_thread --  Return threaded by REFERENCES tree

Description

int imap_thread ( int stream_id [, int flags])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

XLIII. Informix functions

The Informix driver for Informix (IDS) 7.x, SE 7.x, Universal Server (IUS) 9.x and IDS 2000 is implemented in "ifx.ec" and "php3_ifx.h" in the informix extension directory. IDS 7.x support is fairly complete, with full support for BYTE and TEXT columns. IUS 9.x support is partly finished: the new data types are there, but SLOB and CLOB support is still under construction.

Configuration notes: You need a version of ESQL/C to compile the PHP Informix driver. ESQL/C versions from 7.2x on should be OK. ESQL/C is now part of the Informix Client SDK.

Make sure that the "INFORMIXDIR" variable has been set, and that $INFORMIXDIR/bin is in your PATH before you run the "configure" script.

The configure script will autodetect the libraries and include directories, if you run "configure --with_informix=yes". You can override this detection by specifying "IFX_LIBDIR", "IFX_LIBS" and "IFX_INCDIR" in the environment. The configure script will also try to detect your Informix server version. It will set the "HAVE_IFX_IUS" conditional compilation variable if your Informix version >= 9.00.

Runtime considerations: Make sure that the Informix environment variables INFORMIXDIR and INFORMIXSERVER are available to the PHP ifx driver, and that the INFORMIX bin directory is in the PATH. Check this by running a script that contains a call to phpinfo()() before you start testing. The phpinfo()() output should list these environment variables. This is TRUE for both CGI php and Apache mod_php. You may have to set these environment variables in your Apache startup script.

The Informix shared libraries should also be available to the loader (check LD_LINBRARY_PATH or ld.so.conf/ldconfig).

Some notes on the use of BLOBs (TEXT and BYTE columns): BLOBs are normally addressed by BLOB identifiers. Select queries return a "blob id" for every BYTE and TEXT column. You can get at the contents with "string_var = ifx_get_blob($blob_id);" if you choose to get the BLOBs in memory (with : "ifx_blobinfile(0);"). If you prefer to receive the content of BLOB columns in a file, use "ifx_blobinfile(1);", and "ifx_get_blob($blob_id);" will get you the filename. Use normal file I/O to get at the blob contents.

For insert/update queries you must create these "blob id's" yourself with "ifx_create_blob();". You then plug the blob id's into an array, and replace the blob columns with a question mark (?) in the query string. For updates/inserts, you are responsible for setting the blob contents with ifx_update_blob().

The behaviour of BLOB columns can be altered by configuration variables that also can be set at runtime :

configuration variable : ifx.textasvarchar

configuration variable : ifx.byteasvarchar

runtime functions :

ifx_textasvarchar(0) : use blob id's for select queries with TEXT columns

ifx_byteasvarchar(0) : use blob id's for select queries with BYTE columns

ifx_textasvarchar(1) : return TEXT columns as if they were VARCHAR columns, so that you don't need to use blob id's for select queries.

ifx_byteasvarchar(1) : return BYTE columns as if they were VARCHAR columns, so that you don't need to use blob id's for select queries.

configuration variable : ifx.blobinfile

runtime function :

ifx_blobinfile_mode(0) : return BYTE columns in memory, the blob id lets you get at the contents.

ifx_blobinfile_mode(1) : return BYTE columns in a file, the blob id lets you get at the file name.

If you set ifx_text/byteasvarchar to 1, you can use TEXT and BYTE columns in select queries just like normal (but rather long) VARCHAR fields. Since all strings are "counted" in PHP, this remains "binary safe". It is up to you to handle this correctly. The returned data can contain anything, you are responsible for the contents.

If you set ifx_blobinfile to 1, use the file name returned by ifx_get_blob(..) to get at the blob contents. Note that in this case YOU ARE RESPONSIBLE FOR DELETING THE TEMPORARY FILES CREATED BY INFORMIX when fetching the row. Every new row fetched will create new temporary files for every BYTE column.

The location of the temporary files can be influenced by the environment variable "blobdir", default is "." (the current directory). Something like : putenv(blobdir=tmpblob"); will ease the cleaning up of temp files accidentally left behind (their names all start with "blb").

Automatically trimming "char" (SQLCHAR and SQLNCHAR) data: This can be set with the configuration variable

ifx.charasvarchar : if set to 1 trailing spaces will be automatically trimmed, to save you some "chopping".

NULL values: The configuration variable ifx.nullformat (and the runtime function ifx_nullformat()) when set to TRUE will return NULL columns as the string "NULL", when set to FALSE they return the empty string. This allows you to discriminate between NULL columns and empty columns.

Spis treści
ifx_connect -- Open Informix server connection
ifx_pconnect -- Open persistent Informix connection
ifx_close -- Close Informix connection
ifx_query -- Send Informix query
ifx_prepare -- Prepare an SQL-statement for execution
ifx_do --  Execute a previously prepared SQL-statement
ifx_error -- Returns error code of last Informix call
ifx_errormsg -- Returns error message of last Informix call
ifx_affected_rows -- Get number of rows affected by a query
ifx_getsqlca --  Get the contents of sqlca.sqlerrd[0..5] after a query
ifx_fetch_row -- Get row as enumerated array
ifx_htmltbl_result --  Formats all rows of a query into a HTML table
ifx_fieldtypes -- List of Informix SQL fields
ifx_fieldproperties -- List of SQL fieldproperties
ifx_num_fields -- Returns the number of columns in the query
ifx_num_rows -- Count the rows already fetched from a query
ifx_free_result -- Releases resources for the query
ifx_create_char -- Creates an char object
ifx_free_char -- Deletes the char object
ifx_update_char -- Updates the content of the char object
ifx_get_char -- Return the content of the char object
ifx_create_blob -- Creates an blob object
ifx_copy_blob -- Duplicates the given blob object
ifx_free_blob -- Deletes the blob object
ifx_get_blob -- Return the content of a blob object
ifx_update_blob -- Updates the content of the blob object
ifx_blobinfile_mode -- Set the default blob mode for all select queries
ifx_textasvarchar -- Set the default text mode
ifx_byteasvarchar -- Set the default byte mode
ifx_nullformat --  Sets the default return value on a fetch row
ifxus_create_slob -- Creates an slob object and opens it
ifxus_free_slob -- Deletes the slob object
ifxus_close_slob -- Deletes the slob object
ifxus_open_slob -- Opens an slob object
ifxus_tell_slob -- Returns the current file or seek position
ifxus_seek_slob -- Sets the current file or seek position
ifxus_read_slob -- Reads nbytes of the slob object
ifxus_write_slob -- Writes a string into the slob object

ifx_connect

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

ifx_connect -- Open Informix server connection

Description

int ifx_connect ( [string database [, string userid [, string password]]])

Returns a connection identifier on success, or FALSE on error.

ifx_connect() establishes a connection to an Informix server. All of the arguments are optional, and if they're missing, defaults are taken from values supplied in configuration file (ifx.default_host for the host (Informix libraries will use INFORMIXSERVER environment value if not defined), ifx.default_user for user, ifx.default_password for the password (none if not defined).

In case a second call is made to ifx_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling ifx_close().

See also ifx_pconnect(), and ifx_close().

Przykład 1. Connect to a Informix database

$conn_id = ifx_connect ("mydb@ol_srv1", "imyself", "mypassword");

ifx_pconnect

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

ifx_pconnect -- Open persistent Informix connection

Description

int ifx_pconnect ( [string database [, string userid [, string password]]])

Returns: A positive Informix persistent link identifier on success, or FALSE on error

ifx_pconnect() acts very much like ifx_connect() with two major differences.

This function behaves exactly like ifx_connect() when PHP is not running as an Apache module. First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ifx_close() will not close links established by ifx_pconnect()).

This type of links is therefore called 'persistent'.

See also: ifx_connect().

ifx_close

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

ifx_close -- Close Informix connection

Description

int ifx_close ( [int link_identifier])

Returns: always TRUE.

ifx_close() closes the link to an Informix database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

ifx_close() will not close persistent links generated by ifx_pconnect().

See also: ifx_connect(), and ifx_pconnect().

Przykład 1. Closing a Informix connection

$conn_id = ifx_connect ("mydb@ol_srv", "itsme", "mypassword");
... some queries and stuff ...
ifx_close($conn_id);

ifx_query

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

ifx_query -- Send Informix query

Description

int ifx_query ( string query [, int link_identifier [, int cursor_type [, mixed blobidarray]]])

Returns: A positive Informix result identifier on success, or FALSE on error.

A "result_id" resource used by other functions to retrieve the query results. Sets "affected_rows" for retrieval by the ifx_affected_rows() function.

ifx_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if ifx_connect() was called, and use it.

Executes query on connection conn_id. For "select-type" queries a cursor is declared and opened. The optional cursor_type parameter allows you to make this a "scroll" and/or "hold" cursor. It's a bitmask and can be either IFX_SCROLL, IFX_HOLD, or both or'ed together. Non-select queries are "execute immediate". IFX_SCROLL and IFX_HOLD are symbolic constants and as such shouldn't be between quotes. I you omit this parameter the cursor is a normal sequential cursor.

For either query type the number of (estimated or real) affected rows is saved for retrieval by ifx_affected_rows().

If you have BLOB (BYTE or TEXT) columns in an update query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.

If the contents of the TEXT (or BYTE) column allow it, you can also use "ifx_textasvarchar(1)" and "ifx_byteasvarchar(1)". This allows you to treat TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR columns for select queries, and you don't need to bother with blob id's.

With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation), select queries will return BLOB columns as blob id's (integer value). You can get the value of the blob as a string or file with the blob functions (see below).

See also: ifx_connect().

Przykład 1. Show all rows of the "orders" table as a html table

ifx_textasvarchar(1);      // use "text mode" for blobs
$res_id = ifx_query("select * from orders", $conn_id);
if (! $res_id) {
    printf("Can't select orders : %s\n<br>%s<br>\n", ifx_error());
    ifx_errormsg();
    die;
}
ifx_htmltbl_result($res_id, "border=\"1\"");
ifx_free_result($res_id);

Przykład 2. Insert some values into the "catalog" table

// create blob id's for a byte and text column
$textid = ifx_create_blob(0, 0, "Text column in memory");
$byteid = ifx_create_blob(1, 0, "Byte column in memory");
                      // store blob id's in a blobid array
$blobidarray[] = $textid;
$blobidarray[] = $byteid;
                      // launch query
$query = "insert into catalog (stock_num, manu_code, " .
         "cat_descr,cat_picture) values(1,'HRO',?,?)";
$res_id = ifx_query($query, $conn_id, $blobidarray);
if (! $res_id) {
  ... error ...
}
                     // free result id
ifx_free_result($res_id);

ifx_prepare

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

ifx_prepare -- Prepare an SQL-statement for execution

Description

int ifx_prepare ( string query, int conn_id [, int cursor_def, mixed blobidarray])

Returns a integer result_id for use by ifx_do(). Sets affected_rows for retrieval by the ifx_affected_rows() function.

Prepares query on connection conn_id. For "select-type" queries a cursor is declared and opened. The optional cursor_type parameter allows you to make this a "scroll" and/or "hold" cursor. It's a bitmask and can be either IFX_SCROLL, IFX_HOLD, or both or'ed together.

For either query type the estimated number of affected rows is saved for retrieval by ifx_affected_rows().

If you have BLOB (BYTE or TEXT) columns in the query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.

If the contents of the TEXT (or BYTE) column allow it, you can also use "ifx_textasvarchar(1)" and "ifx_byteasvarchar(1)". This allows you to treat TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR columns for select queries, and you don't need to bother with blob id's.

With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation), select queries will return BLOB columns as blob id's (integer value). You can get the value of the blob as a string or file with the blob functions (see below).

See also: ifx_do().

ifx_do

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

ifx_do --  Execute a previously prepared SQL-statement

Description

int ifx_do ( int result_id)

Returns TRUE on success, FALSE on error.

Executes a previously prepared query or opens a cursor for it.

Does NOT free result_id on error.

Also sets the real number of ifx_affected_rows() for non-select statements for retrieval by ifx_affected_rows()

See also: ifx_prepare(). There is a example.

ifx_error

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

ifx_error -- Returns error code of last Informix call

Description

string ifx_error ( void)

The Informix error codes (SQLSTATE & SQLCODE) formatted as follows :

x [SQLSTATE = aa bbb SQLCODE=cccc]

where x = space : no error

E : error

N : no more data

W : warning

? : undefined

If the "x" character is anything other than space, SQLSTATE and SQLCODE describe the error in more detail.

See the Informix manual for the description of SQLSTATE and SQLCODE

Returns in a string one character describing the general results of a statement and both SQLSTATE and SQLCODE associated with the most recent SQL statement executed. The format of the string is "(char) [SQLSTATE=(two digits) (three digits) SQLCODE=(one digit)]". The first character can be ' ' (space) (success), 'W' (the statement caused some warning), 'E' (an error happened when executing the statement) or 'N' (the statement didn't return any data).

See also: ifx_errormsg()

ifx_errormsg

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

ifx_errormsg -- Returns error message of last Informix call

Description

string ifx_errormsg ( [int errorcode])

Returns the Informix error message associated with the most recent Informix error, or, when the optional "errorcode" param is present, the error message corresponding to "errorcode".

See also: ifx_error()

printf("%s\n&lt;br>", ifx_errormsg(-201));

ifx_affected_rows

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

ifx_affected_rows -- Get number of rows affected by a query

Description

int ifx_affected_rows ( int result_id)

result_id is a valid result id returned by ifx_query() or ifx_prepare().

Returns the number of rows affected by a query associated with result_id.

For inserts, updates and deletes the number is the real number (sqlerrd[2]) of affected rows. For selects it is an estimate (sqlerrd[0]). Don't rely on it. The database server can never return the actual number of rows that will be returned by a SELECT because it has not even begun fetching them at this stage (just after the "PREPARE" when the optimizer has determined the query plan).

Useful after ifx_prepare() to limit queries to reasonable result sets.

See also: ifx_num_rows()

Przykład 1. Informix affected rows

$rid = ifx_prepare ("select * from emp 
                     where name like " . $name, $connid);
if (! $rid) {
    ... error ...
}
$rowcount = ifx_affected_rows ($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br>", $rowcount);
    die ("Please restrict your query<br>\n");
}

ifx_getsqlca

(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)

ifx_getsqlca --  Get the contents of sqlca.sqlerrd[0..5] after a query

Description

array ifx_getsqlca ( int result_id)

result_id is a valid result id returned by ifx_query() or ifx_prepare().

Returns a pseudo-row (associative array) with sqlca.sqlerrd[0] ... sqlca.sqlerrd[5] after the query associated with result_id.

For inserts, updates and deletes the values returned are those as set by the server after executing the query. This gives access to the number of affected rows and the serial insert value. For SELECTs the values are those saved after the PREPARE statement. This gives access to the *estimated* number of affected rows. The use of this function saves the overhead of executing a "select dbinfo('sqlca.sqlerrdx')" query, as it retrieves the values that were saved by the ifx driver at the appropriate moment.

Przykład 1. Retrieve Informix sqlca.sqlerrd[x] values

/* assume the first column of 'sometable' is a serial */
$qid = ifx_query("insert into sometable 
                  values (0, '2nd column', 'another column') ", $connid);
if (! $qid) {
    ... error ...
}
$sqlca = ifx_getsqlca ($qid);
$serial_value = $sqlca["sqlerrd1"];
echo "The serial value of the inserted row is : " . $serial_value<br>\n";

ifx_fetch_row

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

ifx_fetch_row -- Get row as enumerated array

Description

array ifx_fetch_row ( int result_id [, mixed position])

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

Blob columns are returned as integer blob id values for use in ifx_get_blob() unless you have used ifx_textasvarchar(1) or ifx_byteasvarchar(1), in which case blobs are returned as string values. Returns FALSE on error

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

position is an optional parameter for a "fetch" operation on "scroll" cursors: "NEXT", "PREVIOUS", "CURRENT", "FIRST", "LAST" or a number. If you specify a number, an "absolute" row fetch is executed. This parameter is optional, and only valid for SCROLL cursors.

ifx_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0, with the column name as key.

Subsequent calls to ifx_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Przykład 1. Informix fetch rows

$rid = ifx_prepare ("select * from emp where name like " . $name,
                     $connid, IFX_SCROLL);
if (! $rid) {
    ... error ...
}
$rowcount = ifx_affected_rows($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br>", $rowcount);
    die ("Please restrict your query<br>\n");
}
if (! ifx_do ($rid)) {
   ... error ...
}
$row = ifx_fetch_row ($rid, "NEXT");
while (is_array($row)) {
    for(reset($row); $fieldname=key($row); next($row)) {
        $fieldvalue = $row[$fieldname];
        printf ("%s = %s,", $fieldname, $fieldvalue);
    }
    printf("\n<br>");
    $row = ifx_fetch_row ($rid, "NEXT");
}
ifx_free_result ($rid);

ifx_htmltbl_result

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

ifx_htmltbl_result --  Formats all rows of a query into a HTML table

Description

int ifx_htmltbl_result ( int result_id [, string html_table_options])

Returns the number of rows fetched or FALSE on error.

Formats all rows of the result_id query into a html table. The optional second argument is a string of <table> tag options

Przykład 1. Informix results as HTML table

$rid = ifx_prepare ("select * from emp where name like " . $name,
                     $connid, IFX_SCROLL);
if (! $rid) {
   ... error ...
}
$rowcount = ifx_affected_rows ($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br>", $rowcount);
    die ("Please restrict your query<br>\n");
}
if (! ifx_do($rid) {
  ... error ...
}

ifx_htmltbl_result ($rid, "border=\"2\"");

ifx_free_result($rid);

ifx_fieldtypes

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

ifx_fieldtypes -- List of Informix SQL fields

Description

array ifx_fieldtypes ( int result_id)

Returns an associative array with fieldnames as key and the SQL fieldtypes as data for query with result_id. Returns FALSE on error.

Przykład 1. Fieldnames and SQL fieldtypes

$types = ifx_fieldtypes ($resultid);
if (! isset ($types)) {
  ... error ...
}
for ($i = 0; $i < count($types); $i++) {
    $fname = key($types);
    printf("%s :\t type =  %s\n", $fname, $types[$fname]);
    next($types);
}

ifx_fieldproperties

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

ifx_fieldproperties -- List of SQL fieldproperties

Description

array ifx_fieldproperties ( int result_id)

Returns an associative array with fieldnames as key and the SQL fieldproperties as data for a query with result_id. Returns FALSE on error.

Returns the Informix SQL fieldproperties of every field in the query as an associative array. Properties are encoded as: "SQLTYPE;length;precision;scale;ISNULLABLE" where SQLTYPE = the Informix type like "SQLVCHAR" etc. and ISNULLABLE = "Y" or "N".

Przykład 1. Informix SQL fieldproperties

$properties = ifx_fieldproperties ($resultid);
if (! isset($properties)) {
  ... error ...
}
for ($i = 0; $i < count($properties); $i++) {
    $fname = key ($properties);
    printf ("%s:\t type =  %s\n", $fname, $properties[$fname]);
    next ($properties);
}

ifx_num_fields

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

ifx_num_fields -- Returns the number of columns in the query

Description

int ifx_num_fields ( int result_id)

Returns the number of columns in query for result_id or FALSE on error

After preparing or executing a query, this call gives you the number of columns in the query.

ifx_num_rows

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

ifx_num_rows -- Count the rows already fetched from a query

Description

int ifx_num_rows ( int result_id)

Gives the number of rows fetched so far for a query with result_id after a ifx_query() or ifx_do() query.

ifx_free_result

(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)

ifx_free_result -- Releases resources for the query

Description

int ifx_free_result ( int result_id)

Releases resources for the query associated with result_id. Returns FALSE on error.

ifx_create_char

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

ifx_create_char -- Creates an char object

Description

int ifx_create_char ( string param)

Creates an char object. param should be the char content.

ifx_free_char

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

ifx_free_char -- Deletes the char object

Description

int ifx_free_char ( int bid)

Deletes the charobject for the given char object-id bid. Returns FALSE on error otherwise TRUE.

ifx_update_char

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

ifx_update_char -- Updates the content of the char object

Description

int ifx_update_char ( int bid, string content)

Updates the content of the char object for the given char object bid. content is a string with new data. Returns FALSE on error otherwise TRUE.

ifx_get_char

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

ifx_get_char -- Return the content of the char object

Description

int ifx_get_char ( int bid)

Returns the content of the char object for the given char object-id bid.

ifx_create_blob

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

ifx_create_blob -- Creates an blob object

Description

int ifx_create_blob ( int type, int mode, string param)

Creates an blob object.

type: 1 = TEXT, 0 = BYTE

mode: 0 = blob-object holds the content in memory, 1 = blob-object holds the content in file.

param: if mode = 0: pointer to the content, if mode = 1: pointer to the filestring.

Return FALSE on error, otherwise the new blob object-id.

ifx_copy_blob

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

ifx_copy_blob -- Duplicates the given blob object

Description

int ifx_copy_blob ( int bid)

Duplicates the given blob object. bid is the ID of the blob object.

Returns FALSE on error otherwise the new blob object-id.

ifx_free_blob

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

ifx_free_blob -- Deletes the blob object

Description

int ifx_free_blob ( int bid)

Deletes the blobobject for the given blob object-id bid. Returns FALSE on error otherwise TRUE.

ifx_get_blob

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

ifx_get_blob -- Return the content of a blob object

Description

int ifx_get_blob ( int bid)

Returns the content of the blob object for the given blob object-id bid.

ifx_update_blob

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

ifx_update_blob -- Updates the content of the blob object

Description

ifx_update_blob ( int bid, string content)

Updates the content of the blob object for the given blob object bid. content is a string with new data. Returns FALSE on error otherwise TRUE.

ifx_blobinfile_mode

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

ifx_blobinfile_mode -- Set the default blob mode for all select queries

Description

void ifx_blobinfile_mode ( int mode)

Set the default blob mode for all select queries. Mode "0" means save Byte-Blobs in memory, and mode "1" means save Byte-Blobs in a file.

ifx_textasvarchar

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

ifx_textasvarchar -- Set the default text mode

Description

void ifx_textasvarchar ( int mode)

Sets the default text mode for all select-queries. Mode "0" will return a blob id, and mode "1" will return a varchar with text content.

ifx_byteasvarchar

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

ifx_byteasvarchar -- Set the default byte mode

Description

void ifx_byteasvarchar ( int mode)

Sets the default byte mode for all select-queries. Mode "0" will return a blob id, and mode "1" will return a varchar with text content.

ifx_nullformat

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

ifx_nullformat --  Sets the default return value on a fetch row

Description

void ifx_nullformat ( int mode)

Sets the default return value of a NULL-value on a fetch row. Mode "0" returns "", and mode "1" returns "NULL".

ifxus_create_slob

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

ifxus_create_slob -- Creates an slob object and opens it

Description

int ifxus_create_slob ( int mode)

Creates an slob object and opens it. Modes: 1 = LO_RDONLY, 2 = LO_WRONLY, 4 = LO_APPEND, 8 = LO_RDWR, 16 = LO_BUFFER, 32 = LO_NOBUFFER -> or-mask. You can also use constants named IFX_LO_RDONLY, IFX_LO_WRONLY etc. Return FALSE on error otherwise the new slob object-id.

ifxus_free_slob

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

ifxus_free_slob -- Deletes the slob object

Description

int ifxus_free_slob ( int bid)

Deletes the slob object. bid is the Id of the slob object. Returns FALSE on error otherwise TRUE.

ifxus_close_slob

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

ifxus_close_slob -- Deletes the slob object

Description

int ifxus_close_slob ( int bid)

Deletes the slob object on the given slob object-id bid. Return FALSE on error otherwise TRUE.

ifxus_open_slob

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

ifxus_open_slob -- Opens an slob object

Description

int ifxus_open_slob ( long bid, int mode)

Opens an slob object. bid should be an existing slob id. Modes: 1 = LO_RDONLY, 2 = LO_WRONLY, 4 = LO_APPEND, 8 = LO_RDWR, 16 = LO_BUFFER, 32 = LO_NOBUFFER -> or-mask. Returns FALSE on error otherwise the new slob object-id.

ifxus_tell_slob

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

ifxus_tell_slob -- Returns the current file or seek position

Description

int ifxus_tell_slob ( long bid)

Returns the current file or seek position of an open slob object bid should be an existing slob id. Return FALSE on error otherwise the seek position.

ifxus_seek_slob

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

ifxus_seek_slob -- Sets the current file or seek position

Description

int ifxus_seek_slob ( long bid, int mode, long offset)

Sets the current file or seek position of an open slob object. bid should be an existing slob id. Modes: 0 = LO_SEEK_SET, 1 = LO_SEEK_CUR, 2 = LO_SEEK_END and offset is an byte offset. Return FALSE on error otherwise the seek position.

ifxus_read_slob

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

ifxus_read_slob -- Reads nbytes of the slob object

Description

int ifxus_read_slob ( long bid, long nbytes)

Reads nbytes of the slob object. bid is a existing slob id and nbytes is the number of bytes read. Return FALSE on error otherwise the string.

ifxus_write_slob

(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)

ifxus_write_slob -- Writes a string into the slob object

Description

int ifxus_write_slob ( long bid, string content)

Writes a string into the slob object. bid is a existing slob id and content the content to write. Return FALSE on error otherwise bytes written.

XLIV. InterBase functions

InterBase is a popular database put out by Borland/Inprise. More information about InterBase is available at http://www.interbase.com/. Oh, by the way, InterBase just joined the open source movement!

Notatka: Full support for InterBase 6 was added in PHP 4.0.

This database uses a single quote (') character for escaping, a behavior similar to the Sybase database, add to your php.ini the following directive:

magic_quotes_sybase = On

Spis treści
ibase_connect --  Open a connection to an InterBase database
ibase_pconnect --  Creates an persistent connection to an InterBase database
ibase_close --  Close a connection to an InterBase database
ibase_query -- Execute a query on an InterBase database
ibase_errmsg --  Returns error messages
ibase_fetch_row -- Fetch a row from an InterBase database
ibase_fetch_object -- Get an object from a InterBase database
ibase_field_info --  Get information about a field
ibase_free_query --  Free memory allocated by a prepared query
ibase_free_result -- Free a result set
ibase_prepare --  Prepare a query for later binding of parameter placeholders and execution
ibase_execute -- Execute a previously prepared query
ibase_trans -- Begin a transaction
ibase_commit -- Commit a transaction
ibase_rollback -- Rolls back a transaction
ibase_timefmt --  Sets the format of timestamp, date and time type columns returned from queries
ibase_num_fields --  Get the number of fields in a result set
ibase_blob_add --  Add data into created blob
ibase_blob_cancel --  Cancel creating blob
ibase_blob_close --  Close blob
ibase_blob_create --  Create blob for adding data
ibase_blob_echo --  Output blob contents to browser
ibase_blob_get --  Get len bytes data from open blob
ibase_blob_import --  Create blob, copy file in it, and close it
ibase_blob_info --  Return blob length and other useful info
ibase_blob_open --  Open blob for retrieving data parts

ibase_connect

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

ibase_connect --  Open a connection to an InterBase database

Description

int ibase_connect ( string database [, string username [, string password [, string charset [, int buffers [, int dialect [, string role]]]]]])

Establishes a connection to an InterBase server. The database argument has to be a valid path to database file on the server it resides on. If the server is not local, it must be prefixed with either 'hostname:' (TCP/IP), '//hostname/' (NetBEUI) or 'hostname@' (IPX/SPX), depending on the connection protocol used. username and password can also be specified with PHP configuration directives ibase.default_user and ibase.default_password. charset is the default character set for a database. buffers is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default. dialect selects the default SQL dialect for any statement executed within a connection, and it defaults to the highest one supported by client libraries.

In case a second call is made to ibase_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling ibase_close().

Przykład 1. ibase_connect() example

<?php
    $dbh = ibase_connect($host, $username, $password);
    $stmt = 'SELECT * FROM tblname';
    $sth = ibase_query($dbh, $stmt);
    while ($row = ibase_fetch_object($sth)) {
        echo $row->email, "\n";
    }
    ibase_free_result($sth);
    ibase_close($dbh);
?>

Notatka: buffers was added in PHP 4.0RC2.

Notatka: dialect was added in PHP 4.0RC2. It is functional only with InterBase 6 and versions higher than that.

Notatka: role was added in PHP 4.0RC2. It is functional only with InterBase 5 and versions higher than that.

See also ibase_pconnect().

ibase_pconnect

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

ibase_pconnect --  Creates an persistent connection to an InterBase database

Description

int ibase_pconnect ( string database [, string username [, string password [, string charset [, int buffers [, int dialect [, string role]]]]]])

ibase_pconnect() acts very much like ibase_connect() with two major differences. First, when connecting, the function will first try to find a (persistent) link that's already opened with the same parameters. If one is found, an identifier for it will be returned instead of opening a new connection. Second, the connection to the InterBase server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ibase_close() will not close links established by ibase_pconnect()). This type of link is therefore called 'persistent'.

Notatka: buffers was added in PHP4-RC2.

Notatka: dialect was added in PHP4-RC2. It is functional only with InterBase 6 and versions higher than that.

Notatka: role was added in PHP4-RC2. It is functional only with InterBase 5 and versions higher than that.

See also ibase_connect() for the meaning of parameters passed to this function. They are exactly the same.

ibase_close

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

ibase_close --  Close a connection to an InterBase database

Description

int ibase_close ( [int connection_id])

Closes the link to an InterBase database that's associated with a connection id returned from ibase_connect(). If the connection id is omitted, the last opened link is assumed. Default transaction on link is committed, other transactions are rolled back.

ibase_query

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

ibase_query -- Execute a query on an InterBase database

Description

int ibase_query ( [int link_identifier, string query [, int bind_args]])

Performs a query on an InterBase database. If the query is not successful, returns FALSE. If it is successful and there are resulting rows (such as with a SELECT query), returns a result identifier. If the query was successful and there were no results, returns TRUE. Returns FALSE if the query fails.

See also ibase_errmsg(), ibase_fetch_row(), ibase_fetch_object(), and ibase_free_result().

ibase_errmsg

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

ibase_errmsg --  Returns error messages

Description

string ibase_errmsg ( void)

Returns a string containing an error message.

ibase_fetch_row

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

ibase_fetch_row -- Fetch a row from an InterBase database

Description

array ibase_fetch_row ( int result_identifier)

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

ibase_fetch_row() fetches one row of data from the result associated with the specified result_identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Subsequent call to ibase_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

ibase_fetch_object

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

ibase_fetch_object -- Get an object from a InterBase database

Description

object ibase_fetch_object ( int result_id)

Fetches a row as a pseudo-object from a result_id obtained either by ibase_query() or ibase_execute().

<php
    $dbh = ibase_connect ($host, $username, $password);
    $stmt = 'SELECT * FROM tblname';
    $sth = ibase_query ($dbh, $stmt);
    while ($row = ibase_fetch_object ($sth)) {
        print $row->email . "\n";
    }
    ibase_close ($dbh);
?>

Subsequent call to ibase_fetch_object() would return the next row in the result set, or FALSE if there are no more rows.

See also ibase_fetch_row().

ibase_field_info

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

ibase_field_info --  Get information about a field

Description

array ibase_field_info ( int result, int field number)

Returns an array with information about a field after a select query has been run. The array is in the form of name, alias, relation, length, type.

$rs=ibase_query("SELECT * FROM tablename"); 
$coln = ibase_num_fields($rs);
for ($i=0; $i < $coln; $i++) {
    $col_info = ibase_field_info($rs, $i); 
    echo "name: ".$col_info['name']."\n"; 
    echo "alias: ".$col_info['alias']."\n"; 
    echo "relation: ".$col_info['relation']."\n"; 
    echo "length: ".$col_info['length']."\n"; 
    echo "type: ".$col_info['type']."\n"; 
    }

ibase_free_query

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

ibase_free_query --  Free memory allocated by a prepared query

Description

int ibase_free_query ( int query)

Free a query prepared by ibase_prepare().

ibase_free_result

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

ibase_free_result -- Free a result set

Description

int ibase_free_result ( int result_identifier)

Free's a result set the has been created by ibase_query().

ibase_prepare

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

ibase_prepare --  Prepare a query for later binding of parameter placeholders and execution

Description

int ibase_prepare ( [int link_identifier, string query])

Prepare a query for later binding of parameter placeholders and execution (via ibase_execute()).

ibase_execute

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

ibase_execute -- Execute a previously prepared query

Description

int ibase_execute ( int query [, int bind_args])

Execute a query prepared by ibase_prepare(). This is a lot more effective than using ibase_query() if you are repeating a same kind of query several times with only some parameters changing.

<?php
    $updates = array(
        1 => 'Eric',
        5 => 'Filip',
        7 => 'Larry'
    );

    $query = ibase_prepare("UPDATE FOO SET BAR = ? WHERE BAZ = ?");

    while (list($baz, $bar) = each($updates)) {
        ibase_execute($query, $bar, $baz);
    }
?>

ibase_trans

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

ibase_trans -- Begin a transaction

Description

int ibase_trans ( [int trans_args [, int link_identifier]])

Begins a transaction.

ibase_commit

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

ibase_commit -- Commit a transaction

Description

int ibase_commit ( [int link_identifier, int trans_number])

Commits transaction trans_number which was created with ibase_trans().

ibase_rollback

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

ibase_rollback -- Rolls back a transaction

Description

int ibase_rollback ( [int link_identifier, int trans_number])

Rolls back transaction trans_number which was created with ibase_trans().

ibase_timefmt

(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)

ibase_timefmt --  Sets the format of timestamp, date and time type columns returned from queries

Description

int ibase_timefmt ( string format [, int columntype])

Sets the format of timestamp, date or time type columns returned from queries. Internally, the columns are formatted by c-function strftime(), so refer to it's documentation regarding to the format of the string. columntype is one of the constants IBASE_TIMESTAMP, IBASE_DATE and IBASE_TIME. If omitted, defaults to IBASE_TIMESTAMP for backwards compatibility.

<?php
       // InterBase 6 TIME-type columns will be returned in
       // the form '05 hours 37 minutes'. 
       ibase_timefmt("%H hours %M minutes", IBASE_TIME);
       ?>

You can also set defaults for these formats with PHP configuration directives ibase.timestampformat, ibase.dateformat and ibase.timeformat.

Notatka: columntype was added in PHP 4.0. It has any meaning only with InterBase version 6 and higher.

Notatka: A backwards incompatible change happened in PHP 4.0 when PHP configuration directive ibase.timeformat was renamed to ibase.timestampformat and directives ibase.dateformat and ibase.timeformat were added, so that the names would match better their functionality.

ibase_num_fields

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

ibase_num_fields --  Get the number of fields in a result set

Description

int ibase_num_fields ( int result_id)

Returns an integer containing the number of fields in a result set.

<?php
       $dbh = ibase_connect ($host, $username, $password);
       $stmt = 'SELECT * FROM tblname';
       $sth = ibase_query ($dbh, $stmt);

       if (ibase_num_fields($sth) > 0) {
       while ($row = ibase_fetch_object ($sth)) {
       print $row->email . "\n";
       }
       } else {
       die ("No Results were found for your query");
       }

       ibase_close ($dbh);
       ?>

See also: ibase_field_info().

ibase_blob_add

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

ibase_blob_add --  Add data into created blob

Description

int ibase_blob_add ( int blob_id, string data)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ibase_blob_cancel

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

ibase_blob_cancel --  Cancel creating blob

Description

int ibase_blob_cancel ( int blob_id)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ibase_blob_close

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

ibase_blob_close --  Close blob

Description

int ibase_blob_close ( int blob_id)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ibase_blob_create

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

ibase_blob_create --  Create blob for adding data

Description

int ibase_blob_create ( [int link_identifier])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ibase_blob_echo

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

ibase_blob_echo --  Output blob contents to browser

Description

int ibase_blob_echo ( string blob_id_str)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ibase_blob_get

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

ibase_blob_get --  Get len bytes data from open blob

Description

string ibase_blob_get ( int blob_id, int len)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ibase_blob_import

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

ibase_blob_import --  Create blob, copy file in it, and close it

Description

string ibase_blob_import ( [int link_identifier, int file_id])

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ibase_blob_info

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

ibase_blob_info --  Return blob length and other useful info

Description

object ibase_blob_info ( string blob_id_str)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ibase_blob_open

(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)

ibase_blob_open --  Open blob for retrieving data parts

Description

int ibase_blob_open ( string blob_id)

Ostrze¿enie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

XLV. Ingres II functions

Ostrze¿enie

Ten moduł jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie tych funkcji, ich nazwy, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tego modułu na własne ryzyko.

These functions allow you to access Ingres II database servers.

In order to have these functions available, you must compile php with Ingres support by using the --with-ingres option. You need the Open API library and header files included with Ingres II. If the II_SYSTEM environment variable isn't correctly set you may have to use --with-ingres=DIR to specify your Ingres installation directory.

When using this extension with Apache, if Apache does not start and complains with "PHP Fatal error: Unable to start ingres_ii module in Unknown on line 0" then make sure the environement variable II_SYSTEM is correctly set. Adding "export II_SYSTEM="/home/ingres/II" in the script that starts Apache, just before launching httpd, should be fine.

Notatka: If you already used PHP extensions to access other database servers, note that Ingres doesn't allow concurrent queries and/or transaction over one connection, thus you won't find any result or transaction handle in this extension. The result of a query must be treated before sending another query, and a transaction must be commited or rolled back before opening another transaction (which is automaticaly done when sending the first query).

Spis treści
ingres_connect --  Open a connection to an Ingres II database
ingres_pconnect --  Open a persistent connection to an Ingres II database
ingres_close -- Close an Ingres II database connection
ingres_query -- Send a SQL query to Ingres II
ingres_num_rows --  Get the number of rows affected or returned by the last query
ingres_num_fields --  Get the number of fields returned by the last query
ingres_field_name -- Get the name of a field in a query result.
ingres_field_type --  Get the type of a field in a query result
ingres_field_nullable -- Test if a field is nullable
ingres_field_length -- Get the length of a field
ingres_field_precision -- Get the precision of a field
ingres_field_scale -- Get the scale of a field
ingres_fetch_array -- Fetch a row of result into an array
ingres_fetch_row --  Fetch a row of result into an enumerated array
ingres_fetch_object -- Fetch a row of result into an object.
ingres_rollback -- Roll back a transaction
ingres_commit -- Commit a transaction
ingres_autocommit -- Switch autocommit on or off

ingres_connect

(PHP 4 >= 4.0.2)

ingres_connect --  Open a connection to an Ingres II database

Description

resource ingres_connect ( [string database [, string username [, string password]]])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Returns a Ingres II link resource on success, or FALSE on failure.

ingres_connect() opens a connection with the Ingres database designated by database, which follows the syntax [node_id::]dbname[/svr_class].

If some parameters are missing, ingres_connect() uses the values in php.ini for ingres.default_database, ingres.default_user, and ingres.default_password.

The connection is closed when the script ends or when ingres_close() is called on this link.

All the other ingres functions use the last opened link as a default, so you need to store the returned value only if you use more than one link at a time.

Przykład 1. ingres_connect() example

<?php
    $link = ingres_connect ("mydb", "user", "pass")
        or die ("Could not connect");
    print ("Connected successfully");
    ingres_close ($link);
?>

Przykład 2. ingres_connect() example using default link

<?php
    ingres_connect ("mydb", "user", "pass")
        or die ("Could not connect");
    print ("Connected successfully");
    ingres_close ();
?>

See also ingres_pconnect() and ingres_close().

ingres_pconnect

(PHP 4 >= 4.0.2)

ingres_pconnect --  Open a persistent connection to an Ingres II database

Description

resource ingres_pconnect ( [string database [, string username [, string password]]])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Returns a Ingres II link resource on success, or FALSE on failure.

See ingres_connect() for parameters details and examples. There are only 2 differences between ingres_pconnect() and ingres_connect() : First, when connecting, the function will first try to find a (persistent) link that's already opened with the same parameters. If one is found, an identifier for it will be returned instead of opening a new connection. Second, the connection to the Ingres server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ingres_close() will not close links established by ingres_pconnect()). This type of link is therefore called 'persistent'.

See also ingres_connect() and ingres_close().

ingres_close

(PHP 4 >= 4.0.2)

ingres_close -- Close an Ingres II database connection

Description

bool ingres_close ( [resource link])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Returns TRUE on success, or FALSE on failure.

ingres_close() closes the connection to the Ingres server that's associated with the specified link. If the link parameter isn't specified, the last opened link is used.

ingres_close() isn't usually necessary, as it won't close persistent connections and all non-persistent connections are automatically closed at the end of the script.

See also ingres_connect() and ingres_pconnect().

ingres_query

(PHP 4 >= 4.0.2)

ingres_query -- Send a SQL query to Ingres II

Description

bool ingres_query ( string query [, resource link])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Returns TRUE on success, or FALSE on failure.

ingres_query() sends the given query to the Ingres server. This query must be a valid SQL query (see the Ingres SQL reference guide)

The query becomes part of the currently open transaction. If there is no open transaction, ingres_query() opens a new transaction. To close the transaction, you can either call ingres_commit() to commit the changes made to the database or ingres_rollback() to cancel these changes. When the script ends, any open transaction is rolled back (by calling ingres_rollback()). You can also use ingres_autocommit() before opening a new transaction to have every SQL query immediatly commited.

Some types of SQL queries can't be sent with this function:

Przykład 1. ingres_query() example

<?php
ingres_connect ($database, $user, $password);

ingres_query ("select * from table");
while ($row = ingres_fetch_row()) {
    echo $row[1];
    echo $row[2];
}
?>

See also ingres_fetch_array(), ingres_fetch_object(), ingres_fetch_row(), ingres_commit(), ingres_rollback(), and ingres_autocommit().

ingres_num_rows

(PHP 4 >= 4.0.2)

ingres_num_rows --  Get the number of rows affected or returned by the last query

Description

int ingres_num_rows ( [resource link])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

For delete, insert or update queries, ingres_num_rows() returns the number of rows affected by the query. For other queries, ingres_num_rows() returns the number of rows in the query's result.

Notatka: This function is mainly meant to get the number of rows modified in the database. If this function is called before using ingres_fetch_array(), ingres_fetch_object() or ingres_fetch_row() the server will delete the result's data and the script won't be able to get them.

You should instead retrieve the result's data using one of these fetch functions in a loop until it returns FALSE, indicating that no more results are available.

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_num_fields

(PHP 4 >= 4.0.2)

ingres_num_fields --  Get the number of fields returned by the last query

Description

int ingres_num_fields ( [resource link])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

ingres_num_fields() returns the number of fields in the results returned by the Ingres server after a call to ingres_query()

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_field_name

(PHP 4 >= 4.0.2)

ingres_field_name -- Get the name of a field in a query result.

Description

string ingres_field_name ( int index [, resource link])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

ingres_field_name() returns the name of a field in a query result, or FALSE on failure.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object() and ingres_fetch_row().

ingres_field_type

(PHP 4 >= 4.0.2)

ingres_field_type --  Get the type of a field in a query result

Description

string ingres_field_type ( int index [, resource link])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

ingres_field_type() returns the type of a field in a query result, or FALSE on failure. Examples of types returned are "IIAPI_BYTE_TYPE", "IIAPI_CHA_TYPE", "IIAPI_DTE_TYPE", "IIAPI_FLT_TYPE", "IIAPI_INT_TYPE", "IIAPI_VCH_TYPE". Some of these types can map to more than one SQL type depending on the length of the field (see ingres_field_length()). For example "IIAPI_FLT_TYPE" can be a float4 or a float8. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_field_nullable

(PHP 4 >= 4.0.2)

ingres_field_nullable -- Test if a field is nullable

Description

bool ingres_field_nullable ( int index [, resource link])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

ingres_field_nullable() returns TRUE if the field can be set to the NULL value and FALSE if it can't.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_field_length

(PHP 4 >= 4.0.2)

ingres_field_length -- Get the length of a field

Description

int ingres_field_length ( int index [, resource link])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

ingres_field_length() returns the length of a field. This is the number of bytes used by the server to store the field. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_field_precision

(PHP 4 >= 4.0.2)

ingres_field_precision -- Get the precision of a field

Description

int ingres_field_precision ( int index [, resource link])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

ingres_field_precision() returns the precision of a field. This value is used only for decimal, float and money SQL data types. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_field_scale

(PHP 4 >= 4.0.2)

ingres_field_scale -- Get the scale of a field

Description

int ingres_field_scale ( int index [, resource link])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

ingres_field_scale() returns the scale of a field. This value is used only for the decimal SQL data type. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_fetch_array

(PHP 4 >= 4.0.2)

ingres_fetch_array -- Fetch a row of result into an array

Description

array ingres_fetch_array ( [int result_type [, resource link]])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

ingres_fetch_array() Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

This function is an extended version of ingres_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must use the numeric index of the column or make an alias for the column.

ingres_query(select t1.f1 as foo t2.f1 as bar from t1, t2);
$result = ingres_fetch_array();
$foo = $result["foo"];
$bar = $result["bar"];

result_type can be INGRES_NUM for enumerated array, INGRES_ASSOC for associative array, or INGRES_BOTH (default).

Speed-wise, the function is identical to ingres_fetch_object(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

Przykład 1. ingres_fetch_array() example

<?php
ingres_connect ($database, $user, $password);

ingres_query ("select * from table");
while ($row = ingres_fetch_array()) {
    echo $row["user_id"];  # using associative array
    echo $row["fullname"];
    echo $row[1];          # using enumerated array
    echo $row[2];
}
?>

See also ingres_query(), ingres_num_fields(), ingres_field_name(), ingres_fetch_object(), and ingres_fetch_row().

ingres_fetch_row

(PHP 4 >= 4.0.2)

ingres_fetch_row --  Fetch a row of result into an enumerated array

Description

array ingres_fetch_row ( [resource link])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

ingres_fetch_row() returns an array that corresponds to the fetched row, or FALSE if there are no more rows. Each result column is stored in an array offset, starting at offset 1.

Subsequent call to ingres_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Przykład 1. ingres_fetch_row() example

<?php
ingres_connect ($database, $user, $password);

ingres_query ("select * from table");
while ($row = ingres_fetch_row()) {
    echo $row[1];
    echo $row[2];
}
?>

See also ingres_num_fields(), ingres_query(), ingres_fetch_array(), and ingres_fetch_object().

ingres_fetch_object

(PHP 4 >= 4.0.2)

ingres_fetch_object -- Fetch a row of result into an object.

Description

object ingres_fetch_object ( [int result_type [, resource link]])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

ingres_fetch_object() Returns an object that corresponds to the fetched row, or FALSE if there are no more rows.

This function is similar to ingres_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

The optional argument result_type is a constant and can take the following values: INGRES_ASSOC, INGRES_NUM, and INGRES_BOTH.

Speed-wise, the function is identical to ingres_fetch_array(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

Przykład 1. ingres_fetch_object() example

<?php
ingres_connect ($database, $user, $password);
ingres_query ("select * from table");
while ($row = ingres_fetch_object()) {
    echo $row->user_id;
    echo $row->fullname;
}
?>

See also ingres_query(), ingres_num_fields(), ingres_field_name(), ingres_fetch_array(), and ingres_fetch_row().

ingres_rollback

(PHP 4 >= 4.0.2)

ingres_rollback -- Roll back a transaction

Description

bool ingres_rollback ( [resource link])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

ingres_rollback() rolls back the currently open transaction, actually canceling all changes made to the database during the transaction.

This closes the transaction. A new one can be open by sending a query with ingres_query().

See also ingres_query(), ingres_commit(), and ingres_autocommit().

ingres_commit

(PHP 4 >= 4.0.2)

ingres_commit -- Commit a transaction

Description

bool ingres_commit ( [resource link])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

ingres_commit() commits the currently open transaction, making all changes made to the database permanent.

This closes the transaction. A new one can be open by sending a query with ingres_query().

You can also have the server commit automaticaly after every query by calling ingres_autocommit() before opening the transaction.

See also ingres_query(), ingres_rollback(), and ingres_autocommit().

ingres_autocommit

(PHP 4 >= 4.0.2)

ingres_autocommit -- Switch autocommit on or off

Description

bool ingres_autocommit ( [resource link])

Ostrze¿enie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

ingres_autocommit() is called before opening a transaction (before the first call to ingres_query() or just after a call to ingres_rollback() or ingres_autocommit()) to switch the "autocommit" mode of the server on or off (when the script begins the autocommit mode is off).

When the autocommit mode is on, every query is automaticaly commited by the server, as if ingres_commit() was called after every call to ingres_query().

See also ingres_query(), ingres_rollback(), and ingres_commit().

XLVI. IRC Gateway Functions

What is ircg?

With ircg you can build powerful, fast and scalable webchat solutions in conjunction with dedicated or public IRC servers.


Platforms

IRCG runs under

  • AIX

  • FreeBSD

  • HP-UX

  • Irix

  • Linux

  • Solaris

  • Tru64


Requirements

To install and use IRCG you need the following software:

  1. IRCG-Library from Sascha Schumann.

  2. SGI Static Threads Library

  3. thttpd webserver


Installation

A detailed installation instruction can be found here.

Spis treści
ircg_pconnect --  Connect to an IRC server
ircg_fetch_error_msg --  Returns the error from previous ircg operation
ircg_set_current --  Set current connection for output
ircg_join --  Join a channel on a connected server
ircg_part --  Leave a channel on server
ircg_msg --  Send message to channel or user on server
ircg_notice --  Send a notice to a user on server
ircg_nick --  Change nickname on server
ircg_topic --  Set topic for channel on server
ircg_channel_mode --  Set channel mode flags for user
ircg_html_encode --  Encodes HTML preserving output
ircg_whois --  Query user information for nick on server
ircg_kick --  Kick a user out of a channel on server
ircg_ignore_add --  Add a user to your ignore list on a server
ircg_ignore_del --  Remove a user from your ignore list on a server
ircg_disconnect --  Close connection to server
ircg_is_conn_alive --  Check connection status
ircg_lookup_format_messages --  Select a set of format strings for display of IRC messages
ircg_register_format_messages --  Register a set of format strings for display of IRC messages
ircg_set_on_die --  Set hostaction to be execute when connection dies
ircg_set_file --  Set logfile for connection
ircg_get_username --  Get username for connection
ircg_nickname_escape --  Encode special characters in nickname to be IRC-compliant
ircg_nickname_unescape --  Decodes encoded nickname

ircg_pconnect

(PHP 4 >= 4.0.4)

ircg_pconnect --  Connect to an IRC server

Description

resource ircg_pconnect ( string username [, string server_ip [, int server_port [, string msg_format [, array ctcp_messages [, array user_settings]]]]])

ircg_pconnect() will try to establish a connection to an IRC server and return a connection resource handle for further use.

The only mandatory parameter is username, this will set your initial nickname on the server. server_ip and server_port are optional and default to 127.0.0.1 and 6667.

Notatka: For now parameter server_ip will not do any hostname lookups and will only accept IP addresses in numerical form.

You can customize the output of IRC messages and events by selection a format string set previously created with ircg_register_format_messages() by specifing the sets name in msg_format.

ctcp_messages

user_settings

See also: ircg_disconnect(), ircg_is_conn_alive(), ircg_register_format_messages().

ircg_fetch_error_msg

(PHP 4 >= 4.1.0)

ircg_fetch_error_msg --  Returns the error from previous ircg operation

Description

array ircg_fetch_error_msg ( resource connection)

ircg_fetch_error_msg() returns the error from the last called ircg function.

Notatka: Errorcode is stored in first array element, errortext in second.

Przykład 1. ircg_fetch_error_msg() example

if (!ircg_join ($id, "#php")) {
    $error = ircg_fetch_error_msg($id);
    print ("Can't join channel #php. Errorcode: 
            $error[0] Description: $error[1]");
}

ircg_set_current

(PHP 4 >= 4.0.4)

ircg_set_current --  Set current connection for output

Description

boolean ircg_set_current ( resource connection)

Select the current connection for output in this execution context. Every output sent from the server connected to by connection will be copied to standard output while using default formating or a formar string set specified by ircg_register_format_messages() and selected by ircg_lookup_format_messages().

See also: ircg_register_format_messages() and ircg_lookup_format_messages().

ircg_join

(PHP 4 >= 4.0.4)

ircg_join --  Join a channel on a connected server

Description

boolean ircg_join ( resource connection, string channel)

Join the channel channel on the server connected to by connection.

ircg_part

(PHP 4 >= 4.0.4)

ircg_part --  Leave a channel on server

Description

boolean ircg_part ( resource connection, string channel)

Leave the channel channel on the server connected to by connection.

ircg_msg

(PHP 4 >= 4.0.4)

ircg_msg --  Send message to channel or user on server

Description

boolean ircg_msg ( resource connection, string recipient, string message [, boolean suppress])

ircg_msg() will send the message to a channel or user on the server connected to by connection. A recipient starting with # or & will send the message to a channel, anything else will be interpreted as a username.

Setting the optional parameter suppress to a TRUE value will suppress output of your message to your own connection.

ircg_notice

(PHP 4 >= 4.0.5)

ircg_notice --  Send a notice to a user on server

Description

boolean ircg_notice ( resource connection, string , string message)

This function will send the message text to the user nick on the server connected to by connection. Query your IRC documentation of choice for the exact difference between a MSG and a NOTICE.

ircg_nick

(PHP 4 >= 4.0.5)

ircg_nick --  Change nickname on server

Description

boolean ircg_nick ( resource connection, string nick)

Change your nickname on the given connection to the one given in nick if possible.

Will return TRUE on success and FALSE on failure.

ircg_topic

(PHP 4 >= 4.0.5)

ircg_topic --  Set topic for channel on server

Description

boolean ircg_topic ( resource connection, string channel, string new_topic)

Change the topic for channel channel on the server connected to by connection to new_topic.

ircg_channel_mode

(PHP 4 >= 4.0.5)

ircg_channel_mode --  Set channel mode flags for user

Description

boolean ircg_channel_mode ( resource connection, string channel, string mode_spec, string nick)

Set channel mode flags for channel on server connected to by connection. Mode flags are passed in mode_spec and are applied to the user specified by nick.

Mode flags are set or cleared by specifind a mode character and prepending it with a plus or minus character respectively. E.g. operator mode is granted by '+o' and revoked by '-o' passed as mode_spec.

ircg_html_encode

(PHP 4 >= 4.0.5)

ircg_html_encode --  Encodes HTML preserving output

Description

boolean ircg_html_encode ( string html_string)

Encodes a HTML string html_string for output. This feature could be usable, e.g. if someone wants to discuss about an html problem.

ircg_whois

(PHP 4 >= 4.0.5)

ircg_whois --  Query user information for nick on server

Description

boolean ircg_whois ( resource connection, string nick)

Sends a query to the connected server connection to send information for the specified user nick.

ircg_kick

(PHP 4 >= 4.0.5)

ircg_kick --  Kick a user out of a channel on server

Description

boolean ircg_kick ( resource connection, string channel, string nick, string reason)

Kick user nick from channel on server connected to by connection. reason should give a short message describing why this action was performed.

ircg_ignore_add

(PHP 4 >= 4.0.5)

ircg_ignore_add --  Add a user to your ignore list on a server

Description

boolean ircg_ignore_add ( resource connection, string nick)

This function will add user nick to your ignore list on the server connected to by connection. By doing so you will suppress all messages from this user from being send to you.

See also: ircg_ignore_del().

ircg_ignore_del

(PHP 4 >= 4.0.5)

ircg_ignore_del --  Remove a user from your ignore list on a server

Description

boolean ircg_ignore_del ( resource connection, string nick)

This function remove user nick from your ignore list on the server connected to by connection.

See also: ircg_ignore_add().

ircg_disconnect

(PHP 4 >= 4.0.4)

ircg_disconnect --  Close connection to server

Description

boolean ircg_disconnect ( resource connection, string reason)

ircg_disconnect() will close a connection to a server previously established with ircg-pconnect().

See also: ircg_pconnect().

ircg_is_conn_alive

(PHP 4 >= 4.0.5)

ircg_is_conn_alive --  Check connection status

Description

boolean ircg_is_conn_alive ( resource connection)

ircg_is_conn_alive() returns TRUE if connection is still alive and working or FALSE if the server no longer talks to us.

ircg_lookup_format_messages

(PHP 4 >= 4.0.5)

ircg_lookup_format_messages --  Select a set of format strings for display of IRC messages

Description

boolean ircg_lookup_format_messages ( string name)

Select the set of format strings to use for display of IRC messages and events. Sets may be registered with ircg_register_format_messages(), a default set named ircg is always available.

See also: ircg_register_format_messages()

ircg_register_format_messages

(PHP 4 >= 4.0.5)

ircg_register_format_messages --  Register a set of format strings for display of IRC messages

Description

boolean ircg_register_format_messages ( string name, array messages)

With ircg_register_format_messages() you can customize the way your IRC output looks like. You can even register different format string sets and switch between them on the fly with ircg_lookup_format_messages().

  • Plain channel message

  • Private message received

  • Private message sent

  • Some user leaves channel

  • Some user enters channel

  • Some user was kicked from the channel

  • Topic has been changed

  • Error

  • Fatal error

  • Join list end(?)

  • Self part(?)

  • Some user changes his nick

  • Some user quits his connection

  • Mass join begin

  • Mass join element

  • Mass join end

  • Whois user

  • Whois server

  • Whois idle

  • Whois channel

  • Whois end

  • Voice status change on user

  • Operator status change on user

  • Banlist

  • Banlist end

  • %f - from

  • %t - to

  • %c - channel

  • %r - plain message

  • %m - encoded message

  • %j - js encoded message

  • 1 - mod encode

  • 2 - nickname decode

See also: ircg_lookup_format_messages().

ircg_set_on_die

(PHP 4 CVS only)

ircg_set_on_die --  Set hostaction to be execute when connection dies

Description

bool ircg_set_on_die ( int connection, string host, int port, string data)

In case of the termination of connection connection IRCG will connect to host at port (Note: host must be an IPv4 address, IRCG does not resolve host-names due to blocking issues), send data to the new host connection and will wait until the remote part closes connection. This can be used to trigger a php script for example.

ircg_set_file

(PHP 4 CVS only)

ircg_set_file --  Set logfile for connection

Description

bool ircg_set_file ( int connection, string path)

Function ircg_set_file() specifies a logfile path in which all output from connection connection will be logged. Returns TRUE on success, otherwise FALSE.

ircg_get_username

(PHP 4 >= 4.1.0)

ircg_get_username --  Get username for connection

Description

string ircg_get_username ( int connection)

Function ircg_get_username() returns the username for specified connection connection. Returns FALSE if connection died or is not valid.

ircg_nickname_escape

(PHP 4 >= 4.0.6)

ircg_nickname_escape --  Encode special characters in nickname to be IRC-compliant

Description

string ircg_nickname_escape ( string nick)

Function ircg_nickname_escape() returns a decoded nickname specified by nick wich is IRC-compliant.

See also: ircg_nickname_unescape()

ircg_nickname_unescape

(PHP 4 >= 4.0.6)

ircg_nickname_unescape --  Decodes encoded nickname

Description

string ircg_nickname_unescape ( string nick)

Function ircg_nickname_unescape() returns a decoded nickname, which is specified in nick.

See also: ircg_nickname_escape()

XLVII. Java

There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by the Java extension.

PHP 4 ext/java provides a simple and effective means for creating and invoking methods on Java objects from PHP. The JVM is created using JNI, and everything runs in-process. Build instructions for ext/java can be found in php4/ext/java/README.

Przykład 1. Java Example

<?php
  // get instance of Java class java.lang.System in PHP
  $system = new Java('java.lang.System');

  // demonstrate property access
  print 'Java version='.$system->getProperty('java.version').' <br>';
  print 'Java vendor=' .$system->getProperty('java.vendor').'  <br>';
  print 'OS='.$system->getProperty('os.name').' '.
              $system->getProperty('os.version').' on '.
              $system->getProperty('os.arch').' <br>';

  // java.util.Date example
  $formatter = new Java('java.text.SimpleDateFormat',
                        "EEEE, MMMM dd, yyyy 'at' h:mm:ss a zzzz");

  print $formatter->format(new Java('java.util.Date'));
?>

Przykład 2. AWT Example

<?php
  // This example is only intented to be run as a CGI.

  $frame  = new Java('java.awt.Frame', 'PHP');
  $button = new Java('java.awt.Button', 'Hello Java World!');

  $frame->add('North', $button);
  $frame->validate();
  $frame->pack();
  $frame->visible = True;

  $thread = new Java('java.lang.Thread');
  $thread->sleep(10000);

  $frame->dispose();
?>
Notes:

  • new Java() will create an instance of a class if a suitable constructor is available. If no parameters are passed and the default constructor is useful as it provides access to classes like java.lang.System which expose most of their functionallity through static methods.

  • Accessing a member of an instance will first look for bean properties then public fields. In other words, print $date.time will first attempt to be resolved as $date.getTime(), then as $date.time.

  • Both static and instance members can be accessed on an object with the same syntax. Furthermore, if the java object is of type java.lang.Class, then static members of the class (fields and methods) can be accessed.

  • Exceptions raised result in PHP warnings, and NULL results. The warnings may be eliminated by prefixing the method call with an "@" sign. The following APIs may be used to retrieve and reset the last error:

  • Overload resolution is in general a hard problem given the differences in types between the two languages. The PHP Java extension employs a simple, but fairly effective, metric for determining which overload is the best match.

    Additionally, method names in PHP are not case sensitive, potentially increasing the number of overloads to select from.

    Once a method is selected, the parameters are cooerced if necessary, possibly with a loss of data (example: double precision floating point numbers will be converted to boolean).

  • In the tradition of PHP, arrays and hashtables may pretty much be used interchangably. Note that hashtables in PHP may only be indexed by integers or strings; and that arrays of primitive types in Java can not be sparse. Also note that these constructs are passed by value, so may be expensive in terms of memory and time.

sapi/servlet builds upon the mechanism defined by ext/java to enable the entire PHP processor to be run as a servlet. The primary advanatage of this from a PHP perspective is that web servers which support servlets typically take great care in pooling and reusing JVMs. Build instructions for the Servlet SAPI module can be found in php4/sapi/README. Notes:

  • While this code is intended to be able to run on any servlet engine, it has only been tested on Apache's Jakarta/tomcat to date. Bug reports, success stories and/or patches required to get this code to run on other engines would be appreciated.

  • PHP has a habit of changing the working directory. sapi/servlet will eventually change it back, but while PHP is running the servlet engine may not be able to load any classes from the CLASSPATH which are specified using a relative directory syntax, or find the work directory used for administration and JSP compilation tasks.

Spis treści
java_last_exception_clear -- Clear last Java exception
java_last_exception_get -- Get last Java exception

java_last_exception_clear

(PHP 4 >= 4.0.2)

java_last_exception_clear -- Clear last Java exception

Description

void java_last_exception_clear ( void)

java_last_exception_get

(PHP 4 >= 4.0.2)

java_last_exception_get -- Get last Java exception

Description

exception java_last_exception_get ( void)

The following example demonstrates the usage of Java's exception handler from within PHP:

Przykład 1. Java exception handler

<?php
  $stack = new Java('java.util.Stack');
  $stack->push(1);

  // This should succeed
  $result = $stack->pop();
  $ex = java_last_exception_get();
  if (!$ex) print "$result\n";

  // This should fail (error suppressed by @)
  $result = @$stack->pop();
  $ex = java_last_exception_get();
  if ($ex) print $ex->toString();

  // Clear last exception
  java_last_exception_clear();
?>

XLVIII. LDAP functions

Introduction to LDAP

LDAP is the Lightweight Directory Access Protocol, and is a protocol used to access "Directory Servers". The Directory is a special kind of database that holds information in a tree structure.

The concept is similar to your hard disk directory structure, except that in this context, the root directory is "The world" and the first level subdirectories are "countries". Lower levels of the directory structure contain entries for companies, organisations or places, while yet lower still we find directory entries for people, and perhaps equipment or documents.

To refer to a file in a subdirectory on your hard disk, you might use something like


    /usr/local/myapp/docs
    

The forwards slash marks each division in the reference, and the sequence is read from left to right.

The equivalent to the fully qualified file reference in LDAP is the "distinguished name", referred to simply as "dn". An example dn might be.


    cn=John Smith,ou=Accounts,o=My Company,c=US
    

The comma marks each division in the reference, and the sequence is read from right to left. You would read this dn as ..


    country = US
    organization = My Company
    organizationalUnit = Accounts
    commonName = John Smith
    

In the same way as there are no hard rules about how you organise the directory structure of a hard disk, a directory server manager can set up any structure that is meaningful for the purpose. However, there are some conventions that are used. The message is that you can not write code to access a directory server unless you know something about its structure, any more than you can use a database without some knowledge of what is available.


Complete code example

Retrieve information for all entries where the surname starts with "S" from a directory server, displaying an extract with name and email address.

Przykład 1. LDAP search example

<?php
// basic sequence with LDAP is connect, bind, search, interpret search
// result, close connection

echo "<h3>LDAP query test</h3>";
echo "Connecting ...";
$ds=ldap_connect("localhost");  // must be a valid LDAP server!
echo "connect result is ".$ds."<p>";

if ($ds) { 
    echo "Binding ..."; 
    $r=ldap_bind($ds);     // this is an "anonymous" bind, typically
                           // read-only access
    echo "Bind result is ".$r."<p>";

    echo "Searching for (sn=S*) ...";
    // Search surname entry
    $sr=ldap_search($ds,"o=My Company, c=US", "sn=S*");  
    echo "Search result is ".$sr."<p>";

    echo "Number of entires returned is ".ldap_count_entries($ds,$sr)."<p>";

    echo "Getting entries ...<p>";
    $info = ldap_get_entries($ds, $sr);
    echo "Data for ".$info["count"]." items returned:<p>";

    for ($i=0; $i<$info["count"]; $i++) {
        echo "dn is: ". $info[$i]["dn"] ."<br>";
        echo "first cn entry is: ". $info[$i]["cn"][0] ."<br>";
        echo "first email entry is: ". $info[$i]["mail"][0] ."<p>";
    }

    echo "Closing connection";
    ldap_close($ds);

} else {
    echo "<h4>Unable to connect to LDAP server</h4>";
}
?>

Using the PHP LDAP calls

You will need to get and compile LDAP client libraries from either the University of Michigan ldap-3.3 package or the Netscape Directory SDK 3.0. You will also need to recompile PHP with LDAP support enabled before PHP's LDAP calls will work.

Before you can use the LDAP calls you will need to know ..

  • The name or address of the directory server you will use

  • The "base dn" of the server (the part of the world directory that is held on this server, which could be "o=My Company,c=US")

  • Whether you need a password to access the server (many servers will provide read access for an "anonymous bind" but require a password for anything else)

The typical sequence of LDAP calls you will make in an application will follow this pattern:


  ldap_connect()    // establish connection to server
     |
  ldap_bind()       // anonymous or authenticated "login"
     |
  do something like search or update the directory
  and display the results
     |
  ldap_close()      // "logout"


More Information

Lots of information about LDAP can be found at

The Netscape SDK contains a helpful Programmer's Guide in .html format.

Spis treści
ldap_add -- Add entries to LDAP directory
ldap_bind -- Bind to LDAP directory
ldap_close -- Close link to LDAP server
ldap_compare -- Compare value of attribute found in entry specified with DN
ldap_connect -- Connect to an LDAP server
ldap_count_entries -- Count the number of entries in a search
ldap_delete -- Delete an entry from a directory
ldap_dn2ufn -- Convert DN to User Friendly Naming format
ldap_err2str --  Convert LDAP error number into string error message
ldap_errno --  Return the LDAP error number of the last LDAP command
ldap_error --  Return the LDAP error message of the last LDAP command
ldap_explode_dn -- Splits DN into its component parts
ldap_first_attribute -- Return first attribute
ldap_first_entry -- Return first result id
ldap_free_result -- Free result memory
ldap_get_attributes -- Get attributes from a search result entry
ldap_get_dn -- Get the DN of a result entry
ldap_get_entries -- Get all result entries
ldap_get_option -- Get the current value for given option
ldap_get_values -- Get all values from a result entry
ldap_get_values_len -- Get all binary values from a result entry
ldap_list -- Single-level search
ldap_modify -- Modify an LDAP entry
ldap_mod_add -- Add attribute values to current attributes
ldap_mod_del -- Delete attribute values from current attributes
ldap_mod_replace -- Replace attribute values with new ones
ldap_next_attribute -- Get the next attribute in result
ldap_next_entry -- Get next result entry
ldap_read -- Read an entry
ldap_rename -- Modify the name of an entry
ldap_search -- Search LDAP tree
ldap_set_option -- Set the value of the given option
ldap_unbind -- Unbind from LDAP directory
ldap_8859_to_t61 --  Translate