14-02-2002
Copyright © 1997, 1998, 1999, 2000, 2001, 2002 the PHP Documentation Group
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.
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'.
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:
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.
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:
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.
Adabas D Ingres Oracle (OCI7 i OCI8) dBase InterBase Ovrimos Empress FrontBase PostgreSQL FilePro (tylko do odczytu) mSQL Solid Hyperwave Direct MS-SQL Sybase IBM DB2 MySQL Velocis Informix ODBC Unix dbm
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.
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.
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:
Jako moduł Apache
Jako moduł fhttpd
Do użycia z AOLServer, NSAPI, phttpd, Pi3Web, Roxen, thttpd, lub Zeus.
Jako plik wykonywalny CGI
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.
Ten rozdział zawiera wskazówki dotyczące instalacji PHP na dystrybucjach Linuksowych.
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.
Ta sekcja zawiera wskazówki dotyczące instalacji PHP na systemach HP-UX.
Przykład 2-2. Instrukcja instalacji dla HP-UX 10
|
Ten rozdział zawiera wskazówki dotyczące instalacji PHP na systemach Solaris.
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
Możesz uprościć instalację pod systemem Solaris używając pkgadd aby zainstalować większość wymaganych komponentów.
Ten rozdział zawiera wskazówki dotyczące instalacji PHP na systemach OpenBSD.
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ć.
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.
Ten rozdział zawiera wskazówki dotyczące instalacji PHP na systemach Mac OS X Server.
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.
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
|
Inne przykłady dla Mac OS X client i Mac OS X server są dostępne na Stepwise.
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"
* #AddType application/x-httpd-php .php * #AddType application/x-httpd-php-source .phps |
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.
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.
PHP 3, PHP 4: Dołącz obsługę Adabas D. DIR jest katalogiem gdzie została zainstalowana baza Adabas, domyślnie /usr/local.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Buduj DBA jako obiekt współdzielony
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Dołącz obsługę DBX
PHP 3: Opcja niedostępna; zamiast tego użyj --with-dbase.
PHP 4: Dołącz wbudowaną bibliotekę dbase. Nie potrzebne są zewnętrzne biblioteki.
PHP 3: Dołącz wbudowaną bibliotekę dbase. Nie potrzebne są zewnętrzne biblioteki.
PHP 4: Opcja niedostępna; zamiast tego użyj --enable-dbase.
PHP 3, PHP 4: Dołącz obsługę Berkeley DB2
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Dołącz obsługę Berkeley DB3
PHP 3, PHP 4: Dołącz obsługę DBM
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).
PHP 3, PHP 4: Dołącz obsługę Empress. DIR to katalog instalacji Empress, domyślnie $EMPRESSPATH
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.
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.
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.
PHP 3, PHP 4: Dołącz obsługę GDBM
PHP 3, PHP 4: Dołącz obsługę Hyperwave
PHP 3, PHP 4: Dołącz obsługę IBM DB2. DIR to katalog instalcji DB2, domyślnie /home/db2inst1/sqllib.
PHP 3, PHP 4: Dołącz obsługę Informix. DIR to katalog gdzie został zainstalowany Informix. Brak wartości domyślnej.
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.
PHP 3, PHP 4: Dołącz obsługę InterBase. DIR to katalog instalacji InterBase'a, domyślnie /usr/interbase.
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.
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.
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.
PHP 3, PHP 4: Dołącz obsługę NDBM
PHP 3, PHP 4: Dołącz obsługę Ovrimos.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Dołącz obsługę Oracle-oci8. Domyślnie DIR to $ORACLE_HOME.
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.
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.
PHP 3, PHP 4: Dołącz obsługę Solid. DIR to katalog instalacji Solid, domyślnie /usr/local/solid
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.
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.
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.
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.
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
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.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Dołącz obsługę unixODBC. DIR to katalog instalacji unixODBC, domyślnie /usr/local.
PHP 3, PHP 4: Dołącz obsługę Velocis. DIR to katalog instalacji Velocis, domyślnie /usr/local/velocis.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Dołącz obsługę CCVS. DIR to katalog instalacji CCVS.
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.
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.
PHP 3: Opcja niedostępna; zamiast tego użyj --with-mck.
PHP 4: Dołącz obsługę CyberCash. DIR to katalog instalacji CyberCash MCK.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Dołącz obsługę Verisign Payflow Pro
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Dołącz obsługę FreeType2 (eksperymentalne).
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.
PHP 3, PHP 4: Wyłącz obsługę GD.
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
PHP 3: Katalog jpeg dla pdflib 2.0
PHP 4: Katalog jpeg dla pdflib 3.x i 4.x
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Katalog png dla pdflib 3.x i 4.x
PHP 3: Włącz obsługę t1lib.
PHP 4: Opcja niedostępna; zamiast tego użyj --with-t1lib.
PHP 3: Opcja niedostępna; zamiast tego użyj --enable-t1lib.
PHP 4: Dołącz obsługę T1lib.
PHP 3: Katalog tiff dla pdflib 2.0
PHP 4: Katalog tiff dla pdflib 3.x i 4.x
PHP 3, PHP 4: Dołącz obsługę FreeType
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Katalog xpm dla gd-1.8+
Opcje te są w międzyczasie klasyfikowane.
PHP 3, PHP 4 : Dołącz obsługę GMP.
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ć.
PHP 3: Skompiluj bez obsługi pokazywania źródeł
PHP 4: Opcja niedostępna w PHP 4
PHP 3: Opcja niedostępna w PHP 3
PHP 4: unikaj blokowania (może uszkodzić równoległe budowanie)
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Nie instaluj PEAR
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Wyłącz PIC dla obiektów współdzielonych
PHP 3: Opcja niedostępna w PHP 3; zamiast tego użyj --without-posix.
PHP 4: Wyłącz funkcje POSIXowe.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Włącz funkcje kontroli procesów. (fork, waitpid, signal, itp.)
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Wyłącz przekazywanie dodatkowych ścieżek poszukiwania bibliotek
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Wyłącz obsługę sesji
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.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Włącz semantykę C9x-inline
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Włącz obsługę konwersji kalendarza
PHP 3, PHP 4: Kompiluj z symbolami dla debuggera
PHP 3: Kompuluj z funkcjami zdalnego debugowania
PHP 4: Opcja niedostępna w PHP 4
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.
PHP 3, PHP 4: Włącz dmalloc
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Włącz obsługę exif
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Ta opcja najprawdopodobniej przerwie proces budowania
PHP 3: Opcja niedostępna w PHP 3
PHP 4: optymalizacja dla szybkiej instalacji [domyślnie=tak]
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.
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ę.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Włącz jawne linkowanie z libgcc
PHP 3, PHP 4: włącz reguły i zależności programu make nie przydatne (i czasem niejasne) dla zwykłego użytkownika
PHP 4: włącz automatyczne wykrywanie wpisywanych znaków przez http i translację dla wielobajtowych kodowań znaków.
Ostrze¿enie |
|
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. |
PHP 3, PHP 4: Kompiluj z obsługą limitowania pamięci. [domyślnie=nie]
PHP 3, PHP 4: Włącz domyślną pracę w trybie bezpiecznym.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Włącz obsługę CORBA przez Satellite (wymaga ORBit)
PHP 3: Opcja niedostępna w PHP 3
PHP 4: buduj biblioteki współdzielone [domyślnie=tak]
PHP 3, PHP 4: Włącz obsługę SIGCHLD przez PHP.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: buduj statyczne biblioteki [domyślnie=tak]
PHP 3, PHP 4: Włącz obsługę semaforów System V.
PHP 3, PHP 4: Włącz obsługę pamięci dzielonej System V.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Włącz przezroczyste propagowanie id sesji
PHP 3, PHP 4: Dołącz obsługę CDB
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
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.
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.
PHP 3, PHP 4: W trybie bezpiecznym pozwól na uruchamianie plików wykonywalnych tylko w DIR, domyślnie /usr/local/php/bin
PHP 3, PHP 4: Dołącz obsługę fdftk. DIR to katalog instalacji fdftk, domyślnie /usr/local.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: załóż, że kompilator C używa GNU ld [domyślnie=nie]
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Dołącz obsługę ICAP.
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.
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
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).
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Dołącz obsługę Kerberosa w protokole IMAP.
PHP 3, PHP 4: Dołącz obsługę MCAL.
PHP 3, PHP 4: Dołącz obsługę mcrypt. DIR to katalog instalacji mcrypt.
PHP 3, PHP 4: Dołącz obsługę mhash. DIR to katalog gdzie zainstalowano mhash.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Dołącz obsługę mm do przechowywania sesji.
PHP 3, PHP 4: Włącz transfer tablic dla mod_charset (Rosyjski Apache).
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.
PHP 3, PHP 4: Aktywuj pdflib jako bibliotekę współdzieloną.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Dołącz obsługę readline. DIR to katalog instalacji readline.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Typ biblioteki regex: system, apache, php
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.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Dołącz obsługę Flash 4 (Ming)
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Dołącz obsługę swf
PHP 3: Nie używaj wbudowanej biblioteki regex
PHP 4: (niezalecane) Użyj systemową bibliotekę regex.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Użyj GNU Pth.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Użyj wątków POSIX (domyślnie)
PHP 3: użyj X Window System
PHP 4: Opcje niedostępna w PHP 4
PHP 4: Dołącz obsługę bzip2. DIR to katalog instalacji bzip2.
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
PHP 3, PHP 4: Dołącz obsługę zlib (wymaga zlib >= 1.0.9). DIR to katalog instalacji zlib, domyślnie /usr.
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/.
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.
PHP 3: Nie dołączaj funkcji POSIXowych
PHP 4: Opcja niedostępna w PHP 4; zamiast tego użyj --disable-posix.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Włącz obsługę przeciążania właściwości i metod obiektów.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Dołącz obsługę CURL
PHP 3: Opcja niedostępna; zamiast tegu użyj--with-ftp.
PHP 4: Włącz obsługę FTP
PHP 3: Dołącz obsługę FTP.
PHP 4: Opcja niedostępna; zamiast tego użyj --enable-ftp.
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. |
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).
PHP 3, PHP 4: Dołącz obsługę OpenSSL w SNMP.
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.
PHP 3, PHP 4: Włącz poprawkę UCD SNMP
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Włącz obsługę gniazd
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.
PHP 3: Opcja niedostępna; zamiast tego użyj --with-yp instead.
PHP 4: Dołącz obsługę YP
PHP 3: Dołącz obsługę YP
PHP 4: Opcja niedostępna; zamiast tego użyj --enable-yp.
PHP 3, PHP 4: Dołącz obsługę mnoGoSearch.
PHP 3, PHP 4: Włącz domyślnie "magic quotes".
PHP 3, PHP 4: Wyłącz możliwość używania krótkiej formy tagów otwierających <?.
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.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Określ ścieżkę do źródłowej dystrybucji AOLserver
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Określ ścieżkę do zainstalego AOLserver
PHP 3, PHP 4: Zbuduj moduł Apache. DIR to katalog główny Apache, domyślnie /usr/local/etc/httpd.
PHP 3, PHP 4: Zbuduj moduł współdzielony Apache. FILE to opcjonalna ścieżka do narzędzia apxs z pakietu Apache; domyślnie apxs.
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.
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.
PHP 3, PHP 4: Buduj moduł fhttpd. DIR to katalog ze źródłami fhttpd, domyślnie /usr/local/src/fhttpd.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Określ ścieżkę do zainstalowanego Netscape
PHP 3: Opcja niedostępna w PHP 3
PHP 4:
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Buduj PHP jako moduł do użycia z Pi3Web.
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.
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").
PHP 3: Opcja niedostępna w PHP 3
PHP 4:
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Buduj PHP jako moduł ISAPI do użycia z Zeus.
PHP 3, PHP 4: Dołącz obsługę ASPELL.
PHP 3, PHP 4: Dołącz obsługę GNU gettext. DIR to katalog instalacji gettext, domyślnie /usr/local.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Dołącz obsługę iconv.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Dołącz obsługę PSPELL.
PHP 3: Dołącz obsługę GNU recode.
PHP 4: Dołącz obsługę redcode. DIR to katalog instalacji redcode.
PHP 3, PHP 4 : Włącz obsługę shmop.
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
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Włącz błędy opisowe.
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Dołącz obsługę Sablotrona
PHP 3: Opcja niedostępna w PHP 3
PHP 4: Włącz obsługę WDDX
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
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ć.
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ść.
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. |
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 |
'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).
Przed rozpoczęciem warto jest odpowiedzieć sobie na pytanie: "Dlaczego budowanie pod Windowsem jest takie trudne?" Do głowy przechodzą dwie odpowiedzi:
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.
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.
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.
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.
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.
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ą:
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).
c:\windows\system dla Windows 9x/Me c:\winnt\system32 dla Windows NT/2000/XP
Tabela 2-1. Rozszerzenia PHP
Rozszerzenia | Opis | Uwagi |
---|---|---|
php_bz2.dll | bzip2 - funkcje kompresji | Brak |
php_calendar.dll | Calendar - funkcje konwersji kalendarza | Wbudowane od PHP 4.0.3 |
php_cpdf.dll | funkcje ClibPDF | Brak |
php3_crypt.dll | funkcje Crypt | Brak |
php_ctype.dll | rodzina funcjictype | Brak |
php_curl.dll | CURL, Client URL | Wymaga: libeay32.dll, ssleay32.dll (dołączone do dystrybucji) |
php_cybercash.dll | funkcje opłat Cybercash | Brak |
php_db.dll | funkcje DBM | Niezalecane. Zamiast tego użyj DBA (php_dba.dll) |
php_dba.dll | funkcje DBA: DataBase (dbm-style) Abstraction Layer | Brak |
php_dbase.dll | funkcje dBase | Brak |
php3_dbm.dll | biblioteka Berkeley DB2 | Brak |
php_domxml.dll | funkcje DOM XML | Wymaga: libxml2.dll (dołączony do dystrybucji) |
php_dotnet.dll | funkcje .NET | Brak |
php_exif.dll | nagłówki Read EXIF z JPEG | Brak |
php_fbsql.dll | funkcje FrontBase | Brak |
php_fdf.dll | funkcje FDF: Forms Data Format | Wymaga: fdftk.dll (dołączony do dystrybucji) |
php_filepro.dll | funkcje filePro | Dostęp tylko do odczytu |
php_ftp.dll | funkcje FTP | Wbudowane od PHP 4.0.3 |
php_gd.dll | Biblioteka obróbki obrazów GD | Brak |
php_gettext.dll | funkcje Gettext | Wymaga: gnu_gettext.dll (dołączony do dystrybucji) |
php_hyperwave.dll | funkcje HyperWave | Brak |
php_iconv.dll | konwersja tablicy znaków ICONV | Wymaga: iconv-1.3.dll (dołączony do dystrybucji) |
php_ifx.dll | funkcje Informix | Wymaga: bibliotek Informix |
php_iisfunc.dll | funkcje zarządzania IIS | Brak |
php_imap.dll | funkcje IMAP, POP3 i NNTP | PHP 3: php3_imap4r1.dll |
php_ingres.dll | funkcje Ingres II | Wymaga: bibliotek Ingres II |
php_interbase.dll | funkcje InterBase | Wymaga: gds32.dll (dołączony do dystrybucji) |
php_java.dll | rozszerzenie Java | Wymaga: jvm.dll (dołączony do dystrybucji) |
php_ldap.dll | funkcje LDAP | Wymaga: libsasl.dll (dołączony do dystrybucji) |
php_mhash.dll | funkcje Mhash | Brak |
php_ming.dll | funkcje Ming dla Flasha | Brak |
php_msql.dll | funkcje mSQL | Wymaga: msql.dll (dołączony do dystrybucji) |
php3_msql1.dll | klient mSQL 1 | Brak |
php3_msql2.dll | klient mSQL 2 | Brak |
php_mssql.dll | funkcje MSSQL | Wymaga: ntwdblib.dll (dołączony do dystrybucji) |
php3_mysql.dll | funkcje MySQL | Wbudowany w PHP 4 |
php3_nsmail.dll | funkcje poczty Netscape | Brak |
php3_oci73.dll | funkcje Oracle | Brak |
php_oci8.dll | funkcje Oracle 8 | Wymaga: biblioteki klienta Oracle 8 |
php_openssl.dll | funkcje OpenSSL | Wymaga: libeay32.dll (dołączony do dystrybucji) |
php_oracle.dll | funkcje Oracle | Wymaga: biblioteki klienta Oracle 7 |
php_pdf.dll | funkcje PDF | Brak |
php_pgsql.dll | funkcje PostgreSQL | Brak |
php_printer.dll | funkcje Drukarki | brak |
php_sablot.dll | funkcje XSLT | Wymaga: sablot.dll (dołączony do dystrybucji) |
php_snmp.dll | funkcje SNMP | tylko NT! |
php_sybase_ct.dll | funkcje Sybase | Wymaga: biblioteki klienta Sybase |
php_yaz.dll | funkcje YAZ | Brak |
php_zlib.dll | funkcje kompresji ZLib | Brak |
Ten rozdział zawiera wskazówki dotyczące instalacji PHP z serwerem Apache, zarówno na systemach Unix i Windows.
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)
|
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 |
Różne przykłady kompilacji PHP dla Apache:
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.
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().
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.
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.
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"
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".
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.
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.
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.
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.
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
|
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 .
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.
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.
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ź.
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)
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
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
|
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
|
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
|
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
Ten rozdział zawiera wskazówki dotyczące instalacji PHP z serwerem OmniHTTPd.
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.
This section contains notes and hints specific to Oreilly Website Pro.
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).
Ten rozdział zawiera wskazówki specyficzne dla Xitami.
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'.
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.
Niektóre problemy są bardziej popularne niż inne. Tej najczęściej spotykane są wypisane w FAQ PHP, częsci tego podręcznika.
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.
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!
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
|
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.
Ustawia wartość podanej zmiennej.
Ta opcja jest używana do opcji konfiguracji tak/nie.
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.
Ta opcja jest używana do opcji konfiguracji typu tak/nie.
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().
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.
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.
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.
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.
Określa, czy błędy powinny być wyświetlane jako część wyjścia HTML czy nie.
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.
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.
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.
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.
Domyślną wartością dla tej dyrektywy jest 7 (wyświetlane są normalne błędy, normalne ostrzeżenia i błędy parsera).Wyłącz tagi HTMLowe w informacjach o błędach.
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.
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.
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.
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().
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.
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.
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.
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.
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.
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.
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.
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.
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 ?>).
Jeśli dyrektywa ta jest włączona, ostatnia informacja o błędzie będzie dostępna jako zmienna globalna $php_errormsg.
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.
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.
Maksymalny rozmiar uploadowanego pliku. Wartość podawana jest w bajtach.
Podstawowa nazwa katalogu używanego jako katalog domowy użytkownika dla plików PHP, na przykład public_html.
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 (.).
Określa, czy PHP ma pracować w trybie bezpiecznym. Przeczytaj rozdziały Bezpieczeństwo i Safe Mode aby uzyskać więcej informacji.
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.
Nazwa lub adres IP hosta używanego przez debugger.
Numer portu używany przez debugger.
Określa, czy debugger jest włączony.
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.
Katalog, w którym PHP powinno szukać dynamicznie dołączanych rozszerzeń.
Które dynamicznie ładowane rozszerzenia ładować przy starcie PHP.
Czy pozwalać na stałe połączenia MySQL ('persistent connections').
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.
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.
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.
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.
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.
Maksymalna liczba stałych połączeń MySQL na każdy proces.
Maksymalna liczba połączeń MySQL na proces, włączając w to połączenia stałe.
Czy pozwalać na stałe połączenia mSQL.
Maksymalna liczba trwałych połączeń mSQL na każdy proces.
Maksymalna liczna połączeń mSQL na każdy proces, włączając w to połączenia stałe.
Czy pozwalać na stałe połączenia PostgreSQL.
Maksymalna liczba stałych połączeń PostgreSQL na każdy proces.
Maksymalna liczba połączeń PostgreSQL na każdy proces, włączając w to połąćzenia stałe.
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.
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):
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.
Czy pozwalać na stałe połączenia Sybase.
Maksymalna liczba stałych połączeń Sybase na każdy proces.
Maksymalna liczba połączeń Sybase na każdy proces, włączając w to połączenia stałe.
Czy pozwalać na stałe połączenia Sybase-CT. Domyślnie włączone.
Maksymalna liczba stałych połączeń Sybase-CT na każdy proces. Domyślą wartością jest -1, co oznacza brak limitu.
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.
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.
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.
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.
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ń.
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.
Czy pozwalać na stałe połączenia Informix.
Maksymalna liczba stałych połączeń Informix na każdy proces.
Maksymalna liczba połączeń Informix na każdy proces, włączając w to połączenia stałe.
Domyślny host do połączenia jeśli nie podano innego w ifx_connect() lub ifx_pconnect().
Domyślny identyfikator użytkownika używany jeśli nie podano innego w ifx_connect() lub ifx_pconnect().
Domyślne hasło używane jeśli nie podano innego w ifx_connect() lub ifx_pconnect().
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().
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().
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().
Ustaw na TRUE jeśli chcesz obcinać początkowe spacje z kolumn CHAR przy pobieraniu ich.
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().
Liczba dziesiętnych cyfr dla wszystkich funkcji bcmath.
Nazwa pliku opisującego możliwości przeglądarek. Zobacz także get_browser().
Źródło danych ODBC używane jeśli nie podane zostało inne w odbc_connect() lub odbc_pconnect().
Nazwa użytkownika używana jeśli inna nie została podana w odbc_connect() lub odbc_pconnect().
Hasło używane jeśli inne nie zostało podane w odbc_connect() lub odbc_pconnect().
Czy pozwalać na stałe połączenia ODBC.
Maksymalna liczba stałych połączeń ODBC na każdy proces.
Maksymalna liczba połączeń ODBC na każdy proces, włączając w to połączenia stałe.
mbstring.internal_encoding definiuje domyślne wewnętrzne kodowanie znaków.
mbstring.http_input definiuje domyślne kodowanie znaków wejścia HTTP.
mbstring.http_output definiuje domyślne kodowanie znaków wyjścia HTTP.
mbstring.detect_order definiuje domyślną kolejność wykrywania kodowania znaków.
mbstring.substitute_character definiuje znak zastępujące znaki o błędnych kodach.
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.
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.
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.
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).
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.
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.
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:
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.
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.
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-2. ... A filesystem attack
|
Only allow limited permissions to the PHP web user binary.
Check all variables which are submitted.
Przykład 4-3. More secure file name checking
|
Przykład 4-4. More secure file name checking
|
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.
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.
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.
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.
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
|
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)
|
// 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; |
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.
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.
// $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.
$query = "SELECT * FROM products WHERE id LIKE '%a%' exec master..xp_cmdshell 'net user test testpass /ADD'--"; $result = mssql_query($query); |
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.
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
|
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.
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:
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:
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.
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-16. Detecting simple variable poisoning
|
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
|
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?
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).
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:
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.
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
|
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:
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 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 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.
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.
To specify a boolean literal, use either the keyword TRUE or FALSE. Both are case-insensitive.
Usually you use some kind of operator which returns a boolean value, and then pass it on to a control structure.
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:
the boolean FALSE
the integer 0 (zero)
the float 0.0 (zero)
an array with zero elements
an object with zero elements
the special type NULL (including unset variables)
Ostrze¿enie |
-1 is considered TRUE, like any other non-zero (whether negative or positive) number! |
An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}.
See also: Arbitrary precision integers and Floating point numbers
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.
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.
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.
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. See for more information the warning about float-precision. |
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 (AKA "floats", "doubles" or "real numbers") can be specified using any of the following syntaxes:
$a = 1.234; $a = 1.2e3; $a = 7E-10; |
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. |
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.
A string literal can be specified in three different ways.
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 |
If the string is enclosed in double-quotes ("), PHP understands more escape sequences for special characters:
Tabela 6-1. Escaped characters
sequence | meaning |
---|---|
\n | linefeed (LF or 0x0A (10) in ASCII) |
\r | carriage return (CR or 0x0D (13) in ASCII) |
\t | horizontal tab (HT or 0x09 (9) in ASCII) |
\\ | 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.
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
|
Notatka: Here doc support was added in PHP 4.
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.
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.
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}}"; |
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
|
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.
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:
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.
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 |
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 |
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.
The foreach control structure exists specificly for arrays. It provides an easy way to traverse an array.
You might have seen the following syntax in old scripts:
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: 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"; |
$error_descriptions[1] = "A fatal error has occured"; $error_descriptions[2] = "PHP issued a warning"; $error_descriptions[8] = "This is just an informal notice"; |
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.
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.
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()
|
Note that it is currently not possible to change the values of the array directly in such a loop. A workaround is the following:
This example creates a one-based array.
Arrays are ordered. You can also change the order using various sorting-functions. See array-functions for more information.
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.
To initialize an object, you use the new statement to instantiate the object to a variable.
For a full discussion, please read the section Classes and Objects.
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
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
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
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.
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:
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 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.
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:
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:
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':
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 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 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ń.
Określa wersję specyfikacji CGI obsługiwaną przez serwer, np. "CGI/1.1".
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.
Napis identyfikujący serwer, wysyłany z nagłówkami przy odpowiedzi na zapytanie.
Nazwa i wersja protokołu informacyjnego, przez który zostało wysłane zapytanie, np. "HTTP/1.1".
Metoda, która została użyta przy zapytaniu o dokument, np. "GET", "HEAD", "POST".
Łańcuch zapytania (np. ?foo=bar), o ile istnieje, jaki został przesłany z zapytaniem o stronę.
Folder główny na serwerze, taki jak określony w pliku konfiguracyjnym serwera.
Zawartość nagłówka Accept: z aktualnego zapytania, o ile taki występuje.
Zawartość nagłówka Accept-Charset: z aktualnego zapytania, o ile taki występuje, np. "iso-8859-1,*,utf-8". 'iso-8859-1,*,utf-8'.
Zawartość nagłówka Accept-Encoding: z aktualnego zapytania, o ile taki występuje, np. "gzip".
Zawartość nagłówka Accept-Language: z aktualnego zapytania, o ile taki występuje, np. "en".
Zawartość nagłówka Connection: z aktualnego zapytania, o ile taki występuje, np. "Keep-Alive".
Zawartość nagłówka Host: z aktualnego zapytania, o ile taki występuje.
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ę.
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.
Numer IP zdalnego użytkownika przeglądającego stronę.
Port używany na zdalnej maszynie, przez który następuje komunikacja z serwerem.
Bezwzględna ścieżka do aktualnie wykonywanego skrytpu.
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.
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.
Napis zawierający nazwę i wersję serwera, oraz nazwę wirtualnego hosta, który jest dodawany do stron generowanych przez serwer, o ile włączony.
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.
Zawiera ścieżkę do aktualnego skryptu. Przydatne przy stronach, które mają wskazywać na siebie same.
URI, który został podany, aby uzyskać dostęp do aktualnej strony, np. "/index.html".
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 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.
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).
Liczba argumentów przekazanych do skryptu (jeśli uruchamiany z linii poleceń).
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").
Tablica asocjacyjna zmiennych przekazanych do skryptu przez ciasteczka HTTP.
Tablica asocjacyjna zmiennych przekazanych do skryptu przez ciasteczka HTTP. Zawsze globalna w każdym zasięgu. Wprowadzona w PHP 4.1.0.
Tablica asocjacyjna zmiennych przekazanych do skryptu metodą GET protokołu HTTP.
Tablica asocjacyjna zmiennych przekazanych do skryptu metodą GET protokołu HTTP. Zawsze globalna w każdym zasięgu. Wprowadzona w PHP 4.1.0.
Tablica asocjacyjna zmiennych przekazanych do skryptu metodą POST protokołu HTTP.
Tablica asocjacyjna zmiennych przekazanych do skryptu metodą POST protokołu HTTP. Zawsze globalna w każdym zasięgu. Wprowadzona w PHP 4.1.0.
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.
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.
Tablica asocjacyjna zmiennych przekazanych do skryptu ze środowiska operacyjnego serwera.
Tablica asocjacyjna zmiennych przekazanych do skryptu ze środowiska operacyjnego serwera. Zawsze globalna w każdym zasięgu. Wprowadzona w PHP 4.1.0.
Tablica asocjacyjna zmiennych przekazanych do skryptu z serwera HTTP. Zmienne te są analogiczne do zmiennych Apache'a, opisanych powyżej.
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.
Tablica asocjacyjna zmiennych sesji przekazanych do skryptu.
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.
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 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:
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:
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:
$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:
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:
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ć:
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:
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.
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:
znaczy to samo, co:
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.
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.
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
|
W PHP 3 tablice w formularzach mogły być tylko jednowymiarowe. W PHP 4 nie ma takich ograniczeń.
Przy tworzeniu formularza, można użyć obrazka, zamiast standardowego przycisku Wyślij, za pomocą takiego znacznika:
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).
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:
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.
PHP samoczynnie udostępnia zmienne środowiskowe jak zwykłe zmienne PHP.
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().
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 */ |
Warto zatem wiedzieć, że PHP automatycznie zastąpi podkreślnikiem "_" każdą kropkę w nazwie nadchodzącej zmiennej.
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().
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.
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.
Predefiniowanymi stałymi (zawsze dostępnymi) są:
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.
Numer linii w pliku, który jest aktualnie parsowany (przetwarzany). Stała użyta w pliku włączonym (include) zwraca pozycję w tym pliku.
Łańcuch reprezentujący aktualnie używaną wersję parsera PHP, np. '4.0.7-dev'.
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.
Wartość TRUE (zobacz: typ boolean).
Wartość FALSE (zobacz: typboolean).
Wartość NULL (zobacz: typ null).
Oznacza błąd inny niż błąd przy parsowaniu (przetwarzaniu), którego naprawienie nie jest możliwe.
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().
Parser stanął przy nieprawidłowej składni w skrypcie. Naprawa błędu i kontynuacja nie jest możliwa.
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.
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.
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:
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:
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.
Czy pamiętasz podstawy arytmetyki ze szkoły? W PHP operatory działają niemalże tak samo.
Tabela 10-1. Operatory Arytmetyczne
Przykład | Nazwa | Opis |
---|---|---|
$a + $b | Dodawanie | Suma $a i $b. |
$a - $b | Odejmowanie | Różnica $a od $b. |
$a * $b | Mnożenie | Iloczyn $a i $b. |
$a / $b | Dzielenie | Iloraz $a przez $b. |
$a % $b | Modulo | Reszta 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ą.
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ń:
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 służą do operowania na wartościach konkretnych bitów w liczbie.
Tabela 10-2. Operatory Bitowe
Przykład | Nazwa | Opis |
---|---|---|
$a & $b | Mnożenie | Dany bit wynikowy jest równy 1 tylko jeśli obydwa bity składowe są równe 1. |
$a | $b | Sumowanie | Dany bit wynikowy jest równy 1 jeśli conajmniej jeden bit składowy jest równy 1. |
$a ^ $b | Sumowanie modulo 2 | Dany 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. |
~ $a | Negacja | Bity w zmiennej $a mające wartość 1 otrzymują wartość 0 i na odwrót. |
$a << $b | Przesunięcie w lewo | Przesuwa bity w zmiennej $a o $b kroków w lewo (każdy krok znaczy "pomnożone przez dwa"). |
$a >> $b | Przesunięcie w prawo | Przesuwa bity w zmiennej $a o $b kroków w prawo (każdy krok znaczy "podzielone przez dwa"). |
Jak wskazuje ich nazwa, operatory te służą do porównywania dwóch wartości.
Tabela 10-3. Operaatory Porównania
Przykład | Nazwa | Opis |
---|---|---|
$a == $b | Równy | TRUE jesli $a jest równe $b |
$a === $b | Identyczny | TRUE jeśli $a jest równe $b, i obydwa operandy są tego samego typu. (tylko w PHP 4) |
$a != $b | Różny | TRUE jeśli $a nie jest równy $b. |
$a <> $b | Różny | TRUE jeśli $a nie jest równy $b. |
$a !== $b | Nie identyczny | TRUE jeśli $a nie jest równy $b, lub nie są tego samego typu. (tylko w PHP 4) |
$a < $b | Mniejszy niż | TRUE jeśli $a jest mniejszy od $b. |
$a > $b | Większy niż | TRUE jeśli $a jest większy od $b. |
$a <= $b | Mniejszy lub równy | TRUE jeśli $a jest mniejszy lub równy $b. |
$a >= $b | Większy lub równy | TRUE 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.
Wartościa wyrażenia jest expr2 jeśli expr1 jest równe TRUE, lub expr3 jeśli expr1 jest równe FALSE.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. |
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).
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().
PHP obsługuje te operatory w stylu języka C.
Tabela 10-4. Operatory Inkrementacji i Dekrementacji
Przykład | Nazwa | Opis |
---|---|---|
++$a | Pre-inkrementacja | Najpierw zwiększa wartość $a o jeden, potem zwraca $a. |
$a++ | Post-inkrementacja | Najpierw zwraca $a, potem zwiększa $a o jeden. |
--$a | Pre-dekrementacja | Najpierw zmniejsza wartość $a o jeden, potem zwraca $a. |
$a-- | Post-dekrementacja | Najpierw zwraca $a, potem zmniejsza $a o jeden. |
Prosty skrypt przykładowy:
<?php echo "<h3>Post-inkrementacja</h3>"; $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"; ?> |
Tabela 10-5. Opearotory Logiczne
Przykład | Nazwa | Opis |
---|---|---|
$a and $b | I | TRUE jeśli zarówno $a jak i $b są TRUE. |
$a or $b | Lub | TRUE jeśli $a lub $b jest TRUE. |
$a xor $b | Wyłacznie-Lub | TRUE jeśli $a lub $b jest TRUE, ale nie jednocześnie. |
! $a | Nie | TRUE jeśli $a nie jest TRUE. |
$a && $b | I | TRUE jeśli zarówno $a jak i $b są TRUE. |
$a || $b | Lub | TRUE 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.)
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ązanie | Operator |
---|---|
lewe | , |
lewe | or |
lewe | xor |
lewe | and |
prawe | |
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ązania | new |
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.
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.
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:
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:
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 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.
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:
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, 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.
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.
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:
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:
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:
The following examples are identical, and both print numbers from 1 to 10:
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:
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 loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is:
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.
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.
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:
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"; } |
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 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 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++ < 5) { echo "Outer<br>\n"; while (1) { echo " Middle<br>\n"; while (1) { echo " Inner<br>\n"; continue 3; } echo "This never gets output.<br>\n"; } echo "Neither does this.<br>\n"; } |
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:
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 .
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:
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.
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
|
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().
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.
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
|
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.
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
|
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
|
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
|
Because include() and require() are special language constructs, you must enclose them within a statement block if it's inside a conditional block.
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.
$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.
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().
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().
Funkcja może być zdefiniowana używając składni takiej jak poniższa:
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.
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]; } |
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:
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. |
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.
Wartości są zwracana przy użyciu opcjonalnej instrukcji return. Może być zwracany dowonlny typ, włączając w to tablice i obiekty.
Nie możesz zwracać zwracać wielu wartości z funkcji, ale podobne efekty mogą być uzyskane przez zwracanie listy.
Aby funkcja zwracała referencję, musisz użyć operatora referencji & i w deklaracji funkcji i przy przypisywaniu zwracanej wartości do zmiennej:
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. |
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.
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'.
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:
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.
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(); |
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.
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.
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).
// 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 */ |
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.
PHP references allow you to make two variables to refer to the same content. Meaning, when you do:
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):
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:
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.
As said before, references aren't pointers. That means, the following construct won't do what you expect:
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).
You can pass variable to function by reference, so that function could modify its arguments. The syntax is as follows:
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.:
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:
These requirements are for PHP 4.0.4 and later.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:
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.
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:
won't unset $b, just $a.Again, it might be useful to think about this as analogous to Unix unlink call.
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:
When you declare variable as global $var you are in fact creating reference to a global variable. That means, this is the same as:
That means, for example, that unsetting $var won't unset global variable.
There are several types of errors and warnings in PHP. They are:
Tabela 15-1. PHP error types
Value | Constant | Description | Note |
---|---|---|---|
1 | E_ERROR | fatal run-time errors | |
2 | E_WARNING | run-time warnings (non fatal errors) | |
4 | E_PARSE | compile-time parse errors | |
8 | E_NOTICE | run-time notices (less serious than warnings) | |
16 | E_CORE_ERROR | fatal errors that occur during PHP's initial startup | PHP 4 only |
32 | E_CORE_WARNING | warnings (non fatal errors) that occur during PHP's initial startup | PHP 4 only |
64 | E_COMPILE_ERROR | fatal compile-time errors | PHP 4 only |
128 | E_COMPILE_WARNING | compile-time warnings (non fatal errors) | PHP 4 only |
256 | E_USER_ERROR | user-generated error message | PHP 4 only |
512 | E_USER_WARNING | user-generated warning message | PHP 4 only |
1024 | E_USER_NOTICE | user-generated notice message | PHP 4 only |
E_ALL | all 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
|
See also error_reporting(), error_log(), set_error_handler(), restore_error_handler(), trigger_error(), user_error()
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
|
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
|
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
|
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.
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().
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:
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:
The original name of the file on the client machine.
The mime type of the file, if the browser provided this information. An example would be "image/gif".
The size, in bytes, of the uploaded file.
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".
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().
|
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.
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.
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.
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.
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:
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:
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:
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.
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).
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
|
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.
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().
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.
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ść!
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 |
<?php readfile('/etc/passwd'); ?> |
Warning: SAFE MODE Restriction in effect. The script whose uid is 500 is not allowed to access /etc/passwd owned by uid 0 in /docroot/script.php on line 2 |
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> |
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 |
Warning: readfile() has been disabled for security reasons in /docroot/script.php on line 2 |
Jest to najprawdopodobniej wciąż niekompletna lista funkcji ograniczonych przez tryb bezpieczny.
Tabela 23-1. Funkcje ograniczone w trybie bezpiecznym
Funkcja | Ograniczenia |
---|---|
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 apostrof | Ta 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 | ?? |
(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 nimTa 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() 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() 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() 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()
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.
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() 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() 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().
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().
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.
Ten przykład tworzy tablicę o początku 1.
Patrz także: list().
(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 literyarray_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ą.
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()
Powyższy program wyświetli:
|
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.
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.
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() 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()
|
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() 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.
array_fill() wypełni tablicę wartością value, począwszy od indeksu indeks_początkowy przez num kolejnych elementów tablicy.
array_intersect() zwraca tablicę zawierającą wszystkie wartości tablicy tablica1 które istnieją we wszystkich argumentach. Zauważ, ża zachowywane są przypisania kluczy.
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() 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.
Notatka: W PHP 4.0.6 ta funkcja nazywa się key_exists().
Patrz także isset().
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()
|
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.
Patrz także array_values().
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().
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
|
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
|
Patrz także array_filter(), array_reduce().
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.
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() łą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.
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() 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.
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.
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() 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.
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.
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() 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; |
Funkcja zwraca nową liczbę elementów tablicy.
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().
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.
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.
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.
(PHP 4 >= 4.0.5)
array_reduce -- Iteracyjnie zredukuj tablicę do pojedyńczej wartości używając funkcji zwrotnejarray_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.
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() 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.
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() 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()
|
Patrz także array_splice().
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()
|
Patrz także array_slice().
array_sum() zwraca sumę wszystkich wartości w tablicy jako liczbę całkowitą lub rzeczywistą.
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! |
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.
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() zwraca wszystkie wartości z tablicy wejście.
Notatka: Ta funkcja została dodana w PHP 4. Poniżej znajduje się implementacja tej funkcji dla osób używających PHP 3.
Patrz także array_keys().
(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)
array_walk -- Zastosuj funkcję użytkownika do każdego elementu tablicyWykonuje 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()
|
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.
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().
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.
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().
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()
Po tym $wynik będzie zawierał array ("wydarzenie" => "SIGGRAPH", "miasto" => "San Francisco", "stan" => "CA"). |
Patrz także extract().
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.
Notatka: Funkcja sizeof() jest aliasem dla count().
Patrz także sizeof(), isset() i is_array().
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(). |
(PHP 3, PHP 4 >= 4.0.0)
each -- Zwraca bieżącą parę klucza i wartości z tablicy i przesuwa kursor tablicyZwraca 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()
$bar zawiera teraz następujące pary klucz/wartość
$bar zawiera teraz następujące pary klucz/wartość:
|
each() jest zazwyczaj używana w połączeniu z list() aby przejść przez tablicę; na przykład $HTTP_POST_VARS:
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() przesuwa wewnętrzny wskaźnik tablicy tablica na ostatnim elemencie i zwraca ten element.
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:
Jeśli istnieje kolizja, nadpisz istniejącą zmienną.
Jeśli istnieje kolizja, nie nadpisuj istniejącej zmiennej.
Jeśli istnieje kolizja, na początek nazwy zmiennej wstaw prefiks.
Na początek każdej nazwy zmiennej wstaw prefiks. Od PHP 4.0.5 dotyczy to także nazw numerycznych.
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()
|
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().
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 2. Przykład użycia in_array() z parametrem strict
|
Patrz także array_search().
(PHP 4 >= 4.0.5)
array_search -- Przeszukuje tablicę pod kątem podane wartości i w przypadku sukcesu zwraca odpowiedni kluczPrzeszukuje 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().
Sortuje trablicę według klucza w porządku odwrotnym utrzymując skojarzenia kluczy z danymi. Jest to przydatne głównie w przypadku tablic asocjacyjnych.
Ten przykład wyświetli:
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().
Sortuje tablicę według klucza zachowując skojarzenia kluczy z danymi. Jest to przydatne głównie w przypadku tablic asocjacyjnych.
Ten przykład wyświetli:
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.
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()
|
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:
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 ) |
Patrz także natcasesort(), strnatcmp() i strnatcasecmp().
(PHP 4 >= 4.0.0)
natcasesort -- Sortuj tablicę używając algorytmu "porządek naturalny" ignorującego wielkość znakówTa 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().
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(). |
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.
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.
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() przewija wewnętrzny wskaźnik tablicy parametru tablica na jego pierwszy element.
reset() zwraca wartość pierwszego elementu tablicy.
Ta funkcja sortuje tablicę w porządku odwrotnym (od największego do najmniejszego).
Ten przykład wyświetli:
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().
Ta funkcja tasuje tablicę (losuje kolejność elementów w niej). Musisz użyć srand() aby przygotować ziarno dla tej funkcji.
Patrz także arsort(), asort(), ksort(), rsort(), sort() i usort().
Funkcja ta sortuje tablicę. Po zakończeniu działania funkcji elementy będą ułożone od najmniejszego do najwiekszego.
Ten przykład wyświetli:
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.
(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 kluczyFunkcja 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().
(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ącejFunkcja 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.
Ten przykład wyświetli:
Patrz także usort(), uasort(), sort(), asort(), arsort(), ksort(), natsort() i rsort().
(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ącejFunkcja 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.
Powyższy przykład wyświetli:
Notatka: Oczywiście w prostszych przypadkach lepiej jest skorzystać z funkcji rsort().
Przykład 2. Przykład użycia usort() do sortowania wielowymiarowych tablic
|
Sortując tablicę wielowymiarową, $a i $b zawierają referencję do pierwszego indeksu tablicy.
Ten przykład wyświetli:
Przykład 3. Przykład użycia usort() używając funkcji składowej obiektu
|
Ten przykład wyświetli:
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().
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/.
aspell_new() otwiera słownik i zwraca uchwyt do niego, używany w innych funkcjach aspell. W razie błędu zwraca FALSE.
aspell_check() sprawdza pisownię słowa i zwraca TRUE jeśli jest poprawna lub FALSE jeśli jest błędna.
(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]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.
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.
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().
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.
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.
Zwraca moduł (resztę z dzielenia) z liczby lewy_operand dzielonej przez moduł.
Zobacz też bcdiv().
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().
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().
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.
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().
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().
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.
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
|
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() 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.
See also bzdecompress().
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.
See also bzcompress().
Returns the error number of any bzip2 error returned by the file pointer bz.
See also bzerror() and bzerrstr().
Returns the error number and error string, in an associative array, of any bzip2 error returned by the file pointer bz.
See also bzerrno() and bzerrstr().
Returns the error string of any bzip2 error returned by the file pointer bz.
Forces a write of all buffered bzip2 data for the file pointer bz.
Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
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.
See also bzclose().
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.
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.
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.
Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/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.
Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/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.
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.
Converts a Julian Day Count to the French Republican Calendar.
(PHP 3, PHP 4 >= 4.0.0)
FrenchToJD -- Converts a date from the French Republican Calendar to a Julian Day CountConverts 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.
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
Mode | Meaning | Values |
---|---|---|
0 | Gregorian - abbreviated | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec |
1 | Gregorian | January, February, March, April, May, June, July, August, September, October, November, December |
2 | Julian - abbreviated | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec |
3 | Julian | January, February, March, April, May, June, July, August, September, October, November, December |
4 | Jewish | Tishri, Heshvan, Kislev, Tevet, Shevat, AdarI, AdarII, Nisan, Iyyar, Sivan, Tammuz, Av, Elul |
5 | French Republican | Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra |
Returns the day of the week. Can return a string or an integer depending on the mode.
(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)
easter_date -- Get UNIX timestamp for midnight on Easter of a given yearReturns 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).
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.
(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 yearReturns the number of days after March 21 on which Easter falls for a given year. If no year is specified, the current year is assumed.
This function can be used instead of easter_date() to calculate Easter for years which fall outside the range of UNIX timestamps (i.e. before 1970 or after 2037).
The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.
(The code is based on a C program by Simon Kershaw, <webmaster@ely.anglican.org>)
See also easter_date().
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().
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().
(PHP 4 >= 4.1.0)
cal_days_in_month -- Return the number of days in a month for a given year and calendarThis function will return the number of days in the month of year for the specified calendar.
See also jdtounix().
(PHP 4 >= 4.1.0)
cal_from_jd -- Converts from Julian Day Count to a supported calendar and return extended informationThese 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!
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
(PHP 4 >= 4.0.2)
ccvs_count -- Find out how many transactions of a given type are stored in the system
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
(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
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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)
The COM class provides a framework to integrate (D)COM components into your php scripts.
COM class constructor. Parameters:
name or class-id of the requested component.
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.
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)
|
Przykład 2. COM example (2)
|
VARIANT class constructor. Parameters:
initial value. if omitted an VT_EMPTY object is created.
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.
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() 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() invokes a method of the COM component referenced by com_object. Returns FALSE on error, returns the function_name's return value on success.
This function is an alias for com_get().
Returns the value of the property of the COM component referenced by com_object. Returns FALSE on error.
This function is an alias for com_set().
This function is an alias for com_set().
Sets the value of the property of the COM component referenced by com_object. Returns the newly set value if succeeded, FALSE on error.
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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).
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
|
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
|
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:
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
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().
This function returns TRUE if the class given by class_name has been defined, FALSE otherwise.
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()
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:
Przykład 1. get_class_methods() example
|
Will produce:
See also get_class_vars(), get_object_vars()
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
|
Will produce:
See also get_class_methods(), get_object_vars()
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.
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()
|
See also get_class_methods(), get_class_vars()
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()
(PHP 4 CVS only)
is_a -- Returns true if the object is of this class or has this class as one of its parentsThis 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().
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().
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
|
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
|
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.
The cpdf_add_outline() function adds a bookmark with text text that points to the current page.
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().
The cpdf_begin_text() function starts a text section. It must be ended with cpdf_end_text().
See also cpdf_end_text().
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().
The cpdf_clip() function clips all drawing to the current path.
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().
The cpdf_closepath() function closes the current path.
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().
The cpdf_closepath_stroke() function is a combination of cpdf_closepath() and cpdf_stroke(). Then clears the path.
See also cpdf_closepath(), cpdf_stroke().
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().
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().
The cpdf_end_text() function ends a text section which was started with cpdf_begin_text().
See also cpdf_begin_text().
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().
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().
The cpdf_finalize() function ends the document. You still have to call cpdf_close()
See also cpdf_close().
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().
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().
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().
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().
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.
The cpdf_newpath() starts a new path on the document given by the pdf document parameter.
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().
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().
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().
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().
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.
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.
See also cpdf_save().
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().
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().
The cpdf_rotate() function set the rotation in degrees to angle.
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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().
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().
The cpdf_scale() function set the scaling factor in both directions.
The cpdf_set_char_spacing() function sets the spacing between characters.
See also cpdf_set_word_spacing(), cpdf_set_leading().
The cpdf_set_creator() function sets the creator of a pdf document.
See also cpdf_set_subject(), cpdf_set_title(), cpdf_set_keywords().
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().
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.
The cpdf_set_horiz_scaling() function sets the horizontal scaling to scale percent.
The cpdf_set_keywords() function sets the keywords of a pdf document.
See also cpdf_set_title(), cpdf_set_creator(), cpdf_set_subject().
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().
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.
The cpdf_set_subject() function sets the subject of a pdf document.
See also cpdf_set_title(), cpdf_set_creator(), cpdf_set_keywords().
The cpdf_set_text_matrix() function sets a matrix which describes a transformation applied on the current text font.
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().
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.
The cpdf_set_text_rise() function sets the text rising to value units.
The cpdf_set_title() function sets the title of a pdf document.
See also cpdf_set_subject(), cpdf_set_creator(), cpdf_set_keywords().
The cpdf_set_word_spacing() function sets the spacing between words.
See also cpdf_set_char_spacing(), cpdf_set_leading().
The cpdf_setdash() function set the dash pattern white white units and black black units. If both are 0 a solid line is set.
The cpdf_setflat() function set the flatness to a value between 0 and 100.
The cpdf_setgray() function sets the current drawing and filling color to the given gray value.
See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor_fill().
The cpdf_setgray_fill() function sets the current gray value to fill a path.
See also cpdf_setrgbcolor_fill().
The cpdf_setgray_stroke() function sets the current drawing color to the given gray value.
See also cpdf_setrgbcolor_stroke().
The cpdf_setlinecap() function set the linecap parameter between a value of 0 and 2. 0 = butt end, 1 = round, 2 = projecting square.
The cpdf_setlinejoin() function set the linejoin parameter between a value of 0 and 2. 0 = miter, 1 = round, 2 = bevel.
The cpdf_setlinewidth() function set the line width to width.
The cpdf_setmiterlimit() function set the miter limit to a value greater or equal than 1.
(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)
cpdf_setrgbcolor -- Sets drawing and filling color to rgb color valueThe cpdf_setrgbcolor() function sets the current drawing and filling color to the given rgb color value.
See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor_fill().
The cpdf_setrgbcolor_fill() function sets the current rgb color value to fill a path.
See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor().
The cpdf_setrgbcolor_stroke() function sets the current drawing color to the given rgb color value.
See also cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().
The cpdf_show() function outputs the string in text at the current position.
See also cpdf_text(), cpdf_begin_text(), cpdf_end_text().
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().
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().
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
(PHP 4 >= 4.0.6)
cpdf_set_font_map_file -- Sets fontname to filename translation map when using external fonts
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)
cpdf_set_viewer_preferences -- How to show the document in the viewer
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
The cpdf_stroke() function draws a line along current path.
See also cpdf_closepath(), cpdf_closepath_stroke().
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().
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.
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
|
Notatka: If crack_check() returns TRUE, crack_getlastmessage() will return 'strong password'.
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().
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.
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.
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.
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:
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.
See also: curl_close(), curl_setopt()
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.
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.
This function closes a CURL session and frees all resources. The CURL handle, ch, is also deleted.
The curl_version() function returns a string containing the current CURL version.
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
These functions are only available if the interpreter has been compiled with the --with-cybercash=[DIR]. These functions have been added in PHP 4.
The function returns an associative array with the elements "errcode" and, if "errcode" is FALSE, "outbuff" (string), "outLth" (long) and "macbuff" (string).
The function returns an associative array with the elements "errcode" and, if "errcode" is FALSE, "outbuff" (string), "outLth" (long) and "macbuff" (string).
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.
cybermut_creerformulairecm() is used to generate the HTML form of request for payment.
Przykład 1. First step of payment (equiv cgi1.c)
|
See also cybermut_testmac() and cybermut_creerreponsecm().
(PHP 4 >= 4.0.5)
cybermut_testmac -- Make sure that there no was data diddling contained in the received message of confirmationcybermut_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)
|
See also cybermut_creerformulairecm() and cybermut_creerreponsecm().
(PHP 4 >= 4.0.5)
cybermut_creerreponsecm -- Generate the acknowledgement of delivery of the confirmation of paymentcybermut_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().
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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.
(PHP 4 >= 4.0.4)
ctype_punct -- Check for any printable character which is not whitespace or an alphanumeric characterThese 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
Handler | Notes |
---|---|
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) |
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
|
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() 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() 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() 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() 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() 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() 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() 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() 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() 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() 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() 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()
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().
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.
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.
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
|
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
|
To format dates in other languages, you should use the setlocale() and strftime() functions.
See also getlastmod(), gmdate(), mktime(), strftime() and time().
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"
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
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".
See also date(), mktime(), gmmktime() and strftime()
Identical to mktime() except the passed parameters represents a GMT date.
(PHP 3>= 3.0.12, PHP 4 >= 4.0.0)
gmstrftime -- Format a GMT/CUT time/date according to locale settingsBehaves 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".
See also strftime().
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
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
|
See also time().
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".
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".
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).
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().
See also setlocale() and mktime() and the Open Group specification of strftime().
Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
See also date().
(PHP 3>= 3.0.12, PHP 4 >= 4.0.0)
strtotime -- Parse about any English textual datetime description into a UNIX timestampThe 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
|
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.)
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.
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:
Boolean. These do not have a length or precision.
Memo. (Note that these aren't supported by PHP.) These do not have a length or precision.
Date (stored as YYYYMMDD). These do not have a length or precision.
Number. These have both a length and a precision (the number of digits after the decimal point).
String.
If the database is successfully created, a dbase_identifier is returned, otherwise FALSE is returned.
Przykład 1. Creating a dBase database file
|
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.
Closes the database associated with dbase_identifier.
Packs the specified database (permanently deleting all records marked for deletion using dbase_delete_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.
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()).
Marks record to be deleted from the database. To actually remove the record from the database, you must also call dbase_pack().
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
(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 arrayReturns 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
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).
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).
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.
Returns TRUE if there is a value associated with the key.
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().)
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.
Deletes the value for key in the database.
Returns FALSE if the key didn't exist in the database.
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.
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:
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/.
Returns TRUE on success, FALSE on error.
Notatka: Always refer to the module-specific documentation as well.
See also: dbx_connect().
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.
Notatka: Always refer to the module-specific documentation as well.
See also: dbx_close().
(PHP 4 >= 4.0.6)
dbx_error -- Report the error message of the latest function call in the module (not just in the connection)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.
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.
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:
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
|
Notatka: Always refer to the module-specific documentation as well.
See also: dbx_connect().
Returns TRUE on success, FALSE on error.
Przykład 1. dbx_sort() example
|
See also dbx_compare().
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
|
See also dbx_sort().
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++, 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.
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.
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.
Tabela 1. DB++ Error Codes
PHP Constant | db++ constant | meaning |
---|---|---|
DBPLUS_ERR_NOERR | ERR_NOERR | Null error condition |
DBPLUS_ERR_DUPLICATE | ERR_DUPLICATE | Tried to insert a duplicate tuple |
DBPLUS_ERR_EOSCAN | ERR_EOSCAN | End of scan from rget() |
DBPLUS_ERR_EMPTY | ERR_EMPTY | Relation is empty (server) |
DBPLUS_ERR_CLOSE | ERR_CLOSE | The server can't close |
DBPLUS_ERR_WLOCKED | ERR_WLOCKED | The record is write locked |
DBPLUS_ERR_LOCKED | ERR_LOCKED | Relation was already locked |
DBPLUS_ERR_NOLOCK | ERR_NOLOCK | Relation cannot be locked |
DBPLUS_ERR_READ | ERR_READ | Read error on relation |
DBPLUS_ERR_WRITE | ERR_WRITE | Write error on relation |
DBPLUS_ERR_CREATE | ERR_CREATE | Create() system call failed |
DBPLUS_ERR_LSEEK | ERR_LSEEK | Lseek() system call failed |
DBPLUS_ERR_LENGTH | ERR_LENGTH | Tuple exceeds maximum length |
DBPLUS_ERR_OPEN | ERR_OPEN | Open() system call failed |
DBPLUS_ERR_WOPEN | ERR_WOPEN | Relation already opened for writing |
DBPLUS_ERR_MAGIC | ERR_MAGIC | File is not a relation |
DBPLUS_ERR_VERSION | ERR_VERSION | File is a very old relation |
DBPLUS_ERR_PGSIZE | ERR_PGSIZE | Relation uses a different page size |
DBPLUS_ERR_CRC | ERR_CRC | Invalid crc in the superpage |
DBPLUS_ERR_PIPE | ERR_PIPE | Piped relation requires lseek() |
DBPLUS_ERR_NIDX | ERR_NIDX | Too many secondary indices |
DBPLUS_ERR_MALLOC | ERR_MALLOC | Malloc() call failed |
DBPLUS_ERR_NUSERS | ERR_NUSERS | Error use of max users |
DBPLUS_ERR_PREEXIT | ERR_PREEXIT | Caused by invalid usage |
DBPLUS_ERR_ONTRAP | ERR_ONTRAP | Caused by a signal |
DBPLUS_ERR_PREPROC | ERR_PREPROC | Error in the preprocessor |
DBPLUS_ERR_DBPARSE | ERR_DBPARSE | Error in the parser |
DBPLUS_ERR_DBRUNERR | ERR_DBRUNERR | Run error in db |
DBPLUS_ERR_DBPREEXIT | ERR_DBPREEXIT | Exit condition caused by prexit() * procedure |
DBPLUS_ERR_WAIT | ERR_WAIT | Wait a little (Simple only) |
DBPLUS_ERR_CORRUPT_TUPLE | ERR_CORRUPT_TUPLE | A client sent a corrupt tuple |
DBPLUS_ERR_WARNING0 | ERR_WARNING0 | The Simple routines encountered a non fatal error which was corrected |
DBPLUS_ERR_PANIC | ERR_PANIC | The server should not really die but after a disaster send ERR_PANIC to all its clients |
DBPLUS_ERR_FIFO | ERR_FIFO | Can't create a fifo |
DBPLUS_ERR_PERM | ERR_PERM | Permission denied |
DBPLUS_ERR_TCL | ERR_TCL | TCL_error |
DBPLUS_ERR_RESTRICTED | ERR_RESTRICTED | Only two users |
DBPLUS_ERR_USER | ERR_USER | An error in the use of the library by an application programmer |
DBPLUS_ERR_UNKNOWN | ERR_UNKNOWN |
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.
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.
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.
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().
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().
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.
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().
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().
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().
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.
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().
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().
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().
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().
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.
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.
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().
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.
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().
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().
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().
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.
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.
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.
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.
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().
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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().
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().
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.
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.
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().
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.
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.
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().
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().
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,..).
(PHP 4 CVS only)
dio_open -- Opens a new filename with specified permissions of flags and creation permissions of modedio_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
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
(PHP 4 CVS only)
dio_read -- Reads n bytes from fd and returns them, if n is not specified, reads 1k blockThe 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.
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.
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.
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
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
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.
For related functions such as dirname(), is_dir(), mkdir(), and rmdir(), see the Filesystem section.
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.
Changes PHP's current directory to directory. Returns FALSE if unable to change directory, TRUE otherwise.
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.
Notatka: The order in which directory entries are returned by the read method is system-dependent.
Closes the directory stream indicated by dir_handle. The stream must have previously been opened by opendir().
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.
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 readdir() will return the . and .. entries. If you don't want these, simply strip them out:
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
Constant | Value | Description |
---|---|---|
XML_ELEMENT_NODE | 1 | Node is an element |
XML_ATTRIBUTE_NODE | 2 | Node is an attribute |
XML_TEXT_NODE | 3 | Node is a piece of text |
XML_CDATA_SECTION_NODE | 4 | |
XML_ENTITY_REF_NODE | 5 | |
XML_ENTITY_NODE | 6 | Node is an entity like |
XML_PI_NODE | 7 | Node is a processing instruction |
XML_COMMENT_NODE | 8 | Node is a comment |
XML_DOCUMENT_NODE | 9 | Node is a document |
XML_DOCUMENT_TYPE_NODE | 10 | |
XML_DOCUMENT_FRAG_NODE | 11 | |
XML_NOTATION_NODE | 12 | |
XML_GLOBAL_NAMESPACE | 1 | |
XML_LOCAL_NAMESPACE | 2 |
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 name | Function name | Description |
---|---|---|
root | domxml_root() | |
children | domxml_children() | |
add_root | domxml_add_root() | |
dtd | domxml_intdtd() | |
dumpmem | domxml() | |
xpath_init | xpath_init | |
xpath_new_context | xpath_new_context | |
xptr_new_context | xptr_new_context |
Tabela 3. DomDocument class (attributes)
Name | Type | Description |
---|---|---|
doc | class DomDocument | The object itself |
name | string | |
url | string | |
version | string | Version of XML |
encoding | string | |
standalone | long | 1 if the file is a standalone version |
type | long | One of the constants in table ... |
compression | long | 1 if the file is compressed |
charset | long |
Tabela 4. DomNode class (methods)
Name | PHP name | Description |
---|---|---|
lastchild | domxml_last_child() | |
children | domxml_children() | |
parent | domxml_parent() | |
new_child | domxml_new_child() | |
get_attribute | domxml_get_attribute() | |
set_attribute | domxml_set_attribute() | |
attributes | domxml_attributes() | |
node | domxml_node() | |
set_content() | domxml_set_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. |
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()
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()
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.
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
|
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.
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()
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".
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()
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.
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.
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.
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()
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()
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()
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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()
This function returns the version of the XML library version currently used.
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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. |
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.
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
|
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
|
Tabela 1. error_reporting() bit values
constant | value |
---|---|
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
|
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()
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()
|
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()
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:
Notatka: See set_error_handler() for a more extensive example.
See also error_reporting(), set_error_handler(), restore_error_handler(), user_error()
This is an alias for the function trigger_error().
See also error_reporting(), set_error_handler(), restore_error_handler(), and trigger_error()
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.
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() 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() 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.
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.
See also: fbsql_connect() and fbsql_pconnect().
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()
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().
See also fbsql_pconnect() and fbsql_close().
fbsql_create_db() attempts to create a new database on the server associated with the specified link identifier.
See also: fbsql_drop_db().
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
|
See also: fbsql_create_clob(), fbsql_read_blob(), fbsql_read_clob(), and fbsql_set_lob_mode().
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
|
See also: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob(), and fbsql_set_lob_mode().
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
|
See also: fbsql_connect(), fbsql_pconnect() and fbsql_select_db().
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
|
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().
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().
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.
(PHP 4 >= 4.0.6)
fbsql_errno -- Returns the numerical value of the error message from previous FrontBase operationReturns 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().
(PHP 4 >= 4.0.6)
fbsql_error -- Returns the text of the error message from previous FrontBase operationReturns 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().
(PHP 4 >= 4.0.6)
fbsql_fetch_array -- Fetch a result row as an associative array, a numeric array, or bothReturns 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.
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
|
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().
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
|
See also fbsql_field_seek().
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().
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).
See also: fbsql_fetch_array() and fbsql_fetch_row().
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() 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() 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.
The above example would produce the following output:
fbsql_field_len() returns the length of the specified field.
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().
Returns the name of the table that the specified field is in.
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
|
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() 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() will return a result pointer containing the databases available from the current fbsql daemon. Use the fbsql_tablename() function to traverse this result pointer.
The above example would produce the following output:
Notatka: The above code would just as easily work with fbsql_fetch_row() or other similar functions.
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.
The above example would produce the following output:
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.
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
|
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() 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().
See also: fbsql_affected_rows(), fbsql_connect(), fbsql_select_db(), and fbsql_query().
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() 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:
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:
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().
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
|
See also: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob(), and fbsql_set_lob_mode().
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
|
See also: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob(), and fbsql_set_lob_mode().
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().
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()
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().
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().
Returns: TRUE on success, FALSE on failure.
fbsql_start_db()
See also: fbsql_db_status() and fbsql_stop_db().
Returns: TRUE on success, FALSE on failure.
fbsql_stop_db()
See also: fbsql_db_status() and fbsql_start_db().
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.
Returns TRUE if warnings is turned on otherwise FALSE.
fbsql_warnings() enables or disables FrontBase warnings.
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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/.
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.
Returns the name of the field corresponding to field_number.
Returns the edit type of the field corresponding to field_number.
Returns the width of the field corresponding to 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.
Returns the number of fields (columns) in the opened filePro database.
See also filepro().
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().
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 (/).
Notatka: Parametr przyrostek został dodany w PHP 4.1.0.
Patrz także: dirname()
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.
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.
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.
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().
Tworzy kopię pliku. Zwraca TRUE jeśli kopiowanie powiodło się, FALSE w przeciwnym przypadku.
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.
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.
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 (/).
Patrz także: basename()
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.
To jest odradzany alias do disk_free_space(). Użyj tej funkcji zamiast niego.
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.
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().
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().
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().
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().
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
|
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:
Patrz także fread(), fopen(), popen(), fgetc(), fsockopen() i socket_set_timeout().
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().
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().
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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! |
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.
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.
Patrz także fclose(), fsockopen(), socket_set_timeout() i popen().
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() 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() 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().
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.
Patrz także fread(), fgets(), fgetss(), sscanf(), printf() i sprintf().
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.
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:
urządzenie
i-węzeł
liczba dowiązań
identyfikator właściciela
identyfikator grupy właściciela
typ urządzenia (jeśli urządzenie inode)*
rozmiar w bajtach
czas ostatniego dostępu
czas ostatniej modyfikacji
czas ostatniej zmiany
rozmiar bloku w systemie plików I/O *
liczba przydzielonych bloków
Wyniki tej funkcji są cachowane. Zobacz clearstatcache() aby uzyskać więcej szczegółów.
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().
Pobiera wskaźnik pliku, fp, i przycina plik do długości, rozmiar.
Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
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().
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.
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.
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.
Zwraca TRUE jesli nazwa_pliku istnieje i jest zwykłym plikiem.
Wyniki tej funkcji są cachowane. Zobacz clearstatcache() aby uzyskać więcej szczegółów.
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.
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().
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().
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() 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() 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.
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().
Returns TRUE on success and FALSE on failure.
See also rmdir().
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() 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.
Would produce:
pathinfo() returns an associative array containing information about path. The following array elements are returned: dirname, basename and extension.
Would produce:
See also dirname(), basename(), parse_url() and realpath().
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().
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.
See also pclose().
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() 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.
Attempts to rename oldname to newname.
Returns TRUE on success and FALSE on failure.
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.
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().
Gathers the statistics of the file named by filename.
Returns an array with the statistics of the file with the following elements:
device
inode
inode protection mode
number of links
user id of owner
group id owner
device type if inode device *
size in bytes
time of last access
time of last modification
time of last change
blocksize for filesystem I/O *
number of blocks allocated
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.
Gathers the statistics of the file or symbolic link named by filename. This function is identical to the stat() function except that if the filename parameter is a symbolic link, the status of the symbolic link is returned, not the status of the file pointed to by the symbolic link.
Returns an array with the statistics of the file with the following elements:
device
inode
inode protection mode
number of links
user id of owner
group id owner
device type if inode device *
size in bytes
time of last access
time of last modification
time of last change
blocksize for filesystem I/O *
number of blocks allocated
The results of this function are cached. See clearstatcache() for more details.
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.
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.
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.
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.
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.
Patrz także tempnam().
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.
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.
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.
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
|
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.
See also fdf_close().
The fdf_close() function closes the FDF document.
See also fdf_open().
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
|
See also fdf_close(), fdf_save(), fdf_open().
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().
The fdf_get_value() function returns the value of a field.
See also fdf_set_value().
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().
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().
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.
The fdf_set_status() sets the value of the /STATUS key.
See also fdf_get_status().
The fdf_get_status() returns the value of the /STATUS key.
See also fdf_set_status().
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().
The fdf_set_file() returns the value of the /F key.
See also fdf_set_file().
The fdf_set_flags() sets certain flags of the given field fieldname.
See also fdf_set_opt().
The fdf_set_opt() sets options of the given field fieldname.
See also fdf_set_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() sets a javascript action for the given field fieldname.
See also fdf_set_submit_form_action().
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.
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. |
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()
|
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.
Loguje się do podanego strumienia FTP.
Zwraca wartość TRUE w przypadku sukcesu lub FALSE w przypadku napotkania błędu.
Zwraca nazwę bieżącego katalogu lub FALSE w przypadku napotkania błędu.
Zmienia bieżący katalog na nadrzędny.
Zwraca wartość TRUE w przypadku sukcesu lub FALSE w przypadku napotkania błędu.
Zmienia bieżący katalog na ten określony w parametrze katalog.
Zwraca wartość TRUE w przypadku sukcesu lub FALSE w przypadku napotkania błędu.
Tworzy podany katalog.
W przypadku sukcesu zwraca nazwę nowo utworzonego katalogu, lub wartość FALSE w przypadku napotkania błędu.
Tworzy podany katalog.
Zwraca wartość TRUE w przypadku sukcesu lub FALSE w przypadku napotkania błędu.
W przypadku sukcesu zwracana jest tablica z nazwami plików lub wartość FALSE w przypadku napotkania błędu.
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.
(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)
ftp_systype -- Zwraca identyfikator systemu dla zdalnego serwera FTP.Zwraca typ zdalnego systemu lub FALSE w przypadku napotkania błędu.
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() 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.
(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)
ftp_fget -- Pobiera plik z serwera FTP i zapisuje go do otwartego pliku.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() 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.
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() 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() 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() 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() 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() 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.
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 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().
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()
|
Przykład 2. Making a general processing function with create_function()
|
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%) |
Przykład 3. Using anonymous functions as callback functions
|
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.
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.
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.
(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)
function_exists -- Return TRUE if the given function has been definedChecks 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"; } |
See also method_exists().
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().
(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)
register_shutdown_function -- Register a function for execution on shutdownRegisters 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
Registers the function named by func to be executed when a tick is called.
De-registers the function named by func so it is no longer executed when a tick is called.
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.
The bindtextdomain() function sets the path for a domain.
(PHP 4 CVS only)
bind_textdomain_codeset -- Specify the character encoding in which the messages from the DOMAIN message catalog will be re turned
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
This function allows you to override the current domain for a single message lookup. It also allows you to specify a category.
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
The dgettext() function allows you to override the current domain for a single message lookup.
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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.
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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.
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. |
This will calculate factorial of 1000 (pretty big number) very fast.
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.
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().
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(). |
Convert GMP number to string representation in base base. The default base is 10. Allowed values for the base are from 2 to 36.
Add two GMP numbers. The result will be a GMP number representing the sum of the arguments.
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()
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()
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.
See also gmp_div_q(), gmp_div_r().
Calculates n modulo d. The result is always non-negative, the sign of d is ignored.
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.
Returns a positive value if a > b, zero if a = b and negative value if a < b.
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Return sign of a - 1 if a is positive and -1 if it's negative.
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).
Returns TRUE if a is a perfect square, FALSE otherwise.
See also: gmp_sqrt(), gmp_sqrtrm().
Raise base into power exp. The case of 0^0 yields 1. exp cannot be negative.
Calculate (base raised into power exp) modulo mod. If exp is negative, result is undefined.
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.
Calculate greatest common divisor of a and b. The result is always positive even if either of, or both, input operands are negative.
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.
Computes the inverse of a modulo b. Returns FALSE if an inverse does not exist.
Compute the Legendre symbol of a and p. p should be odd and must be positive.
Computes Jacobi symbol of a and p. p should be odd and must be positive.
Generate a random number. The number will be between limiter and zero in value. If limiter is negative, negative numbers are generated.
Calculates logical inclusive OR of two GMP numbers.
Calculates logical exclusive OR (XOR) of two GMP numbers.
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.
Scans a, starting with bit start, towards more significant bits, until the first clear bit is found. Returns the index of the found bit.
Scans a, starting with bit start, towards more significant bits, until the first set bit is found. Returns the index of the found bit.
Te funkcje pozwalają ci operować na danych wysyłanych do przeglądarki internetowej na poziomie protokołu HTTP.
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:
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:
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.
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.
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.
<?php require("user_logging.inc") ?> <?php header ("Content-Type: audio/x-pn-realaudio"); ?> // 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.
<?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() zwraca TRUE jeśli nagłówki HTTP już zostały wysłane, lub FALSE w przeciwnym wypadku.
Zobacz też header()
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:
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:
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:
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<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.
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:
Number of object records with attribute PresentationHints set to Hidden.
Number of object records with attribute PresentationHints set to CollectionHead.
Number of object records with attribute PresentationHints set to FullCollectionHead.
Index in array of object records with attribute PresentationHints set to CollectionHead.
Index in array of object records with attribute PresentationHints set to FullCollectionHead.
Total: Number of object records.
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:
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: 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 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.
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.
(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)
hw_Array2Objrec -- convert attributes from object array to object recordConverts an object_array into an object record. Multiple attributes like 'Title' in different languages are treated properly.
See also hw_objrec2array().
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.
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.
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.
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().
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().
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().
Returns an th object id of the document to which anchorID belongs.
Returns an th object record of the document to which anchorID belongs.
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().
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.
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().
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().
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.
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.
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().
Returns the last error number. If the return value is 0 no error has occurred. The error relates to the last command.
Frees the memory occupied by the Hyperwave document.
Returns an indexed array of object ids. Each object id belongs to a parent of the object with ID 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.
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().
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().
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().
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().
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().
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().
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().
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().
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().
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().
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().
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().
Returns array of object ids for child documents of a collection.
See also hw_children(), and hw_getchildcoll().
(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)
hw_GetChildDocCollObj -- object records of child documents of collectionReturns an array of object records for child documents of a collection.
See also hw_childrenobj(), and hw_getchildcollobj().
Returns an array of object ids with anchors of the document with object ID objectID.
Returns an array of object records with anchors of the document with object ID objectID.
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().
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().
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.
Returns information about the current connection. The returned string has the following format: <Serverstring>, <Host>, <Port>, <Username>, <Port of Client>, <Byte swapping>
Inserts a new collection with attributes as in object_array into collection with object ID objectID.
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().
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().
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().
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
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().
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:
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.
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().
(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)
hw_Objrec2Array -- convert attributes from object record to object arrayConverts 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().
Prints the document without the BODY tag.
For backward compatibility, hw_outputdocument() is also accepted. This is deprecated, however.
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().
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().
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.
Unlocks a document, so other users regain access.
See also hw_getandlock().
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.
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)
hw_connection_info -- Prints information about the connection to Hyperwave server
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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.
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_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.
int year - year
int month - month
int mday - day of month
int hour - hour
int min - minutes
int sec - seconds
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() 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() deletes the calendar event specified by the uid.
Returns TRUE.
icap_snooze() turns on an alarm for a calendar event specified by the uid.
Returns TRUE.
(PHP 4 >= 4.0.0)
icap_list_alarms -- Return a list of events that has an alarm triggered at the given datetimeReturns 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
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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.
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.
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().
Zmienia wartość zmiennej typ na zestaw_znaków i zwraca TRUE jeśli zmiana się powiedzie, lub FALSE w przeciwnym razie.
Zobacz też: iconv_get_encoding() i ob_iconv_handler().
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.
Zobacz też: iconv_get_encoding() i iconv_set_encoding().
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].
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.
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.
Notatka: This function does not require the GD image library.
Notatka: URL support was added in PHP 4.0.5
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() 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() 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() 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:
IMG_ARC_PIE
IMG_ARC_CHORD
IMG_ARC_NOFILL
IMG_ARC_EDGED
Notatka: This function was added in PHP 4.0.6 and requires GD 2.0.1
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() 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() 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() 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() 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.
Returns -1 if the allocation failed.
The ImageColorDeAllocate() function de-allocates a color previously allocated with the ImageColorAllocate() function.
Returns the index of the color of the pixel at the specified location in the image.
See also imagecolorset() and imagecolorsforindex().
(PHP 3, PHP 4 >= 4.0.0)
ImageColorClosest -- Get the index of the closest color to the specified colorReturns 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().
(PHP 4 >= 4.0.6)
ImageColorClosestAlpha -- Get the index of the closest color to the specified color + alphaReturns 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
(unknown)
ImageColorClosestThwb -- Get the index of the color which has the hue, white and blackness nearest to the given color
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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().
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
(PHP 3>= 3.0.2, PHP 4 >= 4.0.0)
ImageColorResolve -- Get the index of the specified color or its closest possible alternativeThis function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.
See also imagecolorclosest().
(PHP 4 >= 4.0.6)
ImageColorResolveAlpha -- Get the index of the specified color + alpha or its closest possible alternativeThis 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
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.
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().
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().
This returns the number of colors in the specified image's palette.
See also imagecolorat() and imagecolorsforindex().
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.
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.
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() 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() 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() 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() 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.
|
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() 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
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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)
|
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() 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 )
|
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)
|
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)
|
Notatka: WBMP support is only available if PHP was compiled against GD-1.8 or later.
ImageCreateFromString() returns an image identifier representing the image obtained from the given string.
ImageCreateFromXBM() returns an image identifier representing the image obtained from the given filename.
ImageCreateFromXPM() returns an image identifier representing the image obtained from the given filename.
This function is deprecated. Use combination of ImageSetStyle() and ImageLine() instead.
ImageDestroy() frees any memory associated with image im. Im is the image identifier returned by the ImageCreate() function.
ImageFill() performs a flood fill starting at coordinate x, y (top left is 0, 0) with color col in the image im.
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() 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() 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.
Returns the pixel height of a character in the specified font.
See also ImageFontWidth() and ImageLoadFont().
Returns the pixel width of a character in font.
See also ImageFontHeight() and ImageLoadFont().
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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:
See also ImagePNG(), ImageWBMP(), ImageJPEG(), ImageTypes().
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.
See also ImageGIF(), ImageWBMP(), ImageJPEG(), ImageTypes().
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() 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() 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() 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() 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 position | C data type | description |
---|---|---|
byte 0-3 | int | number of characters in the font |
byte 4-7 | int | value of first character in the font (often 32 for space) |
byte 8-11 | int | pixel width of each character |
byte 12-15 | int | pixel height of each character |
byte 16- | char | array with character data, one byte per pixel in each character, for a total of (nchars*width*height) bytes. |
See also ImageFontWidth() and ImageFontHeight().
imagepalettecopy() copies the palette from the source image to the destination image.
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().
(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)
ImagePSBBox -- Give the bounding box of a text rectangle using PostScript Type1 fontsSize 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:
See also imagepstext().
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.
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().
Extend or condense a font (font_index), if the value of the extend parameter is less than one you will be condensing the font.
Slant a font given by the font_index parameter with a slant of the value of the slant parameter.
(PHP 3>= 3.0.9, PHP 4 >= 4.0.0)
ImagePSText -- To draw a text string over an image using PostScript Type1 fontsSize 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:
See also imagepsbbox().
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() draws a pixel at x, y (top left is 0, 0) in image im of color col.
See also ImageCreate() and ImageColorAllocate().
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() 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
|
See also ImageSetBrush(), ImageLine().
Notatka: This function was added in PHP 4.0.6
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() 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() 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() 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() returns the width of the image identified by im.
See also ImageCreate() and ImageSY().
ImageSY() returns the height of the image identified by im.
See also ImageCreate() and ImageSX().
This function calculates and returns the bounding box in pixels for a TrueType text.
The string to be measured.
The font size in pixels.
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 in degrees in which text will be measured.
0 | lower left corner, X position |
1 | lower left corner, Y position |
2 | lower right corner, X position |
3 | lower right corner, Y position |
4 | upper right corner, X position |
5 | upper right corner, Y position |
6 | upper left corner, X position |
7 | upper left corner, Y position |
This function requires both the GD library and the FreeType library.
See also ImageTTFText().
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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: {) 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
|
This function requires both the GD library and the FreeType library.
See also ImageTTFBBox().
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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:
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().
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().
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
|
Notatka: This function is only available in PHP 4 compiled using --enable-exif
This function does not require the GD image library.
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).
Convert an 8bit string to a quoted-printable string (according to RFC2045, section 6.7).
Returns a quoted-printable string.
See also imap_qprint().
(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 resetThis 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.
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
|
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().
Convert an 8bit string to a base64 string (according to RFC2045, Section 6.8).
Returns a base64 string.
See also imap_base64().
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.
(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)
imap_bodystruct -- Read the structure of a specified body section of a specific message
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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
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:
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() 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
|
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
|
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.
(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.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() deletes all the messages marked for deletion by imap_delete(), imap_mail_move(), or imap_setflag_full().
Returns TRUE.
(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 messageThis 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
|
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().
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)
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()
type | Primary body type |
encoding | Body transfer encoding |
ifsubtype | TRUE if there is a subtype string |
subtype | MIME subtype |
ifdescription | TRUE if there is a description string |
description | Content description string |
ifid | TRUE if there is an identification string |
id | Identification string |
lines | Number of lines |
bytes | Number of bytes |
ifdisposition | TRUE if there is a disposition string |
disposition | Disposition string |
ifdparameters | TRUE if the dparameters array exists |
dparameters | An array of objects where each object has an "attribute" and a "value" property corresponding to the parameters on the Content-disposition MIMEheader. |
ifparameters | TRUE if the parameters array exists |
parameters | An array of objects where each object has an "attribute" and a "value" property. |
parts | An array of objects identical in structure to the top-level object, each of which corresponds to a MIME body part. |
See also: imap_fetchbody().
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
|
See also imap_open(), imap_set_quota().
(PHP 3>= 3.0.12, PHP 4 >= 4.0.0)
imap_getmailboxes -- Read the list of mailboxes, returning detailed information on each oneReturns 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
|
See also imap_getsubscribed().
This function is identical to imap_getmailboxes(), except that it only returns mailboxes that the user is subscribed to.
This is an alias to imap_headerinfo() and is identical to this in any way.
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)
Returns an array of string formatted with header info. One element per mail message.
(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 requestThis 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.
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
|
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.
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.
(PHP 3>= 3.0.5, PHP 4 >= 4.0.0)
imap_mail_compose -- Create a MIME message based on given envelope and body sections
Przykład 1. imap_mail_compose() example
|
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
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.
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
Date | date of last change |
Driver | driver |
Mailbox | name of the mailbox |
Nmsgs | number of messages |
Recent | number of recent messages |
Unread | number of unread messages |
Deleted | number of deleted messages |
Size | mailbox size |
Przykład 1. imap_mailboxmsginfo() example
|
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".
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.
(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)
imap_msgno -- This function returns the message sequence number for the given UIDThis function returns the message sequence number for the given UID. It is the inverse of imap_uid().
Return the number of messages in the current mailbox.
See also: imap_num_recent() and imap_status().
Returns the number of recent messages in the current mailbox.
See also: imap_num_msg() and imap_status().
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:
To connect to a POP3 server on port 110 on the local server, use: To connect to an SSL IMAP or POP3 server, add /ssl after the protocol specification: To connect to an SSL IMAP or POP3 server with a self-signed certificate, add /ssl/novalidate-cert after the protocol specification: To connect to an NNTP server on port 119 on the local server, use: 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
|
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.)
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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().
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.
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.
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
|
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.
(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.Returns a properly formatted email address as defined in RFC2822 given the mailbox, host, and personal info.
(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 mailboxReturns 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.
(PHP 3>= 3.0.12, PHP 4 >= 4.0.0)
imap_search -- This function returns an array of messages matching the given search criteriaThis 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.
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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.
See also imap_open(), imap_set_quota().
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:
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:
(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)
imap_status -- This function returns status information on a mailbox other than the current oneThis 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
|
Subscribe to a new mailbox.
Returns TRUE on success and FALSE on error.
(PHP 3>= 3.0.3, PHP 4 >= 4.0.0)
imap_uid -- This function returns the UID for the given message sequence numberThis 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.
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.
Unsubscribe from a specified mailbox.
Returns TRUE on success and FALSE on error.
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).
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.
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.
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().
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().
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().
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
|
Przykład 2. Insert some values into the "catalog" table
|
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().
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.
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()
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()
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
|
(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)
ifx_getsqlca -- Get the contents of sqlca.sqlerrd[0..5] after a queryresult_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
|
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
|
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
|
Returns an associative array with fieldnames as key and the SQL fieldtypes as data for query with result_id. Returns FALSE on error.
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".
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.
Gives the number of rows fetched so far for a query with result_id after a ifx_query() or ifx_do() query.
Releases resources for the query associated with result_id. Returns FALSE on error.
Creates an char object. param should be the char content.
Deletes the charobject for the given char object-id bid. Returns FALSE on error otherwise TRUE.
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.
Returns the content of the char object for the given char object-id bid.
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.
Duplicates the given blob object. bid is the ID of the blob object.
Returns FALSE on error otherwise the new blob object-id.
Deletes the blobobject for the given blob object-id bid. Returns FALSE on error otherwise TRUE.
Returns the content of the blob object for the given blob object-id bid.
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.
(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)
ifx_blobinfile_mode -- Set the default blob mode for all select queriesSet 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.
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.
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.
Sets the default return value of a NULL-value on a fetch row. Mode "0" returns "", and mode "1" returns "NULL".
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.
Deletes the slob object. bid is the Id of the slob object. Returns FALSE on error otherwise TRUE.
Deletes the slob object on the given slob object-id bid. Return FALSE on error otherwise TRUE.
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.
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.
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.
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.
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!
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().
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().
(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)
ibase_pconnect -- Creates an persistent connection to an InterBase databaseibase_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.
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.
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().
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.
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().
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"; } |
Free's a result set the has been created by ibase_query().
(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)
ibase_prepare -- Prepare a query for later binding of parameter placeholders and executionPrepare a query for later binding of parameter placeholders and execution (via ibase_execute()).
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.
Commits transaction trans_number which was created with ibase_trans().
Rolls back transaction trans_number which was created with ibase_trans().
(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)
ibase_timefmt -- Sets the format of timestamp, date and time type columns returned from queriesSets 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.
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().
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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).
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.
See also ingres_pconnect() and ingres_close().
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().
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().
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:
close (see ingres_close())
commit (see ingres_commit())
connect (see ingres_connect())
disconnect (see ingres_close())
get dbevent
prepare to commit
rollback (see ingres_rollback())
savepoint
set autocommit (see ingres_autocommit())
all cursor related queries are unsupported
See also ingres_fetch_array(), ingres_fetch_object(), ingres_fetch_row(), ingres_commit(), ingres_rollback(), and ingres_autocommit().
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().
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().
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().
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().
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().
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().
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().
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().
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).
See also ingres_query(), ingres_num_fields(), ingres_field_name(), ingres_fetch_object(), and ingres_fetch_row().
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.
See also ingres_num_fields(), ingres_query(), ingres_fetch_array(), and ingres_fetch_object().
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).
See also ingres_query(), ingres_num_fields(), ingres_field_name(), ingres_fetch_array(), and ingres_fetch_row().
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().
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().
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().
With ircg you can build powerful, fast and scalable webchat solutions in conjunction with dedicated or public IRC servers.
To install and use IRCG you need the following software:
IRCG-Library from Sascha Schumann.
thttpd webserver
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() returns the error from the last called ircg function.
Notatka: Errorcode is stored in first array element, errortext in second.
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().
Join the channel channel on the server connected to by connection.
Leave the channel channel on the server connected to by connection.
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.
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.
Change your nickname on the given connection to the one given in nick if possible.
Will return TRUE on success and FALSE on failure.
Change the topic for channel channel on the server connected to by connection to new_topic.
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.
Encodes a HTML string html_string for output. This feature could be usable, e.g. if someone wants to discuss about an html problem.
Sends a query to the connected server connection to send information for the specified user nick.
Kick user nick from channel on server connected to by connection. reason should give a short message describing why this action was performed.
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().
This function remove user nick from your ignore list on the server connected to by connection.
See also: ircg_ignore_add().
ircg_disconnect() will close a connection to a server previously established with ircg-pconnect().
See also: ircg_pconnect().
ircg_is_conn_alive() returns TRUE if connection is still alive and working or FALSE if the server no longer talks to us.
(PHP 4 >= 4.0.5)
ircg_lookup_format_messages -- Select a set of format strings for display of IRC messagesSelect 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()
(PHP 4 >= 4.0.5)
ircg_register_format_messages -- Register a set of format strings for display of IRC messagesWith 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().
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.
Function ircg_set_file() specifies a logfile path in which all output from connection connection will be logged. Returns TRUE on success, otherwise FALSE.
Function ircg_get_username() returns the username for specified connection connection. Returns FALSE if connection died or is not valid.
Function ircg_nickname_escape() returns a decoded nickname specified by nick wich is IRC-compliant.
See also: ircg_nickname_unescape()
Function ircg_nickname_unescape() returns a decoded nickname, which is specified in nick.
See also: ircg_nickname_escape()
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
|
Przykład 2. AWT Example
|
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.
The following example demonstrates the usage of Java's exception handler from within PHP:
Przykład 1. Java exception handler
|
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.
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
|
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"
Lots of information about LDAP can be found at
The Netscape SDK contains a helpful Programmer's Guide in .html format.
Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
The ldap_add() function is used to add entries in the LDAP directory. The DN of the entry to be added is specified by dn. Array entry specifies the information about the entry. The values in the entries are indexed by individual attributes. In case of multiple values for an attribute, they are indexed using integers starting with 0.
Przykład 1. Complete example with authenticated bind
|
Binds to the LDAP directory with specified RDN and password. Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
ldap_bind() does a bind operation on the directory. bind_rdn and bind_password are optional. If not specified, anonymous bind is attempted.
Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
ldap_close() closes the link to the LDAP server that's associated with the specified link_identifier.
This call is internally identical to ldap_unbind(). The LDAP API uses the call ldap_unbind(), so perhaps you should use this in preference to ldap_close().
Notatka: This function is an alias of ldap_unbind().
Returns TRUE if value matches otherwise returns FALSE. Returns -1 on error.
ldap_compare() is used to compare value of attribute to value of same attribute in LDAP directory entry specified with dn.
The following example demonstrates how to check whether or not given password matches the one defined in DN specified entry.
Przykład 1. Complete example of password check
|
Ostrze¿enie |
ldap_compare() can NOT be used to compare BINARY values! |
Notatka: This function was added in 4.0.2.
Returns a positive LDAP link identifier on success, or FALSE on error.
ldap_connect() establishes a connection to a LDAP server on a specified hostname and port. Both the arguments are optional. If no arguments are specified then the link identifier of the already opened link will be returned. If only hostname is specified, then the port defaults to 389.
If you are using OpenLDAP 2.x.x you can specify a URL instead of the hostname. To use LDAP with SSL, compile OpenLDAP 2.x.x with SSL support, configure PHP with SSL, and use ldaps://hostname/ as host parameter. The port parameter is not used when using URLs.
Notatka: URL and SSL support were added in 4.0.4.
Returns number of entries in the result or FALSE on error.
ldap_count_entries() returns the number of entries stored in the result of previous search operations. result_identifier identifies the internal ldap result.
Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
ldap_delete() function delete a particular entry in LDAP directory specified by dn.
ldap_dn2ufn() function is used to turn a DN, specified by dn, into a more user-friendly form, stripping off type names.
Returns string error message.
This function returns the string error message explaining the error number errno. While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check.
See also ldap_errno() and ldap_error().
Return the LDAP error number of the last LDAP command for this link.
This function returns the standardized error number returned by the last LDAP command for the given link_identifier. This number can be converted into a textual error message using ldap_err2str().
Unless you lower your warning level in your php.ini sufficiently or prefix your LDAP commands with @ (at) characters to suppress warning output, the errors generated will also show up in your HTML output.
Przykład 1. Generating and catching an error
|
See also ldap_err2str() and ldap_error().
(PHP 3>= 3.0.12, PHP 4 >= 4.0.0)
ldap_error -- Return the LDAP error message of the last LDAP commandReturns string error message.
This function returns the string error message explaining the error generated by the last LDAP command for the given link_identifier While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check.
Unless you lower your warning level in your php.ini sufficiently or prefix your LDAP commands with @ (at) characters to suppress warning output, the errors generated will also show up in your HTML output.
See also ldap_err2str() and ldap_errno().
ldap_explode_dn() function is used to split the DN returned by ldap_get_dn() and breaks it up into its component parts. Each part is known as Relative Distinguished Name, or RDN. ldap_explode_dn() returns an array of all those components. with_attrib is used to request if the RDNs are returned with only values or their attributes as well. To get RDNs with the attributes (i.e. in attribute=value format) set with_attrib to 0 and to get only values set it to 1.
Returns the first attribute in the entry on success and FALSE on error.
Similar to reading entries, attributes are also read one by one from a particular entry. ldap_first_attribute() returns the first attribute in the entry pointed by the result_entry_identifier. Remaining attributes are retrieved by calling ldap_next_attribute() successively. ber_identifier is the identifier to internal memory location pointer. It is passed by reference. The same ber_identifier is passed to the ldap_next_attribute() function, which modifies that pointer.
See also ldap_get_attributes()
Returns the result entry identifier for the first entry on success and FALSE on error.
Entries in the LDAP result are read sequentially using the ldap_first_entry() and ldap_next_entry() functions. ldap_first_entry() returns the entry identifier for first entry in the result. This entry identifier is then supplied to lap_next_entry() routine to get successive entries from the result.
See also ldap_get_entries().
Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
ldap_free_result() frees up the memory allocated internally to store the result and pointed by the result_identifier. All result memory will be automatically freed when the script terminates.
Typically all the memory allocated for the ldap result gets freed at the end of the script. In case the script is making successive searches which return large result sets, ldap_free_result() could be called to keep the runtime memory usage by the script low.
Returns a complete entry information in a multi-dimensional array on success and FALSE on error.
ldap_get_attributes() function is used to simplify reading the attributes and values from an entry in the search result. The return value is a multi-dimensional array of attributes and values.
Having located a specific entry in the directory, you can find out what information is held for that entry by using this call. You would use this call for an application which "browses" directory entries and/or where you do not know the structure of the directory entries. In many applications you will be searching for a specific attribute such as an email address or a surname, and won't care what other data is held.
return_value["count"] = number of attributes in the entry
return_value[0] = first attribute
return_value[n] = nth attribute
return_value["attribute"]["count"] = number of values for attribute
return_value["attribute"][0] = first value of the attribute
return_value["attribute"][i] = (i+1)th value of the attribute
Przykład 1. Show the list of attributes held for a particular directory entry
|
See also ldap_first_attribute() and ldap_next_attribute()
Returns the DN of the result entry and FALSE on error.
ldap_get_dn() function is used to find out the DN of an entry in the result.
Returns a complete result information in a multi-dimenasional array on success and FALSE on error.
ldap_get_entries() function is used to simplify reading multiple entries from the result, specified with result_identifier, and then reading the attributes and multiple values. The entire information is returned by one function call in a multi-dimensional array. The structure of the array is as follows.
The attribute index is converted to lowercase. (Attributes are case-insensitive for directory servers, but not when used as array indices.)
return_value["count"] = number of entries in the result
return_value[0] : refers to the details of first entry
return_value[i]["dn"] = DN of the ith entry in the result
return_value[i]["count"] = number of attributes in ith entry
return_value[i][j] = jth attribute in the ith entry in the result
return_value[i]["attribute"]["count"] = number of values for
attribute in ith entry
return_value[i]["attribute"][j] = jth value of attribute in ith entry
See also ldap_first_entry() and ldap_next_entry()
Sets retval to the value of the specified option. Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
The parameter option can be one of: LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT, LDAP_OPT_PROTOCOL_VERSION, LDAP_OPT_ERROR_NUMBER, LDAP_OPT_REFERRALS, LDAP_OPT_RESTART, LDAP_OPT_HOST_NAME, LDAP_OPT_ERROR_STRING, LDAP_OPT_MATCHED_DN. These are described in draft-ietf-ldapext-ldap-c-api-xx.txt
Notatka: This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x, and was added in PHP 4.0.4
See also ldap_set_option().
Returns an array of values for the attribute on success and FALSE on error.
ldap_get_values() function is used to read all the values of the attribute in the entry in the result. entry is specified by the result_entry_identifier. The number of values can be found by indexing "count" in the resultant array. Individual values are accessed by integer index in the array. The first index is 0.
This call needs a result_entry_identifier, so needs to be preceded by one of the ldap search calls and one of the calls to get an individual entry.
You application will either be hard coded to look for certain attributes (such as "surname" or "mail") or you will have to use the ldap_get_attributes() call to work out what attributes exist for a given entry.
LDAP allows more than one entry for an attribute, so it can, for example, store a number of email addresses for one person's directory entry all labeled with the attribute "mail"
return_value["count"] = number of values for attribute
return_value[0] = first value of attribute
return_value[i] = ith value of attribute
Przykład 1. List all values of the "mail" attribute for a directory entry
|
Returns an array of values for the attribute on success and FALSE on error.
ldap_get_values_len() function is used to read all the values of the attribute in the entry in the result. entry is specified by the result_entry_identifier. The number of values can be found by indexing "count" in the resultant array. Individual values are accessed by integer index in the array. The first index is 0.
This function is used exactly like ldap_get_values() except that it handles binary data and not string data.
Notatka: This function was added in 4.0.
Returns a search result identifier or FALSE on error.
ldap_list() performs the search for a specified filter on the directory with the scope LDAP_SCOPE_ONELEVEL.
LDAP_SCOPE_ONELEVEL means that the search should only return information that is at the level immediately below the base_dn given in the call. (Equivalent to typing "ls" and getting a list of files and folders in the current working directory.)
This call takes 5 optional parameters. See ldap_search() notes.
Notatka: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.
Przykład 1. Produce a list of all organizational units of an organization
|
Notatka: From 4.0.5 on it's also possible to do parallel searches. See ldap_search() for details.
Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
ldap_modify() function is used to modify the existing entries in the LDAP directory. The structure of the entry is same as in ldap_add().
Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
This function adds attribute(s) to the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level additions are done by the ldap_add() function.
Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
This function removes attribute(s) from the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level deletions are done by the ldap_delete() function.
Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
This function replaces attribute(s) from the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level modifications are done by the ldap_modify() function.
Returns the next attribute in an entry on success and FALSE on error.
ldap_next_attribute() is called to retrieve the attributes in an entry. The internal state of the pointer is maintained by the ber_identifier. It is passed by reference to the function. The first call to ldap_next_attribute() is made with the result_entry_identifier returned from ldap_first_attribute().
See also ldap_get_attributes()
Returns entry identifier for the next entry in the result whose entries are being read starting with ldap_first_entry(). If there are no more entries in the result then it returns FALSE.
ldap_next_entry() function is used to retrieve the entries stored in the result. Successive calls to the ldap_next_entry() return entries one by one till there are no more entries. The first call to ldap_next_entry() is made after the call to ldap_first_entry() with the result_entry_identifier as returned from the ldap_first_entry().
See also ldap_get_entries()
Returns a search result identifier or FALSE on error.
ldap_read() performs the search for a specified filter on the directory with the scope LDAP_SCOPE_BASE. So it is equivalent to reading an entry from the directory.
An empty filter is not allowed. If you want to retrieve absolutely all information for this entry, use a filter of "objectClass=*". If you know which entry types are used on the directory server, you might use an appropriate filter such as "objectClass=inetOrgPerson".
This call takes 5 optional parameters. See ldap_search() notes.
Notatka: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.
From 4.0.5 on it's also possible to do parallel searches. See ldap_search() for details.
The entry specified by dn is renamed/moved. The new RDN is specified by newrdn and the new parent/superior entry is specified by newparent. If the parameter deleteoldrdn is TRUE the old RDN value(s) is removed, else the old RDN value(s) is retained as non-distinguished values of the entry. Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
Notatka: This function currently only works with LDAPv3. You may have to use ldap_set_option() prior to binding to use LDAPv3. This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x, and was added in PHP 4.0.5.
Returns a search result identifier or FALSE on error.
ldap_search() performs the search for a specified filter on the directory with the scope of LDAP_SCOPE_SUBTREE. This is equivalent to searching the entire directory. base_dn specifies the base DN for the directory.
There is a optional fourth parameter, that can be added to restrict the attributes and values returned by the server to just those required. This is much more efficient than the default action (which is to return all attributes and their associated values). The use of the fourth parameter should therefore be considered good practice.
The fourth parameter is a standard PHP string array of the required attributes, eg array("mail","sn","cn") Note that the "dn" is always returned irrespective of which attributes types are requested.
Note too that some directory server hosts will be configured to return no more than a preset number of entries. If this occurs, the server will indicate that it has only returned a partial results set. This occurs also if the sixth parameter sizelimit has been used to limit the count of fetched entries.
The fifth parameter attrsonly should be set to 1 if only attribute types are wanted. If set to 0 both attributes types and attribute values are fetched which is the default behaviour.
With the sixth parameter sizelimit it is possible to limit the count of entries fetched. Setting this to 0 means no limit. NOTE: This parameter can NOT override server-side preset sizelimit. You can set it lower though.
The seventh parameter timelimit sets the number of seconds how long is spend on the search. Setting this to 0 means no limit. NOTE: This parameter can NOT override server-side preset timelimit. You can set it lower though.
The eigth parameter deref specifies how aliases should be handled during the search. It can be one of the following:
LDAP_DEREF_NEVER - (default) aliases are never dereferenced.
LDAP_DEREF_SEARCHING - aliases should be dereferenced during the search but not when locating the base object of the search.
LDAP_DEREF_FINDING - aliases should be dereferenced when locating the base object but not during the search.
LDAP_DEREF_ALWAYS - aliases should be dereferenced always.
Notatka: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.
The search filter can be simple or advanced, using boolean operators in the format described in the LDAP doumentation (see the Netscape Directory SDK for full information on filters).
The example below retrieves the organizational unit, surname, given name and email address for all people in "My Company" where the surname or given name contains the substring $person. This example uses a boolean filter to tell the server to look for information in more than one attribute.
Przykład 1. LDAP search
|
From 4.0.5 on it's also possible to do parallel searches. To do this you use an array of link identifiers, rather than a single identifier, as the first argument. If you don't want the same base DN and the same filter for all the searches, you can also use an array of base DNs and/or an array of filters. Those arrays must be of the same size as the link identifier array since the first entries of the arrays are used for one search, the second entries are used for another, and so on. When doing parallel searches an array of search result identifiers is returned, except in case of error, then the entry corresponding to the search will be FALSE. This is very much like the value normally returned, except that a result identifier is always returned when a search was made. There are some rare cases where the normal search returns FALSE while the parallel search returns an identifier.
Sets the value of the specified option to be newval. Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki. on error.
The parameter option can be one of: LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT, LDAP_OPT_PROTOCOL_VERSION, LDAP_OPT_ERROR_NUMBER, LDAP_OPT_REFERRALS, LDAP_OPT_RESTART, LDAP_OPT_HOST_NAME, LDAP_OPT_ERROR_STRING, LDAP_OPT_MATCHED_DN, LDAP_OPT_SERVER_CONTROLS, LDAP_OPT_CLIENT_CONTROLS. Here's a brief description, see draft-ietf-ldapext-ldap-c-api-xx.txt for details.
The options LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT, LDAP_OPT_PROTOCOL_VERSION and LDAP_OPT_ERROR_NUMBER have integer value, LDAP_OPT_REFERRALS and LDAP_OPT_RESTART have boolean value, and the options LDAP_OPT_HOST_NAME, LDAP_OPT_ERROR_STRING and LDAP_OPT_MATCHED_DN have string value. The first example illustrates their use. The options LDAP_OPT_SERVER_CONTROLS and LDAP_OPT_CLIENT_CONTROLS require a list of controls, this means that the value must be an array of controls. A control consists of an oid identifying the control, an optional value, and an optional flag for criticality. In PHP a control is given by an array containing an element with the key oid and string value, and two optional elements. The optional elements are key value with string value and key iscritical with boolean value. iscritical defaults to FALSE if not supplied. See also the second example below.
Notatka: This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x, and was added in PHP 4.0.4.
Przykład 2. Set server controls
|
See also ldap_get_option().
Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
ldap_unbind() function unbinds from the LDAP directory.
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Funkcja mail() pozwala ci wysyłać listy e-mail.
Dyrektywy konfiguracyjne poczty elektronicznej
Adres w DNS-ie lub numer IP serwera SMTP, którego PHP pod Windowsem ma użyć do wysłania poczty za pomocą funkcji mail()
Określa adres pocztowy w polu "From:" w listach wysyłanych z PHP pod Windowsem.
Określa, gdzie znajduje się program sendmail, zwykle /usr/sbin/sendmail lub /usr/lib/sendmail configure próbuje samodzielnie zlokalizować ten program i ucznić go domyślnym, ale w przypadku niepowodzenia, można ręcznie ustawić ścieżkę za pomocš tej dyrektywy.
W systemach nie używających sendmaila, dyrektywa ta powinna wskazywać na program będący odpowiednikiem sendmaila, o ile jest taki program w tym systemie. Na przykład użytkownicy programu Qmail mogą ustawić ścieżkę na /var/qmail/bin/sendmail.
mail() automatycznie wysyła wiadomość określoną w treść do odbiorcy określonego w do. Można wysłać wiadomość do kilku odbiorców na raz, wypisując ich adresy po przecinku w argumencie do. Poprzez tę funkcję można też wysłać listy zawierające załączniki lub inne typy wiadomości. Jest to możliwe dzięki kodowaniu MIME - po więcej informacji, zajrzyj http://www.zend.com/zend/spotlight/sendmimeemailpart1.php lub Klasy Mime PEAR.
Poniższe RFC mogą być przydatne: RFC 1896, RFC 2045, RFC 2046, RFC 2047, RFC 2048 i RFC 2049.
mail() zwraca TRUE jeśli udało się wysłać e-mail, lub FALSE w przeciwnym wypadku.
Jeśli zostanie podany czwarty argument, będzie on dopisany na końcu nagłówka wiadomości. Ten argument wykorzystuje się do wstawienia dodatkowych nagłówków. Dodatkowe nagłówki rozdziela się znakiem powrotu karetki i nowego wiersza.
Notatka: Aby rozdzielić nagłówki, trzeba użyć sekwencji \r\n, chociaż niektóre uniksowe agenty pocztowe obsługują także pojedynczy znak nowej linii (\n). W nagłówku Cc: jest rozróżniana wielkość liter i z tego powodu, w systemach Win32 musi być pisany jako Cc:. Nagłówek Bcc: nie jest obsługiwany w systemach Win32.
Argumentu dodatkowe_parametry używa się do przekazania dodatkowych paramterów do programu wysyłającego pocztę skonfigurowanego w dyrektywie sendmail_path. Używa się tego na przykład do ustawienia adresu zwrotnego koperty (envelope sender adress) przy wysyłaniu listy za pomocą sendmaila. Możesz być zmuszony dodać użytkownika jakim jest twój serwer www do listy zaufanych użytkowników w pliku konfiguracyjnym sendmaila, aby sendmail nie dodał nagłówka "X-warning" do wiadomości przy wysyłaniu koperty (envelope) tą metodą.
Notatka: Piąty argument funkcji mail() został dodany w PHP 4.0.5.
Można tez użyć zwykłych operacji na łańcuchach znaków do tworzenia złożonych wiadomości e-mail.
Przykład 4. Wysyłanie złożonego e-maila.
|
Notatka: Upewnij się, że nie ma żadnych znaków nowej linii w argumencie do lub temat, gdyż w przeciwnym razie, e-mail może nie być wysłany poprawnie.
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. |
(PHP 4 CVS only)
mailparse_uudecode_all -- Scans the data from fp and extract each embedded uuencoded file. Returns an array listing filename informationOstrze¿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. |
(PHP 4 >= 4.1.0)
mailparse_rfc822_parse_addresses -- Parse addresses and returns a hash containing that dataOstrze¿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. |
(PHP 4 >= 4.1.0)
mailparse_determine_best_xfer_encoding -- Figures out the best way of encoding the content read from the file pointer fp, which must be seek-ableOstrze¿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. |
(PHP 4 >= 4.1.0)
mailparse_stream_encode -- Streams data from source file pointer, apply encoding and write to destfpOstrze¿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. |
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. |
(PHP 4 >= 4.1.0)
mailparse_msg_parse_file -- Parse file and return a resource representing the structureOstrze¿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. |
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. |
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. |
(PHP 4 >= 4.1.0)
mailparse_msg_get_structure -- Returns an array of mime section names in the supplied messageOstrze¿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. |
(PHP 4 >= 4.1.0)
mailparse_msg_extract_part -- Extracts/decodes a message section. If callbackfunc is not specified, the contents will be sent to "stdout"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. |
(PHP 4 >= 4.1.0)
mailparse_msg_extract_part_file -- Extracts/decodes a message section, decoding the transfer encodingOstrze¿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. |
(PHP 4 >= 4.1.0)
mailparse_msg_get_part_data -- Returns an associative array of info about the messageOstrze¿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. |
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. |
Omówione poniżej funkcje operują na wartościach z przedziałów typów integer i float na twoim komputerze (co odpowiada zakresowi long resp. double języka C). Jeśli potrzebujesz obsługi większych liczb, zajrzyj do funkcji matematycznych dla liczb dowolnej dokładności
Poniższe wartości są zdefiniowane w PHP jako stałe w rozszerzeniu matematycznym:
Tabela 1. Stałe matematyczne
Stała | Wartosć | Opis |
---|---|---|
M_PI | 3.14159265358979323846 | Pi |
M_E | 2.7182818284590452354 | e |
M_LOG2E | 1.4426950408889634074 | log_2 e |
M_LOG10E | 0.43429448190325182765 | log_10 e |
M_LN2 | 0.69314718055994530942 | log_e 2 |
M_LN10 | 2.30258509299404568402 | log_e 10 |
M_PI_2 | 1.57079632679489661923 | pi/2 |
M_PI_4 | 0.78539816339744830962 | pi/4 |
M_1_PI | 0.31830988618379067154 | 1/pi |
M_2_PI | 0.63661977236758134308 | 2/pi |
M_SQRTPI | 1.77245385090551602729 | sqrt(pi) [4.0.2] |
M_2_SQRTPI | 1.12837916709551257390 | 2/sqrt(pi) |
M_SQRT2 | 1.41421356237309504880 | sqrt(2) |
M_SQRT3 | 1.73205080756887729352 | sqrt(3) [4.0.2] |
M_SQRT1_2 | 0.70710678118654752440 | 1/sqrt(2) |
M_LNPI | 1.14472988584940017414 | log_e(pi) [4.0.2] |
M_EULER | 0.57721566490153286061 | Stała Eulera [4.0.2] |
Zwraca wartość bezwzględną podanej liczby. Jeśli argument jest typu float, zwracana jest także wartość float, inaczej zwracana jest wartość integer (float ma zwykle szerszy zakres niż integer).
Zwraca odwrotny cosinus hiperboliczny z liczby arg, tzn. taką wartość, której cosinus hiperboliczny jest równy arg.
Notatka: Ta funkcja nie jest dostępna na platformie Windows.
Zwraca odwrotny sinus hiperboliczny z liczby arg, tzn. taką wartość, której sinus hiperboliczny jest równy arg.
Notatka: Ta funkcja nie jest dostępna na platformie Windows.
Zwraca odwrotny tangens hiperboliczny z liczby arg, tzn. taką wartość, dla której tangens hiperboliczny jest równy arg.
Notatka: Ta funkcja nie jest dostępna na platformie Windows.
Ta funkcja oblicza arcus tangens dwóch zmiennych x i y. Jej działanie przypomina obliczanie arcus tangens z y / x, a do tego, znaki obydwu argumentów wykorzystywane są do określenia ćwiartki (kwadrantu) układu współrzędnych.
Funkcja zwraca wartość w radianach, zawierającą się między -PI a PI włącznie.
(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)
base_convert -- Konwertuje liczbę pomiędzy różnymi systemami liczbowymiZwraca łańcuch znaków zawierający liczbę w reprezentacji w system_docelowy. System w którym podajemy liczbę jest określony w system_bazowy. Parametry system_bazowy i system_docelowy muszą zawierać się pomiędzy 2 a 36 włącznie. Cyfry w liczbach o bazie większej niż 10 są reprezentowane za pomocą liter a-z, gdzie a oznacza 10, b oznacza 11, a z oznacza 35.
Zwraca liczbę dziesiętną odpowiadającą liczbie dwójkowej podanej w argumencie liczba_dwójkowa.
bindec() konwertuje liczby dwójkowe do liczb całkowitych. Największą konwertowaną liczbą jest 31 bitów jedynek, czyli 2 147 483 647 dziesiętnie.
Zobacz też decbin().
Zwraca nabliższą liczbę całkowitą, większą lub równą podanemu argumentowi liczba. Zwracana przez funkcję ceil() wartość jest nadal typu float gdyż zakres tego typu jest zwykle większy niż zakres typu int.
Zwraca cosinus hiperboliczny z liczby arg, definiowany jako (exp(arg) + exp(-arg))/2.
Zwraca łańcuch znaków stanowiący dwójkową reprezentację liczby dziesiętnej podanej jako argument. Największą liczbą możliwą do skonwertowania jest 4 294 967 295 dziesiętnie, co równe jest 32 bitom jedynek.
Zobacz też bindec().
Zwraca łańcuch znaków stanowiący szesnastkową reprezentację podanej liczby dziesiętnej. Największą liczbą, która może być skonwertowana jest 2 147 483 647 dziesiętnie, co odpowiada "7fffffff" szesnastkowo.
Zobacz też hexdec().
Zwraca łańcuch znaków zawierający ósemkową reprezentację podanej liczby dziesiętnej. Największą liczbą, która może być skonwertowana jest 2 147 483 647 dziesiętnie, co odpowiada "17777777777" ósemkowo.
Zobacz też octdec().
deg2rad() przelicza stopnie podane w liczba na radiany.
Zobacz też rad2deg().
(PHP 4 >= 4.1.0)
expm1 -- Zwraca exp(liczba) - 1, obliczoną w taki sposób, że wartość jest dokładna, nawet jeśli liczba jest bliska zeruOstrze¿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. |
Zwraca najbliższą liczbę całkowitą, mniejszą lub równą podanemu arumentowi liczba. Zwracana przez funkcję floor() wartość jest nadal typu float ponieważ zakres tego typu jest zwykle większy niż zakres typu int.
Zwraca największą liczbę, jaka może być zwrócona przez funkcję rand().
Zobacz też rand(), srand(), mt_rand(), mt_srand(), i mt_getrandmax().
Zwraca dziesiętny odpowiednik liczby szesnastkowej podanej w argumencie hex_string. hexdec() konwertuje szesnastkowy łańcuch znaków do postaci liczby dziesiętnej. Największą liczbą, która może być skonwertowana jest 7fffffff, czyli 2147483647 dziesiętnie.
hexdec() zastąpi każdy znak, nie będący cyfrą w systemie szesnastkowym liczbą 0. W ten sposób, wszystko zera stojące z lewej strony są ignorowane, ale zera z prawej strony są brane pod uwagę.
Zobacz też dechex().
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. |
lcg_value() zwraca liczbę pseudolosową z przedziału (0, 1). Funkcja łączy dwa CG o okresach 2^31 - 85 i 2^31 - 249. Okres tej funkcji jest równy wartości obydwu składowych.
(PHP 4 >= 4.1.0)
log1p -- Zwraca log(1 + liczba), obliczony w taki sposób, że wartości są dokładne, nawet, jeśli liczba jest bliska zeruOstrze¿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. |
max() zwraca największą liczbę spośród podanych argumentów.
Jeśli pierwszy argument jest tablicą, max() zwróci największą liczbę z tej tablicy. Jeśli pierwszy argument jest liczbą całkowitą, zmiennoprzecinkową czy łańcuchem znaków, musisz mieć conajmniej dwa argumenty, spomiędzy których funkcja max() zwróci największą wartość. Za pomocą tej funkcji możesz porównywać nieograniczoną ilość liczb.
Jeśli jedna lub więcej podanych liczb jest zmiennoprzecinkowa, wszystkie liczby zostaną potraktowane jak zmiennoprzecinkowe i także liczba zmiennoprzecinkowa zostanie zwrócona. Jeśli żadna z liczb nie będzie zmiennoprzecinkową, wszystkie zostaną potraktowane jako całkowite i zwrócona zostanie liczba całkowita.
min() zwraca najmniejszą liczbę spośród podanych argumentów.
W pierwszym wariancie, po podaniu co najmniej dwóch argumentów, min() zwróci najmniejszy z nich. Można porównywać nieograniczoną ilość wartości.
W drugim wariancie, min() zwróci najmniejszą wartość z tablicy liczby.
Jeśli jedna lub więcej wartości jest typu , wszystkie wartości zostaną potraktowane jako zmiennoprzecinkowe i taka też liczba zostanie zwrócona. Jeśli żadna spośród wartości nie jest typu float, wszystkie zostaną potraktowane jako integer i zwrócona zostanie wartość całkowita.
Wiele generatorów liczb losowych w starych libc ma niepewne albo nieznane charakterystyki i są powolne. Domyślnie PHP używa generatora liczb losowych z libc w funkcji rand(). Funkcja mt_rand() jest jej zamiennikiem. Używa ona generatora liczb losowych o znanej charakterystyce, Mersenne Twistera, który generuje liczby losowe w sam raz dla większości potrzeb kryptografii (aby dowiedzieć się więcej, zajrzyj na strony www Mersenne Twistera) i działa cztery razy szybciej od typowych generatorów zawartych w libc. Stronę www Mersene Twistera można znaleźć pod adresem http://www.math.keio.ac.jp/~matumoto/emt.html, a zoptymalizowaną wersję kodu źródłowego MT pod adresem http://www.scp.syr.edu/~marc/hawk/twister.html.
Jeśli funkcja zostanie wywołana bez opcjonalnych argumentów min i max, funkcja mt_rand() zwróci liczbę pseudolosową z przedziału pomiędzy 0 a RAND_MAX. Jeśli na przykład potrzebujesz liczby losowej z przedziału od 5 do 15 włącznie, użyj mt_rand (5, 15).
Pamiętaj, aby przed użyciem tej funkcji inicjalizować generator liczb losowych za pomocą mt_srand().
Notatka: W wersjach przed 3.0.7 argument max znaczył zakres. Aby otrzymać takie same wyniki w tychże wersjach, należy użyć mt_rand (5, 11) aby otrzymać liczbę losową z przedziału od 5 do 15.
Zobacz też mt_srand(), mt_getrandmax(), srand(), rand() i getrandmax().
Inicjalizuje generator liczb losowych za pomocą ziarna ziarno.
// naziarnij mikrosekundami function make_seed() { list($usec,$sec) = explode(" ", microtime()); return ((float)$sec+(float)$usec) * 100000; } mt_srand(make_seed()); $randval = mt_rand(); |
Zobacz też mt_rand(), mt_getrandmax(), srand(), rand(), i getrandmax().
Zwraca największą liczbę losową, jaką może zwrócić funkcja mt_rand().
Zobacz też mt_rand(), mt_srand() rand(), srand(), i getrandmax().
Funkcja number_format() zwraca sformatowaną liczbę liczba według podanych argumentów. Ta funkcja przyjmuje jeden, dwa lub cztery argumenty (nie trzy):
Jeśli podany jest tylko jeden argument, liczba zostanie sformatowana bez miejsc dziesiętnych ale z przecinkiem (",") pomiędzy każdą grupą tysięcy.
Jeśli podane są dwa argumenty, liczba będzie sformatowana z miejsc_dziesiętnych, z kropką (".") w charakterze przecinka dziesiętnego i przecinkiem (",") pomiędzy każdą grupą tysięcy.
Kiedy wszystkie cztery parametry są podane, liczba będzie sformatowana z miejsc_dziesiętnych, z przecinek_dziesiętny zamiast kropki (".") i separator_tysięcy pomiędzy każdą grupą tysięcy.
Notatka: Tylko pierwszy znak z separator_tysięcy jest wykorzystywany. Na przykład, jeśli użyjesz foo jako separatora, to z liczby 1000 funkcja zwróci 1f000.
Przykład 1. number_format() - przykłady W polskiej notacji liczbowej używa się przecinka (",") jako przecinka dziesiętnego i spacji (" ") jako separatora tysięcy. W PHP można to zrobić tak:
|
Zwraca dziesiętny odpowiednik liczby ósemkowej podanej jako argument liczba_ósemkowa. Największą liczbą, jaka może być skonwertowana jest 17777777777 ósemkowo, czyli 2147483647 dziesiętnie.
Zobacz też decoct().
Zwraca przybliżoną wartość liczby pi. Zwracana wartość typu float ma precyzję określoną w dyrektywie precision w pliku php.ini, domyślnie równą 14. Można także użyć stałej M_PI, która daje taki sam wynik jak funkcja pi().
Zwraca argument podstawa podniesiony do potęgi wykładnik. Jeśli możliwe, funkcja zwróci typ integer.
Jeśli nie da się obliczyć potęgi, zostanie wyświetlone ostrzeżenie a funkcja pow() zwróci FALSE.
Ostrze¿enie |
W PHP 4.0.6 i wcześniejszych funkcja pow() zawsze zwracała typ float i nie wyświetlała ostrzeżeń. |
rad2deg() przelicza kąt liczba podany w radianach na jego odpowiednik w stopniach.
Zobacz też deg2rad().
Jeśli wywołana bez opcjonalnych argumentów min i max, funkcja rand() zwraca liczbę pseudolosową z przedziału pomiędzy 0 a RAND_MAX. Jeśli potrzebujesz liczby losowej z przedziału np. od 5 do 15 (włącznie), użyj rand (5,15).
Pamiętaj, aby przed użyciem tej funkcji inicjalizować generator liczb losowych za pomocą srand().
Notatka: W wersjach przed 3.0.7 argument max znaczył zakres. Aby otrzymać takie same wyniki w tychże wersjach, należy użyć rand (5, 11) aby otrzymać liczbę losową z przedziału od 5 do 15.
Zobacz też srand(), getrandmax(), mt_rand(), mt_srand() i mt_getrandmax().
Zwraca zaokrągloną wartość argumentu wartość do miejsca po przecinku określonego w dokładność. Argument dokładność może być także ujemny lub równy zero (domyślnie).
Uwaga! |
PHP domyślnie nie obsługuje poprawnie łańcuchów znaków takich jak "12,300.2". Zobacz konwersje z łańcuchów znaków . |
$foo = round(3.4); // $foo == 3.0 $foo = round(3.5); // $foo == 4.0 $foo = round(3.6); // $foo == 4.0 $foo = round(3.6, 0); // znaczy to samo, co zapis 1 wiersz wyżej $foo = round(1.95583, 2); // $foo == 1.96 $foo = round(1241757, -3); // $foo == 1242000 |
Notatka: Argument dokładność jest dostępny tylko w PHP 4.
Zwraca sinus hiperboliczny z liczby arg, definiowany jako (exp(arg) - exp(-arg))/2.
Inicjalizuje generator liczb losowych za pomocą ziarna ziarno.
// naziarnij mikrosekundami function make_seed() { list($usec,$sec) = explode(" ", microtime()); return ((float)$sec+(float)$usec) * 100000; } srand(make_seed()); $randval = rand(); |
Zobacz też rand(), getrandmax(), mt_rand(), mt_srand(), i mt_getrandmax().
There are many languages in which all characters can be expressed by single byte. Multi-byte character codes are used to express many characters for many languages. mbstring is developed to handle Japanese characters. However, many mbstring functions are able to handle character encoding other than Japanese.
A multi-byte character encoding represents single character with consecutive bytes. Some character encoding has shift(escape) sequences to start/end multi-byte character strings. Therefore, a multi-byte character string may be destroyed when it is divided and/or counted unless multi-byte character encoding safe method is used. This module provides multi-byte character safe string functions and other utility functions such as conversion functions.
Since PHP is basically designed for ISO-8859-1, some multi-byte character encoding does not work well with PHP. Therefore, it is important to set mbstring.internal_encoding to a character encoding that works with PHP.
PHP4 Character Encoding Requirements
Per byte encoding
Single byte characters in range of 00h-7fh which is compatible with ASCII
Multi-byte characters without 00h-7fh
These are examples of internal character encoding that works with PHP and does NOT work with PHP.
Character encodings work with PHP: ISO-8859-*, EUC-JP, UTF-8 Character encodings do NOT work with PHP: JIS, SJIS |
Character encoding, that does not work with PHP, may be converted with mbstring's HTTP input/output conversion feature/function.
Notatka: SJIS should not be used for internal encoding unless the reader is familiar with parser/compiler, character encoding and character encoding issues.
Notatka: If you use database with PHP, it is recommended that you use the same character encoding for both database and internal encoding for ease of use and better performance.
If you are using PostgreSQL, it supports character encoding that is different from backend character encoding. See the PostgreSQL manual for details.
mbstring is an extended module. You must enable module with configure script. Refer to the Install section for details.
The following configure options are related to mbstring module.
--enable-mbstring : Enable mbstring functions. This option is required to use mbstring functions.
--enable-mbstr-enc-trans : Enable HTTP input character encoding conversion using mbstring conversion engine. If this feature is enabled, HTTP input character encoding may be converted to mbstring.internal_encoding automatically.
HTTP input/output character encoding conversion may convert binary data also. Users are supposed to control character encoding conversion if binary data is used for HTTP input/output.
If enctype for HTML form is set to multipart/form-data, mbstring does not convert character encoding in POST data. If it is the case, strings are needed to be converted to internal character encoding.
HTTP Input
There is no way to control HTTP input character conversion from PHP script. To disable HTTP input character conversion, it has to be done in php.ini.
When using PHP as an Apache module, it is possible to override PHP ini setting per Virtual Host in httpd.conf or per directory with .htaccess. Refer to the Configuration section and Apache Manual for details.
HTTP Output
There are several ways to enable output character encoding conversion. One is using php.ini, another is using ob_start() with mb_output_handler() as ob_start callback function.
Notatka: For PHP3-i18n users, mbstring's output conversion differs from PHP3-i18n. Character encoding is converted using output buffer.
Currently, the following character encoding is supported by mbstring module. Caracter encoding may be specified for mbstring functions' encoding parameter.
The following character encoding is supported in this PHP extension :
UCS-4, UCS-4BE, UCS-4LE, UCS-2, UCS-2BE, UCS-2LE, UTF-32, UTF-32BE, UTF-32LE, UCS-2LE, UTF-16, UTF-16BE, UTF-16LE, UTF-8, UTF-7, ASCII, EUC-JP, SJIS, eucJP-win, SJIS-win, ISO-2022-JP, JIS, ISO-8859-1, ISO-8859-2, ISO-8859-3, ISO-8859-4, ISO-8859-5, ISO-8859-6, ISO-8859-7, ISO-8859-8, ISO-8859-9, ISO-8859-10, ISO-8859-13, ISO-8859-14, ISO-8859-15, byte2be, byte2le, byte4be, byte4le, BASE64, 7bit, 8bit and UTF7-IMAP.
php.ini entry, which accepts encoding name, accepts "auto" and "pass" also. mbstring functions, which accepts encoding name, and accepts "auto".
If "pass" is set, no character encoding conversion is performed.
If "auto" is set, it is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS".
See also mb_detect_order()
Notatka: "Supported character encoding" does not mean that it works as internal character code.
mbstring.internal_encoding defines default internal character encoding.
mbstring.http_input defines default HTTP input character encoding.
mbstring.http_output defines default HTTP output character encoding.
mbstring.detect_order defines default character code detection order. See also mb_detect_order().
mbstring.substitute_character defines character to substitute for invalid character encoding.
Web Browsers are supposed to use the same character encoding when submitting form. However, browsers may not use the same character encoding. See mb_http_input() to detect character encoding used by browsers.
If enctype is set to multipart/form-data in HTML forms, mbstring does not convert character encoding in POST data. The user must convert them in the script, if conversion is needed.
Although, browsers are smart enough to detect character encoding in HTML. charset is better to be set in HTTP header. Change default_charset according to character encoding.
Przykład 4. php.ini setting example
|
Przykład 5. php.ini setting for EUC-JP users
|
Przykład 6. php.ini setting for SJIS users
|
Most Japanese characters need more than 1 byte per character. In addition, several character encoding schemas are used under a Japanese environment. There are EUC-JP, Shift_JIS(SJIS) and ISO-2022-JP(JIS) character encoding. As Unicode becomes popular, UTF-8 is used also. To develop Web applications for a Japanese environment, it is important to use the character set for the task in hand, whether HTTP input/output, RDBMS and E-mail.
Storage for a character can be up to six bytes
A multi-byte character is usually twice of the width compared to single-byte characters. Wider characters are called "zen-kaku" - meaning full width, narrower characters are called "han-kaku" - meaning half width. "zen-kaku" characters are usually fixed width.
Some character encoding defines shift(escape) sequence for entering/exiting multi-byte character strings.
ISO-2022-JP must be used for SMTP/NNTP.
"i-mode" web site is supposed to use SJIS.
Multi-byte character encoding and its related issues are very complex. It is impossible to cover in sufficient detail here. Please refer to the following URLs and other resources for further readings.
Unicode/UTF/UCS/etc
http://www.unicode.org/
Japanese/Korean/Chinese character information
ftp://ftp.ora.com/pub/examples/nutshell/ujip/doc/cjk.inf
mb_language() sets language. If language is omitted, it returns current language as string.
language setting is used for encoding e-mail messages. Valid languages are "Japanese", "ja","English","en" and "uni" (UTF-8). mb_send_mail() uses this setting to encode e-mail.
Language and its setting is ISO-2022-JP/Base64 for Japanese, UTF-8/Base64 for uni, ISO-8859-1/quoted printable for English.
Return Value: If language is set and language is valid, it returns TRUE. Otherwise, it returns FALSE. When language is omitted, it returns language name as string. If no language is set previously, it returns FALSE.
See also mb_send_mail().
mb_parse_str() parses GET/POST/COOKIE data and sets global variables. Since PHP does not provide raw POST/COOKIE data, it can only used for GET data for now. It preses URL encoded data, detects encoding, converts coding to internal encoding and set values to result array or global variables.
encoded_string: URL encoded data.
result: Array contains decoded and character encoding converted values.
Return Value: It returns TRUE for success or FALSE for failure.
See also mb_detect_order(), mb_internal_encoding().
mb_internal_encoding() sets internal character encoding to encoding If parameter is omitted, it returns current internal encoding.
encoding is used for HTTP input character encoding conversion, HTTP output character encoding conversion and default character encoding for string functions defined by mbstring module.
encoding: Character encoding name
Return Value: If encoding is set,mb_internal_encoding() returns TRUE for success, otherwise returns FALSE. If encoding is omitted, it returns current character encoding name.
See also mb_http_input(), mb_http_output(), mb_detect_order().
mb_http_input() returns result of HTTP input character encoding detection.
type: Input string specifies input type. "G" for GET, "P" for POST, "C" for COOKIE. If type is omitted, it returns last input type processed.
Return Value: Character encoding name. If mb_http_input() does not process specified HTTP input, it returns FALSE.
See also mb_internal_encoding(), mb_http_output(), mb_detect_order().
If encoding is set, mb_http_output() sets HTTP output character encoding to encoding. Output after this function is converted to encoding. mb_http_output() returns TRUE for success and FALSE for failure.
If encoding is omitted, mb_http_output() returns current HTTP output character encoding.
See also mb_internal_encoding(), mb_http_input(), mb_detect_order().
mb_detect_order() sets automatic character encoding detection order to encoding-list. It returns TRUE for success, FALSE for failure.
encoding-list is array or comma separated list of character encoding. ("auto" is expanded to "ASCII, JIS, UTF-8, EUC-JP, SJIS")
If encoding-list is omitted, it returns current character encoding detection order as array.
This setting affects mb_detect_encoding() and mb_send_mail().
Notatka: mbstring currently implements following encoding detection filters. If there is a invalid byte sequence for following encoding, encoding detection will fail.
Notatka: UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP
For ISO-8859-*, mbstring always detects as ISO-8859-*.
For UTF-16, UTF-32, UCS2 and UCS4, encoding detection will fail always.
Przykład 2. mb_detect_order() examples
|
See also mb_internal_encoding(), mb_http_input(), mb_http_output() mb_send_mail().
mb_substitute_character() specifies substitution character when input character encoding is invalid or character code is not exist in output character encoding. Invalid characters may be substituted NULL(no output), string or integer value (Unicode character code value).
This setting affects mb_detect_encoding() and mb_send_mail().
substchar : Specify Unicode value as integer or specify as string as follows
"none" : no output
"long" : Output character code value (Example: U+3000,JIS+7E7E)
Return Value: If substchar is set, it returns TRUE for success, otherwise returns FALSE. If substchar is not set, it returns Unicode value or "none"/"long".
mb_output_handler() is ob_start() callback function. mb_output_handler() converts characters in output buffer from internal character encoding to HTTP output character encoding.
4.1.0 or later version, this hanlder adds charset HTTP header when following conditions are met:
Does not set Content-Type by header()
Default MIME type begins with text/
http_output setting is other than pass
contents : Output buffer contents
status : Output buffer status
Return Value: String converted
Notatka: If you want to output some binary data such as image from PHP script, you must set output encoding to "pass" using mb_http_output().
See also ob_start().
mb_preferred_mime_name() returns MIME charset string for character encoding encoding. It returns charset string.
mb_strlen() returns number of characters in string str having character encoding encoding. A multi-byte character is counted as 1.
encoding is character encoding for str. If encoding is omitted, internal character encoding is used.
See also mb_internal_encoding(), strlen().
mb_strpos() returns the numeric position of the first occurrence of needle in the haystack string. If needle is not found, it returns FALSE.
mb_strpos() performs multi-byte safe strpos() operation based on number of characters. needle position is counted from the beginning of the haystack. First character's position is 0. Second character position is 1, and so on.
If encoding is omitted, internal character encoding is used. mb_strrpos() accepts string for needle where strrpos() accepts only character.
offset is search offset. If it is not specified, 0 is used.
encoding is character encoding name. If it is omitted, internal character encoding is used.
See also mb_strpos(), mb_internal_encoding(), strpos()
mb_strrpos() returns the numeric position of the last occurrence of needle in the haystack string. If needle is not found, it returns FALSE.
mb_strrpos() performs multi-byte safe strrpos() operation based on number of characters. needle position is counted from the beginning of haystack. First character's position is 0. Second character position is 1.
If encoding is omitted, internal encoding is assumed. mb_strrpos() accepts string for needle where strrpos() accepts only character.
encoding is character encoding. If it is not specified, internal character encoding is used.
See also mb_strpos(), mb_internal_encoding(), strrpos().
mb_substr() returns the portion of str specified by the start and length parameters.
mb_substr() performs multi-byte safe substr() operation based on number of characters. Position is counted from the beginning of str. First character's position is 0. Second character position is 1, and so on.
If encoding is omitted, internal encoding is assumed.
encoding is character encoding. If it is omitted, internal character encoding is used.
See also mb_strcut(), mb_internal_encoding().
mb_strcut() returns the portion of str specified by the start and length parameters.
mb_strcut() performs equivalent operation as mb_substr() with different method. If start position is multi-byte character's second byte or larger, it starts from first byte of multi-byte character.
It subtracts string from str that is shorter than length AND character that is not part of multi-byte string or not being middle of shift sequence.
encoding is character encoding. If it is not set, internal character encoding is used.
See also mb_substr(), mb_internal_encoding().
mb_strwidth() returns width of string str.
Multi-byte character usually twice of width compare to single byte character.
encoding is character encoding. If it is omitted, internal encoding is used.
See also: mb_strimwidth(), mb_internal_encoding().
mb_strimwidth() truncates string str to specified width. It returns truncated string.
If trimmarker is set, trimmarker is appended to return value.
start is start position offset. Number of characters from the beginning of string. (First character is 0)
trimmarker is string that is added to the end of string when string is truncated.
encoding is character encoding. If it is omitted, internal encoding is used.
See also: mb_strwidth(), mb_internal_encoding().
mb_convert_encoding() converts character encoding of string str from from-encoding to to-encoding.
str : String to be converted.
from-encoding is specified by character code name before conversion. it can be array or string - comma separated enumerated list.
Przykład 1. mb_convert_encoding() example
|
See also: mb_detect_order().
mb_detect_encoding() detects character encoding in string str. It returns detected character encoding.
encoding-list is list of character encoding. Encoding order may be specified by array or comma separated list string.
If encoding_list is omitted, detect_order is used.
Przykład 1. mb_detect_encoding() example
|
See also: mb_detect_order().
(PHP 4 >= 4.0.6)
mb_convert_kana -- Convert "kana" one from another ("zen-kaku" ,"han-kaku" and more)mb_convert_kana() performs "han-kaku" - "zen-kaku" conversion for string str. It returns converted string. This function is only useful for Japanese.
option is conversion option. Default value is "KV".
encoding is character encoding. If it is omitted, internal character encoding is used.
Applicable Conversion Options option : Specify with conversion of following options. Default "KV" "r" : Convert "zen-kaku" alphabets to "han-kaku" "R" : Convert "han-kaku" alphabets to "zen-kaku" "n" : Convert "zen-kaku" numbers to "han-kaku" "N" : Convert "han-kaku" numbers to "zen-kaku" "a" : Convert "zen-kaku" alphabets and numbers to "han-kaku" "A" : Convert "zen-kaku" alphabets and numbers to "han-kaku" (Characters included in "a", "A" options are U+0021 - U+007E excluding U+0022, U+0027, U+005C, U+007E) "s" : Convert "zen-kaku" space to "han-kaku" (U+3000 -> U+0020) "S" : Convert "han-kaku" space to "zen-kaku" (U+0020 -> U+3000) "k" : Convert "zen-kaku kata-kana" to "han-kaku kata-kana" "K" : Convert "han-kaku kata-kana" to "zen-kaku kata-kana" "h" : Convert "zen-kaku hira-gana" to "han-kaku kata-kana" "H" : Convert "han-kaku kata-kana" to "zen-kaku hira-gana" "c" : Convert "zen-kaku kata-kana" to "zen-kaku hira-gana" "C" : Convert "zen-kaku hira-gana" to "zen-kaku kata-kana" "V" : Collapse voiced sound notation and convert them into a character. Use with "K","H" |
mb_encode_mimeheader() converts string str to encoded-word for header field. It returns converted string in ASCII encoding.
charset is character encoding name. Default is ISO-2022-JP.
transfer-encoding is transfer encoding. It should be one of "B" (Base64) or "Q" (Quoted-Printable). Default is "B".
linefeed is end of line marker. Default is "\r\n" (CRLF).
Przykład 1. mb_convert_kana() example
|
See also mb_decode_mimeheader().
mb_decode_mimeheader() decodes encoded-word string str in MIME header.
It returns decoded string in internal character encoding.
See also mb_encode_mimeheader().
mb_convert_variables() convert character encoding of variables vars in encoding from-encoding to encoding to-encoding. It returns character encoding before conversion for success, FALSE for failure.
mb_convert_variables() join strings in Array or Object to detect encoding, since encoding detection tends to fail for short strings. Therefore, it is impossible to mix encoding in single array or object.
It from-encoding is specified by array or comma separated string, it tries to detect encoding from from-coding. When encoding is omitted, detect_order is used.
vars (3rd and larger) is reference to variable to be converted. String, Array and Object are accepted. mb_convert_variables() assumes all parameters have the same encoding.
mb_encode_numericentity() converts specified character codes in string str from HTML numeric character reference to character code. It returns converted string.
array is array specifies code area to convert.
encoding is character encoding.
Przykład 1. convmap example
|
Przykład 2. mb_encode_numericentity() example
|
See also: mb_decode_numericentity().
Convert numeric string reference of string str in specified block to character. It returns converted string.
array is array to specifies code area to convert.
encoding is character encoding. If it is omitted, internal character encoding is used.
Przykład 1. convmap example
|
See also: mb_encode_numericentity().
mb_send_mail() sends email. Headers and message are converted and encoded according to mb_language() setting. mb_send_mail() is wrapper function of mail(). See mail() for details.
to is mail addresses send to. Multiple recipients can be specified by putting a comma between each address in to. This parameter is not automatically encoded.
subject is subject of mail.
message is mail message.
additional_headers is inserted at the end of the header. This is typically used to add extra headers. Multiple extra headers are separated with a newline ("\n").
additional_parameter is a MTA command line parameter. It is useful when setting the correct Return-Path header when using sendmail.
Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
See also mail(), mb_encode_mimeheader(), and mb_language().
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. |
mb_get_info() returns internal setting parameter of mbstring.
If type isn't specified or is specified to "all", an array having the elements "internal_encoding", "http_output", "http_input", "func_overload" will be returned.
If type is specified for "http_output", "http_input", "internal_encoding", "func_overload", the specified setting parameter will be returned.
See also mb_internal_encoding(), mb_http_output().
MCAL stands for Modular Calendar Access Library.
Libmcal is a C library for accessing calendars. It's written to be very modular, with pluggable drivers. MCAL is the calendar equivalent of the IMAP module for mailboxes.
With mcal support, a calendar stream can be opened much like the mailbox stream with the IMAP support. Calendars can be local file stores, remote ICAP servers, or other formats that are supported by the mcal library.
Calendar events can be pulled up, queried, and stored. There is also support for calendar triggers (alarms) and recurring events.
With libmcal, central calendar servers can be accessed, removing the need for any specific database or local file programming.
To get these functions to work, you have to compile PHP with --with-mcal. That requires the mcal library to be installed. Grab the latest version from http://mcal.chek.com/ and compile and install it.
The following constants are defined when using the MCAL module. For weekdays :
MCAL_SUNDAY
MCAL_MONDAY
MCAL_TUESDAY
MCAL_WEDNESDAY
MCAL_THURSDAY
MCAL_FRIDAY
MCAL_SATURDAY
MCAL_RECUR_NONE
MCAL_RECUR_DAILY
MCAL_RECUR_WEEKLY
MCAL_RECUR_MONTHLY_MDAY
MCAL_RECUR_MONTHLY_WDAY
MCAL_RECUR_YEARLY
MCAL_JANUARY
MCAL_FEBRUARY
MCAL_MARCH
MCAL_APRIL
MCAL_MAY
MCAL_JUNE
MCAL_JULY
MCAL_AUGUST
MCAL_SEPTEMBER
MCAL_OCTOBER
MCAL_NOVEMBER
MCAL_DECEMBER
Returns an MCAL stream on success, FALSE on error.
mcal_open() opens up an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also. The streams internal event structure is also initialized upon connection.
Returns an MCAL stream on success, FALSE on error.
mcal_popen() opens up an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also. The streams internal event structure is also initialized upon connection.
Reopens an MCAL stream to a new calendar.
mcal_reopen() reopens an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also.
Creates a new calendar named calendar.
Renames the calendar old_name to new_name.
Deletes the calendar named calendar.
mcal_fetch_event() fetches an event from the calendar stream specified by 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.
int recur_type - recurrence type
int recur_interval - recurrence interval
datetime recur_enddate - recurrence end date
int recur_data - recurrence data
int year - year
int month - month
int mday - day of month
int hour - hour
int min - minutes
int sec - seconds
int alarm - minutes before event to send an alarm
0 - Indicates that this event does not recur
1 - This event recurs daily
2 - This event recurs on a weekly basis
3 - This event recurs monthly on a specific day of the month (e.g. the 10th of the month)
4 - This event recurs monthly on a sequenced day of the week (e.g. the 3rd Saturday)
5 - This event recurs on an annual basis
(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)
mcal_list_events -- Return a list of IDs for a date or a range of dates.Returns an array of ID's that are between the start and end dates, or if just a stream is given, uses the start and end dates in the global event structure.
mcal_list_events() function takes in an beginning date and an optional end date for a calendar stream. An array of event id's that are between the given dates or the internal event dates are returned.
mcal_append_event() Stores the global event into an MCAL calendar for the given stream.
Returns the id of the newly inserted event.
mcal_store_event() Stores the modifications to the current global event for the given stream.
Returns the event id of the modified event on success and FALSE on error.
mcal_delete_event() deletes the calendar event specified by the event_id.
Returns TRUE.
mcal_snooze() turns off an alarm for a calendar event specified by the id.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)
mcal_list_alarms -- Return a list of events that has an alarm triggered at the given datetimeReturns an array of event ID's that has an alarm going off between the start and end dates, or if just a stream is given, uses the start and end dates in the global event structure.
mcal_list_events() function takes in an optional beginning date and an end date for a calendar stream. An array of event id's that are between the given dates or the internal event dates are returned.
mcal_event_init() initializes a streams global event structure. this effectively sets all elements of the structure to 0, or the default settings.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)
mcal_event_set_category -- Sets the category of the streams global event structuremcal_event_set_category() sets the streams global event structure's category to the given string.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)
mcal_event_set_title -- Sets the title of the streams global event structuremcal_event_set_title() sets the streams global event structure's title to the given string.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)
mcal_event_set_description -- Sets the description of the streams global event structuremcal_event_set_description() sets the streams global event structure's description to the given string.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)
mcal_event_set_start -- Sets the start date and time of the streams global event structuremcal_event_set_start() sets the streams global event structure's start date and time to the given values.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)
mcal_event_set_end -- Sets the end date and time of the streams global event structuremcal_event_set_end() sets the streams global event structure's end date and time to the given values.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)
mcal_event_set_alarm -- Sets the alarm of the streams global event structuremcal_event_set_alarm() sets the streams global event structure's alarm to the given minutes before the event.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)
mcal_event_set_class -- Sets the class of the streams global event structuremcal_event_set_class() sets the streams global event structure's class to the given value. The class is either 1 for public, or 0 for private.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)
mcal_is_leap_year -- Returns if the given year is a leap year or notmcal_is_leap_year() returns 1 if the given year is a leap year, 0 if not.
mcal_days_in_month() Returns the number of days in the given month, taking into account if the given year is a leap year or not.
(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)
mcal_date_valid -- Returns TRUE if the given year, month, day is a valid datemcal_date_valid() Returns TRUE if the given year, month and day is a valid date, FALSE if not.
(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)
mcal_time_valid -- Returns TRUE if the given year, month, day is a valid timemcal_time_valid() Returns TRUE if the given hour, minutes and seconds is a valid time, FALSE if not.
mcal_day_of_week() returns the day of the week of the given date. Possible return values range from 0 for Sunday through 6 for Saturday.
mcal_day_of_year() returns the day of the year of the given date.
mcal_date_compare() Compares the two given dates, returns <0, 0, >0 if a<b, a==b, a>b respectively.
mcal_next_recurrence() returns an object filled with the next date the event occurs, on or after the supplied date. Returns empty date field if event does not occur or something is invalid. Uses weekstart to determine what day is considered the beginning of the week.
(PHP 3>= 3.0.15, PHP 4 >= 4.0.0)
mcal_event_set_recur_none -- Sets the recurrence of the streams global event structuremcal_event_set_recur_none() sets the streams global event structure to not recur (event->recur_type is set to MCAL_RECUR_NONE).
(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)
mcal_event_set_recur_daily -- Sets the recurrence of the streams global event structuremcal_event_set_recur_daily() sets the streams global event structure's recurrence to the given value to be reoccuring on a daily basis, ending at the given date.
(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)
mcal_event_set_recur_weekly -- Sets the recurrence of the streams global event structuremcal_event_set_recur_weekly() sets the streams global event structure's recurrence to the given value to be reoccuring on a weekly basis, ending at the given date.
(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)
mcal_event_set_recur_monthly_mday -- Sets the recurrence of the streams global event structuremcal_event_set_recur_monthly_mday() sets the streams global event structure's recurrence to the given value to be reoccuring on a monthly by month day basis, ending at the given date.
(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)
mcal_event_set_recur_monthly_wday -- Sets the recurrence of the streams global event structuremcal_event_set_recur_monthly_wday() sets the streams global event structure's recurrence to the given value to be reoccuring on a monthly by week basis, ending at the given date.
(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)
mcal_event_set_recur_yearly -- Sets the recurrence of the streams global event structuremcal_event_set_recur_yearly() sets the streams global event structure's recurrence to the given value to be reoccuring on a yearly basis,ending at the given date.
(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)
mcal_fetch_current_stream_event -- Returns an object containing the current streams event structuremcal_fetch_current_stream_event() returns the current stream's event structure as an object containing:
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.
int recur_type - recurrence type
int recur_interval - recurrence interval
datetime recur_enddate - recurrence end date
int recur_data - recurrence data
int year - year
int month - month
int mday - day of month
int hour - hour
int min - minutes
int sec - seconds
int alarm - minutes before event to send an alarm
(PHP 3>= 3.0.15, PHP 4 >= 4.0.0)
mcal_event_add_attribute -- Adds an attribute and a value to the streams global event structuremcal_event_add_attribute() adds an attribute to the stream's global event structure with the value given by "value".
mcal_expunge() Deletes all events which have been previously marked for deletion.
These functions work using mcrypt.
This is an interface to the mcrypt library, which supports a wide variety of block algorithms such as DES, TripleDES, Blowfish (default), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST in CBC, OFB, CFB and ECB cipher modes. Additionally, it supports RC6 and IDEA which are considered "non-free".
If you linked against libmcrypt 2.4.x, the following additional block algorithms are supported: CAST, LOKI97, RIJNDAEL, SAFERPLUS, SERPENT and the following stream ciphers: ENIGMA (crypt), PANAMA, RC4 and WAKE. With libmcrypt 2.4.x another cipher mode is also available; nOFB.
To use it, download libmcrypt-x.x.tar.gz from here and follow the included installation instructions. You need to compile PHP with the --with-mcrypt parameter to enable this extension. Make sure you compile libmcrypt with the option --disable-posix-threads.
Mcrypt can be used to encrypt and decrypt using the above mentioned ciphers. If you linked against libmcrypt-2.2.x, the four important mcrypt commands (mcrypt_cfb(), mcrypt_cbc(), mcrypt_ecb(), and mcrypt_ofb()) can operate in both modes which are named MCRYPT_ENCRYPT and MCRYPT_DECRYPT, respectively.
If you linked against libmcrypt 2.4.x, these functions are still available, but it is recommended that you use the advanced functions.
Przykład 2. Encrypt an input value with TripleDES under 2.4.x in ECB mode
|
Mcrypt can operate in four block cipher modes (CBC, OFB, CFB, and ECB). If linked against libmcrypt-2.4.x mcrypt can also operate in the block cipher mode nOFB and in STREAM mode. Then there are also constants in the form MCRYPT_MODE_mode for use with several functions. We will outline the normal use for each of these modes. For a more complete reference and discussion see Applied Cryptography by Schneier (ISBN 0-471-11709-9).
ECB (electronic codebook) is suitable for random data, such as encrypting other keys. Since data there is short and random, the disadvantages of ECB have a favorable negative effect.
CBC (cipher block chaining) is especially suitable for encrypting files where the security is increased over ECB significantly.
CFB (cipher feedback) is the best mode for encrypting byte streams where single bytes must be encrypted.
OFB (output feedback, in 8bit) is comparable to CFB, but can be used in applications where error propagation cannot be tolerated. It's insecure (because it operates in 8bit mode) so it is not recommended to use it.
nOFB (output feedback, in nbit) is comparable to OFB, but more secure because it operates on the block size of the algorithm.
STREAM is an extra mode to include some stream algorithms like WAKE or RC4.
PHP does not support encrypting/decrypting bit streams currently. As of now, PHP only supports handling of strings.
For a complete list of supported ciphers, see the defines at the end of mcrypt.h. The general rule with the mcrypt-2.2.x API is that you can access the cipher from PHP with MCRYPT_ciphername. With the mcrypt-2.4.x API these constants also work, but it is possible to specify the name of the cipher as a string with a call to mcrypt_module_open().
Here is a short list of ciphers which are currently supported by the mcrypt extension. If a cipher is not listed here, but is listed by mcrypt as supported, you can safely assume that this documentation is outdated.
MCRYPT_3DES
MCRYPT_ARCFOUR_IV (libmcrypt 2.4.x only)
MCRYPT_ARCFOUR (libmcrypt 2.4.x only)
MCRYPT_BLOWFISH
MCRYPT_CAST_128
MCRYPT_CAST_256
MCRYPT_CRYPT
MCRYPT_DES
MCRYPT_DES_COMPAT (libmcrypt 2.2.x only)
MCRYPT_ENIGMA (libmcrypt 2.4.x only, alias for MCRYPT_CRYPT)
MCRYPT_GOST
MCRYPT_IDEA (non-free)
MCRYPT_LOKI97 (libmcrypt 2.4.x only)
MCRYPT_MARS (libmcrypt 2.4.x only, non-free)
MCRYPT_PANAMA (libmcrypt 2.4.x only)
MCRYPT_RIJNDAEL_128 (libmcrypt 2.4.x only)
MCRYPT_RIJNDAEL_192 (libmcrypt 2.4.x only)
MCRYPT_RIJNDAEL_256 (libmcrypt 2.4.x only)
MCRYPT_RC2
MCRYPT_RC4 (libmcrypt 2.2.x only)
MCRYPT_RC6 (libmcrypt 2.4.x only)
MCRYPT_RC6_128 (libmcrypt 2.2.x only)
MCRYPT_RC6_192 (libmcrypt 2.2.x only)
MCRYPT_RC6_256 (libmcrypt 2.2.x only)
MCRYPT_SAFER64
MCRYPT_SAFER128
MCRYPT_SAFERPLUS (libmcrypt 2.4.x only)
MCRYPT_SERPENT (libmcrypt 2.4.x only)
MCRYPT_SERPENT_128 (libmcrypt 2.2.x only)
MCRYPT_SERPENT_192 (libmcrypt 2.2.x only)
MCRYPT_SERPENT_256 (libmcrypt 2.2.x only)
MCRYPT_SKIPJACK (libmcrypt 2.4.x only)
MCRYPT_TEAN (libmcrypt 2.2.x only)
MCRYPT_THREEWAY
MCRYPT_TRIPLEDES (libmcrypt 2.4.x only)
MCRYPT_TWOFISH (for older mcrypt 2.x versions, or mcrypt 2.4.x )
MCRYPT_TWOFISH128 (TWOFISHxxx are available in newer 2.x versions, but not in the 2.4.x versions)
MCRYPT_TWOFISH192
MCRYPT_TWOFISH256
MCRYPT_WAKE (libmcrypt 2.4.x only)
MCRYPT_XTEA (libmcrypt 2.4.x only)
You must (in CFB and OFB mode) or can (in CBC mode) supply an initialization vector (IV) to the respective cipher function. The IV must be unique and must be the same when decrypting/encrypting. With data which is stored encrypted, you can take the output of a function of the index under which the data is stored (e.g. the MD5 key of the filename). Alternatively, you can transmit the IV together with the encrypted data (see chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9) for a discussion of this topic).
mcrypt_get_cipher_name() is used to get the name of the specified cipher.
mcrypt_get_cipher_name() takes the cipher number as an argument (libmcrypt 2.2.x) or takes the cipher name as an argument (libmcrypt 2.4.x) and returns the name of the cipher or FALSE, if the cipher does not exist.
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x.
mcrypt_get_block_size() is used to get the size of a block of the specified cipher.
mcrypt_get_block_size() takes one or two arguments, the cipher and module, and returns the size in bytes.
See also: mcrypt_get_key_size().
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x.
mcrypt_get_key_size() is used to get the size of a key of the specified cipher.
mcrypt_get_key_size() takes one or two arguments, the cipher and module, and returns the size in bytes.
See also: mcrypt_get_block_size().
(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)
mcrypt_create_iv -- Create an initialization vector (IV) from a random sourcemcrypt_create_iv() is used to create an IV.
mcrypt_create_iv() takes two arguments, size determines the size of the IV, source specifies the source of the IV.
The source can be MCRYPT_RAND (system random number generator), MCRYPT_DEV_RANDOM (read data from /dev/random) and MCRYPT_DEV_URANDOM (read data from /dev/urandom). If you use MCRYPT_RAND, make sure to call srand() before to initialize the random number generator.
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x.
mcrypt_cbc() encrypts or decrypts (depending on mode) the data with cipher and key in CBC cipher mode and returns the resulting string.
Cipher is one of the MCRYPT_ciphername constants.
Key is the key supplied to the algorithm. It must be kept secret.
Data is the data which shall be encrypted/decrypted.
Mode is MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
IV is the optional initialization vector.
See also: mcrypt_cfb(), mcrypt_ecb(), and mcrypt_ofb().
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x.
mcrypt_cfb() encrypts or decrypts (depending on mode) the data with cipher and key in CFB cipher mode and returns the resulting string.
Cipher is one of the MCRYPT_ciphername constants.
Key is the key supplied to the algorithm. It must be kept secret.
Data is the data which shall be encrypted/decrypted.
Mode is MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
IV is the initialization vector.
See also: mcrypt_cbc(), mcrypt_ecb(), and mcrypt_ofb().
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x.
mcrypt_ecb() encrypts or decrypts (depending on mode) the data with cipher and key in ECB cipher mode and returns the resulting string.
Cipher is one of the MCRYPT_ciphername constants.
Key is the key supplied to the algorithm. It must be kept secret.
Data is the data which shall be encrypted/decrypted.
Mode is MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
See also: mcrypt_cbc(), mcrypt_cfb(), and mcrypt_ofb().
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x.
mcrypt_ofb() encrypts or decrypts (depending on mode) the data with cipher and key in OFB cipher mode and returns the resulting string.
Cipher is one of the MCRYPT_ciphername constants.
Key is the key supplied to the algorithm. It must be kept secret.
Data is the data which shall be encrypted/decrypted.
Mode is MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
IV is the initialization vector.
See also: mcrypt_cbc(), mcrypt_cfb(), and mcrypt_ecb().
mcrypt_list_algorithms() is used to get an array of all supported algorithms in the
lib_dir. mcrypt_list_algorithms() takes as optional parameter a directory which specifies the directory where all algorithms are located. If not specifies, the value of the mcrypt.algorithms_dir php.ini directive is used.
mcrypt_list_modes() is used to get an array of all supported modes in the lib_dir.
mcrypt_list_modes() takes as optional parameter a directory which specifies the directory where all modes are located. If not specifies, the value of the mcrypt.modes_dir php.ini directive is used.
Przykład 1. mcrypt_list_modes() Example
The above example will produce a list with all supported algorithms in the default mode directory. If it is not set with the ini directive mcrypt.modes_dir, the default directory of mcrypt is used (which is /usr/local/lib/libmcrypt). |
(PHP 4 >= 4.0.2)
mcrypt_get_iv_size -- Returns the size of the IV belonging to a specific cipher/mode combinationThe first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x.
mcrypt_get_iv_size() returns the size of the Initialisation Vector (IV) in bytes. On error the function returns FALSE. If the IV is ignored in the specified cipher/mode combination zero is returned.
Cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.
Mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".
Td is the algorithm specified.
mcrypt_encrypt() encrypts the data and returns the encrypted data.
Cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.
Key is the key with which the data will be encrypted. If it's smaller that the required keysize, it is padded with '\0'. It is better not to use ASCII strings for keys. It is recommended to use the mhash functions to create a key from a string.
Data is the data that will be encrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with '\0'. The returned crypttext can be larger that the size of the data that is given by data.
Mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".
The IV parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to '\0'.
Przykład 1. mcrypt_encrypt() Example
The above example will print out:
|
mcrypt_decrypt() decrypts the data and returns the unencrypted data.
Cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.
Key is the key with which the data is encrypted. If it's smaller that the required keysize, it is padded with '\0'.
Data is the data that will be decrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with '\0'.
Mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".
The IV parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to '\0'.
(PHP 4 >= 4.0.2)
mcrypt_module_open -- This function opens the module of the algorithm and the mode to be usedThis function opens the module of the algorithm and the mode to be used. The name of the algorithm is specified in algorithm, eg "twofish" or is one of the MCRYPT_ciphername constants. The library is closed by calling mcrypt_module_close(), but there is no need to call that function if mcrypt_generic_end() is called. Normally it returns an encryption descriptor, or FALSE on error.
The algorithm_directory and mode_directory are used to locate the encryption modules. When you supply a directory name, it is used. When you set one of these to the empty string (""), the value set by the mcrypt.algorithms_dir or mcrypt.modes_dir ini-directive is used. When these are not set, the default directory are used that are compiled in into libmcrypt (usally /usr/local/lib/libmcrypt).
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
(PHP 4 >= 4.1.1)
mcrypt_generic_deinit -- This function terminates encrypt specified by the descriptor td
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
The maximum length of the key should be the one obtained by calling mcrypt_enc_get_key_size() and every value smaller than this is legal. The IV should normally have the size of the algorithms block size, but you must obtain the size by calling mcrypt_enc_get_iv_size(). IV is ignored in ECB. IV MUST exist in CFB, CBC, STREAM, nOFB and OFB modes. It needs to be random and unique (but not secret). The same IV must be used for encryption/decryption. If you do not want to use it you should set it to zeros, but this is not recommended. The function returns a negative value on error.
You need to call this function before every mcrypt_generic() or mdecrypt_generic().
This function encrypts data. The data is padded with "\0" to make sure the length of the data is n * blocksize. This function returns the encrypted data. Note that the length of the returned string can in fact be longer then the input, due to the padding of the data.
This function decrypts data. Note that the length of the returned string can in fact be longer then the unencrypted string, due to the padding of the data.
Przykład 1. mdecrypt_generic() Example
The above example shows how to check if the data before the encryption is the same as the data after the decryption. |
This function terminates encryption specified by the encryption descriptor (td). Actually it clears all buffers, and closes all the modules used. Returns FALSE on error, or TRUE on succes.
This function runs the self test on the algorithm specified by the descriptor td. If the self test succeeds it returns zero. In case of an error, it returns 1.
(PHP 4 >= 4.0.2)
mcrypt_enc_is_block_algorithm_mode -- Checks whether the encryption of the opened mode works on blocksThis function returns 1 if the mode is for use with block algorithms, otherwise it returns 0. (eg. 0 for stream, and 1 for cbc, cfb, ofb).
(PHP 4 >= 4.0.2)
mcrypt_enc_is_block_algorithm -- Checks whether the algorithm of the opened mode is a block algorithmThis function returns 1 if the algorithm is a block algorithm, or 0 if it is a stream algorithm.
This function returns 1 if the mode outputs blocks of bytes or 0 if it outputs bytes. (eg. 1 for cbc and ecb, and 0 for cfb and stream).
This function returns the block size of the algorithm specified by the encryption descriptor td in bytes.
This function returns the maximum supported key size of the algorithm specified by the encryption descriptor td in bytes.
(PHP 4 >= 4.0.2)
mcrypt_enc_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithmReturns an array with the key sizes supported by the algorithm specified by the encryption descriptor. If it returns an empty array then all key sizes between 1 and mcrypt_enc_get_key_size() are supported by the algorithm.
This function returns the size of the iv of the algorithm specified by the encryption descriptor in bytes. If it returns '0' then the IV is ignored in the algorithm. An IV is used in cbc, cfb and ofb modes, and in some algorithms in stream mode.
This function returns the name of the algorithm.
This function returns the name of the mode.
This function runs the self test on the algorithm specified. The optional lib_dir parameter can contain the location of where the algorithm module is on the system.
The function returns TRUE if the self test succeeds, or FALSE when if fails.
(PHP 4 >= 4.0.2)
mcrypt_module_is_block_algorithm_mode -- This function returns if the the specified module is a block algorithm or notThis function returns TRUE if the mode is for use with block algorithms, otherwise it returns 0. (eg. 0 for stream, and 1 for cbc, cfb, ofb). The optional lib_dir parameter can contain the location where the mode module is on the system.
(PHP 4 >= 4.0.2)
mcrypt_module_is_block_algorithm -- This function checks whether the specified algorithm is a block algorithmThis function returns TRUE if the specified algorithm is a block algorithm, or FALSE is it is a stream algorithm. The optional lib_dir parameter can contain the location where the algorithm module is on the system.
(PHP 4 >= 4.0.2)
mcrypt_module_is_block_mode -- This function returns if the the specified mode outputs blocks or notThis function returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs just bytes. (eg. 1 for cbc and ecb, and 0 for cfb and stream). The optional lib_dir parameter can contain the location where the mode module is on the system.
(PHP 4 >= 4.0.2)
mcrypt_module_get_algo_block_size -- Returns the blocksize of the specified algorithmThis function returns the block size of the algorithm specified in bytes. The optional lib_dir parameter can contain the location where the mode module is on the system.
(PHP 4 >= 4.0.2)
mcrypt_module_get_algo_key_size -- Returns the maximum supported keysize of the opened modeThis function returns the maximum supported key size of the algorithm specified in bytes. The optional lib_dir parameter can contain the location where the mode module is on the system.
(PHP 4 >= 4.0.2)
mcrypt_module_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithmReturns an array with the key sizes supported by the specified algorithm. If it returns an empty array then all key sizes between 1 and mcrypt_module_get_algo_key_size() are supported by the algorithm. The optional lib_dir parameter can contain the location where the mode module is on the system.
These functions are intended to work with mhash.
This is an interface to the mhash library. mhash supports a wide variety of hash algorithms such as MD5, SHA1, GOST, and many others.
To use it, download the mhash distribution from its web site and follow the included installation instructions. You need to compile PHP with the --with-mhash parameter to enable this extension.
Mhash can be used to create checksums, message digests, message authentication codes, and more.
Przykład 1. Compute the MD5 digest and hmac and print it out as hex
This will produce:
|
Here is a list of hashes which are currently supported by mhash. If a hash is not listed here, but is listed by mhash as supported, you can safely assume that this documentation is outdated.
MHASH_MD5
MHASH_SHA1
MHASH_HAVAL256
MHASH_HAVAL192
MHASH_HAVAL160
MHASH_HAVAL128
MHASH_RIPEMD160
MHASH_GOST
MHASH_TIGER
MHASH_CRC32
MHASH_CRC32B
mhash_get_hash_name() is used to get the name of the specified hash.
mhash_get_hash_name() takes the hash id as an argument and returns the name of the hash or FALSE, if the hash does not exist.
mhash_get_block_size() is used to get the size of a block of the specified hash.
mhash_get_block_size() takes one argument, the hash and returns the size in bytes or FALSE, if the hash does not exist.
mhash_count() returns the highest available hash id. Hashes are numbered from 0 to this hash id.
mhash() applies a hash function specified by hash to the data and returns the resulting hash (also called digest). If the key is specified it will return the resulting HMAC. HMAC is keyed hashing for message authentication, or simply a message digest that depends on the specified key. Not all algorithms supported in mhash can be used in HMAC mode. In case of an error returns FALSE.
mhash_keygen_s2k() generates a key that is bytes long, from a user given password. This is the Salted S2K algorithm as specified in the OpenPGP document (RFC 2440). That algorithm will use the specified hash algorithm to create the key. The salt must be different and random enough for every key you generate in order to create different keys. That salt must be known when you check the keys, thus it is a good idea to append the key to it. Salt has a fixed length of 8 bytes and will be padded with zeros if you supply less bytes. Keep in mind that user supplied passwords are not really suitable to be used as keys in cryptographic algorithms, since users normally choose keys they can write on keyboard. These passwords use only 6 to 7 bits per character (or less). It is highly recommended to use some kind of tranformation (like this function) to the user supplied key.
The MSSQL extension is available on Win32 systems only. You can use the Sybase extension to connect to MSSQL databases from other platforms.
These functions allow you to access MS SQL Server database. The extension requires the MS SQL Client Tools to be installed on the system where PHP is installed. The Client Tools can be installed from the MS SQL Server CD or by copying ntwdblib.dll from \winnt\system32 on the server to \winnt\system32 on the PHP box. Copying ntwdblib.dll will only provide access. Configuration of the client will require installation of all the tools.
The MSSQL extension is enabled by adding extension=php_mssql.dll to php.ini.
Returns: TRUE on success, FALSE on error.
mssql_close() closes the link to a MS SQL Server database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.
Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
mssql_close() will not close persistent links generated by mssql_pconnect().
See also: mssql_connect(), mssql_pconnect().
Returns: A positive MS SQL link identifier on success, or FALSE on error.
mssql_connect() establishes a connection to a MS SQL server. The servername argument has to be a valid servername that is defined in the 'interfaces' file.
In case a second call is made to mssql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.
The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling mssql_close().
See also mssql_pconnect(), mssql_close().
Returns: TRUE on success, FALSE on failure.
mssql_data_seek() moves the internal row pointer of the MS SQL result associated with the specified result identifier to point to the specified row number. The next call to mssql_fetch_row() would return that row.
See also: mssql_data_seek().
Returns: An array that corresponds to the fetched row, or FALSE if there are no more rows.
mssql_fetch_array() is an extended version of mssql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.
An important thing to note is that using mssql_fetch_array() is NOT significantly slower than using mssql_fetch_row(), while it provides a significant added value.
For further details, also see mssql_fetch_row().
Returns an object containing field information.
mssql_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by mssql_fetch_field() is retrieved.
The properties of the object are:
name - column name. if the column is a result of a function, this property is set to computed#N, where #N is a serial number.
column_source - the table from which the column was taken
max_length - maximum length of the column
numeric - 1 if the column is numeric
See also mssql_field_seek().
Returns: An object with properties that correspond to the fetched row, or FALSE if there are no more rows.
mssql_fetch_object() is similar to mssql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).
Speed-wise, the function is identical to mssql_fetch_array(), and almost as quick as mssql_fetch_row() (the difference is insignificant).
See also: mssql_fetch-array() and mssql_fetch-row().
Returns: An array that corresponds to the fetched row, or FALSE if there are no more rows.
mssql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
Subsequent call to mssql_fetch_rows() would return the next row in the result set, or FALSE if there are no more rows.
See also: mssql_fetch_array(), mssql_fetch_object(), mssql_data_seek(), mssql_fetch_lengths(), and mssql_result().
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Seeks to the specified field offset. If the next call to mssql_fetch_field() won't include a field offset, this field would be returned.
See also: mssql_fetch_field().
mssql_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script ends. You may call mssql_free_result() with the result identifier as an argument and the associated result memory will be freed.
(PHP 3, PHP 4 >= 4.0.0)
mssql_get_last_message -- Returns the last message from server (over min_message_severity?)When sending more than one SQL statement to the server or executing a stored procedure with multiple results, it 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 rows from the new result set. The function will return TRUE if an additional result set was available or FALSE otherwise.
Przykład 1. mssql_next_result() example
|
mssql_num_fields() returns the number of fields in a result set.
See also: mssql_db_query(), mssql_query(), mssql_fetch_field(), and mssql_num_rows().
mssql_num_rows() returns the number of rows in a result set.
See also: mssql_db_query(), mssql_query(), and mssql_fetch_row().
Returns: A positive MS SQL persistent link identifier on success, or FALSE on error.
mssql_pconnect() acts very much like mssql_connect() with two major differences.
First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mssql_close() will not close links established by mssql_pconnect()).
This type of links is therefore called 'persistent'.
Returns: A positive MS SQL result identifier on success, or FALSE on error.
mssql_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if mssql_connect() was called, and use it.
See also: mssql_db_query(), mssql_select_db(), and mssql_connect().
mssql_result() returns the contents of one cell from a MS SQL result set. The field argument can be the field's offset, the field's name or the field's table dot field's name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), it uses the alias instead of the column name.
When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than mssql_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.
Recommended high-performance alternatives: mssql_fetch_row(), mssql_fetch_array(), and mssql_fetch_object().
Returns: TRUE on success, FALSE on error
mssql_select_db() sets the current active database on the server that's associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if mssql_connect() was called, and use it.
Every subsequent call to mssql_query() will be made on the active database.
See also: mssql_connect(), mssql_pconnect(), and mssql_query()
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
(PHP 4 CVS only)
mssql_fetch_assoc -- Returns an associative array of the current row in the result set specified by result_id
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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. |
Ming is an open-source (LGPL) library which allows you to create SWF ("Flash") format movies. Ming supports almost all of Flash 4's features, including: shapes, gradients, bitmaps (pngs and jpegs), morphs ("shape tweens"), text, buttons, actions, sprites ("movie clips"), streaming mp3, and color transforms--the only thing that's missing is sound events.
Ming is not an acronym.
Note that all values specifying length, distance, size, etc. are in "twips", twenty units per pixel. That's pretty much arbitrary, though, since the player scales the movie to whatever pixel size is specified in the embed/object tag, or the entire frame if not embedded.
Ming offers a number of advantages over the existing PHP/libswf module. You can use Ming anywhere you can compile the code, whereas libswf is closed-source and only available for a few platforms, Windows not one of them. Ming provides some insulation from the mundane details of the SWF file format, wrapping the movie elements in PHP objects. Also, Ming is still being maintained; if there's a feature that you want to see, just let us know ming@opaque.net.
Ming was added in PHP 4.0.5.
To use Ming with PHP, you first need to build and install the Ming library. Source code and installation instructions are available at the Ming home page : http://www.opaque.net/ming/ along with examples, a small tutorial, and the latest news.
Download the ming archive. Unpack the archive. Go in the Ming directory. make. make install.
This will build libming.so and install it into /usr/lib/, and copy ming.h into /usr/include/. Edit the PREFIX= line in the Makefile to change the installation directory.
download php_ming.so.gz. uncompress it and copy it to your php modules directory. (you can find your php module directory by running php-config --extension-dir). Now either just add extension=php_ming.so to your php.ini file, or put dl('php_ming.so'); at the head of all of your Ming scripts.
Ming introduces 13 new objects in PHP, all with matching methods and attributes. To use them, you need to know about objects.
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
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. |
swfmovie() creates a new movie object, representing an SWF version 4 movie.
SWFMovie has the following methods : swfmovie->output(),swfmovie->save(), swfmovie->add(), swfmovie->remove(), swfmovie->nextframe(), swfmovie->setbackground(), swfmovie->setrate(), swfmovie->setdimension(), swfmovie->setframes() and swfmovie->streammp3().
See examples in : swfdisplayitem->rotateto(), swfshape->setline(), swfshape->addfill()... Any example will use this object.
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. |
swfmovie->output() dumps your lovingly prepared movie out. In PHP, preceding this with the command
<?php header('Content-type: application/x-shockwave-flash'); ?> |
See also swfmovie->save().
See examples in : swfmovie->streammp3(), swfdisplayitem->rotateto(), swfaction()... Any example will use this method.
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. |
swfmovie->save() saves your movie to the file named filename.
See also output().
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. |
swfmovie->add() adds instance to the current movie. instance is any type of data : Shapes, text, fonts, etc. must all be add'ed to the movie to make this work.
For displayable types (shape, text, button, sprite), this returns an SWFDisplayItem(), a handle to the object in a display list. Thus, you can add the same shape to a movie multiple times and get separate handles back for each separate instance.
See also all other objects (adding this later), and swfmovie->remove()
See examples in : swfdisplayitem->rotateto() and swfshape->addfill().
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. |
swfmovie->remove() removes the object instance instance from the display list.
See also swfmovie->add().
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. |
swfmovie->setbackground() sets the background color. Why is there no rgba version? Think about it. (Actually, that's not such a dumb question after all- you might want to let the html background show through. There's a way to do that, but it only works on IE4. Search the http://www.macromedia.com/ site for details.)
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. |
swfmovie->setrate() sets the frame rate to rate, in frame per seconds. Animation will slow down if the player can't render frames fast enough- unless there's a streaming sound, in which case display frames are sacrificed to keep sound from skipping.
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. |
swfmovie->setdimension() sets the movie's width to width and height to height.
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. |
swfmovie->setframes() sets the total number of frames in the animation to numberofframes.
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. |
swfmovie->setframes() moves to the next frame of the animation.
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. |
swfmovie->streammp3() streams the mp3 file mp3FileName. Not very robust in dealing with oddities (can skip over an initial ID3 tag, but that's about it). Like SWFShape->addJpegFill(), this isn't a stable function- we'll probably need to make a separate SWFSound object to contain sound types.
Note that the movie isn't smart enough to put enough frames in to contain the entire mp3 stream- you'll have to add (length of song * frames per second) frames to get the entire stream in.
Yes, now you can use ming to put that rock and roll devil worship music into your SWF files. Just don't tell the RIAA.
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. |
swfdisplayitem() creates a new swfdisplayitem object.
Here's where all the animation takes place. After you define a shape, a text object, a sprite, or a button, you add it to the movie, then use the returned handle to move, rotate, scale, or skew the thing.
SWFDisplayItem has the following methods : swfdisplayitem->move(), swfdisplayitem->moveto(), swfdisplayitem->scaleto(), swfdisplayitem->scale(), swfdisplayitem->rotate(), swfdisplayitem->rotateto(), swfdisplayitem->skewxto(), swfdisplayitem->skewx(), swfdisplayitem->skewyto() swfdisplayitem->skewyto(), swfdisplayitem->setdepth() swfdisplayitem->remove(), swfdisplayitem->setname() swfdisplayitem->setratio(), swfdisplayitem->addcolor() and swfdisplayitem->multcolor().
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. |
swfdisplayitem->moveto() moves the current object to (x,y) in global coordinates.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->move().
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. |
swfdisplayitem->move() moves the current object by (dx,dy) from its current position.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->moveto().
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. |
swfdisplayitem->scaleto() scales the current object to (x,y) in global coordinates.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->scale().
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. |
swfdisplayitem->scale() scales the current object by (dx,dy) from its current size.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->scaleto().
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. |
swfdisplayitem->rotateto() set the current object rotation to degrees degrees in global coordinates.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
This example bring three rotating string from the background to the foreground. Pretty nice.
Przykład 1. swfdisplayitem->rotateto() example
|
See also swfdisplayitem->rotate().
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. |
swfdisplayitem->rotate() rotates the current object by ddegrees degrees from its current rotation.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->rotateto().
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. |
swfdisplayitem->skewxto() sets the x-skew to degrees. For degrees is 1.0, it means a 45-degree forward slant. More is more forward, less is more backward.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->skewx(), swfdisplayitem->skewy() and swfdisplayitem->skewyto().
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. |
swfdisplayitem->skewx() adds ddegrees to current x-skew.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->skewx(), swfdisplayitem->skewy() and swfdisplayitem->skewyto().
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. |
swfdisplayitem->skewyto() sets the y-skew to degrees. For degrees is 1.0, it means a 45-degree forward slant. More is more upward, less is more downward.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->skewy(), swfdisplayitem->skewx() and swfdisplayitem->skewxto().
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. |
swfdisplayitem->skewy() adds ddegrees to current y-skew.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->skewyto(), swfdisplayitem->skewx() and swfdisplayitem->skewxto().
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. |
swfdisplayitem->rotate() sets the object's z-order to depth. Depth defaults to the order in which instances are created (by add'ing a shape/text to a movie)- newer ones are on top of older ones. If two objects are given the same depth, only the later-defined one can be moved.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
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. |
swfdisplayitem->remove() removes this object from the movie's display list.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfmovie->add().
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. |
swfdisplayitem->setname() sets the object's name to name, for targetting with action script. Only useful on sprites.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
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. |
swfdisplayitem->setratio() sets the object's ratio to ratio. Obviously only useful for morphs.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
This simple example will morph nicely three concentric circles.
Przykład 1. swfdisplayitem->setname() example
|
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. |
swfdisplayitem->addcolor() adds the color to this item's color transform. The color is given in its RGB form.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
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. |
swfdisplayitem->multcolor() multiplies the item's color transform by the given values.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
This simple example will modify your picture's atmospher to Halloween (use a landscape or bright picture).
Przykład 1. swfdisplayitem->multcolor() example
|
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. |
swfshape() creates a new shape object.
SWFShape has the following methods : swfshape->setline(), swfshape->addfill(), swfshape->setleftfill(), swfshape->setrightfill(), swfshape->movepento(), swfshape->movepen(), swfshape->drawlineto(), swfshape->drawline(), swfshape->drawcurveto() and swfshape->drawcurve().
This simple example will draw a big red elliptic quadrant.
Przykład 1. swfshape() example
|
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. |
swfshape->setline() sets the shape's line style. width is the line's width. If width is 0, the line's style is removed (then, all other arguments are ignored). If width > 0, then line's color is set to red, green, blue. Last parameter a is optional.
swfshape->setline() accepts 1, 4 or 5 arguments (not 3 or 2).
You must declare all line styles before you use them (see example).
This simple example will draw a big "!#%*@", in funny colors and gracious style.
Przykład 1. swfshape->setline() example
|
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 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 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. |
swfshape->addfill() adds a solid fill to the shape's list of fill styles. swfshape->addfill() accepts three different types of arguments.
red, green, blue is a color (RGB mode). Last parameter a is optional.
The bitmap argument is an swfbitmap() object. The flags argument can be one of the following values : SWFFILL_CLIPPED_BITMAP or SWFFILL_TILED_BITMAP. Default is SWFFILL_TILED_BITMAP. I think.
The gradient argument is an swfgradient() object. The flags argument can be one of the following values : SWFFILL_RADIAL_GRADIENT or SWFFILL_LINEAR_GRADIENT. Default is SWFFILL_LINEAR_GRADIENT. I'm sure about this one. Really.
swfshape->addfill() returns an swffill() object for use with the swfshape->setleftfill() and swfshape->setrightfill() functions described below.
See also swfshape->setleftfill() and swfshape->setrightfill().
This simple example will draw a frame on a bitmap. Ah, here's another buglet in the flash player- it doesn't seem to care about the second shape's bitmap's transformation in a morph. According to spec, the bitmap should stretch along with the shape in this example..
Przykład 1. swfshape->addfill() example
|
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 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. |
What this nonsense is about is, every edge segment borders at most two fills. When rasterizing the object, it's pretty handy to know what those fills are ahead of time, so the swf format requires these to be specified.
swfshape->setleftfill() sets the fill on the left side of the edge- that is, on the interior if you're defining the outline of the shape in a counter-clockwise fashion. The fill object is an SWFFill object returned from one of the addFill functions above.
This seems to be reversed when you're defining a shape in a morph, though. If your browser crashes, just try setting the fill on the other side.
Shortcut for swfshape->setleftfill($s->addfill($r, $g, $b [, $a]));.
See also swfshape->setrightfill().
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 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 swfshape->setleftfill().
Shortcut for swfshape->setrightfill($s->addfill($r, $g, $b [, $a]));.
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. |
swfshape->setrightfill() move the shape's pen to (x,y) in the shape's coordinate space.
See also swfshape->movepen(), swfshape->drawcurveto(), swfshape->drawlineto() and swfshape->drawline().
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. |
swfshape->setrightfill() move the shape's pen from coordinates (current x,current y) to (current x + dx, current y + dy) in the shape's coordinate space.
See also swfshape->movepento(), swfshape->drawcurveto(), swfshape->drawlineto() and swfshape->drawline().
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. |
swfshape->setrightfill() draws a line (using the current line style, set by swfshape->setline()) from the current pen position to point (x,y) in the shape's coordinate space.
See also swfshape->movepento(), swfshape->drawcurveto(), swfshape->movepen() and swfshape->drawline().
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. |
swfshape->drawline() draws a line (using the current line style set by swfshape->setline()) from the current pen position to displacement (dx,dy).
See also swfshape->movepento(), swfshape->drawcurveto(), swfshape->movepen() and swfshape->drawlineto().
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. |
swfshape->drawcurveto() draws a quadratic curve (using the current line style, set by swfshape->setline()) from the current pen position to (anchorx,anchory) using (controlx,controly) as a control point. That is, head towards the control point, then smoothly turn to the anchor point.
See also swfshape->drawlineto(), swfshape->drawline(), swfshape->movepento() and swfshape->movepen().
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. |
swfshape->drawcurve() draws a quadratic curve (using the current line style,set by swfshape->setline()) from the current pen position to the relative position (anchorx,anchory) using relative control point (controlx,controly). That is, head towards the control point, then smoothly turn to the anchor point.
See also swfshape->drawlineto(), swfshape->drawline(), swfshape->movepento() and swfshape->movepen().
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. |
swfgradient() creates a new SWFGradient object.
After you've added the entries to your gradient, you can use the gradient in a shape fill with the swfshape->addfill() method.
SWFGradient has the following methods : swfgradient->addentry().
This simple example will draw a big black-to-white gradient as background, and a redish disc in its center.
Przykład 1. swfgradient() example
|
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. |
swfgradient->addentry() adds an entry to the gradient list. ratio is a number between 0 and 1 indicating where in the gradient this color appears. Thou shalt add entries in order of increasing ratio.
red, green, blue is a color (RGB mode). Last parameter a is optional.
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. |
swfbitmap() creates a new SWFBitmap object from the Jpeg or DBL file named filename. alphafilename indicates a MSK file to be used as an alpha mask for a Jpeg image.
Notatka: We can only deal with baseline (frame 0) jpegs, no baseline optimized or progressive scan jpegs!
SWFBitmap has the following methods : swfbitmap->getwidth() and swfbitmap->getheight().
You can't import png images directly, though- have to use the png2dbl utility to make a dbl ("define bits lossless") file from the png. The reason for this is that I don't want a dependency on the png library in ming- autoconf should solve this, but that's not set up yet.
Przykład 1. Import PNG files
|
And you can put an alpha mask on a jpeg fill.
Przykład 2. swfbitmap() example
|
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. |
swfbitmap->getwidth() returns the bitmap's width in pixels.
See also swfbitmap->getheight().
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. |
swfbitmap->getheight() returns the bitmap's height in pixels.
See also swfbitmap->getwidth().
The swffill() object allows you to transform (scale, skew, rotate) bitmap and gradient fills. swffill() objects are created by the swfshape->addfill() methods.
SWFFill has the following methods : swffill->moveto() and swffill->scaleto(), swffill->rotateto(), swffill->skewxto() and swffill->skewyto().
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. |
swffill->moveto() moves fill's origin to (x,y) in global coordinates.
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. |
swffill->scaleto() sets fill's scale to x in the x-direction, y in the y-direction.
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. |
swffill->rotateto() sets fill's rotation to degrees degrees.
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. |
swffill->skewxto() sets fill x-skew to x. For x is 1.0, it is a is a 45-degree forward slant. More is more forward, less is more backward.
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. |
swffill->skewyto() sets fill y-skew to y. For y is 1.0, it is a is a 45-degree upward slant. More is more upward, less is more downward.
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. |
swfmorph() creates a new SWFMorph object.
Also called a "shape tween". This thing lets you make those tacky twisting things that make your computer choke. Oh, joy!
The methods here are sort of weird. It would make more sense to just have newSWFMorph(shape1, shape2);, but as things are now, shape2 needs to know that it's the second part of a morph. (This, because it starts writing its output as soon as it gets drawing commands- if it kept its own description of its shapes and wrote on completion this and some other things would be much easier.)
SWFMorph has the following methods : swfmorph->getshape1() and swfmorph->getshape1().
This simple example will morph a big red square into a smaller blue black-bordered square.
Przykład 1. swfmorph() example
|
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. |
swfmorph->getshape1() gets a handle to the morph's starting shape. swfmorph->getshape1() returns an swfshape() object.
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. |
swfmorph->getshape2() gets a handle to the morph's ending shape. swfmorph->getshape2() returns an swfshape() object.
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. |
swftext() creates a new SWFText object, fresh for manipulating.
SWFText has the following methods : swftext->setfont(), swftext->setheight(), swftext->setspacing(), swftext->setcolor(), swftext->moveto(), swftext->addstring() and swftext->getwidth().
This simple example will draw a big yellow "PHP generates Flash with Ming" text, on white background.
Przykład 1. swftext() example
|
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. |
swftext->setfont() sets the current font to font.
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. |
swftext->setheight() sets the current font height to height. Default is 240.
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. |
swftext->setspacing() sets the current font spacing to spacingspacing. Default is 1.0. 0 is all of the letters written at the same point. This doesn't really work that well because it inflates the advance across the letter, doesn't add the same amount of spacing between the letters. I should try and explain that better, prolly. Or just fix the damn thing to do constant spacing. This was really just a way to figure out how letter advances work, anyway.. So nyah.
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. |
swftext->setspacing() changes the current text color. Default is black. I think. Color is represented using the RGB system.
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. |
swftext->moveto() moves the pen (or cursor, if that makes more sense) to (x,y) in text object's coordinate space. If either is zero, though, value in that dimension stays the same. Annoying, should be fixed.
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. |
swftext->addstring() draws the string string at the current pen (cursor) location. Pen is at the baseline of the text; i.e., ascending text is in the -y direction.
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. |
swftext->addstring() returns the rendered width of the string string at the text object's current font, scale, and spacing settings.
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. |
If filename is the name of an FDB file (i.e., it ends in ".fdb"), load the font definition found in said file. Otherwise, create a browser-defined font reference.
FDB ("font definition block") is a very simple wrapper for the SWF DefineFont2 block which contains a full description of a font. One may create FDB files from SWT Generator template files with the included makefdb utility- look in the util directory off the main ming distribution directory.
Browser-defined fonts don't contain any information about the font other than its name. It is assumed that the font definition will be provided by the movie player. The fonts _serif, _sans, and _typewriter should always be available. For example:
<?php $f = newSWFFont("_sans"); ?> |
swffont() returns a reference to the font definition, for use in the SWFText->setFont() and the SWFTextField->setFont() methods.
SWFFont has the following methods : swffont->getwidth().
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. |
swffont->getwidth() returns the string string's width, using font's default scaling. You'll probably want to use the SWFText() version of this method which uses the text object's scale.
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. |
swftextfield() creates a new text field object. Text Fields are less flexible than swftext() objects- they can't be rotated, scaled non-proportionally, or skewed, but they can be used as form entries, and they can use browser-defined fonts.
The optional flags change the text field's behavior. It has the following possibles values :
SWFTEXTFIELD_NOEDIT indicates that the field shouldn't be user-editable
SWFTEXTFIELD_PASSWORD obscures the data entry
SWFTEXTFIELD_DRAWBOX draws the outline of the textfield
SWFTEXTFIELD_MULTILINE allows multiple lines
SWFTEXTFIELD_WORDWRAP allows text to wrap
SWFTEXTFIELD_NOSELECT makes the field non-selectable
<?php $t = newSWFTextField(SWFTEXTFIELD_PASSWORD | SWFTEXTFIELD_NOEDIT); ?> |
SWFTextField has the following methods : swftextfield->setfont(), swftextfield->setbounds(), swftextfield->align(), swftextfield->setheight(), swftextfield->setleftmargin(), swftextfield->setrightmargin(), swftextfield->setmargins(), swftextfield->setindentation(), swftextfield->setlinespacing(), swftextfield->setcolor(), swftextfield->setname() and swftextfield->addstring().
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. |
swftextfield->setfont() sets the text field font to the [browser-defined?] font font.
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. |
swftextfield->setbounds() sets the text field width to width and height to height. If you don't set the bounds yourself, Ming makes a poor guess at what the bounds are.
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. |
swftextfield->align() sets the text field alignment to alignement. Valid values for alignement are : SWFTEXTFIELD_ALIGN_LEFT, SWFTEXTFIELD_ALIGN_RIGHT, SWFTEXTFIELD_ALIGN_CENTER and SWFTEXTFIELD_ALIGN_JUSTIFY.
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. |
swftextfield->setheight() sets the font height of this text field font to the given height height. Default is 240.
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. |
swftextfield->setleftmargin() sets the left margin width of the text field to width. Default is 0.
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. |
swftextfield->setrightmargin() sets the right margin width of the text field to width. Default is 0.
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. |
swftextfield->setmargins() set both margins at once, for the man on the go.
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. |
swftextfield->setindentation() sets the indentation of the first line in the text field, to width.
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. |
swftextfield->setlinespacing() sets the line spacing of the text field to the height of height. Default is 40.
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. |
swftextfield->setcolor() sets the color of the text field. Default is fully opaque black. Color is represented using RGB system.
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. |
swftextfield->setname() sets the variable name of this text field to name, for form posting and action scripting purposes.
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. |
swftextfield->setname() concatenates the string string to the text field.
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. |
swfsprite() are also known as a "movie clip", this allows one to create objects which are animated in their own timelines. Hence, the sprite has most of the same methods as the movie.
swfsprite() has the following methods : swfsprite->add(), swfsprite->remove(), swfsprite->nextframe() and swfsprite->setframes().
This simple example will spin gracefully a big red square.
Przykład 1. swfsprite() example
|
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. |
swfsprite->add() adds a swfshape(), a swfbutton(), a swftext(), a swfaction() or a swfsprite() object.
For displayable types (swfshape(), swfbutton(), swftext(), swfaction() or swfsprite()), this returns a handle to the object in a display list.
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. |
swfsprite->remove() remove a swfshape(), a swfbutton(), a swftext(), a swfaction() or a swfsprite() object from the sprite.
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. |
swfsprite->setframes() sets the total number of frames in the animation to numberofframes.
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. |
swfsprite->setframes() moves to the next frame of the animation.
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. |
swfbutton() creates a new Button. Roll over it, click it, see it call action code. Swank.
SWFButton has the following methods : swfbutton->addshape(), swfbutton->setup(), swfbutton->setover() swfbutton->setdown(), swfbutton->sethit() swfbutton->setaction() and swfbutton->addaction().
This simple example will show your usual interactions with buttons : rollover, rollon, mouseup, mousedown, noaction.
Przykład 1. swfbutton() example
|
This simple example will enables you to drag draw a big red button on the windows. No drag-and-drop, just moving around.
Przykład 2. swfbutton->addaction() example
|
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. |
swfbutton->addshape() adds the shape shape to this button. The following flags' values are valid: SWFBUTTON_UP, SWFBUTTON_OVER, SWFBUTTON_DOWN or SWFBUTTON_HIT. SWFBUTTON_HIT isn't ever displayed, it defines the hit region for the button. That is, everywhere the hit shape would be drawn is considered a "touchable" part of the button.
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. |
swfbutton->setup() alias for addShape(shape, SWFBUTTON_UP).
See also swfbutton->addshape() and SWFAction().
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. |
swfbutton->setover() alias for addShape(shape, SWFBUTTON_OVER).
See also swfbutton->addshape() and SWFAction().
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. |
swfbutton->setdown() alias for addShape(shape, SWFBUTTON_DOWN).
See also swfbutton->addshape() and SWFAction().
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. |
swfbutton->sethit() alias for addShape(shape, SWFBUTTON_HIT).
See also swfbutton->addshape() and SWFAction().
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. |
swfbutton->addaction() adds the action action to this button for the given conditions. The following flags are valid: SWFBUTTON_MOUSEOVER, SWFBUTTON_MOUSEOUT, SWFBUTTON_MOUSEUP, SWFBUTTON_MOUSEUPOUTSIDE, SWFBUTTON_MOUSEDOWN, SWFBUTTON_DRAGOUT and SWFBUTTON_DRAGOVER.
See also swfbutton->addshape() and SWFAction().
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. |
swfbutton->setaction() sets the action to be performed when the button is clicked. Alias for addAction(shape, SWFBUTTON_MOUSEUP). action is a swfaction().
See also swfbutton->addshape() and SWFAction().
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. |
swfaction() creates a new Action, and compiles the given script into an SWFAction object.
The script syntax is based on the C language, but with a lot taken out- the SWF bytecode machine is just too simpleminded to do a lot of things we might like. For instance, we can't implement function calls without a tremendous amount of hackery because the jump bytecode has a hardcoded offset value. No pushing your calling address to the stack and returning- every function would have to know exactly where to return to.
So what's left? The compiler recognises the following tokens:
break
for
continue
if
else
do
while
There is no typed data; all values in the SWF action machine are stored as strings. The following functions can be used in expressions:
Returns the number of milliseconds (?) elapsed since the movie started.
Returns a pseudo-random number in the range 0-seed.
Returns the length of the given expression.
Returns the given number rounded down to the nearest integer.
Returns the concatenation of the given expressions.
Returns the ASCII code for the given character
Returns the character for the given ASCII code
Returns the substring of length length at location location of the given string string.
Additionally, the following commands may be used:
Duplicate the named movie clip (aka sprite). The new movie clip has name name and is at depth depth.
Removes the named movie clip.
Write the given expression to the trace log. Doubtful that the browser plugin does anything with this.
Start dragging the movie clip target. The lock argument indicates whether to lock the mouse (?)- use 0 (FALSE) or 1 (TRUE). Optional parameters define a bounding area for the dragging.
Stop dragging my heart around. And this movie clip, too.
Call the named frame as a function.
Load the given URL into the named target. The target argument corresponds to HTML document targets (such as "_top" or "_blank"). The optional method argument can be POST or GET if you want to submit variables back to the server.
Load the given URL into the named target. The target argument can be a frame name (I think), or one of the magical values "_level0" (replaces current movie) or "_level1" (loads new movie on top of current movie).
Go to the next frame.
Go to the last (or, rather, previous) frame.
Start playing the movie.
Stop playing the movie.
Toggle between high and low quality.
Stop playing all sounds.
Go to frame number num. Frame numbers start at 0.
Go to the frame named name. Which does a lot of good, since I haven't added frame labels yet.
Sets the context for action. Or so they say- I really have no idea what this does.
Movie clips (all together now- aka sprites) have properties. You can read all of them (or can you?), you can set some of them, and here they are:
x
y
xScale
yScale
currentFrame - (read-only)
totalFrames - (read-only)
alpha - transparency level
visible - 1=on, 0=off (?)
width - (read-only)
height - (read-only)
rotation
target - (read-only) (???)
framesLoaded - (read-only)
name
dropTarget - (read-only) (???)
url - (read-only) (???)
highQuality - 1=high, 0=low (?)
focusRect - (???)
soundBufTime - (???)
This simple example will move the red square across the window.
Przykład 1. swfaction() example
|
This simple example tracks down your mouse on the screen.
Przykład 2. swfaction() example
|
Same as above, but with nice colored balls...
Przykład 3. swfaction() example
|
This simple example will handles keyboard actions. (You'll probably have to click in the window to give it focus. And you'll probably have to leave your mouse in the frame, too. If you know how to give buttons focus programatically, feel free to share, won't you?)
Przykład 4. swfaction() example
|
Returns TRUE if client disconnected. See the Connection Handling description in the Features chapter for a complete explanation.
Returns the connection status bitfield. See the Connection Handling description in the Features chapter for a complete explanation.
Returns TRUE if script timed out.
Deprecated |
This function is deprecated, and doesn't even exist anymore as of 4.0.5. |
See the Connection Handling description in the Features chapter for a complete explanation.
constant() will return the value of the constant indicated by name.
constant() is useful if you need to retrieve the value of a constant, but do not know it's name. i.e. It is stored in a variable or returned by a function.
Defines a named constant. See the section on constants for more details.
The name of the constant is given by name; the value is given by value.
The optional third parameter case_insensitive is also available. If the value TRUE is given, then the constant will be defined case-insensitive. The default behaviour is case-sensitive; i.e. CONSTANT and Constant represent different values.
define() returns TRUE on success and FALSE if an error occurs.
See also defined(), constant() and the section on Constants.
Returns TRUE if the named constant given by name has been defined, FALSE otherwise.
See also define(), constant() and the section on Constants.
eval() evaluates the string given in code_str as PHP code. Among other things, this can be useful for storing code in a database text field for later execution.
There are some factors to keep in mind when using eval(). Remember that the string passed must be valid PHP code, including things like terminating statements with a semicolon so the parser doesn't die on the line after the eval(), and properly escaping things in code_str.
Also remember that variables given values under eval() will retain these values in the main script afterwards.
A return statement will terminate the evaluation of the string immediately. In PHP 4, eval() returns FALSE unless return() is called in the evaluated code, in which case the value passed to return() is returned. In PHP 3, eval() does not return a value.
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.
Notatka: This is not a real function, but a language construct.
The exit() function terminates execution of the script. It prints status just before exiting.
If status is an integer, that value will also be used as the exit status.
Notatka: The current CVS version does NOT print the status if it is an integer.
Notatka: The die() function is an alias for exit().
get_browser() attempts to determine the capabilities of the user's browser. This is done by looking up the browser's information in the browscap.ini file. By default, the value of $HTTP_USER_AGENT is used; however, you can alter this (i.e., look up another browser's info) by passing the optional user_agent parameter to get_browser().
The information is returned in an object, which will contain various data elements representing, for instance, the browser's major and minor version numbers and ID string; TRUE/false values for features such as frames, JavaScript, and cookies; and so forth.
While browscap.ini contains information on many browsers, it relies on user updates to keep the database current. The format of the file is fairly self-explanatory.
The following example shows how one might list all available information retrieved about the user's browser.
The output of the above script would look something like this:
Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586)<hr> <b>browser_name_pattern:</b> Mozilla/4\.5.*<br> <b>parent:</b> Netscape 4.0<br> <b>platform:</b> Unknown<br> <b>majorver:</b> 4<br> <b>minorver:</b> 5<br> <b>browser:</b> Netscape<br> <b>version:</b> 4<br> <b>frames:</b> 1<br> <b>tables:</b> 1<br> <b>cookies:</b> 1<br> <b>backgroundsounds:</b> <br> <b>vbscript:</b> <br> <b>javascript:</b> 1<br> <b>javaapplets:</b> 1<br> <b>activexcontrols:</b> <br> <b>beta:</b> <br> <b>crawler:</b> <br> <b>authenticodeupdate:</b> <br> <b>msn:</b> <br> |
In order for this to work, your browscap configuration file setting must point to the correct location of the browscap.ini file.
For more information (including locations from which you may obtain a browscap.ini file), check the PHP FAQ at http://www.php.net/FAQ.php.
The highlight_file() function prints out a syntax higlighted version of the code contained in filename using the colors defined in the built-in syntax highlighter for PHP. Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
Notatka: Care should be taken when using the show_source() and highlight_file() functions to make sure that you do not inadvertently reveal sensitive information such as passwords or any other type of information that might create a potential security risk.
Przykład 1. Creating a source highlighting URL To setup a URL that can code hightlight any script that you pass to it, we will make use of the "ForceType" directive in Apache to generate a nice URL pattern, and use the function highlight_file() to show a nice looking code list. In your httpd.conf you can add the following:
And then make a file named "source" and put it in your web root directory.
Then you can use an URL like the one below to display a colorized version of a script located in "/path/to/script.php" in your web site.
|
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.
See also highlight_string(), show_source().
The highlight_string() function prints out a syntax highlighted version of str using the colors defined in the built-in syntax highlighter for PHP. Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
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.
See also highlight_file(), show_source().
(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)
ignore_user_abort -- Set whether a client disconnect should abort script executionThis function sets whether a client disconnect should cause a script to be aborted. It will return the previous setting and can be called without an argument to not change the current setting and only return the current setting. See the Connection Handling section in the Features chapter for a complete description of connection handling in PHP.
(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)
iptcparse -- Parse a binary IPTC http://www.iptc.org/ block into single tags.This function parses a binary IPTC block into its single tags. It returns an array using the tagmarker as an index and the value as the value. It returns FALSE on error or if no IPTC data was found. See GetImageSize() for a sample.
leak() leaks the specified amount of memory.
This is useful when debugging the memory manager, which automatically cleans up "leaked" memory when each request is completed.
Pack given arguments into binary string according to format. Returns binary string containing data.
The idea to this function was taken from Perl and all formatting codes work the same as there, however, there are some formatting codes that are missing such as Perl's "u" format code. The format string consists of format codes followed by an optional repeater argument. The repeater argument can be either an integer value or * for repeating to the end of the input data. For a, A, h, H the repeat count specifies how many characters of one data argument are taken, for @ it is the absolute position where to put the next data, for everything else the repeat count specifies how many data arguments are consumed and packed into the resulting binary string. Currently implemented are
a NUL-padded string
A SPACE-padded string
h Hex string, low nibble first
H Hex string, high nibble first
c signed char
C unsigned char
s signed short (always 16 bit, machine byte order)
S unsigned short (always 16 bit, machine byte order)
n unsigned short (always 16 bit, big endian byte order)
v unsigned short (always 16 bit, little endian byte order)
i signed integer (machine dependent size and byte order)
I unsigned integer (machine dependent size and byte order)
l signed long (always 32 bit, machine byte order)
L unsigned long (always 32 bit, machine byte order)
N unsigned long (always 32 bit, big endian byte order)
V unsigned long (always 32 bit, little endian byte order)
f float (machine dependent size and representation)
d double (machine dependent size and representation)
x NUL byte
X Back up one byte
@ NUL-fill to absolute position
Note that the distinction between signed and unsigned values only affects the function unpack(), where as function pack() gives the same result for signed and unsigned format codes.
Also note that PHP internally stores integer values as signed values of a machine dependent size. If you give it an unsigned integer value too large to be stored that way it is converted to a float which often yields an undesired result.
The show_source() function prints out a syntax higlighted version of the code contained in filename using the colors defined in the built-in syntax highlighter for PHP. It returns TRUE on success, FALSE otherwise (PHP 4).
This function is an alias for the function highlight_file()
Notatka: Care should be taken when using the show_source() and highlight_file() functions to make sure that you do not inadvertently reveal sensitive information such as passwords or any other type of information that might create a potential security risk.
See also highlight_string(), highlight_file().
The sleep function delays program execution for the given number of seconds.
See also usleep().
uniqid() returns a prefixed unique identifier based on the current time in microseconds. The prefix can be useful for instance if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same microsecond. Prefix can be up to 114 characters long.
If the optional lcg parameter is TRUE, uniqid() will add additional "combined LCG" entropy at the end of the return value, which should make the results more unique.
With an empty prefix, the returned string will be 13 characters long. If lcg is TRUE, it will be 23 characters.
Notatka: The lcg parameter is only available in PHP 4 and PHP 3.0.13 and later.
If you need a unique identifier or token and you intend to give out that token to the user via the network (i.e. session cookies), it is recommended that you use something along the lines of
$token = md5(uniqid("")); // no prefix $better_token = md5(uniqid(rand(),1)); // better, difficult to guess |
This will create a 32 character identifier (a 128 bit hex number) that is extremely difficult to predict.
unpack() from binary string into array according to format. Returns array containing unpacked elements of binary string.
unpack() works slightly different from Perl as the unpacked data is stored in an associative array. To accomplish this you have to name the different format codes and separate them by a slash /.
For an explanation of the format codes see also: pack()
Note that PHP internally stores integral values as signed. If you unpack a large unsigned long and it is of the same size as PHP internally stored values the result will be a negative number even though unsigned unpacking was specified.
The usleep() function delays program execution for the given number of micro_seconds.
See also sleep().
Notatka: This function does not work on Windows systems.
These functions allow you to access mnoGoSearch (former UdmSearch) free search engine. In order to have these functions available, you must compile php with mnogosearch support by using the --with-mnogosearch option. If you use this option without specifying the path to mnogosearch, php will look for mnogosearch under /usr/local/mnogosearch path by default. If you installed mnogosearch at other path you should specify it: --with-mnogosearch=DIR.
mnoGoSearch is a full-featured search engine software for intranet and internet servers, distributed under the GNU license. mnoGoSearch has number of unique features, which makes it appropriate for a wide range of application from search within your site to a specialized search system such as cooking recipes or newspaper search, ftp archive search, news articles search, etc. It offers full-text indexing and searching for HTML, PDF, and text documents. mnoGoSearch consists of two parts. The first is an indexing mechanism (indexer). The purpose of indexer is to walk through HTTP, FTP, NEWS servers or local files, recursively grabbing all the documents and storing meta-data about that documents in a SQL database in a smart and effective manner. After every document is referenced by its corresponding URL, meta-data collected by indexer is used later in a search process. The search is performed via Web interface. C CGI, PHP and Perl search front ends are included.
Notatka: php contains built-in mysql access library, which can be used to access mysql. It is known that mnoGoSearch is not compatible with this built-in library and can work only with generic mysql libraries. Thus, if you use mnoGoSearch with mysql, during php configuration you have to indicate directory of mysql installation, that was used during mnoGoSearch configuration, i.e. for example: --with-mnogosearch --with-mysql=/usr.
You need at least 3.1.10 version of mnoGoSearch installed to use these functions.
More information about mnoGoSearch can be found at http://www.mnogosearch.ru/.
udm_add_search_limit() returns TRUE on success, FALSE on error. Adds search restrictions.
agent - a link to Agent, received after call to udm_alloc_agent().
var - defines parameter, indicating limit.
val - defines value of the current parameter.
Possible var values:
UDM_LIMIT_URL - defines document URL limitations to limit search through subsection of database. It supports SQL % and _ LIKE wildcards, where % matches any number of characters, even zero characters, and _ matches exactly one character. E.g. http://my.domain.__/catalog may stand for http://my.domain.ru/catalog and http://my.domain.ua/catalog.
UDM_LIMIT_TAG - defines site TAG limitations. In indexer-conf you can assign specific TAGs to various sites and parts of a site. Tags in mnoGoSearch 3.1.x are lines, that may contain metasymbols % and _. Metasymbols allow searching among groups of tags. E.g. there are links with tags ABCD and ABCE, and search restriction is by ABC_ - the search will be made among both of the tags.
UDM_LIMIT_LANG - defines document language limitations.
UDM_LIMIT_CAT - defines document category limitations. Categories are similar to tag feature, but nested. So you can have one category inside another and so on. You have to use two characters for each level. Use a hex number going from 0-F or a 36 base number going from 0-Z. Therefore a top-level category like 'Auto' would be 01. If it has a subcategory like 'Ford', then it would be 01 (the parent category) and then 'Ford' which we will give 01. Put those together and you get 0101. If 'Auto' had another subcategory named 'VW', then it's id would be 01 because it belongs to the 'Ford' category and then 02 because it's the next category. So it's id would be 0102. If VW had a sub category called 'Engine' then it's id would start at 01 again and it would get the 'VW' id 02 and 'Auto' id of 01, making it 010201. If you want to search for sites under that category then you pass it cat=010201 in the url.
UDM_LIMIT_DATE - defines limitation by date document was modified.
Format of parameter value: a string with first character < or >, then with no space - date in unixtime format, for example:
Udm_Add_Search_Limit($udm,UDM_LIMIT_DATE,"<908012006");
If > character is used, then search will be restricted to those documents having modification date greater than entered. If <, then smaller.
udm_alloc_agent() returns mnogosearch agent identifier on success, FALSE on error. This function creates a session with database parameters.
dbaddr - URL-style database description. Options (type, host, database name, port, user and password) to connect to SQL database. Do not matter for built-in text files support. Format: DBAddr DBType:[//[DBUser[:DBPass]@]DBHost[:DBPort]]/DBName/ Currently supported DBType values are: mysql, pgsql, msql, solid, mssql, oracle, ibase. Actually, it does not matter for native libraries support. But ODBC users should specify one of supported values. If your database type is not supported, you may use "unknown" instead.
dbmode - You may select SQL database mode of words storage. When "single" is specified, all words are stored in the same table. If "multi" is selected, words will be located in different tables depending of their lengths. "multi" mode is usually faster but requires more tables in database. If "crc" mode is selected, mnoGoSearch will store 32 bit integer word IDs calculated by CRC32 algorythm instead of words. This mode requres less disk space and it is faster comparing with "single" and "multi" modes. "crc-multi" uses the same storage structure with the "crc" mode, but also stores words in different tables depending on words lengths like "multi" mode. Format: DBMode single/multi/crc/crc-multi
Notatka: dbaddr and dbmode must match those used during indexing.
Notatka: In fact this function does not open connection to database and thus does not check entered login and password. Actual connection to database and login/password verification is done by udm_find().
udm_api_version() returns mnoGoSearch API version number. E.g. if mnoGoSearch 3.1.10 API is used, this function will return 30110.
This function allows user to identify which API functions are available, e.g. udm_get_doc_count() function is only available in mnoGoSearch 3.1.11 or later.
Example:
udm_cat_path() returns array describing path in the categories tree from the tree root to the current category.
agent - agent link identifier.
category - current category - the one to get path to.
Returns array with the following format:
The array consists of pairs. Elements with even index numbers contain category paths, odd elements contain corresponding category names.
For example, the call $array=udm_cat_path($agent, '02031D'); may return the following array:
$array[0] will contain ''
$array[1] will contain 'Root'
$array[2] will contain '02'
$array[3] will contain 'Sport'
$array[4] will contain '0203'
$array[5] will contain 'Auto'
$array[4] will contain '02031D'
$array[5] will contain 'Ferrari'
Przykład 1. Specifying path to the current category in the following format: '> Root > Sport > Auto > Ferrari'
|
udm_cat_list() returns array listing all categories of the same level as current category in the categories tree.
The function can be useful for developing categories tree browser.
Returns array with the following format:
The array consists of pairs. Elements with even index numbers contain category paths, odd elements contain corresponding category names.
$array[0] will contain '020300'
$array[1] will contain 'Audi'
$array[2] will contain '020301'
$array[3] will contain 'BMW'
$array[4] will contain '020302'
$array[5] will contain 'Opel'
...
etc.
Following is an example of displaying links of the current level in format:
Audi
BMW
Opel
...
udm_clear_search_limits() resets defined search limitations and returns TRUE.
udm_errno() returns mnoGoSearch error number, zero if no error.
agent - link to agent identifier, received after call to udm_alloc_agent().
Receiving numeric agent error code.
udm_error() returns mnoGoSearch error message, empty string if no error.
agent - link to agent identifier, received after call to udm_alloc_agent().
Receiving agent error message.
udm_find() returns result link identifier on success, FALSE on error.
The search itself. The first argument - session, the next one - query itself. To find something just type words you want to find and press SUBMIT button. For example, "mysql odbc". You should not use quotes " in query, they are written here only to divide a query from other text. mnoGoSearch will find all documents that contain word "mysql" and/or word "odbc". Best documents having bigger weights will be displayed first. If you use search mode ALL, search will return documents that contain both (or more) words you entered. In case you use mode ANY, the search will return list of documents that contain any of the words you entered. If you want more advanced results you may use query language. You should select "bool" match mode in the search from.
mnoGoSearch understands the following boolean operators:
& - logical AND. For example, "mysql & odbc". mnoGoSearch will find any URLs that contain both "mysql" and "odbc".
| - logical OR. For example "mysql|odbc". mnoGoSearch will find any URLs, that contain word "mysql" or word "odbc".
~ - logical NOT. For example "mysql & ~odbc". mnoGoSearch will find URLs that contain word "mysql" and do not contain word "odbc" at the same time. Note that ~ just excludes given word from results. Query "~odbc" will find nothing!
() - group command to compose more complex queries. For example "(mysql | msql) & ~postgres". Query language is simple and powerful at the same time. Just consider query as usual boolean expression.
udm_free_agent() returns TRUE on success, FALSE on error.
agent - link to agent identifier, received ` after call to udm_alloc_agent().
Freeing up memory allocated for agent session.
udm_free_ispell_data() always returns TRUE.
agent - agent link identifier, received after call to udm_alloc_agent().
Notatka: This function is supported beginning from version 3.1.12 of mnoGoSearch and it does not do anything in previous versions.
udm_free_res() returns TRUE on success, FALSE on error.
res - a link to result identifier, received after call to udm_find().
Freeing up memory allocated for results.
udm_get_doc_count() returns number of documents in database.
agent - link to agent identifier, received after call to udm_alloc_agent().
Notatka: This function is supported only in mnoGoSearch 3.1.11 or later.
udm_get_res_field() returns result field value on success, FALSE on error.
res - a link to result identifier, received after call to udm_find().
row - the number of the link on the current page. May have values from 0 to UDM_PARAM_NUM_ROWS-1.
field - field identifier, may have the following values:
UDM_FIELD_URL - document URL field
UDM_FIELD_CONTENT - document Content-type field (for example, text/html).
UDM_FIELD_CATEGORY - document category field. Use udm_cat_path() to get full path to current category from the categories tree root. (This parameter is available only in PHP 4.0.6 or later).
UDM_FIELD_TITLE - document title field.
UDM_FIELD_KEYWORDS - document keywords field (from META KEYWORDS tag).
UDM_FIELD_DESC - document description field (from META DESCRIPTION tag).
UDM_FIELD_TEXT - document body text (the first couple of lines to give an idea of what the document is about).
UDM_FIELD_SIZE - document size.
UDM_FIELD_URLID - unique URL ID of the link.
UDM_FIELD_RATING - page rating (as calculated by mnoGoSearch).
UDM_FIELD_MODIFIED - last-modified field in unixtime format.
UDM_FIELD_ORDER - the number of the current document in set of found documents.
UDM_FIELD_CRC - document CRC.
udm_get_res_param() returns result parameter value on success, FALSE on error.
res - a link to result identifier, received after call to udm_find().
param - parameter identifier, may have the following values:
UDM_PARAM_NUM_ROWS - number of received found links on the current page. It is equal to UDM_PARAM_PAGE_SIZE for all search pages, on the last page - the rest of links.
UDM_PARAM_FOUND - total number of results matching the query.
UDM_PARAM_WORDINFO - information on the words found. E.g. search for "a good book" will return "a: stopword, good:5637, book: 120"
UDM_PARAM_SEARCHTIME - search time in seconds.
UDM_PARAM_FIRST_DOC - the number of the first document displayed on current page.
UDM_PARAM_LAST_DOC - the number of the last document displayed on current page.
udm_load_ispell_data() loads ispell data. Returns TRUE on success, FALSE on error.
agent - agent link identifier, received after call to udm_alloc_agent().
var - parameter, indicating the source for ispell data. May have the following values:
After using this function to free memory allocated for ispell data, please use udm_free_ispell_data(), even if you use UDM_ISPELL_TYPE_SERVER mode.
The fastest mode is UDM_ISPELL_TYPE_SERVER. UDM_ISPELL_TYPE_TEXT is slower and UDM_ISPELL_TYPE_DB is the slowest. The above pattern is TRUE for mnoGoSearch 3.1.10 - 3.1.11. It is planned to speed up DB mode in future versions and it is going to be faster than TEXT mode.
UDM_ISPELL_TYPE_DB - indicates that ispell data should be loaded from SQL. In this case, parameters val1 and val2 are ignored and should be left blank. flag should be equal to 1.
Notatka: flag indicates that after loading ispell data from defined source it sould be sorted (it is necessary for correct functioning of ispell). In case of loading ispell data from files there may be several calls to udm_load_ispell_data(), and there is no sense to sort data after every call, but only after the last one. Since in db mode all the data is loaded by one call, this parameter should have the value 1. In this mode in case of error, e.g. if ispell tables are absent, the function will return FALSE and code and error message will be accessible through udm_error() and udm_errno().
Example:
UDM_ISPELL_TYPE_AFFIX - indicates that ispell data should be loaded from file and initiates loading affixes file. In this case val1 defines double letter language code for which affixes are loaded, and val2 - file path. Please note, that if a relative path entered, the module looks for the file not in UDM_CONF_DIR, but in relation to current path, i.e. to the path where the script is executed. In case of error in this mode, e.g. if file is absent, the function will return FALSE, and an error message will be displayed. Error message text cannot be accessed through udm_error() and udm_errno(), since those functions can only return messages associated with SQL. Please, see flag parameter description in UDM_ISPELL_TYPE_DB.
Example:
if ((! udm_load_ispell_data($udm,UDM_ISPELL_TYPE_AFFIX,'en','/opt/ispell/en.aff',0)) || (! udm_load_ispell_data($udm,UDM_ISPELL_TYPE_AFFIX,'ru','/opt/ispell/ru.aff',0)) || (! udm_load_ispell_data($udm,UDM_ISPELL_TYPE_SPELL,'en','/opt/ispell/en.dict',0)) || (! udm_load_ispell_data($udm,UDM_ISPELL_TYPE_SPELL,'ru','/opt/ispell/ru.dict',1))) { exit; } |
Notatka: flag is equal to 1 only in the last call.
UDM_ISPELL_TYPE_SPELL - indicates that ispell data should be loaded from file and initiates loading of ispell dictionary file. In this case val1 defines double letter language code for which affixes are loaded, and val2 - file path. Please note, that if a relative path entered, the module looks for the file not in UDM_CONF_DIR, but in relation to current path, i.e. to the path where the script is executed. In case of error in this mode, e.g. if file is absent, the function will return FALSE, and an error message will be displayed. Error message text cannot be accessed through udm_error() and udm_errno(), since those functions can only return messages associated with SQL. Please, see flag parameter description in UDM_ISPELL_TYPE_DB.
if ((! Udm_Load_Ispell_Data($udm,UDM_ISPELL_TYPE_AFFIX,'en','/opt/ispell/en.aff',0)) || (! Udm_Load_Ispell_Data($udm,UDM_ISPELL_TYPE_AFFIX,'ru','/opt/ispell/ru.aff',0)) || (! Udm_Load_Ispell_Data($udm,UDM_ISPELL_TYPE_SPELL,'en','/opt/ispell/en.dict',0)) || (! Udm_Load_Ispell_Data($udm,UDM_ISPELL_TYPE_SPELL,'ru','/opt/ispell/ru.dict',1))) { exit; } |
Notatka: flag is equal to 1 only in the last call.
UDM_ISPELL_TYPE_SERVER - enables spell server support. val1 parameter indicates address of the host running spell server. val2 ` is not used yet, but in future releases it is going to indicate number of port used by spell server. flag parameter in this case is not needed since ispell data is stored on spellserver already sorted.
Spelld server reads spell-data from a separate configuration file (/usr/local/mnogosearch/etc/spelld.conf by default), sorts it and stores in memory. With clients server communicates in two ways: to indexer all the data is transferred (so that indexer starts faster), from search.cgi server receives word to normalize and then passes over to client (search.cgi) list of normalized word forms. This allows fastest, compared to db and text modes processing of search queries (by omitting loading and sorting all the spell data).
udm_load_ispell_data() function in UDM_ISPELL_TYPE_SERVER mode does not actually load ispell data, but only defines server address. In fact, server is automatically used by udm_find() function when performing search. In case of errors, e.g. if spellserver is not running or invalid host indicated, there are no messages returned and ispell conversion does not work.
Notatka: This function is available in mnoGoSearch 3.1.12 or later.
Example:
udm_set_agent_param() returns TRUE on success, FALSE on error. Defines mnoGoSearch session parameters.
The following parameters and their values are available:
UDM_PARAM_PAGE_NUM - used to choose search results page number (results are returned by pages beginning from 0, with UDM_PARAM_PAGE_SIZE results per page).
UDM_PARAM_PAGE_SIZE - number of search results displayed on one page.
UDM_PARAM_SEARCH_MODE - search mode. The following values available: UDM_MODE_ALL - search for all words; UDM_MODE_ANY - search for any word; UDM_MODE_PHRASE - phrase search; UDM_MODE_BOOL - boolean search. See udm_find() for details on boolean search.
UDM_PARAM_CACHE_MODE - turns on or off search result cache mode. When enabled, the search engine will store search results to disk. In case a similar search is performed later, the engine will take results from the cache for faster performance. Available values: UDM_CACHE_ENABLED, UDM_CACHE_DISABLED.
UDM_PARAM_TRACK_MODE - turns on or off trackquery mode. Since version 3.1.2 mnoGoSearch has a query tracking support. Note that tracking is implemented in SQL version only and not available in built-in database. To use tracking, you have to create tables for tracking support. For MySQL, use create/mysql/track.txt. When doing a search, front-end uses those tables to store query words, a number of found documents and current UNIX timestamp in seconds. Available values: UDM_TRACK_ENABLED, UDM_TRACK_DISABLED.
UDM_PARAM_PHRASE_MODE - defines whether index database using phrases ("phrase" parameter in indexer.conf). Possible values: UDM_PHRASE_ENABLED and UDM_PHRASE_DISABLED. Please note, that if phrase search is enabled (UDM_PHRASE_ENABLED), it is still possible to do search in any mode (ANY, ALL, BOOL or PHRASE). In 3.1.10 version of mnoGoSearch phrase search is supported only in sql and built-in database modes, while beginning with 3.1.11 phrases are supported in cachemode as well.
Examples of phrase search:
"Arizona desert" - This query returns all indexed documents that contain "Arizona desert" as a phrase. Notice that you need to put double quotes around the phrase
UDM_PARAM_CHARSET - defines local charset. Available values: set of charsets supported by mnoGoSearch, e.g. koi8-r, cp1251, ...
UDM_PARAM_STOPFILE - Defines name and path to stopwords file. (There is a small difference with mnoGoSearch - while in mnoGoSearch if relative path or no path entered, it looks for this file in relation to UDM_CONF_DIR, the module looks for the file in relation to current path, i.e. to the path where the php script is executed.)
UDM_PARAM_STOPTABLE - Load stop words from the given SQL table. You may use several StopwordTable commands. This command has no effect when compiled without SQL database support.
UDM_PARAM_WEIGHT_FACTOR - represents weight factors for specific document parts. Currently body, title, keywords, description, url are supported. To activate this feature please use degrees of 2 in *Weight commands of the indexer.conf. Let's imagine that we have these weights:
URLWeight 1
BodyWeight 2
TitleWeight 4
KeywordWeight 8
DescWeight 16
As far as indexer uses bit OR operation for word weights when some word presents several time in the same document, it is possible at search time to detect word appearance in different document parts. Word which appears only in the body will have 00000010 argegate weight (in binary notation). Word used in all document parts will have 00011111 aggregate weight.
This parameter's value is a string of hex digits ABCDE. Each digit is a factor for corresponding bit in word weight. For the given above weights configuration:
E is a factor for weight 1 (URL Weight bit)
D is a factor for weight 2 (BodyWeight bit)
C is a factor for weight 4 (TitleWeight bit)
B is a factor for weight 8 (KeywordWeight bit)
A is a factor for weight 16 (DescWeight bit)
Examples:
UDM_PARAM_WEIGHT_FACTOR=00001 will search through URLs only.
UDM_PARAM_WEIGHT_FACTOR=00100 will search through Titles only.
UDM_PARAM_WEIGHT_FACTOR=11100 will search through Title,Keywords,Description but not through URL and Body.
UDM_PARAM_WEIGHT_FACTOR=F9421 will search through:
Description with factor 15 (F hex)
Keywords with factor 9
Title with factor 4
Body with factor 2
URL with factor 1
If UDM_PARAM_WEIGHT_FACTOR variable is ommited, original weight value is taken to sort results. For a given above weight configuration it means that document description has a most big weight 16.
UDM_PARAM_WORD_MATCH - word match. You may use this parameter to choose word match type. This feature works only in "single" and "multi" modes using SQL based and built-in database. It does not work in cachemode and other modes since they use word CRC and do not support substring search. Available values:
UDM_MATCH_BEGIN - word beginning match;
UDM_MATCH_END - word ending match;
UDM_MATCH_WORD - whole word match;
UDM_MATCH_SUBSTR - word substring match.
UDM_PARAM_MIN_WORD_LEN - defines minimal word length. Any word shorter this limit is considered to be a stopword. Please note that this parameter value is inclusive, i.e. if UDM_PARAM_MIN_WORD_LEN=3, a word 3 characters long will not be considered a stopword, while a word 2 characters long will be. Default value is 1.
UDM_PARAM_ISPELL_PREFIXES - Possible values: UDM_PREFIXES_ENABLED and UDM_PREFIXES_DISABLED, that respectively enable or disable using prefixes. E.g. if a word "tested" is in search query, also words like "test", "testing", etc. Only suffixes are supported by default. Prefixes usually change word meanings, for example if somebody is searching for the word "tested" one hardly wants "untested" to be found. Prefixes support may also be found useful for site's spelling checking purposes. In order to enable ispell, you have to load ispell data with udm_load_ispell_data().
UDM_PARAM_CROSS_WORDS - enables or disables crosswords support. Possible values: UDM_CROSS_WORDS_ENABLED and UDM_CROSS_WORDS_DISABLED.
The corsswords feature allows to assign words between <a href="xxx"> and </a> also to a document this link leads to. It works in SQL database mode and is not supported in built-in database and Cachemode.
Notatka: Crosswords are supported only in mnoGoSearch 3.1.11 or later.
UDM_PARAM_VARDIR - specifies a custom path to directory where indexer stores data when using built-in database and in cache mode. By default /var directory of mnoGoSearch installation is used. Can have only string values. The parameter is available in PHP 4.1.0 or later.
UDM_PARAM_VARDIR - specifies a custom path to directory where indexer stores data when using built-in database and in cache mode. By default /var directory of mnoGoSearch installation is used. Can have only string values. The parameter is available in PHP 4.1.0 or later.
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
These functions allow you to access mSQL database servers. In order to have these functions available, you must compile php with msql support by using the --with-msql[=dir] option. The default location is /usr/local/Hughes.
More information about mSQL can be found at http://www.hughes.com.au/.
Returns a positive mSQL query identifier to the query result, or FALSE on error.
msql() selects a database and executes a query on it. If the optional link identifier isn't specified, the function will try to find an open link to the mSQL server and if no such link is found it'll try to create one as if msql_connect() was called with no arguments (see msql_connect()).
Returns number of affected ("touched") rows by a specific query (i.e. the number of rows returned by a SELECT, the number of rows modified by an update, or the number of rows removed by a delete).
See also: msql_query().
Returns TRUE on success, FALSE on error.
msql_close() closes the link to a mSQL database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.
Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
msql_close() will not close persistent links generated by msql_pconnect().
See also: msql_connect() and msql_pconnect().
Returns a positive mSQL link identifier on success, or FALSE on error.
msql_connect() establishes a connection to a mSQL server. The server parameter can also include a port number. eg. "hostname:port". It defaults to 'localhost'.
In case a second call is made to msql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.
The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling msql_close().
See also msql_pconnect(), msql_close().
msql_create_db() attempts to create a new database on the server associated with the specified link identifier.
See also: msql_drop_db().
Identical to msql_create_db().
Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
msql_data_seek() moves the internal row pointer of the mSQL result associated with the specified query identifier to pointer to the specifyed row number. The next call to msql_fetch_row() would return that row.
See also: msql_fetch_row().
msql_dbname() returns the database name stored in position i of the result pointer returned from the msql_listdbs() function. The msql_numrows() function can be used to determine how many database names are available.
Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
msql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier.
See also: msql_create_db().
Errors coming back from the mSQL database backend no longer issue warnings. Instead, use these functions to retrieve the error string.
Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
msql_fetch_array() is an extended version of msql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.
The second optional argument result_type in msql_fetch_array() is a constant and can take the following values: MSQL_ASSOC, MSQL_NUM, and MSQL_BOTH.
Be careful if you are retrieving results from a query that may return a record that contains only one field that has a value of 0 (or an empty string, or NULL).
An important thing to note is that using msql_fetch_array() is NOT significantly slower than using msql_fetch_row(), while it provides a significant added value.
For further details, also see msql_fetch_row().
Returns an object containing field information
msql_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retreived by msql_fetch_field() is retreived.
The properties of the object are:
name - column name
table - name of the table the column belongs to
not_null - 1 if the column cannot be NULL
primary_key - 1 if the column is a primary key
unique - 1 if the column is a unique key
type - the type of the column
See also msql_field_seek().
Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.
msql_fetch_object() is similar to msql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).
The optional second argument result_type in msql_fetch_array() is a constant and can take the following values: MSQL_ASSOC, MSQL_NUM, and MSQL_BOTH.
Speed-wise, the function is identical to msql_fetch_array(), and almost as quick as msql_fetch_row() (the difference is insignificant).
See also: msql_fetch_array() and msql_fetch_row().
Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
msql_fetch_row() fetches one row of data from the result associated with the specified query identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
Subsequent call to msql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.
See also: msql_fetch_array(), msql_fetch_object(), msql_data_seek(), and msql_result().
msql_fieldname() returns the name of the specified field. query_identifier is the query identifier, and field is the field index. msql_fieldname($result, 2); will return the name of the second field in the result associated with the result identifier.
Seeks to the specified field offset. If the next call to msql_fetch_field() won't include a field offset, this field would be returned.
See also: msql_fetch_field().
Returns the name of the table field was fetched from.
msql_fieldtype() is similar to the msql_fieldname() function. The arguments are identical, but the field type is returned. This will be one of "int", "char" or "real".
msql_fieldflags() returns the field flags of the specified field. Currently this is either, "not NULL", "primary key", a combination of the two or "" (an empty string).
msql_fieldlen() returns the length of the specified field.
msql_free_result() frees the memory associated with query_identifier. When PHP completes a request, this memory is freed automatically, so you only need to call this function when you want to make sure you don't use too much memory while the script is running.
msql_list_fields() retrieves information about the given tablename. Arguments are the database name and the table name. A result pointer is returned which can be used with msql_fieldflags(), msql_fieldlen(), msql_fieldname(), and msql_fieldtype(). A query identifier is a positive integer. The function returns -1 if a error occurs. A string describing the error will be placed in $phperrmsg, and unless the function was called as @msql_list_fields() then this error string will also be printed out.
See also msql_error().
msql_list_dbs() will return a result pointer containing the databases available from the current msql daemon. Use the msql_dbname() function to traverse this result pointer.
msql_list_tables() takes a database name and result pointer much like the msql() function. The msql_tablename() function should be used to extract the actual table names from the result pointer.
msql_num_fields() returns the number of fields in a result set.
See also: msql(), msql_query(), msql_fetch_field(), and msql_num_rows().
msql_num_rows() returns the number of rows in a result set.
See also: msql(), msql_query(), and msql_fetch_row().
Returns a positive mSQL persistent link identifier on success, or FALSE on error.
msql_pconnect() acts very much like msql_connect() with two major differences.
First, when connecting, the function would first try to find a (persistent) link that's already open with the same host. If one is found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (msql_close() will not close links established by msql_pconnect()).
This type of links is therefore called 'persistent'.
msql_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if msql_connect() was called, and use it.
Returns a positive mSQL query identifier on success, or FALSE on error.
Przykład 1. msql_query()
|
See also: msql(), msql_select_db(), and msql_connect().
Returns the contents of the cell at the row and offset in the specified mSQL result set.
msql_result() returns the contents of one cell from a mSQL result set. The field argument can be the field's offset, or the field's name, or the field's table dot field's name (fieldname.tablename). If the column name has been aliased ('select foo as bar from ...'), use the alias instead of the column name.
When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than msql_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.
Recommended high-performance alternatives: msql_fetch_row(), msql_fetch_array(), and msql_fetch_object().
Returns TRUE on success, FALSE on error.
msql_select_db() sets the current active database on the server that's associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if msql_connect() was called, and use it.
Every subsequent call to msql_query() will be made on the active database.
See also: msql_connect(), msql_pconnect(), and msql_query().
msql_tablename() takes a result pointer returned by the msql_list_tables() function as well as an integer index and returns the name of a table. The msql_numrows() function may be used to determine the number of tables in the result pointer.
Funkcje te umożliwiają dostęp do serwerów baz danych MySQL. Aby je uaktywnić musisz skompilować PHP z obsługą MySQL używając opcji --with-mysql. Jeśli użyjesz tej opcji bez podania ścieżki do MySQL, PHP wykorzysta własne biblioteki klienta. Użytkownicy, którzy uruchamiają inne aplikacje korzystające z MySQL (na przykład równocześnie PHP3 i PHP4 jako moduły apache, lub moduł auth-mysql) powinni zawsze podawać ścieżkę do MySQL: --with-mysql=/sciezka/do/mysql. To wymusi na PHP użycie bibliotek zainstalowanych przez MySQL, co pozwoli uniknąć konfliktów.
Więcej informacji o MySQL można znaleźć na stronie http://www.mysql.com/.
Dokumentacja do MySQL znajduje się pod adresem http://www.mysql.com/documentation/.
Zachowanie funkcji MySQL zależy od ustawień w pliku konfiguracyjnym.
Tabela 1. Opcje konfiguracyjne MySQL
Nazwa | Domyślnie | Zmiana |
---|---|---|
mysql.allow_persistent | "On" | PHP_INI_SYSTEM |
mysql.max_persistent | "-1" | PHP_INI_SYSTEM |
mysql.max_links | "-1" | PHP_INI_SYSTEM |
mysql.default_port | NULL | PHP_INI_ALL |
mysql.default_socket | NULL | PHP_INI_ALL |
mysql.default_host | NULL | PHP_INI_ALL |
mysql.default_user | NULL | PHP_INI_ALL |
Ten prosty przykład demonstruje jak się połączyć, wykonać zapytanie, wyświetlić wyniki i rozłączyć z bazą MySQL.
Przykład 1. Wykorzystanie funkcji MySQL
|
(PHP 3, PHP 4 >= 4.0.0)
mysql_affected_rows -- Zwraca ilość wierszy przetworzonych w poprzedniej operacji MySQLmysql_affected_rows() zwraca ilość wierszy przetworzonych w ostatniej operacji INSERT, UPDATE lub DELETE na serwerze skojarzonym z podanym identyfikatorem połączenia. Jeżeli identyfikator połączenia nie został podany, domyślnie wykorzystywane jest ostatnie połączenie otwarte przez mysql_connect().
Notatka: Przy korzystaniu z transakcji, funkcję mysql_affected_rows() należy wywołać po operacjach INSERT, UPDATE lub DELETE, a nie po zatwierdzeniu (commit).
Jeżeli ostatnim zapytaniem było DELETE bez użycia WHERE, wszystkie rekordy zostały usunięte z tabeli, ale funkcja zwróci zero.
Notatka: Podczas operacji UPDATE, MySQL nie aktualizuje kolumn w których nowa wartość jest identyczna z poprzednią. Możliwe jest zatem, że zwrócona przez mysql_affected_rows() liczba nie będzie odpowiadać liczbie wierszy pasujących do zapytania, ale tych, które zostały faktycznie zmienione.
mysql_affected_rows() nie ma zastosowania do operacji SELECT, lecz tylko do operacji, które modyfikują rekordy. Aby uzyskać liczbę wierszy zwróconych przez SELECT, użyj funkcji mysql_num_rows().
Jeśli ostatnie zapytanie nie powiodło się, funkcja zwróci -1.
Patrz także: mysql_num_rows().
mysql_change_user() zmienia użytkownika zalogowanego w aktywnym połączeniu lub w połączeniu, którego identyfikator podano. Jeżeli podano nazwę bazy, zostanie ona ustawiona, w przeciwnym przypadku zostanie ustawiona bieżąca. Jeżeli nowa kombinacja użytkownik/hasło będzie nieprawidłowa, bieżący użytkownik pozostanie aktywny.
Notatka: Tę funkcję dodano w PHP 3.0.13 i wymaga ona MySQL w wersji 3.23.3 lub późniejszej.
Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
mysql_close() zamyka połączenie z serwerem MySQL skojarzone z podanym identyfikatorem połączenia. Jeżeli identyfikator_połączenia nie został podany, domyślnie wykorzystywane jest ostatnie połączenie.
Zwykle nie jest potrzebne używanie mysql_close(), jako że połączenia niestałe są automatycznie zamykane po zakończeniu wykonywania skryptu. Patrz także freeing resources.
Notatka: mysql_close() nie zamyka połączeń stałych nawiązanych za pomocą funkcji mysql_pconnect().
Patrz także: mysql_connect() i mysql_pconnect().
Zwraca identyfikator połączenia w przypadku powodzenia, lub FALSE jeśli wystąpi błąd.
mysql_connect() nawiązuje połączenie z serwerem MySQL. Jeśli nie podano argumentów, przyjmowane są następujące wartości domyślne: serwer = 'localhost:3306', użytkownik = nazwa użytkownika będącego właścicielem procesu serwera, hasło = puste hasło.
Argument serwer może również zawierać numer portu, np. "host:port" lub ścieżkę do gniaza np. ":/sciezka/do/gniazda" dla localhosta.
Notatka: Obsługę ":port" dodano w PHP 3.0B4.
Obsługę ":/sciezka/do/gniazda" dodano w PHP 3.0.10.
Możesz pominąć wyświetlenie komunikatu błędu przy niepowodzeniu poprzedzając nazwę funkcji znakiem '@'.
Przy drugim wywołaniu mysql_connect() z tymi samymi argumentami, nie będzie nawiązywane nowe połączenie, lecz zwrócony zostanie identyfikator już otwartego połączenia.
Połączenie z serwerem zostanie zamknięte zaraz po zakończeniu wykonywania skryptu, chyba że zostanie zamknięte wcześniej przez odpowiednie wywołanie mysql_close().
Patrz także mysql_pconnect() i mysql_close().
mysql_create_db() tworzy nową bazę na serwerze skojarzonym z podanym identyfikatorem połączenia.
Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_createdb(). Jest to jednak niezalecane.
Patrz także: mysql_drop_db().
Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
mysql_data_seek() przesuwa wewnętrzny wskaźnik wiersza wyniku operacji MySQL skojarzony z podanym identyfikatorem wyniku na podany numer wiersza. Następne wywołanie mysql_fetch_row() zwróci ten wiersz.
numer_wiersza liczony jest od 0.
Przykład 1. mysql_data_seek
|
mysql_db_name() przyjmuje jako pierwszy parametr wskaźnik wyniku zwrócony przez mysql_list_dbs(). Parametr wiersz działa jako indeks wyniku.
Jeśli wystąpi błąd, zwrócona zostanie wartość FALSE. Użyj mysql_errno() i mysql_error() by poznać przyczynę błędu.
Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_dbname().
Zwraca dodatni identyfikator wyniku MySQL wskazujący na wynik zapytania, lub FALSE w przypadku błędu.
mysql_db_query() wybiera bazę i wykonuje na niej zapytanie. Jeżeli opcjonalny identyfikator połączenia nie został podany, funkcja będzie próbować znaleźć otwarte połączenie z serwerem MySQL. Jeżeli to się nie powiedzie, będzie próbować je stworzyć tak, jakby wywołane zostało mysql_connect() bez argumentów.
Patrz także: mysql_connect() i mysql_query().
Notatka: Od PHP 4.0.6 odradza sie stosowania tej funkcji. Nie używaj jej. W zamian korzystaj z mysql_select_db() i mysql_query().
Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
mysql_drop_db() usuwa całą bazę z serwera skojarzonego z podanym identyfikatorem połączenia.
Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_dropdb(). Jest to jednak niezalecane.
Patrz także: mysql_create_db().
Zwraca numer błędu ostatniej operacji MySQL lub 0 (zero) jeśli wystąpi błąd.
Błędy pochodzące z klienta bazy MySQL już nie powodują wyświetlania ostrzeżeń. Zamiast tego, użyj mysql_errno() by uzyskać numer błędu. Weź pod uwagę, że ta funkcja zwraca numer błędu z ostatnio użytej funkcji MySQL (wyłączając mysql_error() i mysql_errno()), dlatego jeśli jej używasz, upewnij się, by zrobić to przed użyciem następnej funkcji MySQL.
<?php mysql_connect("serwer","uzytkownik","haslo"); echo mysql_errno().": ".mysql_error()."<BR>"; mysql_select_db("niematakiejbazy"); echo mysql_errno().": ".mysql_error()."<BR>"; $conn = mysql_query("SELECT * FROM niematakiejtabeli"); echo mysql_errno().": ".mysql_error()."<BR>"; ?> |
Patrz także: mysql_error()
Zwraca tekst komunikatu błędu z ostatnio użytej funkcji MySQL, lub '' (pusty łańcuch) jeśli wystąpi błąd.
Błędy pochodzące z klienta bazy MySQL już nie powodują wyświetlania ostrzeżeń. Zamiast tego, użyj mysql_error() by uzyskać komunikat błędu. Weź pod uwagę, że ta funkcja zwraca komunikat błędu z ostatnio użytej funkcji MySQL (wyłączając mysql_error() i mysql_errno()), dlatego jeśli jej używasz, upewnij się, by zrobić to przed użyciem następnej funkcji MySQL.
<?php mysql_connect("serwer","uzytkownik","haslo"); echo mysql_errno().": ".mysql_error()."<BR>"; mysql_select_db("niematakiejbazy"); echo mysql_errno().": ".mysql_error()."<BR>"; $conn = mysql_query("SELECT * FROM niematakiejtabeli"); echo mysql_errno().": ".mysql_error()."<BR>"; ?> |
Patrz także: mysql_errno()
Ta funkcja wstawi znaki unikowe do łańcuch_bez_znaków_unikowych, aby bezpiecznym było umieszczenie go w mysql_query().
Notatka: mysql_escape_string() nie dotyczy znaków % i _.
(PHP 3, PHP 4 >= 4.0.0)
mysql_fetch_array -- Zapisuje wiersz wyniku w tablicy asocjacyjnej, numerycznej lub w obuZwraca tablicę zawierającą pobrany wiersz, lub FALSE jeżeli nie ma więcej wierszy w wynik.
mysql_fetch_array() jest rozszerzoną wersją mysql_fetch_row(). Oprócz zapisywania danych w indeksach numerycznych, zapisuje je też w indeksach przyporządkowujących (asocjacyjnych), używając nazw pól jako kluczy.
Jeżeli dwie lub więcej kolumn wyniku ma te same nazwy, ostatnia kolumna będzie brana pod uwagę. Dostęp do innych kolumn o tej samej nazwie jest możliwy jedynie przez indeksowanie numeryczne lub przez stworzenie aliasa. Po stworzeniu aliasa nie można już odwoływać się do danej kolumny używając jej prawdziwej nazwy (w tym przykładzie używając 'pole').
Godne uwagi jest to, że użycie mysql_fetch_array() nie jest znacząco wolniejsze od użycia mysql_fetch_row(), a jest bardziej funkcjonalne.
Opcjonalny drugi argument result_type w funkcji mysql_fetch_array() jest stałą i może przyjmować następujące wartości: MYSQL_ASSOC, MYSQL_NUM i MYSQL_BOTH. Tę funkcjonalność dodano w PHP 3.0.7. Wartością domyślną jest MYSQL_BOTH.
Używając MYSQL_BOTH otrzymasz tablicę indeksowaną zarówno asocjacyjnie jak i numerycznie. MYSQL_ASSOC dostarczy tablicy indeksowanej tylko asocjacyjnie (jak w mysql_fetch_assoc()), natomiast MYSQL_NUM indeksowanej tylko numerycznie (jak w mysql_fetch_row()).
Po dalsze szczegóły patrz także mysql_fetch_row() i mysql_fetch_assoc().
Przykład 1. mysql_fetch_array()
|
Zwraca tablicę zawierającą pobrany wiersz, lub FALSE jeżeli nie ma więcej wierszy w wynik.
Użycie mysql_fetch_assoc() jest równoznaczne z wywołaniem mysql_fetch_array() podając jako drugi argument MYSQL_ASSOC. Zwraca jedynie tablicę asocjacyjną. Początkowo tak właśnie zachowywała się funkcja mysql_fetch_array(). Jeśli oprócz indeksowania asocjacyjnego potrzebujesz także numeryczne, użyj funkcji mysql_fetch_array().
Jeżeli dwie lub więcej kolumn wyniku ma te same nazwy, ostatnia kolumna będzie brana pod uwagę. Dostęp do innych kolumn o tej samej nazwie jest możliwy przy użyciu funkcji mysql_fetch_array(), która wprowadzi również indeksowanie numeryczne.
Godne uwagi jest to, że użycie mysql_fetch_assoc() nie jest znacząco wolniejsze od użycia mysql_fetch_row(), a jest bardziej funkcjonalne.
Po dalsze szczegóły patrz także mysql_fetch_row() i mysql_fetch_array().
(PHP 3, PHP 4 >= 4.0.0)
mysql_fetch_field -- Pobiera z wyniku informacje o kolumnie i zwraca jako obiektZwraca obiekt zawierający informacje o polu.
mysql_fetch_field() pozwala uzyskać informacje o polach w danym wyniku zapytania. Jeżeli ofset pola nie został podany, zwracane zostanie następne pole nie pobrane jeszcze przez mysql_fetch_field().
Właściwości obiektu:
name - nazwa kolumny
table - nazwa tabeli do której należy kolumna
max_length - maksymalna długość kolumny
not_null - 1 jeżeli pole nie może być puste (NULL)
primary_key - 1 jeżeli kolumna jest kluczem podstawowym
unique_key - 1 jeżeli kolumna jest kluczem unikatowym
multiple_key - 1 jeżeli kolumna jest kluczem nieunikatowym
numeric - 1 jeżeli kolumna jest liczbowa
blob - 1 jeżeli kolumna jest typu BLOOB
type - typ kolumny
unsigned - 1 jeżeli kolumna jest bez znaku (plus lub minus)
zerofill - 1 jeżeli kolumna jest wypełniona zerami
Przykład 1. mysql_fetch_field()
|
Patrz także mysql_field_seek().
Zwraca tablicę zawierającą długość każdego pola z wiersza ostatnio pobranego przez mysql_fetch_row(), lub FALSE, jeżeli wystąpi błąd.
mysql_fetch_lengths() zapisuje w tablicy długości wszystkich pól z ostatniego wiersza pobranego przez funkcje mysql_fetch_row(), mysql_fetch_array() i mysql_fetch_object() zaczynając od ofsetu 0.
Patrz także: mysql_fetch_row().
Zwraca: obiekt, którego właściwości zawierają pobrany wiersz, lub FALSE, jeżeli nie ma więcej wierszy.
Funkcja mysql_fetch_object() jest podobna do mysql_fetch_array() z jedną różnicą - zamiast tablicy zwracany jest obiekt. Oczywiście oznacza to, że dane dostępne są tylko przez podanie nazw pól, a nie przed podanie ofsetu (liczby nie są dopuszczalne jako nazwy właściwości).
Opcjonalny argument result_typ jest stałą i może przyjmować następujące wartości: MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH. Zobacz mysql_fetch_array(), by zapoznać się z opisem tych stałych.
Szybkość tej funkcji jest identyczna jak mysql_fetch_array() i prawie taka sama jak mysql_fetch_row() (różnica jest nieznaczna).
Patrz także: mysql_fetch_array() i mysql_fetch_row().
Zwraca tablicę zawierającą wiersz lub FALSE jeżeli nie ma więcej wierszy w wynik.
mysql_fetch_row() pobiera jeden wiersz danych z wyniku skojarzonego z podanym identyfikatorem wyniku. Wiesz zwracany jest jako tablica. Komórki są umieszczone pod oddzielnymi ofsetami, zaczynając od 0.
Kolejne wywołanie mysql_fetch_row() zwróci następny wiersz z wyniku, lub FALSE jeżeli nie ma więcej wierszy.
Patrz także: mysql_fetch_array(), mysql_fetch_object(), mysql_data_seek(), mysql_fetch_lengths() i mysql_result().
mysql_field_flags() zwraca flagi podanego pola. Flagi są przedstawiane jako pojedyncze słowa oddzielone spacją tak, by można było je rodzielić za pomocą funkcji explode().
Następujące flagi są przedstawiane jeżeli wersja MySQLa jest na tyle aktualna by je obsłużyć: "not_null", "primary_key", "unique_key", "multiple_key", "blob", "unsigned", "zerofill", "binary", "enum", "auto_increment", "timestamp".
Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_fieldflags(). Jest to jednak niezalecane.
mysql_field_name() zwraca nazwę danego pola. wynik musi być poprawnym identyfikatorem wyniku, a indeks_pola powinien zawierać liczbowy indeks pola.
Notatka: indeks_pola liczy się od 0.
Indeksem trzeciego pola będzie liczba 2, czwartego 3 i tak dalej...
Przykład 1. mysql_field_name()
Powyższy przykład da następujący wynik:
|
Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_fieldname(). Jest to jednak niezalecane.
mysql_field_len() zwraca długość danego pola.
Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_fieldlen(). Jest to jednak niezalecane.
Przesuwa się na wybrane pole. Jeżeli kolejne wywołanie mysql_fetch_field() nie będzie zawierać indeksu pola, wtedy zwrócone zostanie to pole.
Patrz także: mysql_fetch_field().
Pobiera nazwę tabeli w której znajduje się dane pole
Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_fieldtable(). Jest to jednak niezalecane.
Funkcja mysql_field_type() jest podobna do mysql_field_name(). Argumenty są identyczne, ale zwracany jest typ pola. Będzie to jeden z "int", "real", "string", "blob" lub innych opisanych w dokumentacji MySQL.
Przykład 1. Typy pól MySQL
|
Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_fieldtype(). Jest to jednak niezalecane.
mysql_free_result() zwolni całą pamięć przydzieloną podanemu wskaźnikowi wyniku.
mysql_free_result() używa się tylko w wypadkach obawy zajęcia zbyt dużej ilości pamięci przez zapytania zwracające duże ilości danych. Cała pamięć przydzielona wynikowi skojarzonemu z podanym identyfikatorem wyniku będzie automatycznie zwolniona.
Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_freeresult(). Jest to jednak niezalecane.
(PHP 3, PHP 4 >= 4.0.0)
mysql_insert_id -- Podaje numer id wygenerowany podczas ostatniej operacji INSERTmysql_insert_id() zwraca ID wygenerowane dla pola z własnością AUTO_INCREMENT. Funkcja zwróci ID wygenerowane automatycznie przez ostatnią operację INSERT używającą podanego identyfikatora_połączenia. Jeżeli identyfikator_połączenia nie został podany, wykorzystywane jest ostatnio otwarte połączenie.
mysql_insert_id() zwróci 0 jeśli ostatnie zapytanie nie generowało wartości AUTO_INCREMENT. Jeśli chcesz przechować zwrócony przez tę funkcję wynik, upewnij się, że wywołujesz ją zaraz po zapytaniu generującym nową wartość.
Notatka: Funkcja MySQL LAST_INSERT_ID() zawsze zawiera ostatnio wygenerowane ID, a zwracana wartośc nie jest czyszczona pomiędzy kolejnymi zapytaniami.
Ostrze¿enie |
mysql_insert_id() konwertuje typ wartości otrzymanej od natywnej funkcji MySQL C API mysql_insert_id() na typ long (czyli int w PHP). Jeśli kolumna AUTO_INCREMENT jest typu BIGINT, wartość zwracana przez mysql_insert_id() będzie niepoprawna. Należy w zapytaniu SQL użyć wewnętrznej funkcji MySQL LAST_INSERT_ID(). |
mysql_list_dbs() zwróci wynik zawierający nazwy baz dostępnych na serwerze skojarzonym z identyfikatorem połączenia. Żeby uzyskać nazwy za wskaźnika wyniku należy użyć funkcji mysql_tablename() lub innej operującej na tablicach wyników.
Notatka: Powyższy kod będzie równie dobrze działał z funkcją mysql_fetch_row() lub innymi podobnymi.
Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_listdbs(). Jest to jednak niezalecane.
Patrz także mysql_db_name().
mysql_list_fields() pobiera informacje o danej tabeli. Argumentami są nazwa bazy i nazwa tabeli. Zwracany jest wskaźnik wyniku, który może zostać użyty z funkcjami mysql_field_flags(), mysql_field_len(), mysql_field_name() i mysql_field_type().
Przykład 1. mysql_list_fields()
Powyższy przykład da następujący wynik:
|
Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_listfields(). Jest to jednak niezalecane.
mysql_list_tables() przyjmuje jako argument nazwę bazy i zwraca wskaźnik wyniku podobnie jak funkcja mysql_db_query(). Żeby uzyskać nazwy tabel za wskaźnika wyniku należy użyć funkcji mysql_tablename() lub innej operującej na tablicach wyników.
Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_listtables(). Jest to jednak niezalecane.
mysql_num_fields() zwraca liczbę pól w wyniku.
Patrz także: mysql_db_query(), mysql_query(), mysql_fetch_field(), mysql_num_rows().
Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_numfields().
mysql_num_rows() zwraca liczbę wierszy w wyniku. Tę funkcję stosuje się tylko do operacji SELECT. Aby pobrać ilość wierszy przetworzonych w operacjach INSERT, UPDATE lub DELETE należy użyć funkcji mysql_affected_rows().
Patrz także: mysql_affected_rows(), mysql_connect(), mysql_select_db() i mysql_query().
Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_numrows(). Jest to jednak niezalecane.
Zwraca identyfikator połączenia w przypadku powodzenia, lub FALSE jeśli wystąpi błąd.
mysql_connect() nawiązuje połączenie z serwerem MySQL. Jeśli nie podano argumentów, przyjmowane są następujące wartości domyślne: host:port = 'localhost:3306', użytkownik = nazwa użytkownika będącego właścicielem procesu serwera, hasło = puste hasło.
Argument host może również zawierać numer portu, np. "host:port" lub ścieżkę do gniaza np. ":/sciezka/do/gniazda" dla localhosta.
Notatka: Obsługę ":port" dodano w PHP 3.0B4.
Obsługę ":/sciezka/do/gniazda" dodano w PHP 3.0.10.
mysql_pconnect() zachowuje się prawie jak mysql_connect() z dwoma zasadniczymi różnicami.
Pierwsza, podczas łączenia funkcja najpierw spróbuje znaleźć połączenie (stałe) już otwarte dla tego samego hosta, użytkownika i hasła. Jeżeli je znajdzie, jego identyfikator zostanie zwrócony zamiast otwierania nowego połączenia.
Druga, połączenie z serwerem SQL nie zostanie zamknięte po zakończeniu wykonywania skryptu. Zamiast tego połączenie pozostanie otwarte do późniejszego użycia (mysql_close() nie zamyka połączeń nawiązanych za pomocą mysql_pconnect()).
Dlatego też ten typ połączeń nazywany jest 'stałym'.
Notatka: Trzeba zaznaczyć, że stałe połączenia działają jedynie z PHP pracującym jako moduł. Przeczytaj rozdział Stałe połączenia z bazami danych by dowiedzieć się więcej.
Ostrze¿enie |
Używanie stałych połączeń może wymagać dostrojenia konfiguracji Apache'a i MySQLa, aby nie przekroczyć limitu jednoczesnych połączeń dozwolonych przez MySQL. |
mysql_query() wysyła zapytanie do aktywnej bazy na serwerze skojarzonym z podanym identyfikatorem połączenia. Jeżeli identyfikator_połączenia nie został podany, wykorzystywane jest ostatnio otwarte połączenie. Jeżeli żadne połączenie nie jest otwarte, podjęta zostanie próba ustanowienia go, poprzez wywołanie mysql_connect() bez argumentów.
Notatka: Zapytanie nie powinno kończyć się znakiem średnika.
mysql_query() zwraca identyfikator wyniku (lub FALSE w przypadku niepowodzenia) jedynie dla zapytań typu SELECT. Dla innych zapytań SQL mysql_query() zwraca TRUE lub FALSE informując czy zapytanie zakończyło się sukcesem czy też nie. Jeśli nie została zwrócona wartość FALSE to znaczy, że zapytanie było prawidłowe i może być wykonane przez serwer. Nie mówi natomiast nic o liczbie przetworzonych lub zwróconych wierszy. Jest również możliwe, że zapytanie zostanie wykonane poprawnie, nie przetwarzając lub zwracając żadnych wierszy.
Następujące zapytanie jest niepoprawne składniowo, dlatego mysql_query() zwróci FALSE:
Następujące zapytanie jest niepoprawne semantycznie, jeżeli my_col nie jest kolumną w tabeli my_tbl, dlatego mysql_query() zwróci FALSE:
mysql_query() zwróci FALSE również wtedy, gdy nie będzie praw dostępu do tabel wyszczególnionych w zapytaniu.
Przyjmując, że zapytanie się powiodło, można użyć mysql_num_rows() by uzyskać informację o liczbie wierszy zwróconych w instrukcji SELECT, lub mysql_affected_rows() w celu uzyskania liczby wierszy przetworzonych przez instrukcje DELETE, INSERT, REPLACE i UPDATE.
Jedynie po operacji SELECT, mysql_query() zwróci identyfikator wyniku, który można przekazać do funkcji mysql_result() lub innych funkcji operujących na tablicach wyników. Po zakończeniu operacji na wyniku, można zwolnić zasoby przez niego wykorzystywane wywołując mysql_free_result(). Po zakończeniu działania skryptu pamięć i tak będzie automatycznie zwolniona.
Patrz także: mysql_num_rows(), mysql_affected_rows(), mysql_unbuffered_query(), mysql_free_result(), mysql_fetch_array(), mysql_fetch_row(), mysql_fetch_assoc(), mysql_result(), mysql_select_db() i mysql_connect().
(PHP 4 >= 4.0.6)
mysql_unbuffered_query -- Wysyła zapytanie do serwera MySQL nie pobierając i buforując wynikumysql_unbuffered_query() wysyła zapytanie SQL do serwera MySQL nie pobierając i buforując wyniku, jak to czyni mysql_query(). Po pierwsze, zauważalnie oszczędza to pamięć, jeśli zapytania SQL generują duże wyniki. Po drugie, można pracować na zbiorze wynikowym już po odebraniu od bazy pierwszego wiersza. Nie trzeba czekać, aż zakończy się działanie zapytania. Przy pracy z kilkoma połączeniami do bazy, należy dodać opcjonalny parametr identyfikator_połączenia.
Notatka: Oprócz korzyści, funkcja mysql_unbuffered_query() wprowadza pewne ograniczenia: nie można użyć funkcji mysql_num_rows() na zbiorze wyników zwróconym przez mysql_unbuffered_query(). Trzeba także pobrać wszystkie wiersze wyniku niebuforowanego zapytania SQL przed wysłaniem kolejnego.
Patrz także: mysql_query().
mysql_result() zwraca zawartość jednej komórki z wyniku. Jako argument pole można podać ofset, nazwę pola lub nazwę tabeli z nazwą pola (tabela.pole). Jeżeli nazwa kolumny została zastąpiona synonimem ('select foo as bar from...'), należy użyć tej nazwy zamiast rzeczywistej.
Przy pracy z dużymi wynikami, powinno się rozważyć użycie jednej z funkcji pobierających cały wiersz (patrz niżej). Jako, że funkcje te zwracają zawartość kilku komórek w jednym wywołaniu, są one ZNACZNIE szybsze niż mysql_result(). Podanie przesunięcia (offset) w argumencie pole jest znacznie szybsze niż podanie nazwy pola lub konstrukcji tabela.pole.
Wywołania mysql_result() nie powinny być mieszane z wywołaniami innych funkcji operujących na wyniku.
Zalecane wydajniejsze akternatywy: mysql_fetch_row(), mysql_fetch_array() i mysql_fetch_object().
Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
mysql_select_db() ustawia aktywną bazę danych na serwerze określonym przez podany identyfikator połączenia. Jeżeli identyfikator nie zostanie podany, wykorzystane zostanie ostatnio otwarte połączenie. Jeżeli żadne połączenie nie jest otwarte, funkcja spróbuje je nawiązać wywołując mysql_connect() bez argumentów.
Kolejne wywołania funkcji mysql_query() będą dotyczyły aktywnej bazy danych.
Patrz także: mysql_connect(), mysql_pconnect() i mysql_query().
Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_selectdb(). Jest to jednak niezalecane.
mysql_tablename() przyjmuje jako parametry wskaźnik wyniku zwrócony przez mysql_list_tables() oraz indeks, zwracając nazwę tabeli. Liczbę tabel zwróconych w wyniku można określić używając funkcji mysql_num_rows().
mysql_get_client_info() zwraca ciąg znaków zawierający wersję bibliotek klienta MySQL.
mysql_get_client_info() dodano w PHP 4.0.5.
mysql_get_host_info() zwraca ciąg znaków opisujący typ połączenia wykorzystywany przez identyfikator_połączenia, włączając to nazwę serwera. Jeżeli identyfikator_połączenia nie zostanie podany, wykorzystane zostanie ostatnio otwarte połączenie.
mysql_get_host_info() dodano w PHP 4.0.5.
mysql_get_proto_info() zwraca wersję protokołu, używanego przez identyfikator_połączenia. Jeżeli identyfikator_połączenia nie zostanie podany, wykorzystane zostanie ostatnio otwarte połączenie.
mysql_get_proto_info() dodano w PHP 4.0.5.
mysql_get_server_info() zwraca wersję serwera, używanego przez identyfikator_połączenia. Jeżeli identyfikator_połączenia nie zostanie podany, wykorzystane zostanie ostatnio otwarte połączenie.
mysql_get_server_info() dodano w PHP 4.0.5.
msession is an interface to a high speed session daemon which can run either locally or remotely. It is designed to provide consistent session management for a PHP web farm.
The session server software can be found at http://www.mohawksoft.com/phoenix.html.
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Returns an associative array of value, session for all sessions with a variable named name.
Used for searching sessions with common attributes.
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
(PHP 4 >= 4.0.5)
muscat_setup -- Creates a new muscat session and returns the handle. Size is the ammount of memory in bytes to allocate for muscat muscat_dir is the muscat installation dir e.g. "/usr/local/empower", it defaults to the compile time muscat directoryOstrze¿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. |
(PHP 4 >= 4.0.5)
muscat_setup_net -- Creates a new muscat session and returns the handle. muscat_host is the hostname to connect to port is the port number to connect to - actually takes exactly the same args as fsockopenOstrze¿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. |
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. |
(PHP 4 >= 4.0.5)
muscat_get -- Gets a line back from the core muscat api. Returns a literal FALSE when there is no more to get (as opposed to ""). Use === FALSE or !== FALSE to check for thisOstrze¿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. |
(PHP 4 >= 4.0.5)
muscat_close -- Shuts down the muscat session and releases any memory back to php. [Not back to the system, note!]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. |
(PHP 3, PHP 4 >= 4.0.0)
checkdnsrr -- Check DNS records corresponding to a given Internet host name or IP addressSearches DNS for records of type type corresponding to host. Returns TRUE if any records are found; returns FALSE if no records were found or if an error occurred.
type may be any one of: A, MX, NS, SOA, PTR, CNAME, or ANY. The default is MX.
Host may either be the IP address in dotted-quad notation or the host name.
Notatka: Ta funkcja nie jest dostępna na platformie Windows.
See also getmxrr(), gethostbyaddr(), gethostbyname(), gethostbynamel(), and the named(8) manual page.
closelog() closes the descriptor being used to write to the system logger. The use of closelog() is optional.
See also define_syslog_variables(), syslog() and openlog().
Disables the internal PHP debugger. The debugger is still under development.
Enables the internal PHP debugger, connecting it to address. The debugger is still under development.
Initializes all constants used in the syslog functions.
See also openlog(), syslog() and closelog().
Initiates a stream connection in the Internet (AF_INET, using TCP or UDP) or Unix (AF_UNIX) domain. For the Internet domain, it will open a TCP socket connection to hostname on port port. hostname may in this case be either a fully qualified domain name or an IP address. For UDP connections, you need to explicitly specify the protocol by prefixing hostname with 'udp://'. For the Unix domain, hostname will be used as the path to the socket, port must be set to 0 in this case. The optional timeout can be used to set a timeout in seconds for the connect system call.
fsockopen() returns a file pointer which may be used together with the other file functions (such as fgets(), fgetss(), fputs(), fclose(), and feof()).
If the call fails, it will return FALSE and if the optional errno and errstr arguments are present they will be set to indicate the actual system level error that occurred in the system-level connect() call. If the value returned in errno is 0 and the function returned FALSE, it is an indication that the error occurred before the connect() call. This is most likely due to a problem initializing the socket. Note that the errno and errstr arguments will always be passed by reference.
Depending on the environment, the Unix domain or the optional connect timeout may not be available.
The socket will by default be opened in blocking mode. You can switch it to non-blocking mode by using socket_set_blocking().
Notatka: The timeout parameter was introduced in PHP 3.0.9 and UDP support was added in PHP 4.
(PHP 3, PHP 4 >= 4.0.0)
gethostbyaddr -- Get the Internet host name corresponding to a given IP addressReturns the host name of the Internet host specified by ip_address. If an error occurs, returns ip_address.
See also gethostbyname().
(PHP 3, PHP 4 >= 4.0.0)
gethostbyname -- Get the IP address corresponding to a given Internet host nameReturns the IP address of the Internet host specified by hostname.
See also gethostbyaddr().
(PHP 3, PHP 4 >= 4.0.0)
gethostbynamel -- Get a list of IP addresses corresponding to a given Internet host nameReturns a list of IP addresses to which the Internet host specified by hostname resolves.
See also gethostbyname(), gethostbyaddr(), checkdnsrr(), getmxrr(), and the named(8) manual page.
Searches DNS for MX records corresponding to hostname. Returns TRUE if any records are found; returns FALSE if no records were found or if an error occurred.
A list of the MX records found is placed into the array mxhosts. If the weight array is given, it will be filled with the weight information gathered.
See also checkdnsrr(), gethostbyname(), gethostbynamel(), gethostbyaddr(), and the named(8) manual page.
getprotobyname() returns the protocol number associated with the protocol name as per /etc/protocols.
See also: getprotobynumber().
getprotobynumber() returns the protocol name associated with protocol number as per /etc/protocols.
See also: getprotobyname().
getservbyname() returns the Internet port which corresponds to service for the specified protocol as per /etc/services. protocol is either TCP or UDP.
See also: getservbyport().
getservbyport() returns the Internet service associated with port for the specified protocol as per /etc/services. protocol is either TCP or UDP.
See also: getservbyname().
(PHP 4 >= 4.0.0)
ip2long -- Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address.The function ip2long() generates an IPv4 Internet network address from its Internet standard format (dotted string) representation.
Notatka: Because PHP's integer type is signed, and many IP addresses will result in negative integers, you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned IP address.
See also: long2ip()
(PHP 4 >= 4.0.0)
long2ip -- Converts an (IPv4) Internet network address into a string in Internet standard dotted formatThe function long2ip() generates an Internet address in dotted format (i.e.: aaa.bbb.ccc.ddd) from the proper address representation.
See also: ip2long()
openlog() opens a connection to the system logger for a program. The string ident is added to each message. Values for option and facility are given below. The option argument is used to indicate what loggin options will be used when generating a log message. The facility argument is used to specify what type of program is logging the message. This allows you to specify (in your machine's syslog configuration) how messages coming from different facilities will be handled. The use of openlog() is optional. It will automatically be called by syslog() if necessary, in which case ident will default to FALSE.
Tabela 1. openlog() Options
Constant | Description |
---|---|
LOG_CONS | if there is an error while sending data to the system logger, write directly to the system console |
LOG_NDELAY | open the connection to the logger immediately |
LOG_ODELAY | (default) delay openning the connection until the first message is logged |
LOG_PERROR | print log message also to standard error |
LOG_PID | include PID with each message |
Tabela 2. openlog() Facilities
Constant | Description |
---|---|
LOG_AUTH | security/authorization messages (use LOG_AUTHPRIV instead in systems where that constant is defined) |
LOG_AUTHPRIV | security/authorization messages (private) |
LOG_CRON | clock daemon (cron and at) |
LOG_DAEMON | other system daemons |
LOG_KERN | kernel messages |
LOG_LOCAL0 ... LOG_LOCAL7 | reserved for local use |
LOG_LPR | line printer subsystem |
LOG_MAIL | mail subsystem |
LOG_NEWS | USENET news subsystem |
LOG_SYSLOG | messages generated internally by syslogd |
LOG_USER | generic user-level messages |
LOG_UUCP | UUCP subsystem |
See also define_syslog_variables(), syslog() and closelog().
(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)
pfsockopen -- Open persistent Internet or Unix domain socket connectionThis function behaves exactly as fsockopen() with the difference that the connection is not closed after the script finishes. It is the persistent version of fsockopen().
Returns information about an existing socket resource. Currently returns four entries in the result array:
timed_out (bool) - The socket timed out waiting for data
blocked (bool) - The socket was blocked
eof (bool) - Indicates EOF event
unread_bytes (int) - Number of bytes left in the socket buffer
See also: socket_accept(), socket_bind(), socket_connect(), socket_listen(), socket_strerror(), and the Socket extension.
If mode is FALSE, the given socket descriptor will be switched to non-blocking mode, and if TRUE, it will be switched to blocking mode. This affects calls like fgets() that read from the socket. In non-blocking mode an fgets() call will always return right away while in blocking mode it will wait for data to become available on the socket.
This function was previously called as set_socket_blocking() but this usage is deprecated.
Sets the timeout value on socket descriptor, expressed in the sum of seconds and microseconds.
This function was previously called as set_socket_timeout() but this usage is deprecated.
See also: fsockopen() and fopen().
syslog() generates a log message that will be distributed by the system logger. priority is a combination of the facility and the level, values for which are given in the next section. The remaining argument is the message to send, except that the two characters %m will be replaced by the error message string (strerror) corresponding to the present value of errno.
Tabela 1. syslog() Priorities (in descending order)
Constant | Description |
---|---|
LOG_EMERG | system is unusable |
LOG_ALERT | action must be taken immediately |
LOG_CRIT | critical conditions |
LOG_ERR | error conditions |
LOG_WARNING | warning conditions |
LOG_NOTICE | normal, but significant, condition |
LOG_INFO | informational message |
LOG_DEBUG | debug-level message |
Przykład 1. Using syslog()
|
On Windows NT, the syslog service is emulated using the Event Log.
See also define_syslog_variables(), openlog() and closelog().
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. |
ncurses (new curses) is a free software emulation of curses in System V Rel 4.0 (and above). It uses terminfo format, supports pads, colors, multiple highlights, form characters and function key mapping.
Ncurses is available for the following platforms:
AIX
BeOS
Cygwin
Digital Unix (aka OSF1)
FreeBSD
GNU/Linux
HPUX
IRIX
OS/2
SCO OpenServer
Solaris
SunOS
You need the ncurses libraries and headerfiles. Download the latest version from the ftp://ftp.gnu.org/pub/gnu/ncurses/ or from an other GNU-Mirror.
To get these functions to work, you have to compile the CGI version of PHP with --with-ncurses.
On error ncurses functions return NCURSES_ERR.
Tabela 1. ncurses color constants
constant | meaning |
---|---|
NCURSES_COLOR_BLACK | no color (black) |
NCURSES_COLOR_WHITE | white |
NCURSES_COLOR_RED | red - supported when terminal is in color mode |
NCURSES_COLOR_GREEN | green - supported when terminal is in color mod |
NCURSES_COLOR_YELLOW | yellow - supported when terminal is in color mod |
NCURSES_COLOR_BLUE | blue - supported when terminal is in color mod |
NCURSES_COLOR_CYAN | cyan - supported when terminal is in color mod |
NCURSES_COLOR_MAGENTA | magenta - supported when terminal is in color mod |
Tabela 2. ncurses key constants
constant | meaning |
---|---|
NCURSES_KEY_F0 - NCURSES_KEY_F64 | function keys F1 - F64 |
NCURSES_KEY_DOWN | down arrow |
NCURSES_KEY_UP | up arrow |
NCURSES_KEY_LEFT | left arrow |
NCURSES_KEY_RIGHT | right arrow |
NCURSES_KEY_HOME | home key (upward+left arrow) |
NCURSES_KEY_BACKSPACE | backspace |
NCURSES_KEY_DL | delete line |
NCURSES_KEY_IL | insert line |
NCURSES_KEY_DC | delete character |
NCURSES_KEY_IC | insert char or enter insert mode |
NCURSES_KEY_EIC | exit insert char mode |
NCURSES_KEY_CLEAR | clear screen |
NCURSES_KEY_EOS | clear to end of screen |
NCURSES_KEY_EOL | clear to end of line |
NCURSES_KEY_SF | scroll one line forward |
NCURSES_KEY_SR | scroll one line backward |
NCURSES_KEY_NPAGE | next page |
NCURSES_KEY_PPAGE | previous page |
NCURSES_KEY_STAB | set tab |
NCURSES_KEY_CTAB | clear tab |
NCURSES_KEY_CATAB | clear all tabs |
NCURSES_KEY_SRESET | soft (partial) reset |
NCURSES_KEY_RESET | reset or hard reset |
NCURSES_KEY_PRINT | |
NCURSES_KEY_LL | lower left |
NCURSES_KEY_A1 | upper left of keypad |
NCURSES_KEY_A3 | upper right of keypad |
NCURSES_KEY_B2 | center of keypad |
NCURSES_KEY_C1 | lower left of keypad |
NCURSES_KEY_C3 | lower right of keypad |
NCURSES_KEY_BTAB | back tab |
NCURSES_KEY_BEG | beginning |
NCURSES_KEY_CANCEL | cancel |
NCURSES_KEY_CLOSE | close |
NCURSES_KEY_COMMAND | cmd (command) |
NCURSES_KEY_COPY | copy |
NCURSES_KEY_CREATE | create |
NCURSES_KEY_END | end |
NCURSES_KEY_EXIT | exit |
NCURSES_KEY_FIND | find |
NCURSES_KEY_HELP | help |
NCURSES_KEY_MARK | mark |
NCURSES_KEY_MESSAGE | message |
NCURSES_KEY_MOVE | move |
NCURSES_KEY_NEXT | next |
NCURSES_KEY_OPEN | open |
NCURSES_KEY_OPTIONS | options |
NCURSES_KEY_PREVIOUS | previous |
NCURSES_KEY_REDO | redo |
NCURSES_KEY_REFERENCE | ref (reference) |
NCURSES_KEY_REFRESH | refresh |
NCURSES_KEY_REPLACE | replace |
NCURSES_KEY_RESTART | restart |
NCURSES_KEY_RESUME | resume |
NCURSES_KEY_SAVE | save |
NCURSES_KEY_SBEG | shiftet beg (beginning) |
NCURSES_KEY_SCANCEL | shifted cancel |
NCURSES_KEY_SCOMMAND | shifted command |
NCURSES_KEY_SCOPY | shifted copy |
NCURSES_KEY_SCREATE | shifted create |
NCURSES_KEY_SDC | shifted delete char |
NCURSES_KEY_SDL | shifted delete line |
NCURSES_KEY_SELECT | select |
NCURSES_KEY_SEND | shifted end |
NCURSES_KEY_SEOL | shifted end of line |
NCURSES_KEY_SEXIT | shifted exit |
NCURSES_KEY_SFIND | shifted find |
NCURSES_KEY_SHELP | shifted help |
NCURSES_KEY_SHOME | shifted home |
NCURSES_KEY_SIC | shifted input |
NCURSES_KEY_SLEFT | shifted left arrow |
NCURSES_KEY_SMESSAGE | shifted message |
NCURSES_KEY_SMOVE | shifted move |
NCURSES_KEY_SNEXT | shifted next |
NCURSES_KEY_SOPTIONS | shifted options |
NCURSES_KEY_SPREVIOUS | shifted previous |
NCURSES_KEY_SPRINT | shifted print |
NCURSES_KEY_SREDO | shifted redo |
NCURSES_KEY_SREPLACE | shifted replace |
NCURSES_KEY_SRIGHT | shifted right arrow |
NCURSES_KEY_SRSUME | shifted resume |
NCURSES_KEY_SSAVE | shifted save |
NCURSES_KEY_SSUSPEND | shifted suspend |
NCURSES_KEY_UNDO | undo |
NCURSES_KEY_MOUSE | mouse event has occured |
NCURSES_KEY_MAX | maximum key value |
Tabela 3. mouse constants
Constant | meaning |
---|---|
NCURSES_BUTTON1_RELEASED - NCURSES_BUTTON4_RELEASED | button (1-4) released |
NCURSES_BUTTON1_PRESSED - NCURSES_BUTTON4_PRESSED | button (1-4) pressed |
NCURSES_BUTTON1_CLICKED - NCURSES_BUTTON4_CLICKED | button (1-4) clicked |
NCURSES_BUTTON1_DOUBLE_CLICKED - NCURSES_BUTTON4_DOUBLE_CLICKED | button (1-4) double clicked |
NCURSES_BUTTON1_TRIPLE_CLICKED - NCURSES_BUTTON4_TRIPLE_CLICKED | button (1-4) triple clicked |
NCURSES_BUTTON_CTRL | ctrl pressed during click |
NCURSES_BUTTON_SHIFT | shift pressed during click |
NCURSES_BUTTON_ALT | alt pressed during click |
NCURSES_ALL_MOUSE_EVENTS | report all mouse events |
NCURSES_REPORT_MOUSE_POSITION | report mouse position |
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 ncurses_can_change_color() returns TRUE or FALSE, depending on whether the terminal has color capabilities and whether the programmer can change the colors.
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. |
ncurses_cbreak() disables line buffering and character processing (interrupt and flow control characters are unaffected), making characters typed by the user immediately available to the program.
ncurses_cbreak() returns TRUE or NCURSES_ERR if any error occured.
See also: ncurses_nocbreak()
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. |
ncurses_clear() clears the screen completely without setting blanks. Returns FALSE on success, otherwise TRUE.
Note: ncurses_clear() clears the screen without setting blanks, which have the current background rendition. To clear screen with blanks, use ncurses_erase().
See also: ncurses_erase()
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. |
ncurses_clrtobot() erases all lines from cursor to end of screen and creates blanks. Blanks created by ncurses_clrtobot() have the current background rendition. Returns TRUE if any error occured, otherwise FALSE.
See also: ncurses_clear(), ncurses_clrtoeol()
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. |
ncurses_clrtoeol() erases the current line from cursor position to the end. Blanks created by ncurses_clrtoeol() have the current background rendition. Returns TRUE if any error occured, otherwise FALSE.
See also: ncurses_clear(), ncurses_clrtobot()
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. |
ncurses_def_prog_mode() saves the current terminal modes for program (in curses) for use by ncurses_reset_prog_mode(). Returns FALSE on success, otherwise TRUE.
See also: ncurses_reset_prog_mode()
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. |
ncurses_def_shell_mode() saves the current terminal modes for shell (not in curses) for use by ncurses_reset_shell_mode(). Returns FALSE on success, otherwise TRUE.
See also: ncurses_reset_shell_mode()
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. |
ncurses_delch() deletes the character under the cursor. All characters to the right of the cursor on the same line are moved to the left one position and the last character on the line is filled with a blank. The cursor position does not change. Returns FALSE on success, otherwise TRUE.
See also: ncurses_deleteln()
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. |
ncurses_deleteln() deletes the current line under cursorposition. All lines below the current line are moved up one line. The bottom line of window is cleared. Cursor position does not change. Returns FALSE on success, otherwise TRUE.
See also: ncurses_delch()
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. |
ncurses_doupdate()() compares the virtual screen to the physical screen and updates the physical screen. This way is more effective than using multiple refresh calls. Returns FALSE on success, TRUE if any error occured.
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. |
ncurses_echo() enables echo mode. All characters typed by user are echoed by ncurses_getch(). Returns FALSE on success, TRUE if any error occured.
To disable echo mode use ncurses_noecho().
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. |
ncurses_erase() fills the terminal screen with blanks. Created blanks have the current background rendition, set by ncurses_bkgd(). Returns FALSE on success, TRUE if any error occured.
See also: ncurses_bkgd(), ncurses_clear()
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. |
ncurses_erasechar() returns the current erase char character.
See also: ncurses_killchar()
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. |
ncurses_flash() flashes the screen, and if its not possible, sends an audible alert (bell). Returns FALSE on success, otherwise TRUE.
See also: ncurses_beep()
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 ncurses_flushinp() throws away any typeahead that has been typed and has not yet been read by your program. Returns FALSE on success, otherwise TRUE.
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. |
ncurses_has_colors() returns TRUE or FALSE depending on whether the terminal has color capacitites.
See also: ncurses_can_change_color()
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. |
ncurses_has_ic() checks terminals insert- and delete capabilitites. It returns TRUE when terminal has insert/delete-capabilities, otherwise FALSE.
See also: ncurses_has_il()
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. |
ncurses_has_il() checks terminals insert- and delete-line-capabilities. It returns TRUE when terminal has insert/delete-line capabilities, otherwise FALSE
See also: ncurses_has_ic()
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. |
ncurses_inch() returns the character from the current position.
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. |
ncurses_insertln() inserts a new line above the current line. The bottom line will be lost.
(PHP 4 >= 4.1.0)
ncurses_isendwin -- Ncurses is in endwin mode, normal screen output may be performedOstrze¿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. |
ncurses_isendwin() returns TRUE, if ncurses_endwin() has been called without any subsequent calls to ncurses_wrefresh(), otherwise FALSE.
See also: ncurses_endwin() ncurses_wrefresh()()
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. |
ncurses_killchar() returns the current line kill character.
See also: ncurses_erasechar()
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. |
undocumented
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. |
ncurses_nocbreak() routine returns terminal to normal (cooked) mode. Initially the terminal may or may not in cbreak mode as the mode is inherited. Therefore a program should call ncurses_cbreak() and ncurses_nocbreak() explicitly. Returns TRUE if any error occured, otherwise FALSE.
See also: ncurses_cbreak()
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. |
ncurses_noecho() prevents echoing of user typed characters. Returns TRUE if any error occured, otherwise FALSE.
See also: ncurses_echo(), ncurses_getch()
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. |
undocumented
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. |
ncurses_noraw() switches the terminal out of raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences that are that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal. Returns TRUE if any error occured, otherwise FALSE.
See also: ncurses_raw(), ncurses_cbreak(), ncurses_nocbreak()
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. |
ncurses_raw() places the terminal in raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences that are that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal. Returns TRUE if any error occured, otherwise FALSE.
See also: ncurses_noraw(), ncurses_cbreak(), ncurses_nocbreak()
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. |
Function ncurses_resetty() restores the terminal state, which was previously saved by calling ncurses_savetty(). This function always returns FALSE.
See also: ncurses_savetty()
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. |
Function ncurses_savetty() saves the current terminal state. The saved terminal state can be restored with function ncurses_resetty(). ncurses_savetty() always returns FALSE.
See also: ncurses_resetty()
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. |
Funtion ncurses_slk_init() must be called before ncurses_initscr() or ncurses_newterm() is called. If ncurses_initscr() eventually uses a line from stdscr to emulate the soft labels, then format determines how the labels are arranged of the screen. Setting format to 0 indicates a 3-2-3 arrangement of the labels, 1 indicates a 4-4 arrangement and 2 indicates the PC like 4-4-4 mode, but in addition an index line will be created.
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. |
ncurses_slk_attr() returns the current soft label key attribute. On error returns TRUE, otherwise FALSE.
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 ncurses_slk_clear() clears soft label keys from screen. Returns TRUE on error, otherwise FALSE.
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. |
undocumented
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. |
ncurses_slk_refresh() copies soft label keys from virtual screen to physical screen. Returns TRUE on error, otherwise FALSE.
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 ncurses_slk_restore() restores the soft label keys after ncurses_slk_clear() has been performed.
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 ncurses_slk_touch() function forces all the soft labels to be output the next time a ncurses_slk_noutrefresh() is performed.
(PHP 4 >= 4.1.0)
ncurses_termattrs -- Returns a logical OR of all attribute flags supported by terminalOstrze¿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. |
undocumented
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. |
undocumented
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. |
undocumented
(PHP 4 CVS only)
ncurses_addchnstr -- Add attributed string with specified length at current positionOstrze¿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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
ncurses_beep() sends an audlible alert (bell) and if its not possible flashes the screen. Returns FALSE on success, otherwise TRUE.
See also: ncurses_flash()
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
(PHP 4 CVS only)
ncurses_hline -- Draw a horizontal line at current position using an attributed character and max. n characters longOstrze¿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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
(PHP 4 >= 4.1.0)
ncurses_insch -- Insert character moving rest of line including character at current positionOstrze¿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. |
undocumented
(PHP 4 >= 4.1.0)
ncurses_insdelln -- Insert lines before current line scrolling down (negative numbers delete and scroll up)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. |
undocumented
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. |
undocumented
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. |
ncurses_instr() returns the number of charaters read from the current character position until end of line. buffer contains the characters. Atrributes are stripped from the characters.
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
(PHP 4 CVS only)
ncurses_mvaddchnstr -- Move position and add attrributed string with specified lengthOstrze¿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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
(PHP 4 CVS only)
ncurses_mvhline -- Set new position and draw a horizontal line using an attributed character and max. n characters longOstrze¿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. |
undocumented
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. |
undocumented
(unknown)
ncurses_mvvline -- Set new position and draw a vertical line using an attributed character and max. n characters longOstrze¿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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
(PHP 4 >= 4.1.0)
ncurses_use_extended_names -- Control use of extended names in terminfo descriptionsOstrze¿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. |
undocumented
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. |
undocumented
(PHP 4 CVS only)
ncurses_vline -- Draw a vertical line at current position using an attributed character and max. n characters longOstrze¿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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
undocumented
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. |
ncurses_termname() returns terminals shortname. The shortname is truncated to 14 characters. On error ncurses_termname() returns NULL.
See also: ncurses_longname()
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. |
ncurses_longname() returns a verbose description of the terminal. The descritpion is truncated to 128 characters. On Error ncurses_longname() returns NULL.
See also: ncurses_termname()
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. |
Function ncurses_mousemask() will set mouse events to be reported. By default no mouse events will be reported. The function ncurses_mousemask() will return a mask to indicated which of the in parameter newmask specified mouse events can be reported. On complete failure, it returns 0. In parameter oldmask, which is passed by reference ncurses_mousemask() returns the previous value of mouse event mask. Mouse events are represented bei NCURSES_KEY_MOUSE in the ncurses_wgetch() input stream. To read the event data and pop the event of of queue, call ncurses_getmouse().
As a side effect, setting a zero mousemask in newmask turns off the mouse pointer. Setting a non zero value turns mouse pointer on.
mouse mask options can be set with the following predefined constants:
NCURSES_BUTTON1_PRESSED
NCURSES_BUTTON1_RELEASED
NCURSES_BUTTON1_CLICKED
NCURSES_BUTTON1_DOUBLE_CLICKED
NCURSES_BUTTON1_TRIPLE_CLICKED
NCURSES_BUTTON2_PRESSED
NCURSES_BUTTON2_RELEASED
NCURSES_BUTTON2_CLICKED
NCURSES_BUTTON2_DOUBLE_CLICKED
NCURSES_BUTTON2_TRIPLE_CLICKED
NCURSES_BUTTON3_PRESSED
NCURSES_BUTTON3_RELEASED
NCURSES_BUTTON3_CLICKED
NCURSES_BUTTON3_DOUBLE_CLICKED
NCURSES_BUTTON3_TRIPLE_CLICKED
NCURSES_BUTTON4_PRESSED
NCURSES_BUTTON4_RELEASED
NCURSES_BUTTON4_CLICKED
NCURSES_BUTTON4_DOUBLE_CLICKED
NCURSES_BUTTON4_TRIPLE_CLICKED
NCURSES_BUTTON_SHIFT>
NCURSES_BUTTON_CTRL
NCURSES_BUTTON_ALT
NCURSES_ALL_MOUSE_EVENTS
NCURSES_REPORT_MOUSE_POSITION
See also: ncurses_getmouse(), ncurses_ungetmouse() ncurese_getch()
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. |
ncurses_getmouse() reads mouse event out of queue. Function ncurses_getmouse() will return ;FALSE if a mouse event is actually visible in the given window, otherwise it will return TRUE. Event options will be delivered in parameter mevent, which has to be an array, passed by reference (see example below). On success an associative array with following keys will be delivered:
"id" : Id to distinguish multiple devices
"x" : screen relative x-position in character cells
"y" : screen relative y-position in character cells
"z" : currently not supported
"mmask" : Mouse action
See also: ncurses_ungetmouse()
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. |
ncurses_getmouse() pushes a KEY_MOUSE event onto the unput queue and associates with this event the given state sata and screen-relative character cell coordinates, specified in mevent. Event options will be specified in associative array mevent:
"id" : Id to distinguish multiple devices
"x" : screen relative x-position in character cells
"y" : screen relative y-position in character cells
"z" : currently not supported
"mmask" : Mouse action
ncurses_ungetmouse() returns FALSE on success, otherwise TRUE.
See also: ncurses_getmouse()
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. |
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. |
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. |
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. |
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. |
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. |
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. |
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. |
(PHP 4 >= 4.0.5)
notes_header_info -- Open the message msg_number in the specified mailbox on the specified server (leave servOstrze¿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. |
(PHP 4 >= 4.0.5)
notes_body -- Open the message msg_number in the specified mailbox on the specified server (leave servOstrze¿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. |
(PHP 4 >= 4.0.5)
notes_find_note -- Returns a note id found in database_name. Specify the name of the note. Leaving type blaOstrze¿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. |
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. |
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. |
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. |
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. |
In addition to normal ODBC support, the Unified ODBC functions in PHP allow you to access several databases that have borrowed the semantics of the ODBC API to implement their own API. Instead of maintaining multiple database drivers that were all nearly identical, these drivers have been unified into a single set of ODBC functions.
The following databases are supported by the Unified ODBC functions: Adabas D, IBM DB2, iODBC, Solid, and Sybase SQL Anywhere.
Notatka: There is no ODBC involved when connecting to the above databases. The functions that you use to speak natively to them just happen to share the same names and syntax as the ODBC functions. The exception to this is iODBC. Building PHP with iODBC support enables you to use any ODBC-compliant drivers with your PHP applications. iODBC is maintained by OpenLink Software. More information on iODBC, as well as a HOWTO, is available at www.iodbc.org.
Without the OnOff parameter, this function returns auto-commit status for connection_id. TRUE is returned if auto-commit is on, FALSE if it is off or an error occurs.
If OnOff is TRUE, auto-commit is enabled, if it is FALSE auto-commit is disabled. Returns TRUE on success, FALSE on failure.
By default, auto-commit is on for a connection. Disabling auto-commit is equivalent with starting a transaction.
See also odbc_commit() and odbc_rollback().
(ODBC SQL types affected: BINARY, VARBINARY, LONGVARBINARY)
ODBC_BINMODE_PASSTHRU: Passthru BINARY data
ODBC_BINMODE_RETURN: Return as is
ODBC_BINMODE_CONVERT: Convert to char and return
When binary SQL data is converted to character C data, each byte (8 bits) of source data is represented as two ASCII characters. These characters are the ASCII character representation of the number in its hexadecimal form. For example, a binary 00000001 is converted to "01" and a binary 11111111 is converted to "FF".
Tabela 1. LONGVARBINARY handling
binmode | longreadlen | result |
---|---|---|
ODBC_BINMODE_PASSTHRU | 0 | passthru |
ODBC_BINMODE_RETURN | 0 | passthru |
ODBC_BINMODE_CONVERT | 0 | passthru |
ODBC_BINMODE_PASSTHRU | 0 | passthru |
ODBC_BINMODE_PASSTHRU | >0 | passthru |
ODBC_BINMODE_RETURN | >0 | return as is |
ODBC_BINMODE_CONVERT | >0 | return as char |
If odbc_fetch_into() is used, passthru means that an empty string is returned for these columns.
If result_id is 0, the settings apply as default for new results.
Notatka: Default for longreadlen is 4096 and binmode defaults to ODBC_BINMODE_RETURN. Handling of binary long columns is also affected by odbc_longreadlen()
odbc_close() will close down the connection to the database server associated with the given connection identifier.
Notatka: This function will fail if there are open transactions on this connection. The connection will remain open in this case.
odbc_close_all() will close down all connections to database server(s).
Notatka: This function will fail if there are open transactions on a connection. This connection will remain open in this case.
Returns: TRUE on success, FALSE on failure. All pending transactions on connection_id are committed.
Returns an ODBC connection id or 0 (FALSE) on error.
The connection id returned by this functions is needed by other ODBC functions. You can have multiple connections open at once. The optional fourth parameter sets the type of cursor to be used for this connection. This parameter is not normally needed, but can be useful for working around problems with some ODBC drivers.
With some ODBC drivers, executing a complex stored procedure may fail with an error similar to: "Cannot open a cursor on a stored procedure that has anything other than a single select statement in it". Using SQL_CUR_USE_ODBC may avoid that error. Also, some drivers don't support the optional row_number parameter in odbc_fetch_row(). SQL_CUR_USE_ODBC might help in that case, too.
The following constants are defined for cursortype:
SQL_CUR_USE_IF_NEEDED
SQL_CUR_USE_ODBC
SQL_CUR_USE_DRIVER
SQL_CUR_DEFAULT
For persistent connections see odbc_pconnect().
odbc_cursor will return a cursorname for the given result_id.
odbc_do() will execute a query on the given connection.
Returns a six-digit ODBC state, or an empty string if there has been no errors. If connection_id is specified, the last state of that connection is returned, else the last state of any connection is returned.
See also: odbc_errormsg() and odbc_exec().
Returns a string containing the last ODBC error message, or an empty string if there has been no errors. If connection_id is specified, the last state of that connection is returned, else the last state of any connection is returned.
See also: odbc_error() and odbc_exec().
Returns FALSE on error. Returns an ODBC result identifier if the SQL command was executed successfully.
odbc_exec() will send an SQL statement to the database server specified by connection_id. This parameter must be a valid identifier returned by odbc_connect() or odbc_pconnect().
See also: odbc_prepare() and odbc_execute() for multiple execution of SQL statements.
Executes a statement prepared with odbc_prepare(). Returns TRUE on successful execution; FALSE otherwise. The array parameters_array only needs to be given if you really have parameters in your statement.
Parameters in parameter_array will be substituted for placeholders in the prepared statement in order.
Any parameters in parameter_array which start and end with single quotes will be taken as the name of a file to read and send to the database server as the data for the appropriate placeholder.
Notatka: As of PHP 4.1.1, this file reading functionality has the following restrictions:
File reading is not subject to any safe mode restrictions.
Remote files are not supported.
If you wish to store a string which actually begins and ends with single quotes, you must escape them or add a space or other non-single-quote character to the beginning or end of the parameter, which will prevent the parameter's being taken as a file name. If this is not an option, then you must use another mechanism to store the string, such as executing the query directly with odbc_exec()).
Returns the number of columns in the result; FALSE on error. result_array must be passed by reference, but it can be of any type since it will be converted to type array. The array will contain the column values starting at array index 0.
As of PHP 4.0.5 the result_array does not need to be passed by reference any longer.
As of PHP 4.0.6 the rownumber cannot be passed as a constant, but rather as a variable.
Future: In PHP 4.1, this function will be moved to the following format: int odbc_fetch_into ( int result_id, array result_array [, int rownumber]) Please note, that rownumber will be optional, while result_array is not.
If odbc_fetch_row() was succesful (there was a row), TRUE is returned. If there are no more rows, FALSE is returned.
odbc_fetch_row() fetches a row of the data that was returned by odbc_do() / odbc_exec(). After odbc_fetch_row() is called, the fields of that row can be accessed with odbc_result().
If row_number is not specified, odbc_fetch_row() will try to fetch the next row in the result set. Calls to odbc_fetch_row() with and without row_number can be mixed.
To step through the result more than once, you can call odbc_fetch_row() with row_number 1, and then continue doing odbc_fetch_row() without row_number to review the result. If a driver doesn't support fetching rows by number, the row_number parameter is ignored.
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
odbc_field_name() will return the name of the field occupying the given column number in the given ODBC result identifier. Field numbering starts at 1. FALSE is returned on error.
odbc_field_num() will return the number of the column slot that corresponds to the named field in the given ODBC result identifier. Field numbering starts at 1. FALSE is returned on error.
odbc_field_type() will return the SQL type of the field referecend by number in the given ODBC result identifier. Field numbering starts at 1.
odbc_field_len() will return the length of the field referecend by number in the given ODBC result identifier. Field numbering starts at 1.
See also: odbc_field_scale() to get the scale of a floating point number.
odbc_field_precision() will return the precision of the field referecend by number in the given ODBC result identifier.
See also: odbc_field_scale() to get the scale of a floating point number.
odbc_field_precision() will return the scale of the field referecend by number in the given ODBC result identifier.
Always returns TRUE.
odbc_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script is finished. But, if you are sure you are not going to need the result data anymore in a script, you may call odbc_free_result(), and the memory associated with result_id will be freed.
Notatka: If auto-commit is disabled (see odbc_autocommit()) and you call odbc_free_result() before commiting, all pending transactions are rolled back.
(ODBC SQL types affected: LONG, LONGVARBINARY) The number of bytes returned to PHP is controled by the parameter length. If it is set to 0, Long column data is passed thru to the client.
Notatka: Handling of LONGVARBINARY columns is also affected by odbc_binmode().
odbc_num_fields() will return the number of fields (columns) in an ODBC result. This function will return -1 on error. The argument is a valid result identifier returned by odbc_exec().
Returns an ODBC connection id or 0 (FALSE) on error. This function is much like odbc_connect(), except that the connection is not really closed when the script has finished. Future requests for a connection with the same dsn, user, password combination (via odbc_connect() and odbc_pconnect()) can reuse the persistent connection.
Notatka: Persistent connections have no effect if PHP is used as a CGI program.
For information about the optional cursor_type parameter see the odbc_connect() function. For more information on persistent connections, refer to the PHP FAQ.
Returns FALSE on error.
Returns an ODBC result identifier if the SQL command was prepared successfully. The result identifier can be used later to execute the statement with odbc_execute().
odbc_num_rows() will return the number of rows in an ODBC result. This function will return -1 on error. For INSERT, UPDATE and DELETE statements odbc_num_rows() returns the number of rows affected. For a SELECT clause this can be the number of rows available.
Note: Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.
Returns the contents of the field.
field can either be an integer containing the column number of the field you want; or it can be a string containing the name of the field. For example:
The first call to odbc_result() returns the value of the third field in the current record of the query result. The second function call to odbc_result() returns the value of the field whose field name is "val" in the current record of the query result. An error occurs if a column number parameter for a field is less than one or exceeds the number of columns (or fields) in the current record. Similarly, an error occurs if a field with a name that is not one of the fieldnames of the table(s) that is(are) being queried.
Field indices start from 1. Regarding the way binary or long column data is returned refer to odbc_binmode() and odbc_longreadlen().
Returns the number of rows in the result or FALSE on error.
odbc_result_all() will print all rows from a result identifier produced by odbc_exec(). The result is printed in HTML table format. With the optional string argument format, additional overall table formatting can be done.
Rolls back all pending statements on connection_id. Returns TRUE on success, FALSE on failure.
(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)
odbc_setoption -- Adjust ODBC settings. Returns FALSE if an error occurs, otherwise TRUE.This function allows fiddling with the ODBC options for a particular connection or query result. It was written to help find work arounds to problems in quirky ODBC drivers. You should probably only use this function if you are an ODBC programmer and understand the effects the various options will have. You will certainly need a good ODBC reference to explain all the different options and values that can be used. Different driver versions support different options.
Because the effects may vary depending on the ODBC driver, use of this function in scripts to be made publicly available is strongly discouraged. Also, some ODBC options are not available to this function because they must be set before the connection is established or the query is prepared. However, if on a particular job it can make PHP work so your boss doesn't tell you to use a commercial product, that's all that really matters.
ID is a connection id or result id on which to change the settings.For SQLSetConnectOption(), this is a connection id. For SQLSetStmtOption(), this is a result id.
Function is the ODBC function to use. The value should be 1 for SQLSetConnectOption() and 2 for SQLSetStmtOption().
Parameter option is the option to set.
Parameter param is the value for the given option.
Przykład 1. ODBC Setoption Examples
|
(PHP 3>= 3.0.17, PHP 4 >= 4.0.0)
odbc_tables -- Get the list of table names stored in a specific data source. Returns a result identifier containing the information.Lists all tables in the requested range. Returns an ODBC result identifier or FALSE on failure.
The result set has the following columns:
TABLE_QUALIFIER
TABLE_OWNER
TABLE_NAME
TABLE_TYPE
REMARKS
The result set is ordered by TABLE_TYPE, TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.
The owner and name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).
To support enumeration of qualifiers, owners, and table types, the following special semantics for the qualifier, owner, name, and table_type are available:
If qualifier is a single percent character (%) and owner and name are empty strings, then the result set contains a list of valid qualifiers for the data source. (All columns except the TABLE_QUALIFIER column contain NULLs.)
If owner is a single percent character (%) and qualifier and name are empty strings, then the result set contains a list of valid owners for the data source. (All columns except the TABLE_OWNER column contain NULLs.)
If table_type is a single percent character (%) and qualifier, owner and name are empty strings, then the result set contains a list of valid table types for the data source. (All columns except the TABLE_TYPE column contain NULLs.)
If table_type is not an empty string, it must contain a list of comma-separated values for the types of interest; each value may be enclosed in single quotes (') or unquoted. For example, "'TABLE','VIEW'" or "TABLE, VIEW". If the data source does not support a specified table type, odbc_tables() does not return any results for that type.
See also odbc_tableprivileges() to retrieve associated privileges.
Lists tables in the requested range and the privileges associated with each table. Returns an ODBC result identifier or FALSE on failure.
The result set has the following columns:
TABLE_QUALIFIER
TABLE_OWNER
TABLE_NAME
GRANTOR
GRANTEE
PRIVILEGE
IS_GRANTABLE
The result set is ordered by TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.
The owner and name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).
(PHP 4 >= 4.0.0)
odbc_columns -- Lists the column names in specified tables. Returns a result identifier containing the information.Lists all columns in the requested range. Returns an ODBC result identifier or FALSE on failure.
The result set has the following columns:
TABLE_QUALIFIER
TABLE_OWNER
TABLE_NAME
COLUMN_NAME
DATA_TYPE
TYPE_NAME
PRECISION
LENGTH
SCALE
RADIX
NULLABLE
REMARKS
The result set is ordered by TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.
The owner, table_name and column_name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).
See also odbc_columnprivileges() to retrieve associated privileges.
(PHP 4 >= 4.0.0)
odbc_columnprivileges -- Returns a result identifier that can be used to fetch a list of columns and associated privilegesLists columns and associated privileges for the given table. Returns an ODBC result identifier or FALSE on failure.
The result set has the following columns:
TABLE_QUALIFIER
TABLE_OWNER
TABLE_NAME
GRANTOR
GRANTEE
PRIVILEGE
IS_GRANTABLE
The result set is ordered by TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.
The column_name argument accepts search patterns ('%' to match zero or more characters and '_' to match a single character).
(PHP 4 >= 4.0.0)
odbc_gettypeinfo -- Returns a result identifier containing information about data types supported by the data source.Retrieves information about data types supported by the data source. Returns an ODBC result identifier or FALSE on failure. The optional argument data_type can be used to restrict the information to a single data type.
The result set has the following columns:
TYPE_NAME
DATA_TYPE
PRECISION
LITERAL_PREFIX
LITERAL_SUFFIX
CREATE_PARAMS
NULLABLE
CASE_SENSITIVE
SEARCHABLE
UNSIGNED_ATTRIBUTE
MONEY
AUTO_INCREMENT
LOCAL_TYPE_NAME
MINIMUM_SCALE
MAXIMUM_SCALE
The result set is ordered by DATA_TYPE and TYPE_NAME.
(PHP 4 >= 4.0.0)
odbc_primarykeys -- Returns a result identifier that can be used to fetch the column names that comprise the primary key for a tableReturns the column names that comprise the primary key for a table. Returns an ODBC result identifier or FALSE on failure.
The result set has the following columns:
TABLE_QUALIFIER
TABLE_OWNER
TABLE_NAME
COLUMN_NAME
KEY_SEQ
PK_NAME
(PHP 4 >= 4.0.0)
odbc_foreignkeys -- Returns a list of foreign keys in the specified table or a list of foreign keys in other tables that refer to the primary key in the specified tableodbc_foreignkeys() retrieves information about foreign keys. Returns an ODBC result identifier or FALSE on failure.
The result set has the following columns:
PKTABLE_QUALIFIER
PKTABLE_OWNER
PKTABLE_NAME
PKCOLUMN_NAME
FKTABLE_QUALIFIER
FKTABLE_OWNER
FKTABLE_NAME
FKCOLUMN_NAME
KEY_SEQ
UPDATE_RULE
DELETE_RULE
FK_NAME
PK_NAME
If pk_table contains a table name, odbc_foreignkeys() returns a result set containing the primary key of the specified table and all of the foreign keys that refer to it.
If fk_table contains a table name, odbc_foreignkeys() returns a result set containing all of the foreign keys in the specified table and the primary keys (in other tables) to which they refer.
If both pk_table and fk_table contain table names, odbc_foreignkeys() returns the foreign keys in the table specified in fk_table that refer to the primary key of the table specified in pk_table. This should be one key at most.
(PHP 4 >= 4.0.0)
odbc_procedures -- Get the list of procedures stored in a specific data source. Returns a result identifier containing the information.Lists all procedures in the requested range. Returns an ODBC result identifier or FALSE on failure.
The result set has the following columns:
PROCEDURE_QUALIFIER
PROCEDURE_OWNER
PROCEDURE_NAME
NUM_INPUT_PARAMS
NUM_OUTPUT_PARAMS
NUM_RESULT_SETS
REMARKS
PROCEDURE_TYPE
The owner and name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).
Returns the list of input and output parameters, as well as the columns that make up the result set for the specified procedures. Returns an ODBC result identifier or FALSE on failure.
The result set has the following columns:
PROCEDURE_QUALIFIER
PROCEDURE_OWNER
PROCEDURE_NAME
COLUMN_NAME
COLUMN_TYPE
DATA_TYPE
TYPE_NAME
PRECISION
LENGTH
SCALE
RADIX
NULLABLE
REMARKS
The result set is ordered by PROCEDURE_QUALIFIER, PROCEDURE_OWNER, PROCEDURE_NAME and COLUMN_TYPE.
The owner, proc and column arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).
(PHP 4 >= 4.0.0)
odbc_specialcolumns -- Returns either the optimal set of columns that uniquely identifies a row in the table or columns that are automatically updated when any value in the row is updated by a transactionWhen the type argument is SQL_BEST_ROWID, odbc_specialcolumns() returns the column or columns that uniquely identify each row in the table.
When the type argument is SQL_ROWVER, odbc_specialcolumns() returns the optimal column or set of columns that, by retrieving values from the column or columns, allows any row in the specified table to be uniquely identified.
Returns an ODBC result identifier or FALSE on failure.
The result set has the following columns:
SCOPE
COLUMN_NAME
DATA_TYPE
TYPE_NAME
PRECISION
LENGTH
SCALE
PSEUDO_COLUMN
The result set is ordered by SCOPE.
Get statistics about a table and it's indexes. Returns an ODBC result identifier or FALSE on failure.
The result set has the following columns:
TABLE_QUALIFIER
TABLE_OWNER
TABLE_NAME
NON_UNIQUE
INDEX_QUALIFIER
INDEX_NAME
TYPE
SEQ_IN_INDEX
COLUMN_NAME
COLLATION
CARDINALITY
PAGES
FILTER_CONDITION
The result set is ordered by NON_UNIQUE, TYPE, INDEX_QUALIFIER, INDEX_NAME and SEQ_IN_INDEX.
These functions allow you to access Oracle8 and Oracle7 databases. It uses the Oracle8 Call-Interface (OCI8). You will need the Oracle8 client libraries to use this extension.
This extension is more flexible than the standard Oracle extension. It supports binding of global and local PHP variables to Oracle placeholders, has full LOB, FILE and ROWID support and allows you to use user-supplied define variables.
Before using this extension, make sure that you have set up your oracle environment variables properly for the Oracle user, as well as your web daemon user. The variables you might need to set are as follows:
ORACLE_HOME
ORACLE_SID
LD_PRELOAD
LD_LIBRARY_PATH
NLS_LANG
ORA_NLS33
After setting up the environment variables for your webserver user, be sure to also add the webserver user (nobody, www) to the oracle group.
If your webserver doesn't start or crashes at startup: Check that Apache is linked with the pthread library:
# ldd /www/apache/bin/httpd libpthread.so.0 => /lib/libpthread.so.0 (0x4001c000) libm.so.6 => /lib/libm.so.6 (0x4002f000) libcrypt.so.1 => /lib/libcrypt.so.1 (0x4004c000) libdl.so.2 => /lib/libdl.so.2 (0x4007a000) libc.so.6 => /lib/libc.so.6 (0x4007e000) /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)If the libpthread is not listed you have to reinstall Apache:
Przykład 1. OCI Hints
|
You can easily access stored procedures in the same way as you would from the commands line.
Przykład 2. Using Stored Procedures
|
(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)
OCIDefineByName -- Use a PHP variable for the define-step during a SELECTOCIDefineByName() uses fetches SQL-Columns into user-defined PHP-Variables. Be careful that Oracle user ALL-UPPERCASE column-names, whereby in your select you can also write lower-case. OCIDefineByName() expects the Column-Name to be in uppercase. If you define a variable that doesn't exists in you select statement, no error will be given!
If you need to define an abstract Datatype (LOB/ROWID/BFILE) you need to allocate it first using OCINewDescriptor() function. See also the OCIBindByName() function.
Przykład 1. OCIDefineByName
|
OCIBindByName() binds the PHP variable variable to the Oracle placeholder ph_name. Whether it will be used for input or output will be determined run-time, and the necessary storage space will be allocated. The length parameter sets the maximum length for the bind. If you set length to -1 OCIBindByName() will use the current length of variable to set the maximum length.
If you need to bind an abstract Datatype (LOB/ROWID/BFILE) you need to allocate it first using OCINewDescriptor() function. The length is not used for abstract Datatypes and should be set to -1. The type variable tells oracle, what kind of descriptor we want to use. Possible values are: OCI_B_FILE (Binary-File), OCI_B_CFILE (Character-File), OCI_B_CLOB (Character-LOB), OCI_B_BLOB (Binary-LOB) and OCI_B_ROWID (ROWID).
Przykład 1. OCIDefineByName
|
Ostrze¿enie |
It is a bad idea to use magic quotes and OciBindByName() simultaneously as no quoting is needed on quoted variables and any quotes magically applied will be written into your database as OciBindByName() is not able to distinguish magically added quotings from those added by intention. |
OCILogon() returns an connection identifier needed for most other OCI calls. The optional third parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora to which you want to connect. If the optional third parameter is not specified, PHP uses the environment variables ORACLE_SID (Oracle instance) or TWO_TASK (tnsnames.ora) to determine which database to connect to.
Connections are shared at the page level when using OCILogon(). This means that commits and rollbacks apply to all open transactions in the page, even if you have created multiple connections.
This example demonstrates how the connections are shared.
Przykład 1. OCILogon
|
See also OCIPLogon() and OCINLogon().
(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)
OCIPLogon -- Connect to an Oracle database and log on using a persistent connection. Returns a new session.OCIPLogon() creates a persistent connection to an Oracle 8 database and logs on. The optional third parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora to which you want to connect. If the optional third parameter is not specified, PHP uses the environment variables ORACLE_SID (Oracle instance) or TWO_TASK (tnsnames.ora) to determine which database to connect to.
See also OCILogon() and OCINLogon().
(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)
OCINLogon -- Connect to an Oracle database and log on using a new connection. Returns a new session.OCINLogon() creates a new connection to an Oracle 8 database and logs on. The optional third parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora to which you want to connect. If the optional third parameter is not specified, PHP uses the environment variables ORACLE_SID (Oracle instance) or TWO_TASK (tnsnames.ora) to determine which database to connect to.
OCINLogon() forces a new connection. This should be used if you need to isolate a set of transactions. By default, connections are shared at the page level if using OCILogon() or at the web server process level if using OCIPLogon(). If you have multiple connections open using OCINLogon(), all commits and rollbacks apply to the specified connection only.
This example demonstrates how the connections are separated.
Przykład 1. OCINLogon
|
See also OCILogon() and OCIPLogon().
OCIExecute() executes a previously parsed statement. (see OCIParse(). The optional mode allows you to specify the execution-mode (default is OCI_COMMIT_ON_SUCCESS). If you don't want statements to be committed automaticly specify OCI_DEFAULT as your mode.
OCICommit() commits all outstanding statements for Oracle connection connection.
OCIRollback() rolls back all outstanding statements for Oracle connection connection.
(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)
OCINewDescriptor -- Initialize a new empty descriptor LOB/FILE (LOB is default)OCINewDescriptor() Allocates storage to hold descriptors or LOB locators. Valid values for the valid type are OCI_D_FILE, OCI_D_LOB, OCI_D_ROWID. For LOB descriptors, the methods load, save, and savefile are associated with the descriptor, for BFILE only the load method exists. See the second example usage hints.
Przykład 1. OCINewDescriptor
|
Przykład 2. OCINewDescriptor
|
OCIRowCount() returns the number of rows affected for eg update-statements. This function will not tell you the number of rows that a select will return!
Przykład 1. OCIRowCount
|
OCINumCols() returns the number of columns in a statement
Przykład 1. OCINumCols
|
OCIResult() returns the data for column column in the current row (see OCIFetch()).OCIResult() will return everything as strings except for abstract types (ROWIDs, LOBs and FILEs).
OCIFetch() fetches the next row (for SELECT statements) into the internal result-buffer.
OCIFetchInto() fetches the next row (for SELECT statements) into the result array. OCIFetchInto() will overwrite the previous content of result. By default result will contain a zero-based array of all columns that are not NULL.
The mode parameter allows you to change the default behaviour. You can specify more than one flag by simply adding them up (eg OCI_ASSOC+OCI_RETURN_NULLS). The known flags are:
OCI_ASSOC Return an associative array. |
OCI_NUM Return an numbered array starting with zero. (DEFAULT) |
OCI_RETURN_NULLS Return empty columns. |
OCI_RETURN_LOBS Return the value of a LOB instead of the descriptor. |
OCIFetchStatement() fetches all the rows from a result into a user-defined array. OCIFetchStatement() returns the number of rows fetched.
Przykład 1. OCIFetchStatement
|
OCIColumnIsNULL() returns TRUE if the returned column column in the result from the statement stmt is NULL. You can either use the column-number (1-Based) or the column-name for the col parameter.
OCIColumnName() returns the name of the column corresponding to the column number (1-based) that is passed in.
Przykład 1. OCIColumnName
|
See also OCINumCols(), OCIColumnType(), and OCIColumnSize().
OCIColumnSize() returns the size of the column as given by Oracle. You can either use the column-number (1-Based) or the column-name for the col parameter.
Przykład 1. OCIColumnSize
|
See also OCINumCols(), OCIColumnName(), and OCIColumnSize().
OCIColumnType() returns the data type of the column corresponding to the column number (1-based) that is passed in.
Przykład 1. OCIColumnType
|
See also OCINumCols(), OCIColumnName(), and OCIColumnSize().
(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)
OCIServerVersion -- Return a string containing server version information.OCIStatementType() returns one of the following values:
"SELECT"
"UPDATE"
"DELETE"
"INSERT"
"CREATE"
"DROP"
"ALTER"
"BEGIN"
"DECLARE"
"UNKNOWN"
Przykład 1. Code examples
|
(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)
OCINewCursor -- Return a new cursor (Statement-Handle) - use to bind ref-cursors.OCINewCursor() allocates a new statement handle on the specified connection.
Przykład 1. Using a REF CURSOR from a stored procedure
|
Przykład 2. Using a REF CURSOR in a select statement
|
OCIFreeStatement() returns TRUE if successful, or FALSE if unsuccessful.
OCIFreeCursor() returns TRUE if successful, or FALSE if unsuccessful.
OCIFreeDesc() returns TRUE if successful, or FALSE if unsuccessful.
OCIParse() parses the query using conn. It returns the statement identity if the query is valid, FALSE if not. The query can be any valid SQL statement or PL/SQL block.
(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)
OCIError -- Return the last error of stmt|conn|global. If no error happened returns FALSE.OCIError() returns the last error found. If the optional stmt|conn|global is not provided, the last error encountered is returned. If no error is found, OCIError() returns FALSE. OCIError() returns the error as an associative array. In this array, code consists the oracle error code and message the oracle errorstring.
(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)
OCIInternalDebug -- Enables or disables internal debug output. By default it is disabledOCIInternalDebug() enables internal debug output. Set onoff to 0 to turn debug output off, 1 to turn it on.
If you do not want read more data from a cursor, then call OCICancel().
Sets the number of top level rows to be prefetched. The default value is 1 row.
Coming soon.
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 module uses the functions of OpenSSL for generation and verification of signatures and for sealing (encrypting) and opening (decrypting) data. PHP-4.0.4pl1 requires OpenSSL >= 0.9.6, but PHP-4.0.5 and greater with also work with OpenSSL >= 0.9.5.
Notatka: Please keep in mind that this extension is still considered experimental!
OpenSSL offers many features that this module currently doesn't support. Some of these may be added in the future.
Quite a few of the openssl functions require a key or a certificate parameter. PHP 4.0.5 and earlier have to use a key or certificate resource returned by one of the openssl_get_xxx functions. Later versions may use one of the following methods:
Certificates
An X.509 resource returned from openssl_x509_read
A string having the format file://path/to/cert.pem; the named file must contain a PEM encoded certificate
A string containing the content of a certificate, PEM encoded
Public/Private Keys
A key resource returned from openssl_get_publickey() or openssl_get_privatekey()
For public keys only: an X.509 resource
A string having the format file://path/to/file.pem - the named file must contain a PEM encoded certificate/private key (it may contain both)
A string containing the content of a certificate/key, PEM encoded
For private keys, you may also use the syntax array($key, $passphrase) where $key represents a key specified using the file:// or textual content notation above, and $passphrase represents a string containing the passphrase for that private key
When calling a function that will verify a signature/certificate, the cainfo parameter is an array containing file and directory names the specify the locations of trusted CA files. If a directory is specified, then it must be a correctly formed hashed directory as the openssl command would use.
The S/MIME functions make use of flags which are specified using a bitfield which can include one or more of the following values:
Tabela 1. PKCS7 CONSTANTS
Constant | Description |
---|---|
PKCS7_TEXT | adds text/plain content type headers to encrypted/signed message. If decrypting or verifying, it strips those headers from the output - if the decrypted or verified message is not of MIME type text/plain then an error will occur. |
PKCS7_BINARY | normally the input message is converted to "canonical" format which is effectively using CR and LF as end of line: as required by the S/MIME specification. When this options is present, no translation occurs. This is useful when handling binary data which may not be in MIME format. |
PKCS7_NOINTERN | when verifying a message, certificates (if any) included in the message are normally searched for the signing certificate. With this option only the certificates specified in the extracerts parameter of openssl_pkcs7_verify() are used. The supplied certificates can still be used as untrusted CAs however. |
PKCS7_NOVERIFY | do not verify the signers certificate of a signed message. |
PKCS7_NOCHAIN | do not chain verification of signers certificates: that is don't use the certificates in the signed message as untrusted CAs. |
PKCS7_NOCERTS | when signing a message the signer's certificate is normally included - with this option it is excluded. This will reduce the size of the signed message but the verifier must have a copy of the signers certificate available locally (passed using the extracerts to openssl_pkcs7_verify() for example. |
PKCS7_NOATTR | normally when a message is signed, a set of attributes are included which include the signing time and the supported symmetric algorithms. With this option they are not included. |
PKCS7_DETACHED | When signing a message, use cleartext signing with the MIME type multipart/signed. This is the default if the flags parameter to openssl_pkcs7_sign() if you do not specify any flags. If you turn this option off, the message will be signed using opaque signing, which is more resistant to translation by mail relays but cannot be read by mail agents that do not support S/MIME. |
PKCS7_NOSIGS | Don't try and verify the signatures on a message |
Notatka: These constants were added in 4.0.6.
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 an error message string, or FALSE if there are no more error messages to return.
openssl_error_string() returns the last error from the openSSL library. Error messages are stacked, so this function should be called multiple times to collect all of the information.
The parameters/return type of this function may change before it appears in a release version of PHP
Notatka: This function was added in 4.0.6.
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. |
openssl_free_key() frees the key associated with the specified key_identifier from memory.
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 positive key resource identifier on success, or FALSE on error.
openssl_get_privatekey() parses the PEM formatted private key specified by key and prepares it for use by other functions. The optional parameter passphrase must be used if the specified key is encrypted (protected by a passphrase).
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 positive key resource identifier on success, or FALSE on error.
openssl_get_publickey() extracts the public key from an X.509 certificate specified by certificate and prepares it for use by other functions.
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 error. If successful the opened data is returned in open_data.
openssl_open() opens (decrypts) sealed_data using the private key associated with the key identifier priv_key_id and the envelope key env_key, and fills open_data with the decrypted data. The envelope key is generated when the data are sealed and can only be used by one specific private key. See openssl_seal() for more information.
Przykład 1. openssl_open() example
|
See also openssl_seal().
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 length of the sealed data on success, or FALSE on error. If successful the sealed data is returned in sealed_data, and the envelope keys in env_keys.
openssl_seal() seals (encrypts) data by using RC4 with a randomly generated secret key. The key is encrypted with each of the public keys associated with the identifiers in pub_key_ids and each encrypted key is returned in env_keys. This means that one can send sealed data to multiple recipients (provided one has obtained their public keys). Each recipient must receive both the sealed data and the envelope key that was encrypted with the recipient's public key.
Przykład 1. openssl_seal() example
|
See also openssl_open().
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. If successful the signature is returned in signature.
openssl_sign() computes a signature for the specified data by using SHA1 for hashing followed by encryption using the private key associated with priv_key_id. Note that the data itself is not encrypted.
Przykład 1. openssl_sign() example
|
See also openssl_verify().
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 1 if the signature is correct, 0 if it is incorrect, and -1 on error.
openssl_verify() verifies that the signature is correct for the specified data using the public key associated with pub_key_id. This must be the public key corresponding to the private key used for signing.
Przykład 1. openssl_verify() example
|
See also openssl_sign().
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. |
Decrypts the S/MIME encrypted message contained in the file specified by infilename using the certificate and it's associated private key specified by recipcert and recipkey.
The decrypted message is output to the file specified by outfilename
Przykład 1. openssl_pkcs7_decrypt() example
|
Notatka: This function was added in 4.0.6.
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. |
openssl_pkcs7_encrypt() takes the contents of the file named infilename and encrypts them using an RC2 40-bit cipher so that they can only be read by the intended recipients specified by recipcerts, which is either a lone X.509 certificate, or an array of X.509 certificates. headers is an array of headers that will be prepended to the data after it has been encrypted. flags can be used to specify options that affect the encoding process - see PKCS7 constants. headers can be either an associative array keyed by header name, or an indexed array, where each element contains a single header line.
Przykład 1. openssl_pkcs7_encrypt() example
|
Notatka: This function was added in 4.0.6.
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. |
openssl_pkcs7_sign() takes the contents of the file named infilename and signs them using the certificate and it's matching private key specified by signcert and privkey parameters.
headers is an array of headers that will be prepended to the data after it has been signed (see openssl_pkcs7_encrypt() for more information about the format of this parameter.
flags can be used to alter the output - see PKCS7 constants - if not specified, it defaults to PKCS7_DETACHED.
extracerts specifies the name of a file containing a bunch of extra certificates to include in the signature which can for example be used to help the recipient to verify the certificate that you used.
Przykład 1. openssl_pkcs7_sign() example
|
Notatka: This function was added in 4.0.6.
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. |
openssl_pkcs7_verify() reads the S/MIME message contained in the filename specified by filename and examines the digital signature. It returns TRUE if the signature is verified, FALSE if it is not correct (the message has been tampered with, or the signing certificate is invalid), or -1 on error.
flags can be used to affect how the signature is verified - see PKCS7 constants for more information.
If the outfilename is specified, it should be a string holding the name of a file into which the certificates of the persons that signed the messages will be stored in PEM format.
If the cainfo is specified, it should hold information about the trusted CA certificates to use in the verification process - see certificate verification for more information about this parameter.
If the extracerts is specified, it is the filename of a file containing a bunch of certificates to use as untrusted CAs.
Notatka: This function was added in 4.0.6.
(PHP 4 >= 4.0.6)
openssl_x509_checkpurpose -- Verifies if a certificate can be used for a particular purposeOstrze¿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 if the certificate can be used for the intended purpose, FALSE if it cannot, or -1 on error.
openssl_x509_checkpurpose() examines the certificate specified by x509cert to see if it can be used for the purpose specified by purpose.
cainfo should be an array of trusted CA files/dirs as described in Certificate Verification.
untrustedfile, if specified, is the name of a PEM encoded file holding certificates that can be used to help verify the certificate, although no trust in placed in the certificates that come from that file.
Tabela 1. openssl_x509_checkpurpose() purposes
Constant | Description |
---|---|
X509_PURPOSE_SSL_CLIENT | Can the certificate be used for the client side of an SSL connection? |
X509_PURPOSE_SSL_SERVER | Can the certificate be used for the server side of an SSL connection? |
X509_PURPOSE_NS_SSL_SERVER | Can the cert be used for Netscape SSL server? |
X509_PURPOSE_SMIME_SIGN | Can the cert be used to sign S/MIME email? |
X509_PURPOSE_SMIME_ENCRYPT | Can the cert be used to encrypt S/MIME email? |
X509_PURPOSE_CRL_SIGN | Can the cert be used to sign a certificate revocation list (CRL)? |
X509_PURPOSE_ANY | Can the cert be used for Any/All purposes? |
Notatka: This function was added in 4.0.6.
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. |
openssl_x509_free() frees the certificate associated with the specified x509cert resource from memory.
Notatka: This function was added in 4.0.6.
(PHP 4 >= 4.0.6)
openssl_x509_parse -- Parse an X509 certificate and return the information as an arrayOstrze¿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. |
openssl_x509_parse() returns information about the supplied x509cert, including fields such as subject name, issuer name, purposes, valid from and valid to dates etc. shortnames controls how the data is indexed in the array - if shortnames is TRUE (the default) then fields will be indexed with the short name form, otherwise, the long name form will be used - e.g.: CN is the shortname form of commonName.
The structure of the returned data is (deliberately) not yet documented, as it is still subject to change.
Notatka: This function was added in 4.0.6.
(PHP 4 >= 4.0.6)
openssl_x509_read -- Parse an X.509 certificate and return a resource identifier for itOstrze¿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. |
openssl_x509_read() parses the certificate supplied by x509certdata and returns a resource identifier for it.
Notatka: This function was added in 4.0.6.
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. |
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. |
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. |
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. |
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. |
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. |
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. |
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. |
(PHP 4 CVS only)
openssl_pkey_export_to_file -- Gets an exportable representation of a key into a fileOstrze¿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. |
(PHP 4 CVS only)
openssl_pkey_export -- Gets an exportable representation of a key into a string or fileOstrze¿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. |
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. |
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. |
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. |
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. |
Returns TRUE if the bind succeeds, otherwise FALSE. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.
This function binds the named PHP variable with a SQL parameter. The SQL parameter must be in the form ":name". With the optional type parameter, you can define whether the SQL parameter is an in/out (0, default), in (1) or out (2) parameter. As of PHP 3.0.1, you can use the constants ORA_BIND_INOUT, ORA_BIND_IN and ORA_BIND_OUT instead of the numbers.
ora_bind must be called after ora_parse() and before ora_exec(). Input values can be given by assignment to the bound PHP variables, after calling ora_exec() the bound PHP variables contain the output values if available.
<?php ora_parse($curs, "declare tmp INTEGER; begin tmp := :in; :out := tmp; :x := 7.77; end;"); ora_bind($curs, "result", ":x", $len, 2); ora_bind($curs, "input", ":in", 5, 1); ora_bind($curs, "output", ":out", 5, 2); $input = 765; ora_exec($curs); echo "Result: $result<BR>Out: $output<BR>In: $input"; ?> |
Returns TRUE if the close succeeds, otherwise FALSE. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.
This function closes a data cursor opened with ora_open().
Returns the name of the field/column column on the cursor cursor. The returned name is in all uppercase letters. Column 0 is the first column.
Returns the size of the Oracle column column on the cursor cursor. Column 0 is the first column.
Returns the Oracle data type name of the field/column column on the cursor cursor. Column 0 is the first column. The returned type will be one of the following:
"VARCHAR2" |
"VARCHAR" |
"CHAR" |
"NUMBER" |
"LONG" |
"LONG RAW" |
"ROWID" |
"DATE" |
"CURSOR" |
Returns TRUE on success, FALSE on error. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.
This function commits an Oracle transaction. A transaction is defined as all the changes on a given connection since the last commit/rollback, autocommit was turned off or when the connection was established.
Returns TRUE on success, FALSE on error. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.
This function turns off automatic commit after each ora_exec().
This function turns on automatic commit after each ora_exec() on the given connection.
Returns TRUE on success, FALSE on error. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.
This function is quick combination of ora_parse(), ora_exec() and ora_fetch(). It will parse and execute a statement, then fetch the first result row.
Returns TRUE on success, FALSE on error. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.
See also ora_parse(),ora_exec(), and ora_fetch().
Returns an error message of the form XXX-NNNNN where XXX is where the error comes from and NNNNN identifies the error message.
Notatka: Support for connection ids was added in 3.0.4.
On UNIX versions of Oracle, you can find details about an error message like this: $ oerr ora 00001 00001, 00000, "unique constraint (%s.%s) violated" // *Cause: An update or insert statement attempted to insert a duplicate key // For Trusted ORACLE configured in DBMS MAC mode, you may see // this message if a duplicate entry exists at a different level. // *Action: Either remove the unique restriction or do not insert the key
Returns the numeric error code of the last executed statement on the specified cursor or connection.
Notatka: Support for connection ids was added in 3.0.4.
Returns TRUE on success, FALSE on error. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.
See also ora_parse(), ora_fetch(), and ora_do().
Returns TRUE (a row was fetched) or FALSE (no more rows, or an error occured). If an error occured, details can be retrieved using the ora_error() and ora_errorcode() functions. If there was no error, ora_errorcode() will return 0.
Retrieves a row of data from the specified cursor.
See also ora_parse(),ora_exec(), and ora_do().
You can fetch a row into an array with this function.
See also ora_parse(),ora_exec(), ora_fetch(), and ora_do().
Returns the column data. If an error occurs, FALSE is returned and ora_errorcode() will return a non-zero value. Note, however, that a test for FALSE on the results from this function may be TRUE in cases where there is not error as well (NULL result, empty string, the number 0, the string "0").
Fetches the data for a column or function result.
Returns TRUE on success, FALSE on error. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.
Logs out the user and disconnects from the server.
See also ora_logon().
Establishes a connection between PHP and an Oracle database with the given username and password.
Connections can be made using SQL*Net by supplying the TNS name to user like this:
If you have character data with non-ASCII characters, you should make sure that NLS_LANG is set in your environment. For server modules, you should set it in the server's environment before starting the server.
Returns a connection index on success, or FALSE on failure. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.
Establishes a persistent connection between PHP and an Oracle database with the given username and password.
See also ora_logon().
ora_numcols() returns the number of columns in a result. Only returns meaningful values after an parse/exec/fetch sequence.
See also ora_parse(),ora_exec(), ora_fetch(), and ora_do().
Opens an Oracle cursor associated with connection.
Returns a cursor index or FALSE on failure. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.
This function parses an SQL statement or a PL/SQL block and associates it with the given cursor.
Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
See also ora_exec(), ora_fetch(), and ora_do().
This function undoes an Oracle transaction. (See ora_commit() for the definition of a transaction.)
Returns TRUE on success, FALSE on error. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.
Ovrimos SQL Server, is a client/server, transactional RDBMS combined with Web capabilities and fast transactions.
Ovrimos SQL Server is available at www.ovrimos.com. To enable ovrimos support in PHP just compile php with the '--with-ovrimos' parameter to configure script. You'll need to install the sqlcli library available in the Ovrimos SQL Server distribution.
Przykład 1. Connect to Ovrimos SQL Server and select from a system table
|
ovrimos_connect() is used to connect to the specified database.
ovrimos_connect() returns a connection id (greater than 0) or 0 for failure. The meaning of 'host' and 'port' are those used everywhere in Ovrimos APIs. 'Host' is a host name or IP address and 'db' is either a database name, or a string containing the port number.
Przykład 1. ovrimos_connect() Example
|
ovrimos_close() is used to close the specified connection.
ovrimos_close() closes a connection to Ovrimos. This has the effect of rolling back uncommitted transactions.
(PHP 4 >= 4.0.3)
ovrimos_longreadlen -- Specifies how many bytes are to be retrieved from long datatypesovrimos_longreadlen() is used to specify how many bytes are to be retrieved from long datatypes.
ovrimos_longreadlen() specifies how many bytes are to be retrieved from long datatypes (long varchar and long varbinary). Default is zero. It currently sets this parameter the specified result set. Returns TRUE.
ovrimos_prepare() is used to prepare an SQL statement.
ovrimos_prepare() prepares an SQL statement and returns a result_id (or FALSE on failure).
Przykład 1. Connect to Ovrimos SQL Server and prepare a statement
|
ovrimos_execute() is used to execute an SQL statement.
ovrimos_execute() executes a prepared statement. Returns TRUE or FALSE. If the prepared statement contained parameters (question marks in the statement), the correct number of parameters should be passed in an array. Notice that I don't follow the PHP convention of placing just the name of the optional parameter inside square brackets. I couldn't bring myself on liking it.
ovrimos_cursor() is used to get the name of the cursor.
ovrimos_cursor() returns the name of the cursor. Useful when wishing to perform positioned updates or deletes.
ovrimos_exec() is used to execute an SQL statement.
ovrimos_exec() executes an SQL statement (query or update) and returns a result_id or FALSE. Evidently, the SQL statement should not contain parameters.
ovrimos_fetch_into() is used to fetch a row from the result set.
ovrimos_fetch_into() fetches a row from the result set into 'result_array', which should be passed by reference. Which row is fetched is determined by the two last parameters. 'how' is one of 'Next' (default), 'Prev', 'First', 'Last', 'Absolute', corresponding to forward direction from current position, backward direction from current position, forward direction from the start, backward direction from the end and absolute position from the start (essentially equivalent to 'first' but needs 'rownumber'). Case is not significant. 'Rownumber' is optional except for absolute positioning. Returns TRUE or FALSE.
Przykład 1. A fetch into example
|
ovrimos_fetch_row() is used to fetch a row from the result set.
ovrimos_fetch_row() fetches a row from the result set. Column values should be retrieved with other calls. Returns TRUE or FALSE.
Przykład 1. A fetch row example
|
ovrimos_result() is used to retrieve the output column.
ovrimos_result() retrieves the output column specified by 'field', either as a string or as an 1-based index.
ovrimos_result_all() is used to print an HTML table containing the whole result set.
ovrimos_result_all() prints the whole result set as an HTML table. Returns TRUE or FALSE.
Przykład 1. Prepare a statement, execute, and view the result
|
Przykład 2. Ovrimos_result_all with meta-information
|
Przykład 3. ovrimos_result_all example
|
ovrimos_num_rows() is used to get the number of rows affected by update operations.
ovrimos_num_rows() returns the number of rows affected by update operations.
ovrimos_num_fields() is used to get the number of columns.
ovrimos_num_fields() returns the number of columns in a result_id resulting from a query.
ovrimos_field_name() is used to get the output column name.
ovrimos_field_name() returns the output column name at the (1-based) index specified.
ovrimos_field_type() is used to get the (numeric) type of the output column.
ovrimos_field_type() returns the (numeric) type of the output column at the (1-based) index specified.
ovrimos_field_len() is used to get the length of the output column with number field_number, in result result_id.
ovrimos_field_len() returns the length of the output column at the (1-based) index specified.
ovrimos_field_num() is used to get the (1-based) index of the output column.
ovrimos_field_num() returns the (1-based) index of the output column specified by name, or FALSE.
ovrimos_free_result() is used to free the result_id.
ovrimos_free_result() frees the specified result_id result_id. Returns TRUE.
ovrimos_commit() is used to commit the transaction.
ovrimos_commit() commits the transaction.
The Output Control functions allow you to control when output is sent from the script. This can be useful in several different situations, especially if you need to send headers to the browser after your script has began outputting data. The Output Control functions do not affect headers sent using header() or setcookie(), only functions such as echo() and data between blocks of PHP code.
In the above example, the output from echo() would be stored in the output buffer until ob_end_flush() was called. In the mean time, the call to setcookie() successfully stored a cookie without causing an error. (You can not normally send headers to the browser after data has already been sent.)
See also header() and setcookie().
Flushes the output buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This effectively tries to push all the output so far to the user's browser.
Notatka: flush() has no effect on the buffering scheme of your webserver or the browser on the client side.
Several servers, especially on Win32, will still buffer the output from your script until it terminates before transmitting the results to the browser.
Server modules for Apache like mod_gzip may do buffering of their own that will cause flush() to not result in data being sent immediately to the client.
Even the browser may buffer its input before displaying it. Netscape, for example, buffers text until it receives an end-of-line or the beginning of a tag, and it won't render tables until the </table> tag of the outermost table is seen.
Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page.
This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.
The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.
An optional output_callback function may be specified. This function takes a string as a parameter and should return a string. The function will be called when ob_end_flush() is called, or when the output buffer is flushed to the browser at the end of the request. When output_callback is called, it will receive the contents of the output buffer as its parameter and is expected to return a new output buffer as a result, which will be sent to the browser.
Notatka: In PHP 4.0.4, ob_gzhandler() was introduced to facilitate sending gz-encoded data to web browsers that support compressed web pages. ob_gzhandler() determines what type of content encoding the browser will accept and will return it's output accordingly.
Output buffers are stackable, that is, you may call ob_start() while another ob_start() is active. Just make sure that you call ob_end_flush() the appropriate number of times. If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order.
Przykład 1. User defined callback function example
|
Would produce:
See also ob_get_contents(), ob_end_flush(), ob_end_clean(), ob_implicit_flush() and ob_gzhandler().
This will return the contents of the output buffer or FALSE, if output buffering isn't active.
See also ob_start() and ob_get_length().
This will return the length of the contents in the output buffer or FALSE, if output buffering isn't active.
See also ob_start() and ob_get_contents().
This will return the level of nested output buffering handlers.
See also ob_start() and ob_get_contents().
Notatka: mode was added in PHP 4.0.5.
ob_gzhandler() is intended to be used as a callback function for ob_start() to help facilitate sending gz-encoded data to web browsers that support compressed web pages. Before ob_gzhandler() actually sends compressed data, it determines what type of content encoding the browser will accept ("gzip", "deflate" or none at all) and will return it's output accordingly. All browsers are supported since it's up to the browser to send the correct header saying that it accepts compressed web pages.
See also ob_start() and ob_end_flush().
This function will send the contents of the output buffer (if any). If you want to further process the buffer's contents you have to call ob_get_contents() before ob_flush() as the buffer contents are discarded after ob_flush() is called.
This function does not destroy the output buffer like ob_end_flush() does.
See also ob_get_contents(), ob_clean(), ob_end_flush() and ob_end_clean().
This function discards the contents of the output buffer.
This function does not destroy the output buffer like ob_end_clean() does.
See also ob_flush(), ob_end_flush() and ob_end_clean().
This function will send the contents of the output buffer (if any) and turn output buffering off. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_flush() as the buffer contents are discarded after ob_end_flush() is called.
See also ob_start(), ob_get_contents(), ob_flush() and ob_end_clean().
This function discards the contents of the output buffer and turns off output buffering.
See also ob_start(), ob_clean() and ob_end_flush().
ob_implicit_flush() will turn implicit flushing on or off (if no flag is given, it defaults to on). Implicit flushing will result in a flush operation after every output call, so that explicit calls to flush() will no longer be needed.
Turning implicit flushing on will disable output buffering, the output buffers current output will be sent as if ob_end_flush() had been called.
See also flush(), ob_start(), and ob_end_flush().
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. |
The purpose of this extension is to allow overloading of object property access and method calls. Only one function is defined in this extension, overload() which takes the name of the class that should have this functionality enabled. The class named has to define appropriate methods if it wants to have this functionality: __get(), __set() and __call() respectively for getting/setting a property, or calling a method. This way overloading can be selective. Inside these handler functions the overloading is disabled so you can access object properties normally.
Some simple examples on using the overload() function:
Przykład 1. Overloading a PHP class
|
Ostrze¿enie |
As this is an experimental extension, not all things work. There is no __call() support currently, you can only overload the get and set operations for properties. You cannot invoke the original overloading handlers of the class, and __set() only works to one level of property access. |
The overload() function will enable property and method call overloading for a class identified by class_name. See an example in the introductory section of this part.
The PDF functions in PHP can create PDF files using the PDFlib library created by Thomas Merz. PDFlib is available for download at http://www.pdflib.com/pdflib/index.html, but requires that you purchase a license for commercial use. The JPEG and TIFF libraries are required to compile this extension. Please see the PDFlib installation section for more information about compiling PDF support into PHP.
The documentation in this section is only meant to be an overview of the available functions in the PDFlib library and should not be considered an exhaustive reference. Please consult the documentation included in the source distribution of PDFlib for the full and detailed explanation of each function here. It provides a very good overview of what PDFlib is capable of doing and contains the most up-to-date documentation of all functions.
All of the functions in PDFlib and the PHP module have identical function names and parameters. You will need to understand some of the basic concepts of PDF and PostScript to efficiently use this extension. All lengths and coordinates are measured in PostScript points. There are generally 72 PostScript points to an inch, but this depends on the output resolution. Please see the PDFlib documentation included with the source distribution of PDFlib for a more thorough explanation of the coordinate system used.
Please note that most of the PDF functions require a pdf object as it's first parameter. Please see the examples below for more information.
Starting with PHP 4.0.5, the PHP extension for PDFlib is officially supported by PDFlib GmbH. This means that all the functions described in the PDFlib manual (V3.00 or greater) are supported by PHP 4 with exactly the same meaning and the same parameters. Only the return values may differ from the PDFlib manual, because the PHP convention of returning FALSE was adopted. For compatibility reasons this binding for PDFlib still supports the old functions, but they should be replaced by their new versions. PDFlib GmbH will not support any problems arising from the use of these deprecated functions.
Tabela 1. Deprecated functions and its replacements
Old function | Replacement |
---|---|
pdf_put_image() | Not needed anymore. |
pdf_execute_image() | Not needed anymore. |
pdf_get_annotation() | pdf_get_bookmark() using the same parameters. |
pdf_get_font() | pdf_get_value() passing "font" as the second parameter. |
pdf_get_fontsize() | pdf_get_value() passing "fontsize" as the second parameter. |
pdf_get_fontname() | pdf_get_parameter() passing "fontname" as the second parameter. |
pdf_set_info_creator() | pdf_set_info() passing "Creator" as the second parameter. |
pdf_set_info_title() | pdf_set_info() passing "Title" as the second parameter. |
pdf_set_info_subject() | pdf_set_info() passing "Subject" as the second parameter. |
pdf_set_info_author() | pdf_set_info() passing "Author" as the second parameter. |
pdf_set_info_keywords() | pdf_set_info() passing "Keywords" as the second parameter. |
pdf_set_leading() | pdf_set_value() passing "leading" as the second parameter. |
pdf_set_text_rendering() | pdf_set_value() passing "textrendering" as the second parameter. |
pdf_set_text_rise() | pdf_set_value() passing "textrise" as the second parameter. |
pdf_set_horiz_scaling() | pdf_set_value() passing "horizscaling" as the second parameter. |
pdf_set_text_matrix() | Not available anymore |
pdf_set_char_spacing() | pdf_set_value() passing "charspacing" as the second parameter. |
pdf_set_word_spacing() | pdf_set_value() passing "wordspacing" as the second parameter. |
pdf_set_transition() | pdf_set_parameter() passing "transition" as the second parameter. |
pdf_open() | pdf_new() plus an subsequent call of pdf_open_file() |
pdf_set_font() | pdf_findfont() plus an subsequent call of pdf_setfont() |
pdf_set_duration() | pdf_set_value() passing "duration" as the second parameter. |
pdf_open_gif() | pdf_open_image_file() passing "gif" as the second parameter. |
pdf_open_jpeg() | pdf_open_image_file() passing "jpeg" as the second parameter. |
pdf_open_tiff() | pdf_open_image_file() passing "tiff" as the second parameter. |
pdf_open_png() | pdf_open_image_file() passing "png" as the second parameter. |
pdf_get_image_width() | pdf_get_value() passing "imagewidth" as the second parameter and the image as the third parameter. |
pdf_get_image_height() | pdf_get_value() passing "imageheight" as the second parameter and the image as the third parameter. |
When using version 3.x of PDFlib, you should configure PDFlib with the option --enable-shared-pdflib.
Any version of PHP 4 after March 9, 2000 does not support versions of PDFlib older than 3.0.
PDFlib 3.0 or greater is supported by PHP 3.0.19 and later.
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 to get started. It creates test.pdf with one page. The page contains the text "Times Roman outlined" in an outlined, 30pt font. The text is also underlined.
Przykład 1. Creating a PDF document with PDFlib
The script getpdf.php just returns the pdf document. |
The PDFlib distribution contains a more complex example which creates a page with an analog clock. Here we use the in memory creation feature of PDFlib to alleviate the need to use temporary files. The example, converted to PHP from the PDFlib example, is as follows: (The same example is available in the CLibPDF documentation.)
Przykład 2. pdfclock example from PDFlib distribution
|
Add a nested bookmark under parent, or a new top-level bookmark if parent = 0. Returns a bookmark descriptor which may be used as parent for subsequent nested bookmarks. If open = 1, child bookmarks will be folded out, and invisible if open = 0.
Add a launch annotation (to a target of arbitrary file type).
Add a link annotation to a target within the current PDF file.
Add a note annotation. icon is one of of "comment, "insert", "note", "paragraph", "newparagraph", "key", or "help".
Add a file link annotation (to a PDF target).
Add an existing image as thumbnail for the current page.
Add a weblink annotation to a target URL on the Web.
Draw a counterclockwise circular arc from alpha to beta degrees
See also: pdf_arcn()
Draw a clockwise circular arc from alpha to beta degrees
See also: pdf_arc()
Add a file attachment annotation. icon is one of "graph, "paperclip", "pushpin", or "tag".
Add a new page to the document. The width and height are specified in points, which are 1/72 of an inch.
Starts a new pattern definition and returns a pattern handle. width, and height define the bounding box for the pattern. xstep and ystep give the repeated pattern offsets. painttype=1 means that the pattern has its own colour settings whereas a value of 2 indicates that the current colour is used when the pattern is applied.
Start a new template definition.
Draw a circle with center (x, y) and radius r.
Close the generated PDF file, and free all document-related resources.
Close an image retrieved with one of the pdf_open_image*() functions.
Close all open page handles, and close the input PDF document.
Close the page handle, and free all page-related resources.
Concatenate a matrix to the CTM.
Print text at the next line. The spacing between lines is determined by the leading parameter.
Draw a Bezier curve from the current point, using 3 more control points.
Delete the PDF object, and free all internal resources.
Fill the interior of the path with the current fill color.
Fill and stroke the path with the current fill and stroke color.
Prepare a font for later use with pdf_setfont(). The metrics will be loaded, and if embed is nonzero, the font file will be checked, but not yet used. encoding is one of "builtin", "macroman", "winansi", "host", or a user-defined encoding name, or the name of a CMap.
pdf_findfont() returns a font handle or FALSE on error.
Get the contents of the PDF output buffer. The result must be used by the client before calling any other PDFlib function.
pdf_get_image_height() is deprecated, use pdf_get_value() instead.
The pdf_get_image_width() is deprecated, use pdf_get_value() instead.
Get the contents of some PDFlib parameter with string type.
Get the contents of some PDI document parameter with string type.
Get the contents of some PDI document parameter with numerical type.
Get the contents of some PDFlib parameter with float type.
Reset all implicit color and graphics state parameters to their defaults.
Draw a line from the current point to (x, y).
Make a named spot color from the current color.
Set the current point.
Notatka: The current point for graphics and the current text output position are maintained separately. See pdf_set_text_pos() to set the text output position.
Create a new PDF object, using default error handling and memory management.
pdf_open() is deprecated, use pdf_new() plus pdf_open_file() instead.
See also pdf_new(), pdf_open_file().
Open a raw CCITT image.
Create a new PDF file using the supplied file name. If filename is empty the PDF document will be generated in memory instead of on file. The result must be fetched by the client with the pdf_get_buffer() function.
The following example shows how to create a pdf document in memory and how to output it correctly.
Przykład 1. Creating a PDF document in memory
|
Use image data from a variety of data sources. Supported types are "jpeg", "ccitt", "raw". Supported sources are "memory", "fileref", "url". len is only used for type="raw", params is only used for type="ccitt".
Open an image file. Supported types are "jpeg", "tiff", "gif", and "png". stringparam is either "", "mask", "masked", or "page". intparamis either 0, the image id of the applied mask, or the page.
(PHP 3>= 3.0.10, PHP 4 >= 4.0.0)
pdf_open_memory_image -- Opens an image created with PHP's image functionsThe pdf_open_memory_image() function takes an image created with the PHP's image functions and makes it available for the pdf object. The function returns a pdf image identifier.
See also pdf_close_image(), pdf_place_image().
Open an existing PDF document for later use.
Prepare a page for later use with pdf_place_image()
Deprecated.
See also pdf_open_image(),
Place an image with the lower left corner at (x, y), and scale it.
Place a PDF page with the lower left corner at (x, y), and scale it.
Draw a rectangle at lower left (x, y) with width and height.
Rotate the coordinate system by phi degrees.
Scale the coordinate system.
Set the current color space and color. The parameter type can be "fill", "stroke", or "both" to specify that the color is set for filling, stroking or both filling and stroking. The parameter colorspace can be gray, rgb, cmyk, spot or pattern. The parameters c1, c2, c3 and c4 represent the color components for the color space specified by colorspace. Except as otherwise noted, the color components are floating-point values that range from 0 to 1.
For gray only c1 is used.
For rgb parameters c1, c2, and c3 specify the red, green and blue values respectively.
For cmyk, parameters c1, c2, c3, and c4 are the cyan, magenta, yellow and black values, respectively.
For spot, c1 should be a spot color handles returned by pdf_makespotcolor() and c2 is a tint value between 0 and 1.
For pattern, c1 should be a pattern handle returned by pdf_begin_pattern().
Set the current dash pattern to b black and w white units.
Set the flatness to a value between 0 and 100 inclusive.
Set the current font in the given size, using a font handle returned by pdf_findfont()
See Also: pdf_findfont().
Set the current fill and stroke color.
Notatka: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the current fill color to a gray value between 0 and 1 inclusive.
Notatka: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the current stroke color to a gray value between 0 and 1 inclusive
Notatka: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the linecap parameter to a value between 0 and 2 inclusive.
Set the line join parameter to a value between 0 and 2 inclusive.
Explicitly set the current transformation matrix.
Set the miter limit to a value greater than or equal to 1.
Set a more complicated dash pattern defined by an array.
Set the current fill and stroke color to the supplied RGB values.
Notatka: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the current fill color to the supplied RGB values.
Notatka: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the current stroke color to the supplied RGB values.
Notatka: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
(PHP 3>= 3.0.12, PHP 4 >= 4.0.0)
pdf_set_border_color -- Sets color of border around links and annotationsSet the border color for all kinds of annotations.
Set the border dash style for all kinds of annotations. See pdf_setdash().
(PHP 3>= 3.0.12, PHP 4 >= 4.0.0)
pdf_set_border_style -- Sets style of border around links and annotationsSet the border style for all kinds of annotations. style is "solid" or "dashed".
Deprecated. You should use pdf_findfont() plus pdf_setfont() instead.
See pdf_findfont(), pdf_setfont().
Deprecated.
See also pdf_set_value(),
Fill document information field key with value. key is one of "Subject", "Title", "Creator", "Author", "Keywords", or a user-defined key.
This function is deprecate, use pdf_set_info() instead.
This function is deprecate, use pdf_set_info() instead.
This function is deprecate, use pdf_set_info() instead.
This function is deprecate, use pdf_set_info() instead.
This function is deprecate, use pdf_set_info() instead.
Set some PDFlib parameter with string type.
(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)
pdf_set_text_rendering -- Deprecated: Determines how text is renderedSet the value of some PDFlib parameter with float type.
Print text in the current font and size at the current position.
Format text in the current font and size into the supplied text box according to the requested formatting mode, which must be one of "left", "right", "center", "justify", or "fulljustify". If width and height are 0, only a single line is placed at the point (left, top) in the requested mode.
Returns the number of characters that did not fit in the specified box. Returns 0 if all characters fit or the width and height parameters were set to 0 for single-line formattting.
Print text in the current font at (x, y).
Skew the coordinate system in x and y direction by alpha and beta degrees.
Returns the width of text using the last font set by pdf_setfont(). If the optional parameters font and size are specified, the width will be calculated using that font and size instead. Please note that font is a font handle returned by pdf_findfont().
Notatka: Both the font and size parameters must used together.
See Also: pdf_setfont() and pdf_findfont().
Stroke the path with the current color and line width, and clear it.
This extension allows you to process credit cards and other financial transactions using Verisign Payment Services, formerly known as Signio (http://www.verisign.com/payment/).
These functions are only available if PHP has been compiled with the --with-pfpro[=DIR] option. You will require the appropriate SDK for your platform, which may be downloaded from within the manager interface once you have registered. If you are going to use this extension in an SSL-enabled webserver or with other SSL components (such as the CURL+SSL extension) you MUST get the beta SDK.
Once you have downloaded the SDK you should copy the files from the lib directory of the distribution. Copy the header file pfpro.h to /usr/local/include and the library file libpfpro.so to /usr/local/lib.
When using these functions, you may omit calls to pfpro_init() and pfpro_cleanup() as this extension will do so automatically if required. However the functions are still available in case you are processing a number of transactions and require fine control over the library. You may perform any number of transactions using pfpro_process() between the two.
These functions have been added in PHP 4.0.2.
Notatka: These functions only provide a link to Verisign Payment Services. Be sure to read the Payflow Pro Developers Guide for full details of the required parameters.
pfpro_init() is used to initialise the Payflow Pro library. You may omit this call, in which case this extension will automatically call pfpro_init() before the first transaction.
See also pfpro_cleanup().
pfpro_cleanup() is used to shutdown the Payflow Pro library cleanly. It should be called after you have processed any transactions and before the end of your script. However you may omit this call, in which case this extension will automatically call pfpro_cleanup() after your script terminates.
See also pfpro_init().
Returns: An associative array containing the response
pfpro_process() processes a transaction with Payflow Pro. The first parameter is an associative array containing keys and values that will be encoded and passed to the processor.
The second parameter is optional and specifies the host to connect to. By default this is "test.signio.com", so you will certainly want to change this to "connect.signio.com" in order to process live transactions.
The third parameter specifies the port to connect on. It defaults to 443, the standard SSL port.
The fourth parameter specifies the timeout to be used, in seconds. This defaults to 30 seconds. Note that this timeout appears to only begin once a link to the processor has been established and so your script could potentially continue for a very long time in the event of DNS or network problems.
The fifth parameter, if required, specifies the hostname of your SSL proxy. The sixth parameter specifies the port to use.
The seventh and eighth parameters specify the logon identity and password to use on the proxy.
The function returns an associative array of the keys and values in the response.
Notatka: Be sure to read the Payflow Pro Developers Guide for full details of the required parameters.
Przykład 1. Payflow Pro example
|
Returns: A string containing the response.
pfpro_process_raw() processes a raw transaction string with Payflow Pro. You should really use pfpro_process() instead, as the encoding rules of these transactions are non-standard.
The first parameter in this case is a string containing the raw transaction request. All other parameters are the same as with pfpro_process(). The return value is a string containing the raw response.
Notatka: Be sure to read the Payflow Pro Developers Guide for full details of the required parameters and encoding rules. You would be well advised to use pfpro_process() instead.
Przykład 1. Payflow Pro raw example
|
assert() will check the given assertion and take appropriate action if its result is FALSE.
If the assertion is given as a string it will be evaluated as PHP code by assert(). The advantages of a string assertion are less overhead when assertion checking is off and messages containing the assertion expression when an assertion fails.
Assertions should be used as a debugging feature only. You may use them for sanity-checks that test for conditions that should always be TRUE and that indicate some programming errors if not or to check for the presence of certain features like extension functions or certain system limits and features.
Assertions should not be used for normal runtime operations like input parameter checks. As a rule of thumb your code should always be able to work correctly if assertion checking is not activated.
The behavior of assert() may be configured by assert_options() or by .ini-settings described in that functions manual page.
The assert_options() function and/or ASSERT_CALLBACK configuration directive allow a callback function to be set to handle failed assertions.
assert() callbacks are particularly useful for building automated test suites because they allow you to easily capture the code passed to the assertion, along with information on where the assertion was made. While this information can be captured via other methods, using assertions makes it much faster and easier!
The callback function should accept three arguments. The first argument will contain the file the assertion failed in. The second argument will contain the line the assertion failed on and the third argument will contain the expression that failed (if any - literal values such as 1 or "two" will not be passed via this argument)
Przykład 1. Handle a failed assertion with a custom handler
|
Using assert_options() you may set the various assert() control options or just query their current settings.
Tabela 1. Assert Options
option | ini-parameter | default | description |
---|---|---|---|
ASSERT_ACTIVE | assert.active | 1 | enable assert() evaluation |
ASSERT_WARNING | assert.warning | 1 | issue a PHP warning for each failed assertion |
ASSERT_BAIL | assert.bail | 0 | terminate execution on failed assertions |
ASSERT_QUIET_EVAL | assert.quiet_eval | 0 | disable error_reporting during assertion expression evaluation |
ASSERT_CALLBACK | assert_callback | (NULL) | user function to call on failed assertions |
assert_options() will return the original setting of any option or FALSE on errors.
Returns TRUE if the extension identified by name is loaded. You can see the names of various extensions by using phpinfo().
See also phpinfo().
Notatka: This function was added in 3.0.10.
Loads the PHP extension defined in library. See also the Extension Loading Directives
Returns the value of the environment variable varname, or FALSE on an error.
You can see a list of all the environmental variables by using phpinfo(). You can find out what many of them mean by taking a look at the CGI specification, specifically the page on environmental variables.
Notatka: This function does not work in ISAPI mode.
See also putenv().
Returns the current value of the PHP configuration variable specified by varname, or FALSE if an error occurs.
It will not return configuration information set when the PHP was compiled, or read from an Apache configuration file (using the php3_configuration_option directives).
To check whether the system is using a configuration file, try retrieving the value of the cfg_file_path configuration setting. If this is available, a configuration file is being used.
See also ini_get().
Returns the name of the owner of the current PHP script.
See also getmyuid(), getmygid(), getmypid(), getmyinode(), and getlastmod().
(PHP 4 >= 4.1.0)
get_defined_constants -- Returns an associative array with the names of all the constants and their valuesThis function returns the names and values of all the constants currently defined. This includes those created by extensions as well as those created with the define() function.
For example the line below
will print a list like:Array ( [E_ERROR] => 1 [E_WARNING] => 2 [E_PARSE] => 4 [E_NOTICE] => 8 [E_CORE_ERROR] => 16 [E_CORE_WARNING] => 32 [E_COMPILE_ERROR] => 64 [E_COMPILE_WARNING] => 128 [E_USER_ERROR] => 256 [E_USER_WARNING] => 512 [E_USER_NOTICE] => 1024 [E_ALL] => 2047 [TRUE] => 1 ) |
See also get_loaded_extensions().
This function returns the names of all the functions defined in the module indicated by module_name.
For example the lines below
will print a list of the functions in the modules xml and gd respectively.See also: get_loaded_extensions()
Returns the group ID of the current script, or FALSE on error.
See also getmyuid(), getmypid(), get_current_user(), getmyinode(), and getlastmod().
Returns an array of the names of all files that have been included using include(), include_once(), require() or require_once().
Files that are included or required multiple times only show up once in the returned array.
Notatka: Files included using the auto_prepend_file configuration directive are not included in the returned array.
Notatka: In PHP 4.0.1pl2 and previous versions get_included_files() assumed that the required files ended in the extension .php; other extensions would not be returned. The array returned by get_included_files() was an associative array and only listed files included by include() and include_once().
See also: include(), include_once(), require(), require_once(), and get_required_files().
(PHP 4 >= 4.0.0)
get_loaded_extensions -- Returns an array with the names of all modules compiled and loadedThis function returns the names of all the modules compiled and loaded in the PHP interpreter.
For example the line below
will print a list like:Array ( [0] => xml [1] => wddx [2] => standard [3] => session [4] => posix [5] => pgsql [6] => pcre [7] => gd [8] => ftp [9] => db [10] => Calendar [11] => bcmath ) |
See also: get_extension_funcs().
(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)
get_magic_quotes_gpc -- Gets the current active configuration setting of magic quotes gpcReturns the current active configuration setting of magic_quotes_gpc (0 for off, 1 for on).
See also get_magic_quotes_runtime() and set_magic_quotes_runtime().
(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)
get_magic_quotes_runtime -- Gets the current active configuration setting of magic_quotes_runtimeReturns the current active configuration setting of magic_quotes_runtime (0 for off, 1 for on).
See also get_magic_quotes_gpc() and set_magic_quotes_runtime().
Returns the time of the last modification of the current page. The value returned is a Unix timestamp, suitable for feeding to date(). Returns FALSE on error.
See also date(), getmyuid(), getmygid(), get_current_user(), getmyinode(), and getmypid().
Returns the current script's inode, or FALSE on error.
See also getmygid(), getmyuid(), get_current_user(), getmypid(), and getlastmod().
Notatka: Ta funkcja nie jest dostępna na platformie Windows.
Returns the current PHP process ID, or FALSE on error.
Ostrze¿enie |
Process IDs are not unique, thus they are a weak entropy source. We recommend against relying on pids in security-dependent contexts. |
See also getmygid(), getmyuid(), get_current_user(), getmyinode(), and getlastmod().
Returns the user ID of the current script, or FALSE on error.
See also getmygid(), getmypid(), get_current_user(), getmyinode(), and getlastmod().
As of PHP 4.0.4, this function is an alias for get_included_files()
In PHP 4.0.1pl2 and previous versions get_required_files() assumed that the required files ended in the extension .php, other extensions would not be returned. The array returned by get_required_files() was an associative array and only listed files included by require() and require_once().
See also: require(), require_once(), include(), include_once(), and get_included_files().
This is an interface to getrusage(2). It returns an associative array containing the data returned from the system call. If who is 1, getrusage will be called with RUSAGE_CHILDREN.
All entries are accessible by using their documented field names.
Changes the value of a configuration option, returns FALSE on failure, and the previous value of the configuration option on success.
Notatka: This is an alias of ini_set()
See also ini_get(), ini_get_all(), ini_restore(), and ini_set()
Returns the value of the configuration option on success, an empty string on failure.
See also get_cfg_var(), ini_get_all(), ini_alter(), ini_restore(), and ini_set()
Returns all the registered configuration options as an associative array. If optional extension parameter is set, returns only options specific for that extension.
See also: ini_alter(), ini_restore(), ini_get(), and ini_set()
Restores a given configuration option to its original value.
See also: ini_alter(), ini_get(), ini_get_all(), and ini_set()
Sets the value of the given configuration option. Returns the old value on success, FALSE on failure. The configuration option will keep this new value during the script's execution, and will be restored at the script's ending.
Not all the available options can be changed using ini_set(). Below is a table with a list of all PHP options (as of PHP 4.0.5-dev), indicating which ones can be changed/set and at what level.
Tabela 1. Configuration options
Name | Default | Changeable |
---|---|---|
define_syslog_variables | "0" | PHP_INI_ALL |
highlight.bg | HL_BG_COLOR | PHP_INI_ALL |
highlight.comment | HL_COMMENT_COLOR | PHP_INI_ALL |
highlight.default | HL_DEFAULT_COLOR | PHP_INI_ALL |
highlight.html | HL_HTML_COLOR | PHP_INI_ALL |
highlight.keyword | HL_KEYWORD_COLOR | PHP_INI_ALL |
highlight.string | HL_STRING_COLOR | PHP_INI_ALL |
allow_call_time_pass_reference | "1" | PHP_INI_SYSTEM|PHP_INI_PERDIR |
asp_tags | "0" | PHP_INI_SYSTEM|PHP_INI_PERDIR |
display_errors | "1" | PHP_INI_ALL |
display_startup_errors | "0" | PHP_INI_ALL |
enable_dl | "1" | PHP_INI_SYSTEM |
error_append_string | NULL | PHP_INI_ALL |
error_prepend_string | NULL | PHP_INI_ALL |
expose_php | "1" | PHP_INI_SYSTEM |
html_errors | "1" | PHP_INI_SYSTEM |
ignore_user_abort | "0" | PHP_INI_ALL |
implicit_flush | "0" | PHP_INI_PERDIR|PHP_INI_SYSTEM |
log_errors | "0" | PHP_INI_ALL |
magic_quotes_gpc | "1" | PHP_INI_PERDIR|PHP_INI_SYSTEM |
magic_quotes_runtime | "0" | PHP_INI_ALL |
magic_quotes_sybase | "0" | PHP_INI_PERDIR|PHP_INI_SYSTEM |
output_buffering | "0" | PHP_INI_PERDIR|PHP_INI_SYSTEM |
output_handler | NULL | PHP_INI_PERDIR|PHP_INI_SYSTEM |
register_argc_argv | "1" | PHP_INI_ALL |
register_globals | "1" | PHP_INI_PERDIR|PHP_INI_SYSTEM |
safe_mode | "0" | PHP_INI_SYSTEM |
short_open_tag | "1" | PHP_INI_SYSTEM|PHP_INI_PERDIR |
sql.safe_mode | "0" | PHP_INI_SYSTEM |
track_errors | "0" | PHP_INI_ALL |
y2k_compliance | "0" | PHP_INI_ALL |
arg_separator | "&" | PHP_INI_ALL |
auto_append_file | NULL | PHP_INI_ALL |
auto_prepend_file | NULL | PHP_INI_ALL |
doc_root | NULL | PHP_INI_SYSTEM |
default_charset | SAPI_DEFAULT_CHARSET | PHP_INI_ALL |
default_mimetype | SAPI_DEFAULT_MIMETYPE | PHP_INI_ALL |
error_log | NULL | PHP_INI_ALL |
extension_dir | PHP_EXTENSION_DIR | PHP_INI_SYSTEM |
gpc_order | "GPC" | PHP_INI_ALL |
include_path | PHP_INCLUDE_PATH | PHP_INI_ALL |
max_execution_time | "30" | PHP_INI_ALL |
open_basedir | NULL | PHP_INI_SYSTEM |
safe_mode_exec_dir | "1" | PHP_INI_SYSTEM |
upload_max_filesize | "2M" | PHP_INI_ALL |
file_uploads | "1" | PHP_INI_ALL |
post_max_size | "8M" | PHP_INI_SYSTEM |
upload_tmp_dir | NULL | PHP_INI_SYSTEM |
user_dir | NULL | PHP_INI_SYSTEM |
variables_order | NULL | PHP_INI_ALL |
SMTP | "localhost" | PHP_INI_ALL |
browscap | NULL | PHP_INI_SYSTEM |
error_reporting | NULL | PHP_INI_ALL |
memory_limit | "8M" | PHP_INI_ALL |
precision | "14" | PHP_INI_ALL |
sendmail_from | NULL | PHP_INI_ALL |
sendmail_path | DEFAULT_SENDMAIL_PATH | PHP_INI_SYSTEM |
disable_functions | "" | PHP_INI_SYSTEM |
allow_url_fopen | "1" | PHP_INI_ALL |
Tabela 2. Definition of PHP_INI_* constants
Constant | Value | Meaning |
---|---|---|
PHP_INI_USER | 1 | Entry can be set in user scripts |
PHP_INI_PERDIR | 2 | Entry can be set in .htaccess |
PHP_INI_SYSTEM | 4 | Entry can be set in php.ini or httpd.conf |
PHP_INI_ALL | 7 | Entry can be set anywhere |
See also: ini_alter(), ini_get(), and ini_restore()
This function prints out the credits listing the PHP developers, modules, etc. It generates the appropriate HTML codes to insert the information in a page. A parameter indicating what will be printed (a pre-defined constant flag, see table below) needs to be passed. For example to print the general credits, you will use somewhere in your code:
And if you want to print the core developers and the documentation group, in a page of its own, you will use: And if you feel like embedding all the credits in your page, then code like the one below will do it:<html> <head> <title>My credits page</title> </head> <body> <?php // some code of your own phpcredits(CREDITS_ALL); // some more code ?> </body> </html> |
Tabela 1. Pre-defined phpcredits() flags
name | description |
---|---|
CREDITS_ALL | All the credits, equivalent to using: CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_FULLPAGE. It generates a complete stand-alone HTML page with the appropriate tags. |
CREDITS_DOCS | The credits for the documentation team |
CREDITS_FULLPAGE | Usually used in combination with the other flags. Indicates that the a complete stand-alone HTML page needs to be printed including the information indicated by the other flags. |
CREDITS_GENERAL | General credits: Language design and concept, PHP 4.0 authors and SAPI module. |
CREDITS_GROUP | A list of the core developers |
CREDITS_MODULES | A list of the extension modules for PHP, and their authors |
CREDITS_SAPI | A list of the server API modules for PHP, and their authors |
See also: phpinfo(), phpversion(), and php_logo_guid().
Outputs a large amount of information about the current state of PHP. This includes information about PHP compilation options and extensions, the PHP version, server information and environment (if compiled as a module), the PHP environment, OS version information, paths, master and local values of configuration options, HTTP headers, and the PHP License.
Because every system is setup differently, phpinfo() is commonly used to check configuration settings and for available predefined variables on a given system. Also, phpinfo() is a valuable debugging tool as it contains all EGPCS (Environment, GET, POST, Cookie, Server) data.
The output may be customized by passing one or more of the following constants bitwise values summed together in the optional what parameter. One can also combine the respective constants or bitwise values together with the or operator.
Tabela 1. phpinfo() options
Name (constant) | Value | Description |
---|---|---|
INFO_GENERAL | 1 | The configuration line, php.ini location, build date, Web Server, System and more. |
INFO_CREDITS | 2 | PHP 4 Credits. See also phpcredits(). |
INFO_CONFIGURATION | 4 | Current Local and Master values for php directives. See also ini_get(). |
INFO_MODULES | 8 | Loaded modules and there respective settings. |
INFO_ENVIRONMENT | 16 | Environment Variable information that's also available in $_ENV. |
INFO_VARIABLES | 32 | Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server). |
INFO_LICENSE | 64 | PHP License information. See also the license faq. |
INFO_ALL | -1 | Shows all of the above. This is the default value. |
Notatka: Parts of the information displayed are disabled when the expose_php configuration setting is set to off. This includes the PHP and Zend logos, and the credits.
See also: phpversion(), phpcredits(), php_logo_guid(), ini_get(), ini_set(), and the section on Predefined Variables.
Returns a string containing the version of the currently running PHP parser.
Notatka: This information is also available in the predefined constant PHP_VERSION.
See also version_compare(), phpinfo(), phpcredits(), php_logo_guid(), and zend_version().
Notatka: This functionality was added in PHP 4.0.0.
See also: phpinfo(), phpversion(), and phpcredits().
php_sapi_name() returns a lowercase string which describes the type of interface between web server and PHP (Server API, SAPI). In CGI PHP, this string is "cgi", in mod_php for Apache, this string is "apache" and so on.
php_uname() returns a string with a description of the operating system PHP is built on.
Adds setting to the server environment. The environment variable will only exist for the duration of the current request. At the end of the request the environment is restored to its original state.
Setting certain environment variables may be a potential security breach. The safe_mode_allowed_env_vars directive contains a comma-delimited list of prefixes. In Safe Mode, the user may only alter environment variables whose names begin with the prefixes supplied by this directive. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR). Note: if this directive is empty, PHP will let the user modify ANY environment variable!
The safe_mode_protected_env_vars directive contains a comma-delimited list of environment variables, that the end user won't be able to change using putenv(). These variables will be protected even if safe_mode_allowed_env_vars is set to allow to change them.
Ostrze¿enie |
These directives have only effect when safe-mode itself is enabled! |
See also getenv().
(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)
set_magic_quotes_runtime -- Sets the current active configuration setting of magic_quotes_runtimeSet the current active configuration setting of magic_quotes_runtime (0 for off, 1 for on).
See also: get_magic_quotes_gpc() and get_magic_quotes_runtime().
Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the configuration file. If seconds is set to zero, no time limit is imposed.
When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.
set_time_limit() has no effect when PHP is running in safe mode. There is no workaround other than turning off safe mode or changing the time limit in the configuration file.
Notatka: The set_time_limit() function and the configuration directive max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), the sleep() function, database queries, etc. is not included when determining the maximum time that the script has been running.
version_compare() compares two "PHP-standardized" version number strings. This is useful if you would like to write programs working only on some versions of PHP.
version_compare() returns -1 if the first version is lower than the second, 0 if they are equal, and +1 if the second is lower.
If you specify the third optional operator argument, you can test for a particular relationship. The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively. Using this argument, the function will return 1 if the relationship is the one specified by the operator, 0 otherwise.
Returns a string containing the version of the currently running PHP parser.
See also phpinfo(), phpcredits(), php_logo_guid(), and phpversion().
This module contains an interface to those functions defined in the IEEE 1003.1 (POSIX.1) standards document which are not accessible through other means. POSIX.1 for example defined the open(), read(), write() and close() functions, too, which traditionally have been part of PHP 3 for a long time. Some more system specific functions have not been available before, though, and this module tries to remedy this by providing easy access to these functions.
Send the signal sig to the process with the process identifier pid. Returns FALSE, if unable to send the signal, TRUE otherwise.
See also the kill(2) manual page of your POSIX system, which contains additional information about negative process identifiers, the special pid 0, the special pid -1, and the signal number 0.
Return the process identifier of the parent process of the current process.
Return the numeric real user ID of the current process. See also posix_getpwuid() for information on how to convert this into a useable username.
(PHP 3>= 3.0.10, PHP 4 >= 4.0.0)
posix_geteuid -- Return the effective user ID of the current processReturn the numeric effective user ID of the current process. See also posix_getpwuid() for information on how to convert this into a useable username.
Return the numeric real group ID of the current process. See also posix_getgrgid() for information on how to convert this into a useable group name.
(PHP 3>= 3.0.10, PHP 4 >= 4.0.0)
posix_getegid -- Return the effective group ID of the current processReturn the numeric effective group ID of the current process. See also posix_getgrgid() for information on how to convert this into a useable group name.
Set the real user ID of the current process. This is a privileged function and you need appropriate privileges (usually root) on your system to be able to perform this function.
Returns TRUE on success, FALSE otherwise. See also posix_setgid().
Set the real user ID of the current process. This is a privileged function and you need appropriate privileges (usually root) on your system to be able to perform this function.
Returns TRUE on success, FALSE otherwise. See also posix_setgid().
Set the real group ID of the current process. This is a privileged function and you need appropriate privileges (usually root) on your system to be able to perform this function. The appropriate order of function calls is posix_setgid() first, posix_setuid() last.
Returns TRUE on success, FALSE otherwise.
Set the effective group ID of the current process. This is a privileged function and you need appropriate privileges (usually root) on your system to be able to perform this function.
Returns TRUE on success, FALSE otherwise.
Returns an array of integers containing the numeric group ids of the group set of the current process. See also posix_getgrgid() for information on how to convert this into useable group names.
Returns the login name of the user owning the current process. See posix_getpwnam() for information how to get more information about this user.
Return the process group identifier of the current process. See POSIX.1 and the getpgrp(2) manual page on your POSIX system for more information on process groups.
Make the current process a session leader. See POSIX.1 and the setsid(2) manual page on your POSIX system for more informations on process groups and job control. Returns the session id.
Let the process pid join the process group pgid. See POSIX.1 and the setsid(2) manual page on your POSIX system for more informations on process groups and job control. Returns TRUE on success, FALSE otherwise.
Returns the process group identifier of the process pid.
This is not a POSIX function, but is common on BSD and System V systems. If your system does not support this function at system level, this PHP function will always return FALSE.
Return the sid of the process pid. If pid is 0, the sid of the current process is returned.
This is not a POSIX function, but is common on System V systems. If your system does not support this function at system level, this PHP function will always return FALSE.
Returns a hash of strings with information about the system. The indices of the hash are
sysname - operating system name (e.g. Linux)
nodename - system name (e.g. valiant)
release - operating system release (e.g. 2.2.10)
version - operating system version (e.g. #4 Tue Jul 20 17:01:36 MEST 1999)
machine - system architecture (e.g. i586)
domainname - DNS domainname (e.g. php.net)
domainname is a GNU extension and not part of POSIX.1, so this field is only available on GNU systems or when using the GNU libc.
Posix requires that you must not make any assumptions about the format of the values, e.g. you cannot rely on three digit version numbers or anything else returned by this function.
Returns a hash of strings with information about the current process CPU usage. The indices of the hash are
ticks - the number of clock ticks that have elapsed since reboot.
utime - user time used by the current process.
stime - system time used by the current process.
cutime - user time used by current process and children.
cstime - system time used by current process and children.
(PHP 3>= 3.0.13, PHP 4 >= 4.0.0)
posix_isatty -- Determine if a file descriptor is an interactive terminalNeeds to be written ASAP.
Notatka: Kiedy włączony jest tryb bezpieczny, PHP sprawdza czy katalog, na którym chcesz operować, ma takie same UID jak skrypt, który jest aktualnie wykonywany.
Returns an associative array containing information about a user referenced by an alphanumeric username, passed in the username parameter.
The array elements returned are:
Tabela 1. The user information array
Element | Description |
---|---|
name | The name element contains the username of the user. This is a short, usually less than 16 character "handle" of the user, not her real, full name. This should be the same as the username parameter used when calling the function, and hence redundant. |
passwd | The passwd element contains the user's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead. |
uid | User ID of the user in numeric form. |
gid | The group ID of the user. Use the function posix_getgrgid() to resolve the group name and a list of its members. |
gecos | GECOS is an obsolete term that refers to the finger information field on a Honeywell batch processing system. The field, however, lives on, and its contents have been formalized by POSIX. The field contains a comma separated list containing the user's full name, office phone, office number, and home phone number. On most systems, only the user's full name is available. |
dir | This element contains the absolute path to the home directory of the user. |
shell | The shell element contains the absolute path to the executable of the user's default shell. |
Returns an associative array containing information about a user referenced by a numeric user ID, passed in the uid parameter.
The array elements returned are:
Tabela 1. The user information array
Element | Description |
---|---|
name | The name element contains the username of the user. This is a short, usually less than 16 character "handle" of the user, not her real, full name. |
passwd | The passwd element contains the user's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead. |
uid | User ID, should be the same as the uid parameter used when calling the function, and hence redundant. |
gid | The group ID of the user. Use the function posix_getgrgid() to resolve the group name and a list of its members. |
gecos | GECOS is an obsolete term that refers to the finger information field on a Honeywell batch processing system. The field, however, lives on, and its contents have been formalized by POSIX. The field contains a comma separated list containing the user's full name, office phone, office number, and home phone number. On most systems, only the user's full name is available. |
dir | This element contains the absolute path to the home directory of the user. |
shell | The shell element contains the absolute path to the executable of the user's default shell. |
Ostrze¿enie |
Use of PostgreSQL module with PHP 4.0.6 is not recommended due to a bug in notice message handling. |
Ostrze¿enie | ||
PostgreSQL function names will be changed in 4.2.0 release to confirm current coding standard. Most of new names will have additional under score(s), e.g. pg_lo_open(). Some functions are renamed to different name for consistency. e.g. pg_exec() to pg_query(). Older names may be used in 4.2.0 and a few releases from 4.2.0, but they may be deleted in the future. CVS version has new function names.
Obsolete pg_connect()/pg_pconnect() syntax will be depreciated to support async connect feature in the future. Please use connection string for pg_connect() and pg_pconnect(). |
Postgres, developed originally in the UC Berkeley Computer Science Department, pioneered many of the object-relational concepts now becoming available in some commercial databases. It provides SQL92/SQL99 language support, transaction integrity and type extensibility. PostgreSQL is an open source descendant of this original Berkeley code.
PostgreSQL database is Open Source product and available without cost. To use PostgreSQL support, you need PostgreSQL 6.5 or later. PostgreSQL 7.0 or later to enable all PostgreSQL module feature. PostgreSQL supports many character encoding including multibyte character encoding. The current version and more information about PostgreSQL is available at www.postgresql.org.
In order to enable PostgreSQL support, "--with-pgsql[=DIR]" is required when you compile PHP. If shared object module is available, PostgreSQL module may be loaded using extension directive in php.ini or dl() function. Supported ini directives are described in php.ini-dist file which comes with source distribution.
Not all functions are supported by all builds. It depends on your libpq (The PostgreSQL C Client interface) version and how libpq is compiled. If there is missing function, libpq does not support the feature required for the function.
It is also important that you use newer libpq than PostgreSQL Server to be connected. If you use libpq older than PostgreSQL Server expects, you may have problems.
Since version 6.3 (03/02/1998) PostgreSQL uses unix domain sockets by default. TCP port will NOT be opened by default. A table is shown below describing these new connection possibilities. This socket will be found in /tmp/.s.PGSQL.5432. This option can be enabled with the '-i' flag to postmaster and it's meaning is: "listen on TCP/IP sockets as well as Unix domain sockets".
Tabela 1. Postmaster and PHP
Postmaster | PHP | Status |
---|---|---|
postmaster & | pg_connect("dbname=MyDbName"); | OK |
postmaster -i & | pg_connect("dbname=MyDbName"); | OK |
postmaster & | pg_connect("host=localhost dbname=MyDbName"); | Unable to connect to PostgreSQL server: connectDB() failed: Is the postmaster running and accepting TCP/IP (with -i) connection at 'localhost' on port '5432'? in /path/to/file.php on line 20. |
postmaster -i & | pg_connect("host=localhost dbname=MyDbName"); | OK |
A connection to PostgreSQL server can be established with the following value pairs set in the command string: $conn = pg_connect("host=myHost port=myPort tty=myTTY options=myOptions dbname=myDB user=myUser password=myPassword ");
The previous syntax of: $conn = pg_connect ("host", "port", "options", "tty", "dbname") has been deprecated.
Environmental variable affects PostgreSQL server/client behavior. For example, PostgreSQL module will lookup PGHOST environment variable when hostname is omitted in connection string. Supported environment variables are different from version to version. Refer to PostgreSQL Programmer's Manual (libpq - Environment Variables) for details.
From PostgreSQL 7.1.0, text data type has 1GB as its max size. Older PostgreSQL's text data type is limited by block size. (Default 8KB. Max 32KB defined at compile time)
To use the large object (lo) interface, it is required to enclose large object functions within a transaction block. A transaction block starts with a SQL statement begin and if the transaction was valid ends with commit or end. If the transaction fails the transaction should be closed with rollback or abort.
Przykład 2. Using Large Objects
|
pg_close() closes down the non-persistent connection to a PostgreSQL database associated with the given connection resource. It returns TRUE, if connection is a valid connection resource, otherwise it return FALSE.
Notatka: pg_close() is not usually necessary, as non-persistent open links are automatically closed at the end of the script's execution. pg_close() will not close persistent links generated by pg_pconnect().
If there is open large object resource on the connection, do not close the connection before closing all large object resources.
pg_cmdtuples() returns the number of tuples (instances/records/rows) affected by INSERT, UPDATE, and DELETE queries executed by pg_exec(). If no tuple is affected by this function, it will return 0.
See also pg_exec() and pg_numrows().
pg_connect() returns a connection resource that is needed by other PostgreSQL functions.
pg_connect() opens a connection to a PostgreSQL database specified by connection_string. It returns a connection resource on success. It returns FALSE, if the connection could not be made. connection_string should be a quoted string.
Przykład 1. Using pg_connect
|
If a second call is made to pg_connect() with the same connection_string arguments, no new connection will be established, but instead, the connection resource of the already opened connection will be returned. You can have multiple connections to the same database if you use different connection string.
Syntax supports multiple parameters: $conn = pg_connect ("host", "port", "options", "tty", "dbname") has been deprecated.
See also pg_pconnect(), pg_close(), pg_host(), pg_port(), pg_tty(), pg_options() and pg_dbname().
pg_dbname() returns the name of the database that the given PostgreSQL connection resource. It returns FALSE, if connection is not a valid PostgreSQL connection resource.
pg_end_copy() syncs PostgreSQL frontend (usually a web server process) with the PostgreSQL server after doing a copy operation performed by pg_put_line(). pg_end_copy() must be issued, otherwise the PostgreSQL server may get "out of sync" error with the frontend. It returns TRUE for success, otherwise it returns FALSE.
For further details and an example, see also pg_put_line().
pg_errormessage() returns a string containing the last error message for given connection. It returns FALSE on failure.
pg_errormessage() returns the last error message for given connection and error message may be overwritten if other libpq functions are called on the connection. PostgreSQL functions calls libpq functions internally. Therefore, details about the error may not be retrieved using the pg_errormessage() function. pg_result_error_message() will be added from 4.2.0 to get last error for the result resource.
pg_exec() returns a query result resource if query could be executed. It returns FALSE on failure or if connection is not a valid connection. Details about the error can be retrieved using the pg_errormessage() function if connection is valid. pg_errormessage() sends an SQL statement to the PostgreSQL database specified by the connection resource. The connection must be a valid connection that was returned by pg_connect() or pg_pconnect(). The return value of this function is an query result resource to be used to access the results from other PostgreSQL functions such as pg_fetch_array().
Notatka: connection is a optional parameter for pg_exec(). If connection is not used, default connection is used. Default connection is the last connection made by pg_connect() or pg_pconnect().
Although connection can be omitted, it is not recommended, since it could be a cause of hard to find bug in script.
See also pg_connect(), pg_pconnect(), pg_fetch_array(), pg_fetch_object(), pg_numrows(), and pg_cmdtuples().
pg_fetch_array() returns an array that corresponds to the fetched row (tuples/records). It returns FALSE, if there are no more rows.
pg_fetch_array() is an extended version of pg_fetch_row(). In addition to storing the data in the numeric indices (field index) to the result array, it also stores the data in associative indices (field name) by default.
row is row (record) number to be retrieved. First row is 0.
result_type is optional parameter controls how return value is initialized. result_type is a constant and can take the following values: PGSQL_ASSOC, PGSQL_NUM, and PGSQL_BOTH. pg_fetch_array() returns associative array that has field name as key for PGSQL_ASSOC. field index as key with PGSQL_NUM and both field name/index as key with PGSQL_BOTH. Default is PGSQL_BOTH.
Notatka: result_type was added in PHP 4.0.
pg_fetch_array() is NOT significantly slower than using pg_fetch_row(), while it provides a significant ease of use.
See also pg_fetch_row() and pg_fetch_object() and pg_result().
Przykład 1. PostgreSQL fetch array
|
Notatka: From 4.1.0, row became optional.
pg_fetch_object() returns an object with properties that correspond to the fetched row. It returns FALSE if there are no more rows or error.
pg_fetch_object() is similar to pg_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).
result_type is optional parameter controls how return value is initialized. result_type is a constant and can take the following values: PGSQL_ASSOC, PGSQL_NUM, and PGSQL_BOTH. pg_fetch_array() returns associative array that has field name as key for PGSQL_ASSOC. field index as key with PGSQL_NUM and both field name/index as key with PGSQL_BOTH. Default is PGSQL_BOTH.
Notatka: result_type was added in PHP 4.0.
Speed-wise, the function is identical to pg_fetch_array(), and almost as quick as pg_fetch_row() (the difference is insignificant).
See also pg_exec(), pg_fetch_array(), pg_fetch_row() and pg_result().
Przykład 1. Postgres fetch object
|
Notatka: From 4.1.0, row became optional.
pg_fetch_row() fetches one row of data from the result associated with the specified result resource. The row (record) is returned as an array. Each result column is stored in an array offset, starting at offset 0.
It returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
See also: pg_exec(), pg_fetch_array(), pg_fetch_object() and pg_result().
Przykład 1. Postgres fetch row
|
Notatka: From 4.1.0, row became optional.
pg_fieldisnull() test if a field is NULL or not. It returns 1 if the field in the given row is NULL. It returns 0 if the field in the given row is NOT NULL. Field can be specified as column index (number) or fieldname (string). Row numbering starts at 0.
pg_fieldname() returns the name of the field occupying the given field_number in the given PostgreSQL result resource. Field numbering starts from 0.
See also pg_fieldnum().
pg_fieldnum() will return the number of the column (field) slot that corresponds to the field_name in the given PostgreSQL result resource. Field numbering starts at 0. This function will return -1 on error.
See also pg_fieldname().
pg_fieldprtlen() returns the actual printed length (number of characters) of a specific value in a PostgreSQL result. Row numbering starts at 0. This function will return -1 on an error.
See also pg_fieldsize().
pg_fieldsize() returns the internal storage size (in bytes) of the field number in the given PostgreSQL result. Field numbering starts at 0. A field size of -1 indicates a variable length field. This function will return FALSE on error.
See also pg_fieldlen() and pg_fieldtype().
pg_fieldtype() returns a string containing the type name of the given field_number in the given PostgreSQL result resource. Field numbering starts at 0.
See also pg_fieldlen() and pg_fieldname().
pg_freeresult() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script is finished. But, if you are sure you are not going to need the result data anymore in a script, you may call pg_freeresult() with the result resource as an argument and the associated result memory will be freed. It returns true on success and false if an error occurs.
See also pg_exec().
pg_getlastoid() is used to retrieve the oid assigned to an inserted tuple (record) if the result resource is used from the last command sent via pg_exec() and was an SQL INSERT. Returns a positive integer if there was a valid oid. It returns FALSE if an error occurs or the last command sent via pg_exec() was not an INSERT or INSERT is failed.
See also pg_exec().
pg_host() returns the host name of the given PostgreSQL connection resource is connected to.
See also pg_connect() and pg_pconnect().
pg_last_notice() returns the last notice message from PostgreSQL server specified by connection. PostgreSQL server set notice message when transaction cannot be continued. There one can avoid issuing useless SQL using pg_exec() using pg_last_notice(). There are other cases that PostgreSQL server sets notice message. Programmer must check contents of notice message if it is related to transaction or not.
Ostrze¿enie |
This function is EXPERIMENTAL and it is not fully implemented yet. pg_last_notice() is added form PHP 4.0.6. However, PHP 4.0.6 has problem with notice message handling. Use of PostgreSQL module with PHP 4.0.6 is not recommended even if you are not using pg_last_notice(). |
See also pg_exec() and pg_errormessage().
pg_loclose() closes an Inversion Large Object. large_object is a resource for the large object from pg_loopen().
To use the large object (lo) interface, it is necessary to enclose it within a transaction block.
See also pg_loopen(), pg_locreate() and pg_loimport().
pg_locreate() creates an Inversion Large Object and returns the oid of the large object. connection specifies a valid database connection opened by pg_connect() or pg_pconnect(). PostgreSQL access modes INV_READ, INV_WRITE, and INV_ARCHIVE are not supported, the object is created always with both read and write access. INV_ARCHIVE has been removed from PostgreSQL itself (version 6.3 and above). It returns large object oid otherwise. It returns FALSE, if an error occurred,
To use the large object (lo) interface, it is necessary to enclose it within a transaction block.
The oid argument specifies oid of the large object to export and the pathname argument specifies the pathname of the file. It returns FALSE if an error occurred, TRUE otherwise.
To use the large object (lo) interface, it is necessary to enclose it within a transaction block.
See also pg_loimport().
The pathname argument specifies the pathname of the file to be imported as a large object. It returns FALSE if an error occurred, oid of the just created large object otherwise.
To use the large object (lo) interface, it is necessary to enclose it within a transaction block.
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 pg_loexport() and pg_loopen().
pg_loopen() open an Inversion Large Object and returns large object resource. The resource encapsulates information about the connection. oid specifies a valid large object oid and mode can be either "r", "w", or "rw". It returns FALSE if there is an error.
Ostrze¿enie |
Do not close the database connection before closing the large object resource. |
To use the large object (lo) interface, it is necessary to enclose it within a transaction block.
See also pg_loclose() and pg_locreate().
pg_loread() reads at most len bytes from a large object and returns it as a string. large_object specifies a valid large object resource andlen specifies the maximum allowable size of the large object segment. It returns FALSE if there is an error.
To use the large object (lo) interface, it is necessary to enclose it within a transaction block.
See also pg_loreadall().
pg_loreadall() reads a large object and passes it straight through to the browser after sending all pending headers. Mainly intended for sending binary data like images or sound. It returns number of bytes read. It returns FALSE, if an error occurred.
To use the large object (lo) interface, it is necessary to enclose it within a transaction block.
See also pg_loread().
pg_lounlink() deletes a large object with the oid. It returns TRUE on success, otherwise returns FALSE.
To use the large object (lo) interface, it is necessary to enclose it within a transaction block.
See also pg_locreate() and pg_loimport().
pg_lowrite() writes at most to a large object from a variable data and returns the number of bytes actually written, or FALSE in the case of an error. large_object is a large object resource from pg_loopen().
To use the large object (lo) interface, it is necessary to enclose it within a transaction block.
See also pg_locreate() and pg_loopen().
pg_numfields() returns the number of fields (columns) in a PostgreSQL result. The argument is a result resource returned by pg_exec(). This function will return -1 on error.
See also pg_numrows() and pg_cmdtuples().
pg_numrows() will return the number of rows in a PostgreSQL result resource. result is a query result resource returned by pg_exec(). This function will return -1 on error.
Notatka: Use pg_cmdtuples() to get number of rows affected by INSERT, UPDATE and DELETE query.
See also pg_numfields() and pg_cmdtuples().
pg_options() will return a string containing the options specified on the given PostgreSQL connection resource.
pg_pconnect() opens a connection to a PostgreSQL database. It returns a connection resource that is needed by other PostgreSQL functions.
It returns a connection resource on success, or FALSE if the connection could not be made. The arguments should be within a quoted string. The arguments available include host, port, tty, options, dbname, user, and password.
Przykład 1. Using pg_pconnect
|
If a second call is made to pg_pconnect() with the same arguments, no new connection will be established, but instead, the connection resource of the already opened connection will be returned. You can have multiple connections to the same database if you use different connection string.
Multiple parameters syntax for pg_pconnect() $conn = pg_pconnect ("host", "port", "options", "tty", "dbname") has been deprecated.
To enable persistent connection, pgsql.allow_persistent php.ini directive must be set to "On". (Default is On) Max number of persistent connection can be defined by pgsql.max_persistent php.ini directive. (Default is -1 which is no limit) Total number of connection can be set by pgsql.max_links php.ini directive.
pg_close() will not close persistent links generated by pg_pconnect().
See also pg_connect().
pg_port() returns the port number that the given PostgreSQL connection resource is connected to.
pg_put_line() sends a NULL-terminated string to the PostgreSQL backend server. This is useful for example for very high-speed inserting of data into a table, initiated by starting a PostgreSQL copy-operation. That final NULL-character is added automatically. It returns TRUE if successful, FALSE otherwise.
Notatka: Note the application must explicitly send the two characters "\." on a final line to indicate to the backend that it has finished sending its data.
See also pg_end_copy().
Przykład 1. High-speed insertion of data into a table
|
pg_result() returns values from a result resource returned by pg_exec(). row_number is integer. field is field name(string) or field index (integer). The row_number and field specify what cell in the table of results to return. Row numbering starts from 0. Instead of naming the field, you may use the field index as an unquoted number. Field indices start from 0.
PostgreSQL has many built in types and only the basic ones are directly supported here. All forms of integer, boolean and void types are returned as integer values. All forms of float, and real types are returned as float values. All other types, including arrays are returned as strings formatted in the same default PostgreSQL manner that you would see in the psql program.
pg_set_client_encoding() sets the client encoding and return 0 if success or -1 if error.
encoding is the client encoding and can be either : SQL_ASCII, EUC_JP, EUC_CN, EUC_KR, EUC_TW, UNICODE, MULE_INTERNAL, LATINX (X=1...9), KOI8, WIN, ALT, SJIS, BIG5, WIN1250. Available encoding depends on your PostgreSQL and libpq version. Refer to PostgreSQL manual for supported encodings for your PostgreSQL.
Notatka: This function requires PHP-4.0.3 or higher and PostgreSQL-7.0 or higher. Supported encoding depends on PostgreSQL version. Refer to PostgreSQL manual for details.
The function used to be called pg_setclientencoding().
See also pg_client_encoding().
pg_client_encoding() returns the client encoding as the string. The returned string should be either : SQL_ASCII, EUC_JP, EUC_CN, EUC_KR, EUC_TW, UNICODE, MULE_INTERNAL, LATINX (X=1...9), KOI8, WIN, ALT, SJIS, BIG5, WIN1250.
Notatka: This function requires PHP-4.0.3 or higher and PostgreSQL-7.0 or higher. If libpq is compiled without multibyte encoding support, pg_set_client_encoding() always return "SQL_ASCII". Supported encoding depends on PostgreSQL version. Refer to PostgreSQL manual for details to enable multibyte support and encoding supported.
The function used to be called pg_clientencoding().
See also pg_set_client_encoding().
pg_trace() enables tracing of the PostgreSQL frontend/backend communication to a debugging file specified as pathname. To fully understand the results, one needs to be familiar with the internals of PostgreSQL communication protocol. For those who are not, it can still be useful for tracing errors in queries sent to the server, you could do for example grep '^To backend' trace.log and see what query actually were sent to the PostgreSQL server. For more information, refer to PostgreSQL manual.
Filename and mode are the same as in fopen() (mode defaults to 'w'), connection specifies the connection to trace and defaults to the last one opened.
It returns TRUE if pathname could be opened for logging, FALSE otherwise.
See also fopen() and pg_untrace().
pg_tty() returns the tty name that server side debugging output is sent to on the given PostgreSQL connection resource.
Stop tracing started by pg_trace(). connection specifies the connection that was traced and defaults to the last one opened.
Returns always TRUE.
See also pg_trace().
pg_get_result() get result resource from async query executed by pg_send_query(). pg_send_query() can send multiple queries to PostgreSQL server and pg_get_result() is used to get query result one by one. It returns result resource. If there is no more results, it returns FALSE.
pg_result_status() returns status of result resource. Possible retun values are PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK, PGSQL_COPY_TO, PGSQL_COPY_FROM, PGSQL_BAD_RESPONSE, PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR.
See also pg_connection_status().
pg_send_query() send asynchronous query to the connection. Unlike pg_query(), it can send multiple query to PostgreSQL and get the result one by one using pg_get_result(). Script execution is not block while query is executing. Use pg_connection_busy() to check connection is busy (i.e. query is executing) Query may be canceled by calling pg_cancel_query().
Although, user can send multiple query at once. User cannot send multiple query over busy connection. If query is sent while connection is busy, it waits until last query is finished and discards all result.
See also pg_query(), pg_cancel_query(), pg_get_result() and pg_connection_busy()
pg_cancel_query() cancel asynchronous query sent by pg_send_query(). You cannot cancel query executed by pg_query().
See also pg_send_query(), pg_cancel_result() and pg_connection_busy()
pg_connection_busy() returns TRUE if connection busy. If connection is busy, previously sent query to PostgreSQL server is still executing. If pg_get_result() is called, pg_get_result() will block.
See also pg_connection_status() and pg_get_result()
pg_connection_reset() reset connection with the same parameter when connection is made. It is useful for error recovery. It returns TRUE if it resets connection successfully, otherwise returns FALSE.
See also pg_connect(), pg_pconnect() and pg_connection_status()
pg_connection_status() returns a connection status. Possible status is PGSQL_CONNECTION_O or PGSQL_CONNECTION_BAD.
See also pg_connection_busy()
pg_copy_from() copy table from array. It return TRUE for success, otherwise FALSE.
See also pg_copy_to()
pg_copy_to() copy table to array. The result array is returned if it success to copy. Otherwise it returns FALSE.
See also pg_copy_from()
pg_escape_string() escapes string for bytea datatype. It returns escaped string.
Notatka: This function is requires PostgreSQL 7.2 or later.
See also pg_escape_string()
pg_escape_string() escapes string for text/char datatype. It returns escaped string.
Notatka: This function is requires PostgreSQL 7.2 or later.
See also pg_escape_bytea()
pg_lo_seek() seeks position of large object resource. whence is PGSQL_SEEK_SET, PGSQL_SEEK_CUR or PGSQL_SEEK_END.
See also pg_lo_tell().
pg_lo_tell() returns current position (offset from the beginning of large object).
See also pg_lo_seek().
pg_result_error() returns error message associated with result resource. Therefore, user has better chance to get better error message than pg_last_error().
See also pg_query(), pg_send_query(), pg_get_result(), pg_last_error() and pg_last_notice()
Process Control support in PHP implements the Unix style of process creation, program execution, signal handling and process termination. Process Control should not be enabled within a webserver environment and unexpected results may happen if any Process Control functions are used within a webserver environment.
This documentation is intended to explain the general usage of each of the Process Control functions. For detailed information about Unix process control you are encouraged to consult your systems documentation including fork(2), waitpid(2) and signal(2) or a comprehensive reference such as Advanced Programming in the UNIX Environment by W. Richard Stevens (Addison-Wesley).
Process Control support in PHP is not enabled by default. You will need to use the --enable-pcntl configuration option when compiling PHP to enable Process Control support.
Notatka: Currently, this module will not function on non-Unix platforms (Windows).
The following list of signals are supported by the Process Control functions. Please see your systems signal(7) man page for details of the default behavior of these signals.
Tabela 1. Supported Signals
SIGFPE | SIGCONT | SIGKILL |
SIGSTOP | SIGUSR1 | SIGTSTP |
SIGHUP | SIGUSR2 | SIGTTIN |
SIGINT | SIGSEGV | SIGTTOU |
SIGQUIT | SIGPIPE | SIGURG |
SIGILL | SIGALRM | SIGXCPU |
SIGTRAP | SIGTERM | SIGXFSZ |
SIGABRT | SIGSTKFLT | SIGVTALRM |
SIGIOT | SIGCHLD | SIGPROF |
SIGBUS | SIGCLD | SIGWINCH |
SIGPOLL | SIGIO | SIGPWR |
SIGSYS |
This example forks off a daemon process with a signal handler.
Przykład 1. Process Control Example
|
The pcntl_fork() function creates a child process that differs from the parent process only in it's PID and PPID. Please see your system's fork(2) man page for specific details as to how fork works on your system.
On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and a PHP error is raised.
See also pcntl_waitpid() and pcntl_signal().
The pcntl_signal() function installs a new signal handler for the signal indicated by signo. The signal handler is set to handler which may be the name of a user created function, or either of the two global constants SIG_IGN or SIG_DFL.
pcntl_signal() returns TRUE on success or FALSE on failure.
Przykład 1. pcntl_signal() Example
|
See also pcntl_fork() and pcntl_waitpid().
The pcntl_waitpid() function suspends execution of the current process until a child as specified by the pid argument has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function. If a child as requested by pid has already exited by the time of the call (a so-called "zombie" process), the function returns immediately. Any system resources used by the child are freed. Please see your system's waitpid(2) man page for specific details as to how waitpid works on your system.
pcntl_waitpid() returns the process ID of the child which exited, -1 on error or zero if WNOHANG was used and no child was available
The value of pid can be one of the following:
Tabela 1. possible values for pid
< -1 | wait for any child process whose process group ID is equal to the absolute value of pid. |
-1 | wait for any child process; this is the same behaviour that the wait function exhibits. |
0 | wait for any child process whose process group ID is equal to that of the calling process. |
> 0 | wait for the child whose process ID is equal to the value of pid. |
pcntl_waitpid() will store status information in the status parameter which can be evaluated using the following functions: pcntl_wifexited(), pcntl_wifstopped(), pcntl_wifsignaled(), pcntl_wexitstatus(), pcntl_wtermsig() and pcntl_wstopsig().
The value of options is the value of zero or more of the following two global constants OR'ed together:
Tabela 2. possible values for options
WNOHANG | return immediately if no child has exited. |
WUNTRACED | return for children which are stopped, and whose status has not been reported. |
See also pcntl_fork(), pcntl_signal(), pcntl_wifexited(), pcntl_wifstopped(), pcntl_wifsignaled(), pcntl_wexitstatus(), pcntl_wtermsig() and pcntl_wstopsig().
Returns the return code of a terminated child. This function is only useful if pcntl_wifexited() returned TRUE.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid() and pcntl_wifexited().
Returns TRUE if the child status code represents a successful exit.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid() and pcntl_wexitstatus().
(PHP 4 >= 4.1.0)
pcntl_wifsignaled -- Returns TRUE if status code represents a termination due to a signalReturns TRUE if the child process exited because of a signal which was not caught.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid() and pcntl_signal().
Returns TRUE if the child process which caused the return is currently stopped; this is only possible if the call to pcntl_waitpid() was done using the option WUNTRACED.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid().
Returns the number of the signal which caused the child to stop. This function is only useful if pcntl_wifstopped() returned TRUE.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid() and pcntl_wifstopped().
Returns the number of the signal that caused the child process to terminate. This function is only useful if pcntl_wifsignaled() returned TRUE.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid(), pcntl_signal() and pcntl_wifsignaled().
Those functions provides means to executes commands on the system itself, and means secure such commands. Those functions are also closely related to the backtick operator.
escapeshellarg() adds single quotes around a string and quotes/escapes any existing single quotes allowing you to pass a string directly to a shell function and having it be treated as a single safe argument. This function should be used to escape individual arguments to shell functions coming from user input. The shell functions include exec(), system() and the backtick operator. A standard use would be:
See also exec(), popen(), system(), and the backtick operator.
escapeshellcmd() escapes any characters in a string that might be used to trick a shell command into executing arbitrary commands. This function should be used to make sure that any data coming from user input is escaped before this data is passed to the exec() or system() functions, or to the backtick operator. A standard use would be:
$e = escapeshellcmd($userinput); system("echo $e"); // here we don't care if $e has spaces $f = escapeshellcmd($filename); system("touch \"/tmp/$f\"; ls -l \"/tmp/$f\""); // and here we do, so we use quotes |
See also escapeshellarg(), exec(), popen(), system(), and the backtick operator.
exec() executes the given command, however it does not output anything. It simply returns the last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.
If the array argument is present, then the specified array will be filled with every line of output from the command. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().
If the return_var argument is present along with the array argument, then the return status of the executed command will be written to this variable.
Ostrze¿enie |
If you are going to allow data coming from user input to be passed to this function, then you should be using escapeshellarg() or escapeshellcmd() to make sure that users cannot trick the system into executing arbitrary commands. |
Notatka: If you start a program using this function and want to leave it running in the background, you have to make sure that the output of that program is redirected to a file or some other output stream or else PHP will hang until the execution of the program ends.
See also system(), passthru(), popen(), escapeshellcmd(), and the backtick operator.
The passthru() function is similar to the exec() function in that it executes a command. If the return_var argument is present, the return status of the Unix command will be placed here. This function should be used in place of exec() or system() when the output from the Unix command is binary data which needs to be passed directly back to the browser. A common use for this is to execute something like the pbmplus utilities that can output an image stream directly. By setting the Content-type to image/gif and then calling a pbmplus program to output a gif, you can create PHP scripts that output images directly.
Ostrze¿enie |
If you are going to allow data coming from user input to be passed to this function, then you should be using escapeshellarg() or escapeshellcmd() to make sure that users cannot trick the system into executing arbitrary commands. |
Notatka: If you start a program using this function and want to leave it running in the background, you have to make sure that the output of that program is redirected to a file or some other output stream or else PHP will hang until the execution of the program ends.
See also exec(), system(), popen(), escapeshellcmd(), and the backtick operator.
system() is just like the C version of the function in that it executes the given command and outputs the result. If a variable is provided as the second argument, then the return status code of the executed command will be written to this variable.
Ostrze¿enie |
If you are going to allow data coming from user input to be passed to this function, then you should be using escapeshellarg() or escapeshellcmd() to make sure that users cannot trick the system into executing arbitrary commands. |
Notatka: If you start a program using this function and want to leave it running in the background, you have to make sure that the output of that program is redirected to a file or some other output stream or else PHP will hang until the execution of the program ends.
The system() call also tries to automatically flush the web server's output buffer after each line of output if PHP is running as a server module.
Returns the last line of the command output on success, and FALSE on failure.
If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.
See also exec(), passthru(), popen(), escapeshellcmd(), and the backtick operator.
These functions are only available under Windows 9.x, ME, NT4 and 2000. They have been added in PHP 4 (4.0.4).
This function tries to open a connection to the printer devicename, and returns a handle on success or FALSE on failure.
If no parameter was given it tries to open a connection to the default printer (if not specified in php.ini as printer.default_printer, php tries to detect it).
printer_open() also starts a device context.
This function deletes the printers spool file.
handle must be a valid handle to a printer.
This function closes the printer connection. printer_close() also closes the active device context.
handle must be a valid handle to a printer.
Writes content directly to the printer, and returns TRUE on success or FALSE if it failed.
handle must be a valid handle to a printer.
The function enumerates available printers and their capabilities. level sets the level of information request. Can be 1,2,4 or 5. enumtype must be one of the following predefined constants:
PRINTER_ENUM_LOCAL: enumerates the locally installed printers.
PRINTER_ENUM_NAME: enumerates the printer of name, can be a server, domain or print provider.
PRINTER_ENUM_SHARED: this parameter can't be used alone, it has to be OR'ed with other parameters, i.e. PRINTER_ENUM_LOCAL to detect the locally shared printers.
PRINTER_ENUM_DEFAULT: (Win9.x only) enumerates the default printer.
PRINTER_ENUM_CONNECTIONS: (WinNT/2000 only) enumerates the printers to which the user has made connections.
PRINTER_ENUM_NETWORK: (WinNT/2000 only) enumerates network printers in the computer's domain. Only valid if level is 1.
PRINTER_ENUM_REMOTE: (WinNT/2000 only) enumerates network printers and print servers in the computer's domain. Only valid if level is 1.
The function sets the following options for the current connection: handle must be a valid handle to a printer. For option can be one of the following constants:
PRINTER_COPIES: sets how many copies should be printed, value must be an integer.
PRINTER_MODE: specifies the type of data (text, raw or emf), value must be a string.
PRINTER_TITLE: specifies the name of the document, value must be a string.
PRINTER_ORIENTATION: specifies the orientation of the paper, value can be either PRINTER_ORIENTATION_PORTRAIT or PRINTER_ORIENTATION_LANDSCAPE
PRINTER_RESOLUTION_Y: specifies the y-resolution in DPI, value must be an integer.
PRINTER_RESOLUTION_X: specifies the x-resolution in DPI, value must be an integer.
PRINTER_PAPER_FORMAT: specifies the a predefined paper format, set value to PRINTER_FORMAT_CUSTOM if you want to specify a custom format with PRINTER_PAPER_WIDTH and PRINTER_PAPER_LENGTH. value can be one of the following constants.
PRINTER_FORMAT_CUSTOM: let's you specify a custom paper format.
PRINTER_FORMAT_LETTER: specifies standard letter format (8 1/2- by 11-inches).
PRINTER_FORMAT_LETTER: specifies standard legal format (8 1/2- by 14-inches).
PRINTER_FORMAT_A3: specifies standard A3 format (297- by 420-millimeters).
PRINTER_FORMAT_A4: specifies standard A4 format (210- by 297-millimeters).
PRINTER_FORMAT_A5: specifies standard A5 format (148- by 210-millimeters).
PRINTER_FORMAT_B4: specifies standard B4 format (250- by 354-millimeters).
PRINTER_FORMAT_B5: specifies standard B5 format (182- by 257-millimeter).
PRINTER_FORMAT_FOLIO: specifies standard FOLIO format (8 1/2- by 13-inch).
PRINTER_PAPER_LENGTH: if PRINTER_PAPER_FORMAT is set to PRINTER_FORMAT_CUSTOM, PRINTER_PAPER_LENGTH specifies a custom paper length in mm, value must be an integer.
PRINTER_PAPER_WIDTH: if PRINTER_PAPER_FORMAT is set to PRINTER_FORMAT_CUSTOM, PRINTER_PAPER_WIDTH specifies a custom paper width in mm, value must be an integer.
PRINTER_SCALE: specifies the factor by which the printed output is to be scaled. the page size is scaled from the physical page size by a factor of scale/100. for example if you set the scale to 50, the output would be half of it's original size. value must be an integer.
PRINTER_BACKGROUND_COLOR: specifies the background color for the actual device context, value must be a string containing the rgb information in hex format i.e. "005533".
PRINTER_TEXT_COLOR: specifies the text color for the actual device context, value must be a string containing the rgb information in hex format i.e. "005533".
PRINTER_TEXT_ALIGN: specifies the text alignment for the actual device context, value can be combined through OR'ing the following constants:
PRINTER_TA_BASELINE: text will be aligned at the base line.
PRINTER_TA_BOTTOM: text will be aligned at the bottom.
PRINTER_TA_TOP: text will be aligned at the top.
PRINTER_TA_CENTER: text will be aligned at the center.
PRINTER_TA_LEFT: text will be aligned at the left.
PRINTER_TA_RIGHT: text will be aligned at the right.
The function retrieves the configuration setting of option. handle must be a valid handle to a printer. Take a look at printer_set_option() for the settings that can be retrieved, additionally the following settings can be retrieved:
PRINTER_DEVICENAME returns the devicename of the printer.
PRINTER_DRIVERVERSION returns the printer driver version.
The function creates a new device context. A device context is used to customize the graphic objects of the document. handle must be a valid handle to a printer.
Przykład 1. printer_create_dc() example
|
The function deletes the device context and returns TRUE on success, or FALSE if an error occurred. For an example see printer_create_dc(). handle must be a valid handle to a printer.
The function creates a new document in the printer spooler. A document can contain multiple pages, it's used to schedule the print job in the spooler. handle must be a valid handle to a printer. The optional parameter document can be used to set an alternative document name.
Closes a new document in the printer spooler. The document is now ready for printing. For an example see printer_start_doc(). handle must be a valid handle to a printer.
The function creates a new page in the active document. For an example see printer_start_doc(). handle must be a valid handle to a printer.
The function closes the active page in the active document. For an example see printer_start_doc(). handle must be a valid handle to a printer.
The function creates a new pen and returns a handle to it. A pen is used to draw lines and curves. For an example see printer_select_pen(). color must be a color in RGB hex format, i.e. "000000" for black, width specifies the width of the pen whereas style must be one of the following constants:
PRINTER_PEN_SOLID: creates a solid pen.
PRINTER_PEN_DASH: creates a dashed pen.
PRINTER_PEN_DOT: creates a dotted pen.
PRINTER_PEN_DASHDOT: creates a pen with dashes and dots.
PRINTER_PEN_DASHDOTDOT: creates a pen with dashes and double dots.
PRINTER_PEN_INVISIBLE: creates an invisible pen.
The function deletes the selected pen. For an example see printer_select_pen(). It returns TRUE on success, or FALSE otherwise. handle must be a valid handle to a pen.
The function selects a pen as the active drawing object of the actual device context. A pen is used to draw lines and curves. I.e. if you draw a single line the pen is used. If you draw an rectangle the pen is used to draw the borders, while the brush is used to fill the shape. If you haven't selected a pen before drawing shapes, the shape won't be outlined. printer_handle must be a valid handle to a printer. pen_handle must be a valid handle to a pen.
Przykład 1. printer_select_pen() example
|
The function creates a new brush and returns a handle to it. A brush is used to fill shapes. For an example see printer_select_brush(). color must be a color in RGB hex format, i.e. "000000" for black, style must be one of the following constants:
PRINTER_BRUSH_SOLID: creates a brush with a solid color.
PRINTER_BRUSH_DIAGONAL: creates a brush with a 45-degree upward left-to-right hatch ( / ).
PRINTER_BRUSH_CROSS: creates a brush with a cross hatch ( + ).
PRINTER_BRUSH_DIAGCROSS: creates a brush with a 45 cross hatch ( x ).
PRINTER_BRUSH_FDIAGONAL: creates a brush with a 45-degree downward left-to-right hatch ( \ ).
PRINTER_BRUSH_HORIZONTAL: creates a brush with a horizontal hatch ( - ).
PRINTER_BRUSH_VERTICAL: creates a brush with a vertical hatch ( | ).
PRINTER_BRUSH_CUSTOM: creates a custom brush from an BMP file. The second parameter is used to specify the BMP instead of the RGB color code.
The function deletes the selected brush. For an example see printer_select_brush(). It returns TRUE on success, or FALSE otherwise. handle must be a valid handle to a brush.
The function selects a brush as the active drawing object of the actual device context. A brush is used to fill shapes. If you draw an rectangle the brush is used to draw the shapes, while the pen is used to draw the border. If you haven't selected a brush before drawing shapes, the shape won't be filled. printer_handle must be a valid handle to a printer. brush_handle must be a valid handle to a brush.
Przykład 1. printer_select_brush() example
|
The function creates a new font and returns a handle to it. A font is used to draw text. For an example see printer_select_font(). face must be a string specifying the font face. height specifies the font height, and width the font width. The font_weight specifies the font weight (400 is normal), and can be one of the following predefined constants.
PRINTER_FW_THIN: sets the font weight to thin (100).
PRINTER_FW_ULTRALIGHT: sets the font weight to ultra light (200).
PRINTER_FW_LIGHT: sets the font weight to light (300).
PRINTER_FW_NORMAL: sets the font weight to normal (400).
PRINTER_FW_MEDIUM: sets the font weight to medium (500).
PRINTER_FW_BOLD: sets the font weight to bold (700).
PRINTER_FW_ULTRABOLD: sets the font weight to ultra bold (800).
PRINTER_FW_HEAVY: sets the font weight to heavy (900).
italic can be TRUE or FALSE, and sets whether the font should be italic.
underline can be TRUE or FALSE, and sets whether the font should be underlined.
strikeout can be TRUE or FALSE, and sets whether the font should be striked out.
orientation specifies a rotation. For an example see printer_select_font().
The function deletes the selected font. For an example see printer_select_font(). It returns TRUE on success, or FALSE otherwise. handle must be a valid handle to a font.
The function selects a font to draw text. printer_handle must be a valid handle to a printer. font_handle must be a valid handle to a font.
Przykład 1. printer_select_font() example
|
The function calculates the logical font height of height. handle must be a valid handle to a printer.
The function simply draws a rectangle with rounded corners.
handle must be a valid handle to a printer.
ul_x is the upper left x coordinate of the rectangle.
ul_y is the upper left y coordinate of the rectangle.
lr_x is the lower right x coordinate of the rectangle.
lr_y is the lower right y coordinate of the rectangle.
width is the width of the ellipse.
height is the height of the ellipse.
Przykład 1. printer_draw_roundrect() example
|
The function simply draws a rectangle.
handle must be a valid handle to a printer.
ul_x is the upper left x coordinate of the rectangle.
ul_y is the upper left y coordinate of the rectangle.
lr_x is the lower right x coordinate of the rectangle.
lr_y is the lower right y coordinate of the rectangle.
Przykład 1. printer_draw_rectangle() example
|
The function simply draws an ellipse. handle must be a valid handle to a printer.
ul_x is the upper left x coordinate of the ellipse.
ul_y is the upper left y coordinate of the ellipse.
lr_x is the lower right x coordinate of the ellipse.
lr_y is the lower right y coordinate of the ellipse.
Przykład 1. printer_draw_elipse() example
|
The function simply draws text at position x, y using the selected font. printer_handle must be a valid handle to a printer.
Przykład 1. printer_draw_text() example
|
The function simply draws a line from position from_x, from_y to position to_x, to_y using the selected pen. printer_handle must be a valid handle to a printer.
Przykład 1. printer_draw_line() example
|
The function simply draws an chord. handle must be a valid handle to a printer.
rec_x is the upper left x coordinate of the bounding rectangle.
rec_y is the upper left y coordinate of the bounding rectangle.
rec_x1 is the lower right x coordinate of the bounding rectangle.
rec_y1 is the lower right y coordinate of the bounding rectangle.
rad_x is x coordinate of the radial defining the beginning of the chord.
rad_y is y coordinate of the radial defining the beginning of the chord.
rad_x1 is x coordinate of the radial defining the end of the chord.
rad_y1 is y coordinate of the radial defining the end of the chord.
Przykład 1. printer_draw_chord() example
|
The function simply draws an pie. handle must be a valid handle to a printer.
rec_x is the upper left x coordinate of the bounding rectangle.
rec_y is the upper left y coordinate of the bounding rectangle.
rec_x1 is the lower right x coordinate of the bounding rectangle.
rec_y1 is the lower right y coordinate of the bounding rectangle.
rad1_x is x coordinate of the first radial's ending.
rad1_y is y coordinate of the first radial's ending.
rad2_x is x coordinate of the second radial's ending.
rad2_y is y coordinate of the second radial's ending.
Przykład 1. printer_draw_chord() example
|
These functions allow you to check the spelling of a word and offer suggestions.
You need the aspell and pspell libraries, available from http://aspell.sourceforge.net/ and http://pspell.sourceforge.net/ respectively, and add the --with-pspell[=dir] option when compiling php.
pspell_add_to_personal() adds a word to the personal wordlist. If you used pspell_new_config() with pspell_config_personal() to open the dictionary, you can save the wordlist later with pspell_save_wordlist(). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.
pspell_add_to_session() adds a word to the wordlist associated with the current session. It is very similar to pspell_add_to_personal()
pspell_check() checks the spelling of a word and returns TRUE if the spelling is correct, FALSE if not.
pspell_clear_session() clears the current session. The current wordlist becomes blank, and, for example, if you try to save it with pspell_save_wordlist(), nothing happens.
Przykład 1. pspell_add_to_personal()
|
pspell_config_create() has a very similar syntax to pspell_new(). In fact, using pspell_config_create() immediatelly followed by pspell_new_config() will produce the exact same result. However, after creating a new config, you can also use pspell_config_*() functions before calling pspell_new_config() to take advantage of some advanced functionality.
The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.
The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.
The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.
The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.
The mode parameter is the mode in which spellchecker will work. There are several modes available:
PSPELL_FAST - Fast mode (least number of suggestions)
PSPELL_NORMAL - Normal mode (more suggestions)
PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)
For more information and examples, check out inline manual pspell website:http://pspell.sourceforge.net/.
pspell_config_ignore() should be used on a config before calling pspell_new_config(). This function allows short words to be skipped by the spellchecker. Words less then n characters will be skipped.
pspell_config_mode() should be used on a config before calling pspell_new_config(). This function determines how many suggestions will be returned by pspell_suggest().
The mode parameter is the mode in which spellchecker will work. There are several modes available:
PSPELL_FAST - Fast mode (least number of suggestions)
PSPELL_NORMAL - Normal mode (more suggestions)
PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)
pspell_config_personal() should be used on a config before calling pspell_new_config(). The personal wordlist will be loaded and used in addition to the standard one after you call pspell_new_config(). If the file does not exist, it will be created. The file is also the file where pspell_save_wordlist() will save personal wordlist to. The file should be writable by whoever php runs as (e.g. nobody). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.
pspell_config_repl() should be used on a config before calling pspell_new_config(). The replacement pairs improve the quality of the spellchecker. When a word is misspelled, and a proper suggestion was not found in the list, pspell_store_replacement() can be used to store a replacement pair and then pspell_save_wordlist() to save the wordlist along with the replacement pairs. The file should be writable by whoever php runs as (e.g. nobody). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.
Przykład 1. pspell_config_repl()
|
pspell_config_runtogether() should be used on a config before calling pspell_new_config(). This function determines whether run-together words will be treated as legal compounds. That is, "thecat" will be a legal compound, athough there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.
(PHP 4 >= 4.0.2)
pspell_config_save_repl -- Determine whether to save a replacement pairs list along with the wordlistpspell_config_save_repl() should be used on a config before calling pspell_new_config(). It determines whether pspell_save_wordlist() will save the replacement pairs along with the wordlist. Usually there is no need to use this function because if pspell_config_repl() is used, the replacement pairs will be saved by pspell_save_wordlist() anyway, and if it is not, the replacement pairs will not be saved. Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.
pspell_new() opens up a new dictionary and returns the dictionary link identifier for use in other pspell functions.
The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.
The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.
The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.
The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.
The mode parameter is the mode in which spellchecker will work. There are several modes available:
PSPELL_FAST - Fast mode (least number of suggestions)
PSPELL_NORMAL - Normal mode (more suggestions)
PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)
PSPELL_RUN_TOGETHER - Consider run-together words as legal compounds. That is, "thecat" will be a legal compound, athough there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.
For more information and examples, check out inline manual pspell website:http://pspell.sourceforge.net/.
pspell_new_config() opens up a new dictionary with settings specified in a config, created with with pspell_config_create() and modified with pspell_config_*() functions. This method provides you with the most flexibility and has all the functionality provided by pspell_new() and pspell_new_personal().
The config parameter is the one returned by pspell_config_create() when the config was created.
pspell_new_personal() opens up a new dictionary with a personal wordlist and returns the dictionary link identifier for use in other pspell functions. The wordlist can be modified and saved with pspell_save_wordlist(), if desired. However, the replacement pairs are not saved. In order to save replacement pairs, you should create a config using pspell_config_create(), set the personal wordlist file with pspell_config_personal(), set the file for replacement pairs with pspell_config_repl(), and open a new dictionary with pspell_new_config().
The personal parameter specifies the file where words added to the personal list will be stored. It should be an absolute filename beginning with '/' because otherwise it will be relative to $HOME, which is "/root" for most systems, and is probably not what you want.
The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.
The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.
The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.
The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.
The mode parameter is the mode in which spellchecker will work. There are several modes available:
PSPELL_FAST - Fast mode (least number of suggestions)
PSPELL_NORMAL - Normal mode (more suggestions)
PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)
PSPELL_RUN_TOGETHER - Consider run-together words as legal compounds. That is, "thecat" will be a legal compound, athough there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.
For more information and examples, check out inline manual pspell website:http://pspell.sourceforge.net/.
pspell_save_wordlist() saves the personal wordlist from the current session. The dictionary has to be open with pspell_new_personal(), and the location of files to be saved specified with pspell_config_personal() and (optionally) pspell_config_repl(). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.
Przykład 1. pspell_add_to_personal()
|
pspell_store_replacement() stores a replacement pair for a word, so that replacement can be returned by pspell_suggest() later. In order to be able to take advantage of this function, you have to use pspell_new_personal() to open the dictionary. In order to permanently save the replacement pair, you have to use pspell_config_personal() and pspell_config_repl() to set the path where to save your custom wordlists, and then use pspell_save_wordlist() for the changes to be written to disk. Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.
Przykład 1. pspell_store_replacement()
|
Funkcje readline() implementują interfejs do biblioteki GNU Readline. Funkcje te pozwalają na tworzenie edytowalnych linii poleceń. Jako przykład może posłużyć Bash, który pozwala na używanie klawiszy strzałek do poruszania się po wpisanej części polecenia lub przewijanie histrii. Ze względu na interaktywność tej biblioteki, nie przyda się ona do pisania aplikacji sieciowych, lecz może być przydatna do pisania skryptów które mają być uruchamiane z linii poleceń.
Stronę domową projektu GNU Readline można znaleźć pod adresem http://cnswww.cns.cwru.edu/~chet/readline/rltop.html. Zajmuje się nią Chet Ramey, który jest także autorem Basha.
Funkcja ta zwraca pojedyńczy string pobrany od użytkownika. Jako parametr funkcji można podać string zawierający prompt (znak zachęty) który będzie wyświetlony. Zwracany string ma usunięty z końca znak nowego wiersza. Musisz dodać do linię do historii ręcznie używając readline_add_history().
Funkcja ta rejestruje funkcję dopełniania. Musisz podać nazwę istniejącej funkcji, która przyjmuje jako parametr częściowo wypełnioną linię i zwraca tablicę możliwych dopełnień. Jest to efekt który można zaobserwować wciskając klawisz TAB używając Basha.
Jeśli funkcja zostanie wywołana bez parametrów, to zwrócona zostanie tablica z wartościami wszystkich ustawień biblioteki readline. Elementy tej tablicy będą miały takie indeksy: done, end, erase_empty_line, library_version, line_buffer, mark, pending_input, point, prompt, readline_name, i terminal_name.
Jeśli zostanie wywołana z jednym parametrem, to zwrócona zostanie wartość ustawienia podanego jako parametr. Jeśli zostanie wywołana z dwoma paremetrami, zmienione zostanie podane ustawienie.
Funkcja ta zwraca tablicę zawierającą całą historię linii poleceń. Elementy są indeksowane przez liczby całkowite poczynając od zera.
This module contains an interface to the GNU Recode library, version 3.5. To be able to use the functions defined in this module you must compile you PHP interpreter using the --with-recode option. In order to do so, you must have GNU Recode 3.5 or higher installed on your system.
The GNU Recode library converts files between various coded character sets and surface encodings. When this cannot be achieved exactly, it may get rid of the offending characters or fall back on approximations. The library recognises or produces nearly 150 different character sets and is able to convert files between almost any pair. Most RFC 1345 character sets are supported.
Recode the string string according to the recode request request. Returns the recoded string or FALSE, if unable to perform the recode request.
A simple recode request may be "lat1..iso646-de". See also the GNU Recode documentation of your installation for detailed instructions about recode requests.
Notatka: This is an alias for recode_string(). It has been added in PHP 4.
Recode the file referenced by file handle input into the file referenced by file handle output according to the recode request. Returns FALSE, if unable to comply, TRUE otherwise.
This function does not currently process filehandles referencing remote files (URLs). Both filehandles must refer to local files.
Notatka: PHP also supports regular expressions using a POSIX-extended syntax using the POSIX-extended regex functions..
The syntax for patterns used in these functions closely resembles Perl. The expression should be enclosed in the delimiters, a forward slash (/), for example. Any character can be used for delimiter as long as it's not alphanumeric or backslash (\). If the delimiter character has to be used in the expression itself, it needs to be escaped by backslash. Since PHP 4.0.4, you can also use Perl-style (), {}, [], and <> matching delimiters.
The ending delimiter may be followed by various modifiers that affect the matching. See Pattern Modifiers.
Notatka: The Perl-compatible regular expression functions are available in PHP 4 and in PHP 3.0.9 and up.
Regular expression support is provided by the PCRE library package, which is open source software, written by Philip Hazel, and copyright by the University of Cambridge, England. It is available at ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/.
Searches subject for a match to the regular expression given in pattern.
If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.
Returns TRUE if a match for pattern was found in the subject string, or FALSE if not match was found or an error occurred.
Przykład 2. find the word "web"
|
Przykład 3. Getting the domain name out of a URL
This example will produce:
|
Searches subject for all matches to the regular expression given in pattern and puts them in matches in the order specified by order.
After the first match is found, the subsequent searches are continued on from end of the last match.
order can be one of two things:
Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on.
preg_match_all ("|<[^>]+>(.*)</[^>]+>|U", "<b>example: </b><div align=left>this is a test</div>", $out, PREG_PATTERN_ORDER); print $out[0][0].", ".$out[0][1]."\n"; print $out[1][0].", ".$out[1][1]."\n"; |
This example will produce:
<b>example: </b>, <div align=left>this is a test</div> example: , this is a test |
Orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on.
This example will produce: In this case, $matches[0] is the first set of matches, and $matches[0][0] has text matched by full pattern, $matches[0][1] has text matched by first subpattern and so on. Similarly, $matches[1] is the second set of matches, etc.If order is not specified, it is assumed to be PREG_PATTERN_ORDER.
Returns the number of full pattern matches, or FALSE if no match is found or an error occurred.
Przykład 2. Find matching HTML tags (greedy)
|
matched: <b>bold text</b> part 1: <b> part 2: bold text part 3: </b> matched: <a href=howdy.html>click me</a> part 1: <a href=howdy.html> part 2: click me part 3: </a> |
See also preg_match(), preg_replace(), and preg_split().
Searches subject for matches to pattern and replaces them with replacement. If limit is specified, then only limit matches will be replaced; if limit is omitted or is -1, then all matches are replaced.
Replacement may contain references of the form \\n or (since PHP 4.0.4) $n, with the latter form being the preferred one. Every such reference will be replaced by the text captured by the n'th parenthesized pattern. n can be from 0 to 99, and \\0 or $0 refers to the text matched by the whole pattern. Opening parentheses are counted from left to right (starting from 1) to obtain the number of the capturing subpattern.
If matches are found, the new subject will be returned, otherwise subject will be returned unchanged.
Every parameter to preg_replace() can be an array.
If subject is an array, then the search and replace is performed on every entry of subject, and the return value is an array as well.
If pattern and replacement are arrays, then preg_replace() takes a value from each array and uses them to do search and replace on subject. If replacement has fewer values than pattern, then empty string is used for the rest of replacement values. If pattern is an array and replacement is a string; then this replacement string is used for every value of pattern. The converse would not make sense, though.
/e modifier makes preg_replace() treat the replacement parameter as PHP code after the appropriate references substitution is done. Tip: make sure that replacement constitutes a valid PHP code string, otherwise PHP will complain about a parse error at the line containing preg_replace().
$startDate = 5/27/1999 |
Przykład 3. Convert HTML to text
|
Notatka: Parameter limit was added after PHP 4.0.1pl2.
See also preg_match(), preg_match_all(), and preg_split().
(PHP 4 >= 4.0.5)
preg_replace_callback -- Perform a regular expression search and replace using a callbackThe behavior of this function is almost identical to preg_replace(), except for the fact that instead of replacement parameter, one should specify a callback that will be called and passed an array of matched elements in the subject string. The callback should return the replacement string. This function was added in PHP 4.0.5.
See also preg_replace().
Notatka: Parameter flags was added in PHP 4 Beta 3.
Returns an array containing substrings of subject split along boundaries matched by pattern.
If limit is specified, then only substrings up to limit are returned, and if limit is -1, it actually means "no limit", which is useful for specifying the flags.
flags can be any combination of the following flags (combined with bitwise | operator):
If this flag is set, only non-empty pieces will be returned by preg_split().
If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well. This flag was added for 4.0.5.
See also spliti(), split(), implode(), preg_match(), preg_match_all(), and preg_replace().
preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.
If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter.
The special regular expression characters are:
. \\ + * ? [ ^ ] $ ( ) { } = ! < > | : |
Przykład 2. Italicizing a word within some text
|
preg_grep() returns the array consisting of the elements of the input array that match the given pattern.
Since PHP 4.0.4, the results returned by preg_grep() are indexed using the keys from the input array. If this behavior is undesirable, use array_values() on the array returned by preg_grep() to reindex the values.
The current possible PCRE modifiers are listed below. The names in parentheses refer to internal PCRE names for these modifiers.
- i (PCRE_CASELESS)
If this modifier is set, letters in the pattern match both upper and lower case letters.
- m (PCRE_MULTILINE)
By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless D modifier is set). This is the same as Perl.
When this modifier is set, the "start of line" and "end of line" constructs match immediately following or immediately before any newline in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m modifier. If there are no "\n" characters in a subject string, or no occurrences of ^ or $ in a pattern, setting this modifier has no effect.
- s (PCRE_DOTALL)
If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.
- x (PCRE_EXTENDED)
If this modifier is set, whitespace data characters in the pattern are totally ignored except when escaped or inside a character class, and characters between an unescaped # outside a character class and the next newline character, inclusive, are also ignored. This is equivalent to Perl's /x modifier, and makes it possible to include comments inside complicated patterns. Note, however, that this applies only to data characters. Whitespace characters may never appear within special character sequences in a pattern, for example within the sequence (?( which introduces a conditional subpattern.
- e
If this modifier is set, preg_replace() does normal substitution of backreferences in the replacement string, evaluates it as PHP code, and uses the result for replacing the search string.
Only preg_replace() uses this modifier; it is ignored by other PCRE functions.
- A (PCRE_ANCHORED)
If this modifier is set, the pattern is forced to be "anchored", that is, it is constrained to match only at the start of the string which is being searched (the "subject string"). This effect can also be achieved by appropriate constructs in the pattern itself, which is the only way to do it in Perl.
- D (PCRE_DOLLAR_ENDONLY)
If this modifier is set, a dollar metacharacter in the pattern matches only at the end of the subject string. Without this modifier, a dollar also matches immediately before the final character if it is a newline (but not before any other newlines). This modifier is ignored if m modifier is set. There is no equivalent to this modifier in Perl.
- S
When a pattern is going to be used several times, it is worth spending more time analyzing it in order to speed up the time taken for matching. If this modifier is set, then this extra analysis is performed. At present, studying a pattern is useful only for non-anchored patterns that do not have a single fixed starting character.
- U (PCRE_UNGREEDY)
This modifier inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by "?". It is not compatible with Perl. It can also be set by a (?U) modifier setting within the pattern.
- X (PCRE_EXTRA)
This modifier turns on additional functionality of PCRE that is incompatible with Perl. Any backslash in a pattern that is followed by a letter that has no special meaning causes an error, thus reserving these combinations for future expansion. By default, as in Perl, a backslash followed by a letter with no special meaning is treated as a literal. There are at present no other features controlled by this modifier.
- u (PCRE_UTF8)
This modifier turns on additional functionality of PCRE that is incompatible with Perl. Pattern strings are treated as UTF-8. This modifier is available from PHP 4.1.0 or greater.
The PCRE library is a set of functions that implement regular expression pattern matching using the same syntax and semantics as Perl 5, with just a few differences (see below). The current implementation corresponds to Perl 5.005.
The differences described here are with respect to Perl 5.005.
By default, a whitespace character is any character that the C library function isspace() recognizes, though it is possible to compile PCRE with alternative character type tables. Normally isspace() matches space, formfeed, newline, carriage return, horizontal tab, and vertical tab. Perl 5 no longer includes vertical tab in its set of whitespace characters. The \v escape that was in the Perl documentation for a long time was never in fact recognized. However, the character itself was treated as whitespace at least up to 5.002. In 5.004 and 5.005 it does not match \s.
PCRE does not allow repeat quantifiers on lookahead assertions. Perl permits them, but they do not mean what you might think. For example, (?!a){3} does not assert that the next three characters are not "a". It just asserts that the next character is not "a" three times.
Capturing subpatterns that occur inside negative looka- head assertions are counted, but their entries in the offsets vector are never set. Perl sets its numerical vari- ables from any such patterns that are matched before the assertion fails to match something (thereby succeeding), but only if the negative lookahead assertion contains just one branch.
Though binary zero characters are supported in the sub- ject string, they are not allowed in a pattern string because it is passed as a normal C string, terminated by zero. The escape sequence "\0" can be used in the pattern to represent a binary zero.
The following Perl escape sequences are not supported: \l, \u, \L, \U, \E, \Q. In fact these are implemented by Perl's general string-handling and are not part of its pat- tern matching engine.
The Perl \G assertion is not supported as it is not relevant to single pattern matches.
Fairly obviously, PCRE does not support the (?{code}) construction.
There are at the time of writing some oddities in Perl 5.005_02 concerned with the settings of captured strings when part of a pattern is repeated. For example, matching "aba" against the pattern /^(a(b)?)+$/ sets $2 to the value "b", but matching "aabbaa" against /^(aa(bb)?)+$/ leaves $2 unset. However, if the pattern is changed to /^(aa(b(b))?)+$/ then $2 (and $3) get set. In Perl 5.004 $2 is set in both cases, and that is also TRUE of PCRE. If in the future Perl changes to a consistent state that is different, PCRE may change to follow.
Another as yet unresolved discrepancy is that in Perl 5.005_02 the pattern /^(a)?(?(1)a|b)+$/ matches the string "a", whereas in PCRE it does not. However, in both Perl and PCRE /^(a)?a/ matched against "a" leaves $1 unset.
PCRE provides some extensions to the Perl regular expression facilities:
Although lookbehind assertions must match fixed length strings, each alternative branch of a lookbehind assertion can match a different length of string. Perl 5.005 requires them all to have the same length.
If PCRE_DOLLAR_ENDONLY is set and PCRE_MULTILINE is not set, the $ meta- character matches only at the very end of the string.
If PCRE_EXTRA is set, a backslash followed by a letter with no special meaning is faulted.
If PCRE_UNGREEDY is set, the greediness of the repeti- tion quantifiers is inverted, that is, by default they are not greedy, but if followed by a question mark they are.
The syntax and semantics of the regular expressions sup- ported by PCRE are described below. Regular expressions are also described in the Perl documentation and in a number of other books, some of which have copious examples. Jeffrey Friedl's "Mastering Regular Expressions", published by O'Reilly (ISBN 1-56592-257-3), covers them in great detail. The description here is intended as reference documentation. A regular expression is a pattern that is matched against a subject string from left to right. Most characters stand for themselves in a pattern, and match the corresponding charac- ters in the subject. As a trivial example, the pattern The quick brown fox matches a portion of a subject string that is identical to itself.
The power of regular expressions comes from the ability to include alternatives and repetitions in the pat- tern. These are encoded in the pattern by the use of meta- characters, which do not stand for themselves but instead are interpreted in some special way.
There are two different sets of meta-characters: those that are recognized anywhere in the pattern except within square brackets, and those that are recognized in square brackets. Outside square brackets, the meta-characters are as follows:
general escape character with several uses
assert start of subject (or line, in multiline mode)
assert end of subject (or line, in multiline mode)
match any character except newline (by default)
start character class definition
end character class definition
start of alternative branch
start subpattern
end subpattern
extends the meaning of (, also 0 or 1 quantifier, also quantifier minimizer
0 or more quantifier
1 or more quantifier
start min/max quantifier
end min/max quantifier
general escape character
negate the class, but only if the first character
indicates character range
terminates the character class
The backslash character has several uses. Firstly, if it is followed by a non-alphameric character, it takes away any special meaning that character may have. This use of backslash as an escape character applies both inside and outside character classes.
For example, if you want to match a "*" character, you write "\*" in the pattern. This applies whether or not the follow- ing character would otherwise be interpreted as a meta- character, so it is always safe to precede a non-alphameric with "\" to specify that it stands for itself. In particu- lar, if you want to match a backslash, you write "\\".
If a pattern is compiled with the PCRE_EXTENDED option, whi- tespace in the pattern (other than in a character class) and characters between a "#" outside a character class and the next newline character are ignored. An escaping backslash can be used to include a whitespace or "#" character as part of the pattern.
A second use of backslash provides a way of encoding non- printing characters in patterns in a visible manner. There is no restriction on the appearance of non-printing charac- ters, apart from the binary zero that terminates a pattern, but when a pattern is being prepared by text editing, it is usually easier to use one of the following escape sequences than the binary character it represents:
alarm, that is, the BEL character (hex 07)
"control-x", where x is any character
escape (hex 1B)
formfeed (hex 0C)
newline (hex 0A)
carriage return (hex 0D)
tab (hex 09)
character with hex code hh
character with octal code ddd, or backreference
The precise effect of "\cx" is as follows: if "x" is a lower case letter, it is converted to upper case. Then bit 6 of the character (hex 40) is inverted. Thus "\cz" becomes hex 1A, but "\c{" becomes hex 3B, while "\c;" becomes hex 7B.
After "\x", up to two hexadecimal digits are read (letters can be in upper or lower case).
After "\0" up to two further octal digits are read. In both cases, if there are fewer than two digits, just those that are present are used. Thus the sequence "\0\x\07" specifies two binary zeros followed by a BEL character. Make sure you supply two digits after the initial zero if the character that follows is itself an octal digit.
The handling of a backslash followed by a digit other than 0 is complicated. Outside a character class, PCRE reads it and any following digits as a decimal number. If the number is less than 10, or if there have been at least that many previous capturing left parentheses in the expression, the entire sequence is taken as a back reference. A description of how this works is given later, following the discussion of parenthesized subpatterns.
Inside a character class, or if the decimal number is greater than 9 and there have not been that many capturing subpatterns, PCRE re-reads up to three octal digits follow- ing the backslash, and generates a single byte from the least significant 8 bits of the value. Any subsequent digits stand for themselves. For example:
is another way of writing a space
is the same, provided there are fewer than 40 previous capturing subpatterns
is always a back reference
might be a back reference, or another way of writing a tab
is always a tab
is a tab followed by the character "3"
is the character with octal code 113 (since there can be no more than 99 back references)
is a byte consisting entirely of 1 bits
is either a back reference, or a binary zero followed by the two characters "8" and "1"
Note that octal values of 100 or greater must not be intro- duced by a leading zero, because no more than three octal digits are ever read.
All the sequences that define a single byte value can be used both inside and outside character classes. In addition, inside a character class, the sequence "\b" is interpreted as the backspace character (hex 08). Outside a character class it has a different meaning (see below).
The third use of backslash is for specifying generic charac- ter types:
any decimal digit
any character that is not a decimal digit
any whitespace character
any character that is not a whitespace character
any "word" character
any "non-word" character
Each pair of escape sequences partitions the complete set of characters into two disjoint sets. Any given character matches one, and only one, of each pair.
A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place (see "Locale support" above). For example, in the "fr" (French) locale, some char- acter codes greater than 128 are used for accented letters, and these are matched by \w.
These character type sequences can appear both inside and outside character classes. They each match one character of the appropriate type. If the current matching point is at the end of the subject string, all of them fail, since there is no character to match.
The fourth use of backslash is for certain simple asser- tions. An assertion specifies a condition that has to be met at a particular point in a match, without consuming any characters from the subject string. The use of subpatterns for more complicated assertions is described below. The backslashed assertions are
word boundary
not a word boundary
start of subject (independent of multiline mode)
end of subject or newline at end (independent of multiline mode)
end of subject (independent of multiline mode)
These assertions may not appear in character classes (but note that "\b" has a different meaning, namely the backspace character, inside a character class).
A word boundary is a position in the subject string where the current character and the previous character do not both match \w or \W (i.e. one matches \w and the other matches \W), or the start or end of the string if the first or last character matches \w, respectively.
The \A, \Z, and \z assertions differ from the traditional circumflex and dollar (described below) in that they only ever match at the very start and end of the subject string, whatever options are set. They are not affected by the PCRE_NOTBOL or PCRE_NOTEOL options. The difference between \Z and \z is that \Z matches before a newline that is the last character of the string as well as at the end of the string, whereas \z matches only at the end.
Outside a character class, in the default matching mode, the
circumflex character is an assertion which is true only if
the current matching point is at the start of the subject
string. Inside a character class, circumflex has an entirely
different meaning (see below).
Circumflex need not be the first character of the pattern if
a number of alternatives are involved, but it should be the
first thing in each alternative in which it appears if the
pattern is ever to match that branch. If all possible alter-
natives start with a circumflex, that is, if the pattern is
constrained to match only at the start of the subject, it is
said to be an "anchored" pattern. (There are also other con-
structs that can cause a pattern to be anchored.)
A dollar character is an assertion which is TRUE only if the
current matching point is at the end of the subject string,
or immediately before a newline character that is the last
character in the string (by default). Dollar need not be the
last character of the pattern if a number of alternatives
are involved, but it should be the last item in any branch
in which it appears. Dollar has no special meaning in a
character class.
The meaning of dollar can be changed so that it matches only
at the very end of the string, by setting the
PCRE_DOLLAR_ENDONLY option at compile or matching time. This
does not affect the \Z assertion.
The meanings of the circumflex and dollar characters are
changed if the PCRE_MULTILINE option is set. When this is
the case, they match immediately after and immediately
before an internal "\n" character, respectively, in addition
to matching at the start and end of the subject string. For
example, the pattern /^abc$/ matches the subject string
"def\nabc" in multiline mode, but not otherwise. Conse-
quently, patterns that are anchored in single line mode
because all branches start with "^" are not anchored in mul-
tiline mode. The PCRE_DOLLAR_ENDONLY option is ignored if
PCRE_MULTILINE is set.
Note that the sequences \A, \Z, and \z can be used to match
the start and end of the subject in both modes, and if all
branches of a pattern start with \A is it always anchored,
whether PCRE_MULTILINE is set or not.
Outside a character class, a dot in the pattern matches any
one character in the subject, including a non-printing
character, but not (by default) newline. If the PCRE_DOTALL
option is set, then dots match newlines as well. The han-
dling of dot is entirely independent of the handling of cir-
cumflex and dollar, the only relationship being that they
both involve newline characters. Dot has no special meaning
in a character class.
An opening square bracket introduces a character class, ter-
minated by a closing square bracket. A closing square
bracket on its own is not special. If a closing square
bracket is required as a member of the class, it should be
the first data character in the class (after an initial cir-
cumflex, if present) or escaped with a backslash.
A character class matches a single character in the subject;
the character must be in the set of characters defined by
the class, unless the first character in the class is a cir-
cumflex, in which case the subject character must not be in
the set defined by the class. If a circumflex is actually
required as a member of the class, ensure it is not the
first character, or escape it with a backslash.
For example, the character class [aeiou] matches any lower
case vowel, while [^aeiou] matches any character that is not
a lower case vowel. Note that a circumflex is just a con-
venient notation for specifying the characters which are in
the class by enumerating those that are not. It is not an
assertion: it still consumes a character from the subject
string, and fails if the current pointer is at the end of
the string.
When caseless matching is set, any letters in a class
represent both their upper case and lower case versions, so
for example, a caseless [aeiou] matches "A" as well as "a",
and a caseless [^aeiou] does not match "A", whereas a case-
ful version would.
The newline character is never treated in any special way in
character classes, whatever the setting of the PCRE_DOTALL
or PCRE_MULTILINE options is. A class such as [^a] will
always match a newline.
The minus (hyphen) character can be used to specify a range
of characters in a character class. For example, [d-m]
matches any letter between d and m, inclusive. If a minus
character is required in a class, it must be escaped with a
backslash or appear in a position where it cannot be inter-
preted as indicating a range, typically as the first or last
character in the class.
It is not possible to have the literal character "]" as the
end character of a range. A pattern such as [W-]46] is
interpreted as a class of two characters ("W" and "-") fol-
lowed by a literal string "46]", so it would match "W46]" or
"-46]". However, if the "]" is escaped with a backslash it
is interpreted as the end of range, so [W-\]46] is inter-
preted as a single class containing a range followed by two
separate characters. The octal or hexadecimal representation
of "]" can also be used to end a range.
Ranges operate in ASCII collating sequence. They can also be
used for characters specified numerically, for example
[\000-\037]. If a range that includes letters is used when
caseless matching is set, it matches the letters in either
case. For example, [W-c] is equivalent to [][\^_`wxyzabc],
matched caselessly, and if character tables for the "fr"
locale are in use, [\xc8-\xcb] matches accented E characters
in both cases.
The character types \d, \D, \s, \S, \w, and \W may also
appear in a character class, and add the characters that
they match to the class. For example, [\dABCDEF] matches any
hexadecimal digit. A circumflex can conveniently be used
with the upper case character types to specify a more res-
tricted set of characters than the matching lower case type.
For example, the class [^\W_] matches any letter or digit,
but not underscore.
All non-alphameric characters other than \, -, ^ (at the
start) and the terminating ] are non-special in character
classes, but it does no harm if they are escaped.
Vertical bar characters are used to separate alternative
patterns. For example, the pattern
gilbert|sullivan
matches either "gilbert" or "sullivan". Any number of alter-
natives may appear, and an empty alternative is permitted
(matching the empty string). The matching process tries
each alternative in turn, from left to right, and the first
one that succeeds is used. If the alternatives are within a
subpattern (defined below), "succeeds" means matching the
rest of the main pattern as well as the alternative in the
subpattern.
The settings of PCRE_CASELESS ,
PCRE_MULTILINE ,
PCRE_DOTALL ,
and PCRE_EXTENDED can be changed from within the pattern by
a sequence of Perl option letters enclosed between "(?" and
")". The option letters are
i for PCRE_CASELESS
m for PCRE_MULTILINE
s for PCRE_DOTALL
x for PCRE_EXTENDED
For example, (?im) sets caseless, multiline matching. It is
also possible to unset these options by preceding the letter
with a hyphen, and a combined setting and unsetting such as
(?im-sx), which sets PCRE_CASELESS and PCRE_MULTILINE while
unsetting PCRE_DOTALL and PCRE_EXTENDED , is also permitted.
If a letter appears both before and after the hyphen, the
option is unset.
The scope of these option changes depends on where in the
pattern the setting occurs. For settings that are outside
any subpattern (defined below), the effect is the same as if
the options were set or unset at the start of matching. The
following patterns all behave in exactly the same way:
(?i)abc
a(?i)bc
ab(?i)c
abc(?i)
which in turn is the same as compiling the pattern abc with
PCRE_CASELESS set. In other words, such "top level" set-
tings apply to the whole pattern (unless there are other
changes inside subpatterns). If there is more than one set-
ting of the same option at top level, the rightmost setting
is used.
If an option change occurs inside a subpattern, the effect
is different. This is a change of behaviour in Perl 5.005.
An option change inside a subpattern affects only that part
of the subpattern that follows it, so
(a(?i)b)c
matches abc and aBc and no other strings (assuming
PCRE_CASELESS is not used). By this means, options can be
made to have different settings in different parts of the
pattern. Any changes made in one alternative do carry on
into subsequent branches within the same subpattern. For
example,
(a(?i)b|c)
matches "ab", "aB", "c", and "C", even though when matching
"C" the first branch is abandoned before the option setting.
This is because the effects of option settings happen at
compile time. There would be some very weird behaviour oth-
erwise.
The PCRE-specific options PCRE_UNGREEDY and
PCRE_EXTRA can
be changed in the same way as the Perl-compatible options by
using the characters U and X respectively. The (?X) flag
setting is special in that it must always occur earlier in
the pattern than any of the additional features it turns on,
even when it is at top level. It is best put at the start.
Subpatterns are delimited by parentheses (round brackets),
which can be nested. Marking part of a pattern as a subpat-
tern does two things:
1. It localizes a set of alternatives. For example, the pat-
tern
cat(aract|erpillar|)
matches one of the words "cat", "cataract", or "caterpil-
lar". Without the parentheses, it would match "cataract",
"erpillar" or the empty string.
2. It sets up the subpattern as a capturing subpattern (as
defined above). When the whole pattern matches, that por-
tion of the subject string that matched the subpattern is
passed back to the caller via the ovector argument of
pcre_exec(). Opening parentheses are counted from left to
right (starting from 1) to obtain the numbers of the captur-
ing subpatterns.
For example, if the string "the red king" is matched against
the pattern
the ((red|white) (king|queen))
the captured substrings are "red king", "red", and "king",
and are numbered 1, 2, and 3.
The fact that plain parentheses fulfil two functions is not
always helpful. There are often times when a grouping sub-
pattern is required without a capturing requirement. If an
opening parenthesis is followed by "?:", the subpattern does
not do any capturing, and is not counted when computing the
number of any subsequent capturing subpatterns. For example,
if the string "the white queen" is matched against the
pattern
the ((?:red|white) (king|queen))
the captured substrings are "white queen" and "queen", and
are numbered 1 and 2. The maximum number of captured sub-
strings is 99, and the maximum number of all subpatterns,
both capturing and non-capturing, is 200.
As a convenient shorthand, if any option settings are
required at the start of a non-capturing subpattern, the
option letters may appear between the "?" and the ":". Thus
the two patterns
(?i:saturday|sunday)
(?:(?i)saturday|sunday)
match exactly the same set of strings. Because alternative
branches are tried from left to right, and options are not
reset until the end of the subpattern is reached, an option
setting in one branch does affect subsequent branches, so
the above patterns match "SUNDAY" as well as "Saturday".
Repetition is specified by quantifiers, which can follow any
of the following items:
a single character, possibly escaped
the . metacharacter
a character class
a back reference (see next section)
a parenthesized subpattern (unless it is an assertion -
see below)
The general repetition quantifier specifies a minimum and
maximum number of permitted matches, by giving the two
numbers in curly brackets (braces), separated by a comma.
The numbers must be less than 65536, and the first must be
less than or equal to the second. For example:
z{2,4}
matches "zz", "zzz", or "zzzz". A closing brace on its own
is not a special character. If the second number is omitted,
but the comma is present, there is no upper limit; if the
second number and the comma are both omitted, the quantifier
specifies an exact number of required matches. Thus
[aeiou]{3,}
matches at least 3 successive vowels, but may match many
more, while
\d{8}
matches exactly 8 digits. An opening curly bracket that
appears in a position where a quantifier is not allowed, or
one that does not match the syntax of a quantifier, is taken
as a literal character. For example, {,6} is not a quantif-
ier, but a literal string of four characters.
The quantifier {0} is permitted, causing the expression to
behave as if the previous item and the quantifier were not
present.
For convenience (and historical compatibility) the three
most common quantifiers have single-character abbreviations:
* is equivalent to {0,}
+ is equivalent to {1,}
? is equivalent to {0,1}
It is possible to construct infinite loops by following a
subpattern that can match no characters with a quantifier
that has no upper limit, for example:
(a?)*
Earlier versions of Perl and PCRE used to give an error at
compile time for such patterns. However, because there are
cases where this can be useful, such patterns are now
accepted, but if any repetition of the subpattern does in
fact match no characters, the loop is forcibly broken.
By default, the quantifiers are "greedy", that is, they
match as much as possible (up to the maximum number of per-
mitted times), without causing the rest of the pattern to
fail. The classic example of where this gives problems is in
trying to match comments in C programs. These appear between
the sequences /* and */ and within the sequence, individual
* and / characters may appear. An attempt to match C com-
ments by applying the pattern
/\*.*\*/
to the string
/* first command */ not comment /* second comment */
fails, because it matches the entire string due to the
greediness of the .* item.
However, if a quantifier is followed by a question mark,
then it ceases to be greedy, and instead matches the minimum
number of times possible, so the pattern
/\*.*?\*/
does the right thing with the C comments. The meaning of the
various quantifiers is not otherwise changed, just the pre-
ferred number of matches. Do not confuse this use of ques-
tion mark with its use as a quantifier in its own right.
Because it has two uses, it can sometimes appear doubled, as
in
\d??\d
which matches one digit by preference, but can match two if
that is the only way the rest of the pattern matches.
If the PCRE_UNGREEDY option is set (an option which is not
available in Perl) then the quantifiers are not greedy by
default, but individual ones can be made greedy by following
them with a question mark. In other words, it inverts the
default behaviour.
When a parenthesized subpattern is quantified with a minimum
repeat count that is greater than 1 or with a limited max-
imum, more store is required for the compiled pattern, in
proportion to the size of the minimum or maximum.
If a pattern starts with .* or .{0,} and the PCRE_DOTALL
option (equivalent to Perl's /s) is set, thus allowing the .
to match newlines, then the pattern is implicitly anchored,
because whatever follows will be tried against every charac-
ter position in the subject string, so there is no point in
retrying the overall match at any position after the first.
PCRE treats such a pattern as though it were preceded by \A.
In cases where it is known that the subject string contains
no newlines, it is worth setting PCRE_DOTALL when the pat-
tern begins with .* in order to obtain this optimization, or
alternatively using ^ to indicate anchoring explicitly.
When a capturing subpattern is repeated, the value captured
is the substring that matched the final iteration. For exam-
ple, after
(tweedle[dume]{3}\s*)+
has matched "tweedledum tweedledee" the value of the cap-
tured substring is "tweedledee". However, if there are
nested capturing subpatterns, the corresponding captured
values may have been set in previous iterations. For exam-
ple, after
/(a|(b))+/
matches "aba" the value of the second captured substring is
"b".
Outside a character class, a backslash followed by a digit
greater than 0 (and possibly further digits) is a back
reference to a capturing subpattern earlier (i.e. to its
left) in the pattern, provided there have been that many
previous capturing left parentheses.
However, if the decimal number following the backslash is
less than 10, it is always taken as a back reference, and
causes an error only if there are not that many capturing
left parentheses in the entire pattern. In other words, the
parentheses that are referenced need not be to the left of
the reference for numbers less than 10. See the section
entitled "Backslash" above for further details of the han-
dling of digits following a backslash.
A back reference matches whatever actually matched the cap-
turing subpattern in the current subject string, rather than
anything matching the subpattern itself. So the pattern
(sens|respons)e and \1ibility
matches "sense and sensibility" and "response and responsi-
bility", but not "sense and responsibility". If caseful
matching is in force at the time of the back reference, then
the case of letters is relevant. For example,
((?i)rah)\s+\1
matches "rah rah" and "RAH RAH", but not "RAH rah", even
though the original capturing subpattern is matched case-
lessly.
There may be more than one back reference to the same sub-
pattern. If a subpattern has not actually been used in a
particular match, then any back references to it always
fail. For example, the pattern
(a|(bc))\2
always fails if it starts to match "a" rather than "bc".
Because there may be up to 99 back references, all digits
following the backslash are taken as part of a potential
back reference number. If the pattern continues with a digit
character, then some delimiter must be used to terminate the
back reference. If the PCRE_EXTENDED option is set, this can
be whitespace. Otherwise an empty comment can be used.
A back reference that occurs inside the parentheses to which
it refers fails when the subpattern is first used, so, for
example, (a\1) never matches. However, such references can
be useful inside repeated subpatterns. For example, the pat-
tern
(a|b\1)+
matches any number of "a"s and also "aba", "ababaa" etc. At
each iteration of the subpattern, the back reference matches
the character string corresponding to the previous itera-
tion. In order for this to work, the pattern must be such
that the first iteration does not need to match the back
reference. This can be done using alternation, as in the
example above, or by a quantifier with a minimum of zero.
An assertion is a test on the characters following or
preceding the current matching point that does not actually
consume any characters. The simple assertions coded as \b,
\B, \A, \Z, \z, ^ and $ are described above. More compli-
cated assertions are coded as subpatterns. There are two
kinds: those that look ahead of the current position in the
subject string, and those that look behind it.
An assertion subpattern is matched in the normal way, except
that it does not cause the current matching position to be
changed. Lookahead assertions start with (?= for positive
assertions and (?! for negative assertions. For example,
\w+(?=;)
matches a word followed by a semicolon, but does not include
the semicolon in the match, and
foo(?!bar)
matches any occurrence of "foo" that is not followed by
"bar". Note that the apparently similar pattern
(?!foo)bar
does not find an occurrence of "bar" that is preceded by
something other than "foo"; it finds any occurrence of "bar"
whatsoever, because the assertion (?!foo) is always TRUE
when the next three characters are "bar". A lookbehind
assertion is needed to achieve this effect.
Lookbehind assertions start with (?<= for positive asser-
tions and (?<! for negative assertions. For example,
(?<!foo)bar
does find an occurrence of "bar" that is not preceded by
"foo". The contents of a lookbehind assertion are restricted
such that all the strings it matches must have a fixed
length. However, if there are several alternatives, they do
not all have to have the same fixed length. Thus
(?<=bullock|donkey)
is permitted, but
(?<!dogs?|cats?)
causes an error at compile time. Branches that match dif-
ferent length strings are permitted only at the top level of
a lookbehind assertion. This is an extension compared with
Perl 5.005, which requires all branches to match the same
length of string. An assertion such as
(?<=ab(c|de))
is not permitted, because its single top-level branch can
match two different lengths, but it is acceptable if rewrit-
ten to use two top-level branches:
(?<=abc|abde)
The implementation of lookbehind assertions is, for each
alternative, to temporarily move the current position back
by the fixed width and then try to match. If there are
insufficient characters before the current position, the
match is deemed to fail. Lookbehinds in conjunction with
once-only subpatterns can be particularly useful for match-
ing at the ends of strings; an example is given at the end
of the section on once-only subpatterns.
Several assertions (of any sort) may occur in succession.
For example,
(?<=\d{3})(?<!999)foo
matches "foo" preceded by three digits that are not "999".
Notice that each of the assertions is applied independently
at the same point in the subject string. First there is a
check that the previous three characters are all digits,
then there is a check that the same three characters are not
"999". This pattern does not match "foo" preceded by six
characters, the first of which are digits and the last three
of which are not "999". For example, it doesn't match
"123abcfoo". A pattern to do that is
(?<=\d{3}...)(?<!999)foo
This time the first assertion looks at the preceding six
characters, checking that the first three are digits, and
then the second assertion checks that the preceding three
characters are not "999".
Assertions can be nested in any combination. For example,
(?<=(?<!foo)bar)baz
matches an occurrence of "baz" that is preceded by "bar"
which in turn is not preceded by "foo", while
(?<=\d{3}(?!999)...)foo
is another pattern which matches "foo" preceded by three
digits and any three characters that are not "999".
Assertion subpatterns are not capturing subpatterns, and may
not be repeated, because it makes no sense to assert the
same thing several times. If any kind of assertion contains
capturing subpatterns within it, these are counted for the
purposes of numbering the capturing subpatterns in the whole
pattern. However, substring capturing is carried out only
for positive assertions, because it does not make sense for
negative assertions.
Assertions count towards the maximum of 200 parenthesized
subpatterns.
With both maximizing and minimizing repetition, failure of
what follows normally causes the repeated item to be re-
evaluated to see if a different number of repeats allows the
rest of the pattern to match. Sometimes it is useful to
prevent this, either to change the nature of the match, or
to cause it fail earlier than it otherwise might, when the
author of the pattern knows there is no point in carrying
on.
Consider, for example, the pattern \d+foo when applied to
the subject line
123456bar
After matching all 6 digits and then failing to match "foo",
the normal action of the matcher is to try again with only 5
digits matching the \d+ item, and then with 4, and so on,
before ultimately failing. Once-only subpatterns provide the
means for specifying that once a portion of the pattern has
matched, it is not to be re-evaluated in this way, so the
matcher would give up immediately on failing to match "foo"
the first time. The notation is another kind of special
parenthesis, starting with (?> as in this example:
(?>\d+)bar
This kind of parenthesis "locks up" the part of the pattern
it contains once it has matched, and a failure further into
the pattern is prevented from backtracking into it. Back-
tracking past it to previous items, however, works as nor-
mal.
An alternative description is that a subpattern of this type
matches the string of characters that an identical stan-
dalone pattern would match, if anchored at the current point
in the subject string.
Once-only subpatterns are not capturing subpatterns. Simple
cases such as the above example can be thought of as a max-
imizing repeat that must swallow everything it can. So,
while both \d+ and \d+? are prepared to adjust the number of
digits they match in order to make the rest of the pattern
match, (?>\d+) can only match an entire sequence of digits.
This construction can of course contain arbitrarily compli-
cated subpatterns, and it can be nested.
Once-only subpatterns can be used in conjunction with look-
behind assertions to specify efficient matching at the end
of the subject string. Consider a simple pattern such as
abcd$
when applied to a long string which does not match. Because
matching proceeds from left to right, PCRE will look for
each "a" in the subject and then see if what follows matches
the rest of the pattern. If the pattern is specified as
^.*abcd$
then the initial .* matches the entire string at first, but
when this fails (because there is no following "a"), it
backtracks to match all but the last character, then all but
the last two characters, and so on. Once again the search
for "a" covers the entire string, from right to left, so we
are no better off. However, if the pattern is written as
^(?>.*)(?<=abcd)
then there can be no backtracking for the .* item; it can
match only the entire string. The subsequent lookbehind
assertion does a single test on the last four characters. If
it fails, the match fails immediately. For long strings,
this approach makes a significant difference to the process-
ing time.
When a pattern contains an unlimited repeat inside a subpat-
tern that can itself be repeated an unlimited number of
times, the use of a once-only subpattern is the only way to
avoid some failing matches taking a very long time indeed.
The pattern
(\D+|<\d+>)*[!?]
matches an unlimited number of substrings that either con-
sist of non-digits, or digits enclosed in <>, followed by
either ! or ?. When it matches, it runs quickly. However, if
it is applied to
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
it takes a long time before reporting failure. This is
because the string can be divided between the two repeats in
a large number of ways, and all have to be tried. (The exam-
ple used [!?] rather than a single character at the end,
because both PCRE and Perl have an optimization that allows
for fast failure when a single character is used. They
remember the last single character that is required for a
match, and fail early if it is not present in the string.)
If the pattern is changed to
((?>\D+)|<\d+>)*[!?]
sequences of non-digits cannot be broken, and failure hap-
pens quickly.
It is possible to cause the matching process to obey a sub-
pattern conditionally or to choose between two alternative
subpatterns, depending on the result of an assertion, or
whether a previous capturing subpattern matched or not. The
two possible forms of conditional subpattern are
(?(condition)yes-pattern)
(?(condition)yes-pattern|no-pattern)
If the condition is satisfied, the yes-pattern is used; oth-
erwise the no-pattern (if present) is used. If there are
more than two alternatives in the subpattern, a compile-time
error occurs.
There are two kinds of condition. If the text between the
parentheses consists of a sequence of digits, then the
condition is satisfied if the capturing subpattern of that
number has previously matched. Consider the following pat-
tern, which contains non-significant white space to make it
more readable (assume the PCRE_EXTENDED option) and to
divide it into three parts for ease of discussion:
( \( )? [^()]+ (?(1) \) )
The first part matches an optional opening parenthesis, and
if that character is present, sets it as the first captured
substring. The second part matches one or more characters
that are not parentheses. The third part is a conditional
subpattern that tests whether the first set of parentheses
matched or not. If they did, that is, if subject started
with an opening parenthesis, the condition is TRUE, and so
the yes-pattern is executed and a closing parenthesis is
required. Otherwise, since no-pattern is not present, the
subpattern matches nothing. In other words, this pattern
matches a sequence of non-parentheses, optionally enclosed
in parentheses.
If the condition is not a sequence of digits, it must be an
assertion. This may be a positive or negative lookahead or
lookbehind assertion. Consider this pattern, again contain-
ing non-significant white space, and with the two alterna-
tives on the second line:
(?(?=[^a-z]*[a-z])
\d{2}-[a-z]{3}-\d{2} | \d{2}-\d{2}-\d{2} )
The condition is a positive lookahead assertion that matches
an optional sequence of non-letters followed by a letter. In
other words, it tests for the presence of at least one
letter in the subject. If a letter is found, the subject is
matched against the first alternative; otherwise it is
matched against the second. This pattern matches strings in
one of the two forms dd-aaa-dd or dd-dd-dd, where aaa are
letters and dd are digits.
The sequence (?# marks the start of a comment which
continues up to the next closing parenthesis. Nested
parentheses are not permitted. The characters that make up a
comment play no part in the pattern matching at all.
If the PCRE_EXTENDED option is set, an unescaped # character
outside a character class introduces a comment that contin-
ues up to the next newline character in the pattern.
Consider the problem of matching a string in parentheses,
allowing for unlimited nested parentheses. Without the use
of recursion, the best that can be done is to use a pattern
that matches up to some fixed depth of nesting. It is not
possible to handle an arbitrary nesting depth. Perl 5.6 has
provided an experimental facility that allows regular
expressions to recurse (amongst other things). The special
item (?R) is provided for the specific case of recursion.
This PCRE pattern solves the parentheses problem (assume
the PCRE_EXTENDED option is set so that white space is
ignored):
\( ( (?>[^()]+) | (?R) )* \)
First it matches an opening parenthesis. Then it matches any
number of substrings which can either be a sequence of non-
parentheses, or a recursive match of the pattern itself
(i.e. a correctly parenthesized substring). Finally there is
a closing parenthesis.
This particular example pattern contains nested unlimited
repeats, and so the use of a once-only subpattern for match-
ing strings of non-parentheses is important when applying
the pattern to strings that do not match. For example, when
it is applied to
(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
it yields "no match" quickly. However, if a once-only sub-
pattern is not used, the match runs for a very long time
indeed because there are so many different ways the + and *
repeats can carve up the subject, and all have to be tested
before failure can be reported.
The values set for any capturing subpatterns are those from
the outermost level of the recursion at which the subpattern
value is set. If the pattern above is matched against
(ab(cd)ef)
the value for the capturing parentheses is "ef", which is
the last value taken on at the top level. If additional
parentheses are added, giving
\( ( ( (?>[^()]+) | (?R) )* ) \)
^ ^
^ ^ then the string they capture
is "ab(cd)ef", the contents of the top level parentheses. If
there are more than 15 capturing parentheses in a pattern,
PCRE has to obtain extra memory to store data during a
recursion, which it does by using pcre_malloc, freeing it
via pcre_free afterwards. If no memory can be obtained, it
saves data for the first 15 capturing parentheses only, as
there is no way to give an out-of-memory error from within a
recursion.
Certain items that may appear in patterns are more efficient
than others. It is more efficient to use a character class
like [aeiou] than a set of alternatives such as (a|e|i|o|u).
In general, the simplest construction that provides the
required behaviour is usually the most efficient. Jeffrey
Friedl's book contains a lot of discussion about optimizing
regular expressions for efficient performance.
When a pattern begins with .* and the PCRE_DOTALL option is
set, the pattern is implicitly anchored by PCRE, since it
can match only at the start of a subject string. However, if
PCRE_DOTALL is not set, PCRE cannot make this optimization,
because the . metacharacter does not then match a newline,
and if the subject string contains newlines, the pattern may
match from the character immediately following one of them
instead of from the very start. For example, the pattern
(.*) second
matches the subject "first\nand second" (where \n stands for
a newline character) with the first captured substring being
"and". In order to do this, PCRE has to retry the match
starting after every newline in the subject.
If you are using such a pattern with subject strings that do
not contain newlines, the best performance is obtained by
setting PCRE_DOTALL , or starting the pattern with ^.* to
indicate explicit anchoring. That saves PCRE from having to
scan along the subject looking for a newline to restart at.
Beware of patterns that contain nested indefinite repeats.
These can take a long time to run when applied to a string
that does not match. Consider the pattern fragment
(a+)*
This can match "aaaa" in 33 different ways, and this number
increases very rapidly as the string gets longer. (The *
repeat can match 0, 1, 2, 3, or 4 times, and for each of
those cases other than 0, the + repeats can match different
numbers of times.) When the remainder of the pattern is such
that the entire match is going to fail, PCRE has in princi-
ple to try every possible variation, and this can take an
extremely long time.
An optimization catches some of the more simple cases such
as
(a+)*b
where a literal character follows. Before embarking on the
standard matching procedure, PCRE checks that there is a "b"
later in the subject string, and if there is not, it fails
the match immediately. However, when there is no following
literal this optimization cannot be used. You can see the
difference by comparing the behaviour of
(a+)*\d
with the pattern above. The former gives a failure almost
instantly when applied to a whole line of "a" characters,
whereas the latter takes an appreciable time with strings
longer than about 20 characters.
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. |
(PHP 4 >= 4.0.5)
qdom_error -- Returns the error string from the last QDOM operation or FALSE if no errors occuredOstrze¿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. |
Notatka: PHP also supports regular expressions using a Perl-compatible syntax using the PCRE functions. Those functions support non-greedy matching, assertions, conditional subpatterns, and a number of other features not supported by the POSIX-extended regular expression syntax.
Ostrze¿enie |
These regular expression functions are not binary-safe. The PCRE functions are. |
Regular expressions are used for complex string manipulation in PHP. The functions that support regular expressions are:
These functions all take a regular expression string as their first argument. PHP uses the POSIX extended regular expressions as defined by POSIX 1003.2. For a full description of POSIX regular expressions see the regex man pages included in the regex directory in the PHP distribution. It's in manpage format, so you'll want to do something along the lines of man /usr/local/src/regex/regex.7 in order to read it.
Przykład 1. Regular Expression Examples
|
Notatka: preg_match(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to ereg().
Searches a string for matches to the regular expression given in pattern.
If matches are found for parenthesized substrings of pattern and the function is called with the third argument regs, the matches will be stored in the elements of the array regs. $regs[1] will contain the substring which starts at the first left parenthesis; $regs[2] will contain the substring starting at the second, and so on. $regs[0] will contain a copy of the complete string matched.
Notatka: Up to (and including) PHP 4.1.0 $regs will be filled with exactly ten elements, even though more or fewer than ten parenthesized substrings may actually have matched. This has no effect on ereg()'s ability to match more substrings. If no matches are found, $regs will not be altered by ereg().
Searching is case sensitive.
Returns TRUE if a match for pattern was found in string, or FALSE if no matches were found or an error occurred.
The following code snippet takes a date in ISO format (YYYY-MM-DD) and prints it in DD.MM.YYYY format:
See also eregi(), ereg_replace(), eregi_replace() and preg_match().
Notatka: preg_replace(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to ereg_replace().
This function scans string for matches to pattern, then replaces the matched text with replacement.
The modified string is returned. (Which may mean that the original string is returned if there are no matches to be replaced.)
If pattern contains parenthesized substrings, replacement may contain substrings of the form \\digit, which will be replaced by the text matching the digit'th parenthesized substring; \\0 will produce the entire contents of string. Up to nine substrings may be used. Parentheses may be nested, in which case they are counted by the opening parenthesis.
If no matches are found in string, then string will be returned unchanged.
For example, the following code snippet prints "This was a test" three times:
One thing to take note of is that if you use an integer value as the replacement parameter, you may not get the results you expect. This is because ereg_replace() will interpret the number as the ordinal value of a character, and apply that. For instance:
Przykład 2. ereg_replace() Example
|
See also ereg(), eregi(), eregi_replace(), str_replace(), and preg_match().
This function is identical to ereg() except that this ignores case distinction when matching alphabetic characters.
See also ereg(), ereg_replace(), and eregi_replace().
This function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.
See also ereg(), eregi(), and ereg_replace().
Notatka: preg_split(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to split().
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the regular expression pattern. If limit is set, the returned array will contain a maximum of limit elements with the last element containing the whole rest of string. If an error occurs, split() returns FALSE.
To split off the first four fields from a line from /etc/passwd:
Notatka: If there are n occurrences of pattern, the returned array will contain n+1 items. For example, if there is no occurrence of pattern, an array with only one element will be returned. Of course, this is also true if string is empty.
To parse a date which may be delimited with slashes, dots, or hyphens:
Note that pattern is case-sensitive.
Note that if you don't require the power of regular expressions, it is faster to use explode(), which doesn't incur the overhead of the regular expression engine.
For users looking for a way to emulate Perl's $chars = split('', $str) behaviour, please see the examples for preg_split().
Please note that pattern is a regular expression. If you want to split on any of the characters which are considered special by regular expressions, you'll need to escape them first. If you think split() (or any other regex function, for that matter) is doing something weird, please read the file regex.7, included in the regex/ subdirectory of the PHP distribution. It's in manpage format, so you'll want to do something along the lines of man /usr/local/src/regex/regex.7 in order to read it.
See also: preg_split(), spliti(), explode(), implode(), chunk_split(), and wordwrap().
This function is identical to split() except that this ignores case distinction when matching alphabetic characters.
Returns a valid regular expression which will match string, ignoring case. This expression is string with each character converted to a bracket expression; this bracket expression contains that character's uppercase and lowercase form if applicable, otherwise it contains the original character twice.
[Ff][Oo][Oo] [Bb][Aa][Rr] |
This can be used to achieve case insensitive pattern matching in products which support only case sensitive regular expressions.
This module provides semaphore functions using System V semaphores. Semaphores may be used to provide exclusive access to resources on the current machine, or to limit the number of processes that may simultaneously use a resource.
This module provides also shared memory functions using System V shared memory. Shared memory may be used to provide access to global variables. Different httpd-daemons and even other programs (such as Perl, C, ...) are able to access this data to provide a global data-exchange. Remember, that shared memory is NOT safe against simultaneous access. Use semaphores for synchronization.
Tabela 1. Limits of Shared Memory by the Unix OS
SHMMAX | max size of shared memory, normally 131072 bytes |
SHMMIN | minimum size of shared memory, normally 1 byte |
SHMMNI | max amount of shared memory segments on a system, normally 100 |
SHMSEG | max amount of shared memory segments per process, normally 6 |
Notatka: These functions do not work on Windows systems.
Returns: A positive semaphore identifier on success, or FALSE on error.
sem_get() returns an id that can be used to access the System V semaphore with the given key. The semaphore is created if necessary using the permission bits specified in perm (defaults to 0666). The number of processes that can acquire the semaphore simultaneously is set to max_acquire (defaults to 1). Actually this value is set only if the process finds it is the only process currently attached to the semaphore.
A second call to sem_get() for the same key will return a different semaphore identifier, but both identifiers access the same underlying semaphore.
See also: sem_acquire() and sem_release().
Notatka: This function does not work on Windows systems.
Returns: TRUE on success, FALSE on error.
sem_acquire() blocks (if necessary) until the semaphore can be acquired. A process attempting to acquire a semaphore which it has already acquired will block forever if acquiring the semaphore would cause its max_acquire value to be exceeded.
After processing a request, any semaphores acquired by the process but not explicitly released will be released automatically and a warning will be generated.
See also: sem_get() and sem_release().
Returns: TRUE on success, FALSE on error.
sem_release() releases the semaphore if it is currently acquired by the calling process, otherwise a warning is generated.
After releasing the semaphore, sem_acquire() may be called to re-acquire it.
See also: sem_get() and sem_acquire().
Notatka: This function does not work on Windows systems.
Returns: TRUE on success, FALSE on error.
sem_remove() removes the semaphore sem_identifier if it has been created by sem_get(), otherwise generates a warning.
After removing the semaphore, it is no more accessible.
See also: sem_get(), sem_release() and sem_acquire().
Notatka: This function does not work on Windows systems. It was added on PHP 4.1.0.
shm_attach() returns an id that that can be used to access the System V shared memory with the given key, the first call creates the shared memory segment with mem_size (default: sysvshm.init_mem in the configuration file, otherwise 10000 bytes) and the optional perm-bits (default: 0666).
A second call to shm_attach() for the same key will return a different shared memory identifier, but both identifiers access the same underlying shared memory. Memsize and perm will be ignored.
Notatka: This function does not work on Windows systems.
shm_detach() disconnects from the shared memory given by the shm_identifier created by shm_attach(). Remember, that shared memory still exist in the Unix system and the data is still present.
Removes shared memory from Unix systems. All data will be destroyed.
Notatka: This function does not work on Windows systems.
Inserts or updates a variable with a given variable_key. All variable-types are supported.
Notatka: This function does not work on Windows systems.
shm_get_var() returns the variable with a given variable_key. The variable is still present in the shared memory.
Notatka: This function does not work on Windows systems.
Removes a variable with a given variable_key and frees the occupied memory.
Notatka: This function does not work on Windows systems.
SESAM/SQL-Server is a mainframe database system, developed by Fujitsu Siemens Computers, Germany. It runs on high-end mainframe servers using the operating system BS2000/OSD.
In numerous productive BS2000 installations, SESAM/SQL-Server has proven ...
the ease of use of Java-, Web- and client/server connectivity,
the capability to work with an availability of more than 99.99%,
the ability to manage tens and even hundreds of thousands of users.
Now there is a PHP3 SESAM interface available which allows database operations via PHP-scripts.
Configuration notes: There is no standalone support for the PHP SESAM interface, it works only as an integrated Apache module. In the Apache PHP module, this SESAM interface is configured using Apache directives.
Tabela 1. SESAM Configuration directives
Directive Meaning php3_sesam_oml Name of BS2000 PLAM library containing the loadable SESAM driver modules. Required for using SESAM functions. Example:
php3_sesam_configfile Name of SESAM application configuration file. Required for using SESAM functions. Example:
It will usually contain a configuration like (see SESAM reference manual):php3_sesam_messagecatalog Name of SESAM message catalog file. In most cases, this directive is not neccessary. Only if the SESAM message file is not installed in the system's BS2000 message file table, it can be set with this directive. Example:
In addition to the configuration of the PHP/SESAM interface, you have to configure the SESAM-Database server itself on your mainframe as usual. That means:
starting the SESAM database handler (DBH), and
connecting the databases with the SESAM database handler
To get a connection between a PHP script and the database handler, the CNF and NAM parameters of the selected SESAM configuration file must match the id of the started database handler.
In case of distributed databases you have to start a SESAM/SQL-DCN agent with the distribution table including the host and database names.
The communication between PHP (running in the POSIX subsystem) and the database handler (running outside the POSIX subsystem) is realized by a special driver module called SQLSCI and SESAM connection modules using common memory. Because of the common memory access, and because PHP is a static part of the web server, database accesses are very fast, as they do not require remote accesses via ODBC, JDBC or UTM.
Only a small stub loader (SESMOD) is linked with PHP, and the SESAM connection modules are pulled in from SESAM's OML PLAM library. In the configuration, you must tell PHP the name of this PLAM library, and the file link to use for the SESAM configuration file (As of SESAM V3.0, SQLSCI is available in the SESAM Tool Library, which is part of the standard distribution).
Because the SQL command quoting for single quotes uses duplicated single quotes (as opposed to a single quote preceded by a backslash, used in some other databases), it is advisable to set the PHP configuration directives php3_magic_quotes_gpc and php3_magic_quotes_sybase to On for all PHP scripts using the SESAM interface.
Runtime considerations: Because of limitations of the BS2000 process model, the driver can be loaded only after the Apache server has forked off its server child processes. This will slightly slow down the initial SESAM request of each child, but subsequent accesses will respond at full speed.
When explicitly defining a Message Catalog for SESAM, that catalog will be loaded each time the driver is loaded (i.e., at the initial SESAM request). The BS2000 operating system prints a message after successful load of the message catalog, which will be sent to Apache's error_log file. BS2000 currently does not allow suppression of this message, it will slowly fill up the log.
Make sure that the SESAM OML PLAM library and SESAM configuration file are readable by the user id running the web server. Otherwise, the server will be unable to load the driver, and will not allow to call any SESAM functions. Also, access to the database must be granted to the user id under which the Apache server is running. Otherwise, connections to the SESAM database handler will fail.
Cursor Types: The result cursors which are allocated for SQL "select type" queries can be either "sequential" or "scrollable". Because of the larger memory overhead needed by "scrollable" cursors, the default is "sequential".
When using "scrollable" cursors, the cursor can be freely positioned on the result set. For each "scrollable" query, there are global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT) and the scrolling offset which can either be set once by sesam_seek_row() or each time when fetching a row using sesam_fetch_row(). When fetching a row using a "scrollable" cursor, the following post-processing is done for the global default values for the scrolling type and scrolling offset:
Tabela 2. Scrolled Cursor Post-Processing
Scroll Type Action SESAM_SEEK_NEXT none SESAM_SEEK_PRIOR none SESAM_SEEK_FIRST set scroll type to SESAM_SEEK_NEXT SESAM_SEEK_LAST set scroll type to SESAM_SEEK_PRIOR SESAM_SEEK_ABSOLUTE Auto-Increment internal offset value SESAM_SEEK_RELATIVE none. (maintain global default offset value, which allows for, e.g., fetching each 10th row backwards)
Porting note: Because in the PHP world it is natural to start indexes at zero (rather than 1), some adaptions have been made to the SESAM interface: whenever an indexed array is starting with index 1 in the native SESAM interface, the PHP interface uses index 0 as a starting point. E.g., when retrieving columns with sesam_fetch_row(), the first column has the index 0, and the subsequent columns have indexes up to (but not including) the column count ($array["count"]). When porting SESAM applications from other high level languages to PHP, be aware of this changed interface. Where appropriate, the description of the respective php sesam functions include a note that the index is zero based.
Security concerns: When allowing access to the SESAM databases, the web server user should only have as little privileges as possible. For most databases, only read access privilege should be granted. Depending on your usage scenario, add more access rights as you see fit. Never allow full control to any database for any user from the 'net! Restrict access to php scripts which must administer the database by using password control and/or SSL security.
Migration from other SQL databases: No two SQL dialects are ever 100% compatible. When porting SQL applications from other database interfaces to SESAM, some adaption may be required. The following typical differences should be noted:
Vendor specific data types
Some vendor specific data types may have to be replaced by standard SQL data types (e.g., TEXT could be replaced by VARCHAR(max. size)).
Keywords as SQL identifiers
In SESAM (as in standard SQL), such identifiers must be enclosed in double quotes (or renamed).
Display length in data types
SESAM data types have a precision, not a display length. Instead of int(4) (intended use: integers up to '9999'), SESAM requires simply int for an implied size of 31 bits. Also, the only datetime data types available in SESAM are: DATE, TIME(3) and TIMESTAMP(3).
SQL types with vendor-specific unsigned, zerofill, or auto_increment attributes
Unsigned and zerofill are not supported. Auto_increment is automatic (use "INSERT ... VALUES(*, ...)" instead of "... VALUES(0, ...)" to take advantage of SESAM-implied auto-increment.
int ... DEFAULT '0000'
Numeric variables must not be initialized with string constants. Use DEFAULT 0 instead. To initialize variables of the datetime SQL data types, the initialization string must be prefixed with the respective type keyword, as in: CREATE TABLE exmpl ( xtime timestamp(3) DEFAULT TIMESTAMP '1970-01-01 00:00:00.000' NOT NULL );
$count = xxxx_num_rows();
Some databases promise to guess/estimate the number of the rows in a query result, even though the returned value is grossly incorrect. SESAM does not know the number of rows in a query result before actually fetching them. If you REALLY need the count, try SELECT COUNT(...) WHERE ..., it will tell you the number of hits. A second query will (hopefully) return the results.
DROP TABLE thename;
In SESAM, in the DROP TABLE command, the table name must be either followed by the keyword RESTRICT or CASCADE. When specifying RESTRICT, an error is returned if there are dependent objects (e.g., VIEWs), while with CASCADE, dependent objects will be deleted along with the specified table.
Notes on the use of various SQL types: SESAM does not currently support the BLOB type. A future version of SESAM will have support for BLOB.
At the PHP interface, the following type conversions are automatically applied when retrieving SQL fields:
When retrieving a complete row, the result is returned as an array. Empty fields are not filled in, so you will have to check for the existence of the individual fields yourself (use isset() or empty() to test for empty fields). That allows more user control over the appearance of empty fields (than in the case of an empty string as the representation of an empty field).Tabela 3. SQL to PHP Type Conversions
SQL Type PHP Type SMALLINT, INTEGER integer NUMERIC, DECIMAL, FLOAT, REAL, DOUBLE float DATE, TIME, TIMESTAMP string VARCHAR, CHARACTER string
Support of SESAM's "multiple fields" feature: The special "multiple fields" feature of SESAM allows a column to consist of an array of fields. Such a "multiple field" column can be created like this:
and can be filled in using:
Note that (like in this case) leading empty sub-fields are ignored, and the filled-in values are collapsed, so that in the above example the result will appear as multi(1..2) instead of multi(2..3).
When retrieving a result row, "multiple columns" are accessed like "inlined" additional columns. In the example above, "pkey" will have the index 0, and the three "multi(1..3)" columns will be accessible as indices 1 through 3.
For specific SESAM details, please refer to the SESAM/SQL-Server documentation (english) or the SESAM/SQL-Server documentation (german), both available online, or use the respective manuals.
Returns TRUE if a connection to the SESAM database was made, or FALSE on error.
sesam_connect() establishes a connection to an SESAM database handler task. The connection is always "persistent" in the sense that only the very first invocation will actually load the driver from the configured SESAM OML PLAM library. Subsequent calls will reuse the driver and will immediately use the given catalog, schema, and user.
When creating a database, the "catalog" name is specified in the SESAM configuration directive //ADD-SQL-DATABASE-CATALOG-LIST ENTRY-1 = *CATALOG(CATALOG-NAME = catalogname,...)
The "schema" references the desired database schema (see SESAM handbook).
The "user" argument references one of the users which are allowed to access this "catalog" / "schema" combination. Note that "user" is completely independent from both the system's user id's and from HTTP user/password protection. It appears in the SESAM configuration only.
See also sesam_disconnect().
Returns: always TRUE.
sesam_disconnect() closes the logical link to a SESAM database (without actually disconnecting and unloading the driver).
Note that this isn't usually necessary, as the open connection is automatically closed at the end of the script's execution. Uncommitted data will be discarded, because an implicit sesam_rollback() is executed.
sesam_disconnect() will not close the persistent link, it will only invalidate the currently defined "catalog", "schema" and "user" triple, so that any sesam function called after sesam_disconnect() will fail.
See also: sesam_connect().
Returns: TRUE if the values are valid, and the settransaction() operation was successful, FALSE otherwise.
sesam_settransaction() overrides the default values for the "isolation level" and "read-only" transaction parameters (which are set in the SESAM configuration file), in order to optimize subsequent queries and guarantee database consistency. The overridden values are used for the next transaction only.
sesam_settransaction() can only be called before starting a transaction, not after the transaction has been started already.
To simplify the use in php scripts, the following constants have been predefined in php (see SESAM handbook for detailed explanation of the semantics):
Tabela 1. Valid values for "Isolation_Level" parameter
Value | Constant | Meaning |
---|---|---|
1 | SESAM_TXISOL_READ_UNCOMMITTED | Read Uncommitted |
2 | SESAM_TXISOL_READ_COMMITTED | Read Committed |
3 | SESAM_TXISOL_REPEATABLE_READ | Repeatable Read |
4 | SESAM_TXISOL_SERIALIZABLE | Serializable |
Tabela 2. Valid values for "Read_Only" parameter
Value | Constant | Meaning |
---|---|---|
0 | SESAM_TXREAD_READWRITE | Read/Write |
1 | SESAM_TXREAD_READONLY | Read-Only |
The values set by sesam_settransaction() will override the default setting specified in the SESAM configuration file.
Returns: TRUE on success, FALSE on errors
sesam_commit() commits any pending updates to the database.
Note that there is no "auto-commit" feature as in other databases, as it could lead to accidental data loss. Uncommitted data at the end of the current script (or when calling sesam_disconnect()) will be discarded by an implied sesam_rollback() call.
See also: sesam_rollback().
Returns: TRUE on success, FALSE on errors
sesam_rollback() discards any pending updates to the database. Also affected are result cursors and result descriptors.
At the end of each script, and as part of the sesam_disconnect() function, an implied sesam_rollback() is executed, discarding any pending changes to the database.
See also: sesam_commit().
Przykład 1. Discarding an update to the SESAM database
|
Returns: A SESAM "result identifier" on success, or FALSE on error.
sesam_execimm() executes an "immediate" statement (i.e., a statement like UPDATE, INSERT or DELETE which returns no result, and has no INPUT or OUTPUT variables). "select type" queries can not be used with sesam_execimm(). Sets the affected_rows value for retrieval by the sesam_affected_rows() function.
Note that sesam_query() can handle both "immediate" and "select-type" queries. Use sesam_execimm() only if you know beforehand what type of statement will be executed. An attempt to use SELECT type queries with sesam_execimm() will return $err["sqlstate"] == "42SBW".
The returned "result identifier" can not be used for retrieving anything but the sesam_affected_rows(); it is only returned for symmetry with the sesam_query() function.
$stmt = "INSERT INTO mytable VALUES ('one', 'two')"; $result = sesam_execimm ($stmt); $err = sesam_diagnostic(); print ("sqlstate = ".$err["sqlstate"]."\n". "Affected rows = ".$err["rowcount"]." == ". sesam_affected_rows($result)."\n"); |
Returns: A SESAM "result identifier" on success, or FALSE on error.
A "result_id" resource is used by other functions to retrieve the query results.
sesam_query() sends a query to the currently active database on the server. It can execute both "immediate" SQL statements and "select type" queries. If an "immediate" statement is executed, then no cursor is allocated, and any subsequent sesam_fetch_row() or sesam_fetch_result() call will return an empty result (zero columns, indicating end-of-result). For "select type" statements, a result descriptor and a (scrollable or sequential, depending on the optional boolean scrollable parameter) cursor will be allocated. If scrollable is omitted, the cursor will be sequential.
When using "scrollable" cursors, the cursor can be freely positioned on the result set. For each "scrollable" query, there are global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT) and the scrolling offset which can either be set once by sesam_seek_row() or each time when fetching a row using sesam_fetch_row().
For "immediate" statements, the number of affected rows is saved for retrieval by the sesam_affected_rows() function.
See also: sesam_fetch_row() and sesam_fetch_result().
Przykład 1. Show all rows of the "phone" table as a html table
|
After calling sesam_query() with a "select type" query, this function gives you the number of columns in the result. Returns an integer describing the total number of columns (aka. fields) in the current result_id result set or FALSE on error.
For "immediate" statements, the value zero is returned. The SESAM "multiple field" columns count as their respective dimension, i.e., a three-column "multiple field" counts as three columns.
See also: sesam_query() and sesam_field_array() for a way to distinguish between "multiple field" columns and regular columns.
Returns the name of a field (i.e., the column name) in the result set, or FALSE on error.
For "immediate" queries, or for dynamic columns, an empty string is returned.
Notatka: The column index is zero-based, not one-based as in SESAM.
See also: sesam_field_array(). It provides an easier interface to access the column names and types, and allows for detection of "multiple fields".
Returns an associative array of status and return codes for the last SQL query/statement/command. Elements of the array are:
Tabela 1. Status information returned by sesam_diagnostic()
Element | Contents |
---|---|
$array["sqlstate"] | 5 digit SQL return code (see the SESAM manual for the description of the possible values of SQLSTATE) |
$array["rowcount"] | number of affected rows in last update/insert/delete (set after "immediate" statements only) |
$array["errmsg"] | "human readable" error message string (set after errors only) |
$array["errcol"] | error column number of previous error (0-based; or -1 if undefined. Set after errors only) |
$array["errlin"] | error line number of previous error (0-based; or -1 if undefined. Set after errors only) |
In the following example, a syntax error (E SEW42AE ILLEGAL CHARACTER) is displayed by including the offending SQL statement and pointing to the error location:
Przykład 1. Displaying SESAM error messages with error position
|
See also: sesam_errormsg() for simple access to the error string only
Returns a mixed array with the query result entries, optionally limited to a maximum of max_rows rows. Note that both row and column indexes are zero-based.
Tabela 1. Mixed result set returned by sesam_fetch_result()
Array Element | Contents |
---|---|
int $arr["count"] | number of columns in result set (or zero if this was an "immediate" query) |
int $arr["rows"] | number of rows in result set (between zero and max_rows) |
bool $arr["truncated"] | TRUE if the number of rows was at least max_rows, FALSE otherwise. Note that even when this is TRUE, the next sesam_fetch_result() call may return zero rows because there are no more result entries. |
mixed $arr[col][row] | result data for all the fields at row(row) and column(col), (where the integer index row is between 0 and $arr["rows"]-1, and col is between 0 and $arr["count"]-1). Fields may be empty, so you must check for the existence of a field by using the php isset() function. The type of the returned fields depend on the respective SQL type declared for its column (see SESAM overview for the conversions applied). SESAM "multiple fields" are "inlined" and treated like a sequence of columns. |
See also: sesam_fetch_row(), and sesam_field_array() to check for "multiple fields". See the description of the sesam_query() function for a complete example using sesam_fetch_result().
result_id is a valid result id returned by sesam_query().
Returns the number of rows affected by a query associated with result_id.
The sesam_affected_rows() function can only return useful values when used in combination with "immediate" SQL statements (updating operations like INSERT, UPDATE and DELETE) because SESAM does not deliver any "affected rows" information for "select type" queries. The number returned is the number of affected rows.
See also: sesam_query() and sesam_execimm()
Returns the SESAM error message associated with the most recent SESAM error.
See also: sesam_diagnostic() for the full set of SESAM SQL status information
result_id is a valid result id returned by sesam_query().
Returns a mixed associative/indexed array with meta information (column name, type, precision, ...) about individual columns of the result after the query associated with result_id.
Tabela 1. Mixed result set returned by sesam_field_array()
Array Element | Contents |
---|---|
int $arr["count"] | Total number of columns in result set (or zero if this was an "immediate" query). SESAM "multiple fields" are "inlined" and treated like the respective number of columns. |
string $arr[col]["name"] | column name for column(col), where col is between 0 and $arr["count"]-1. The returned value can be the empty string (for dynamically computed columns). SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same column name. |
string $arr[col]["count"] | The "count" attribute describes the repetition factor when the column has been declared as a "multiple field". Usually, the "count" attribute is 1. The first column of a "multiple field" column however contains the number of repetitions (the second and following column of the "multiple field" contain a "count" attribute of 1). This can be used to detect "multiple fields" in the result set. See the example shown in the sesam_query() description for a sample use of the "count" attribute. |
string $arr[col]["type"] | php variable type of the data for column(col), where col is between 0 and $arr["count"]-1. The returned value can be one of depending on the SQL type of the result. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same php type. |
string $arr[col]["sqltype"] |
SQL variable type of the column data for
column(col), where col
is between 0 and $arr["count"]-1. The
returned value can be one of
|
string $arr[col]["length"] | The SQL "length" attribute of the SQL variable in column(col), where col is between 0 and $arr["count"]-1. The "length" attribute is used with "CHARACTER" and "VARCHAR" SQL types to specify the (maximum) length of the string variable. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same length attribute. |
string $arr[col]["precision"] | The "precision" attribute of the SQL variable in column(col), where col is between 0 and $arr["count"]-1. The "precision" attribute is used with numeric and time data types. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same precision attribute. |
string $arr[col]["scale"] | The "scale" attribute of the SQL variable in column(col), where col is between 0 and $arr["count"]-1. The "scale" attribute is used with numeric data types. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same scale attribute. |
See the sesam_query() function for an example of the sesam_field_array() use.
Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
The number of columns in the result set is returned in an associative array element $array["count"]. Because some of the result columns may be empty, the count() function can not be used on the result row returned by sesam_fetch_row().
result_id is a valid result id returned by sesam_query() (select type queries only!).
whence is an optional parameter for a fetch operation on "scrollable" cursors, which can be set to the following predefined constants:
Tabela 1. Valid values for "whence" parameter
Value | Constant | Meaning |
---|---|---|
0 | SESAM_SEEK_NEXT | read sequentially (after fetch, the internal default is set to SESAM_SEEK_NEXT) |
1 | SESAM_SEEK_PRIOR | read sequentially backwards (after fetch, the internal default is set to SESAM_SEEK_PRIOR) |
2 | SESAM_SEEK_FIRST | rewind to first row (after fetch, the default is set to SESAM_SEEK_NEXT) |
3 | SESAM_SEEK_LAST | seek to last row (after fetch, the default is set to SESAM_SEEK_PRIOR) |
4 | SESAM_SEEK_ABSOLUTE | seek to absolute row number given as offset (Zero-based. After fetch, the internal default is set to SESAM_SEEK_ABSOLUTE, and the internal offset value is auto-incremented) |
5 | SESAM_SEEK_RELATIVE | seek relative to current scroll position, where offset can be a positive or negative offset value. |
When using "scrollable" cursors, the cursor can be freely positioned on the result set. If the whence parameter is omitted, the global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT, and settable by sesam_seek_row()) are used. If whence is supplied, its value replaces the global default.
offset is an optional parameter which is only evaluated (and required) if whence is either SESAM_SEEK_RELATIVE or SESAM_SEEK_ABSOLUTE. This parameter is only valid for "scrollable" cursors.
sesam_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array (indexed by values between 0 and $array["count"]-1). Fields may be empty, so you must check for the existence of a field by using the php isset() function. The type of the returned fields depend on the respective SQL type declared for its column (see SESAM overview for the conversions applied). SESAM "multiple fields" are "inlined" and treated like a sequence of columns.
Subsequent calls to sesam_fetch_row() would return the next (or prior, or n'th next/prior, depending on the scroll attributes) row in the result set, or FALSE if there are no more rows.
Przykład 1. SESAM fetch rows
|
See also: sesam_fetch_array() which returns an associative array, and sesam_fetch_result() which returns many rows per invocation.
Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
sesam_fetch_array() is an alternative version of sesam_fetch_row(). Instead of storing the data in the numeric indices of the result array, it stores the data in associative indices, using the field names as keys.
result_id is a valid result id returned by sesam_query() (select type queries only!).
For the valid values of the optional whenceand offset parameters, see the sesam_fetch_row() function for details.
sesam_fetch_array() fetches one row of data from the result associated with the specified result identifier. The row is returned as an associative array. Each result column is stored with an associative index equal to its column (aka. field) name. The column names are converted to lower case.
Columns without a field name (e.g., results of arithmetic operations) and empty fields are not stored in the array. Also, if two or more columns of the result have the same column names, the later column will take precedence. In this situation, either call sesam_fetch_row() or make an alias for the column.
A special handling allows fetching "multiple field" columns (which would otherwise all have the same column names). For each column of a "multiple field", the index name is constructed by appending the string "(n)" where n is the sub-index of the multiple field column, ranging from 1 to its declared repetition factor. The indices are NOT zero based, in order to match the nomenclature used in the respective query syntax. For a column declared as:
the associative indices used for the individual "multiple field" columns would be "multi(1)", "multi(2)", and "multi(3)" respectively.Subsequent calls to sesam_fetch_array() would return the next (or prior, or n'th next/prior, depending on the scroll attributes) row in the result set, or FALSE if there are no more rows.
Przykład 1. SESAM fetch array
|
See also: sesam_fetch_row() which returns an indexed array.
result_id is a valid result id (select type queries only, and only if a "scrollable" cursor was requested when calling sesam_query()).
whence sets the global default value for the scrolling type, it specifies the scroll type to use in subsequent fetch operations on "scrollable" cursors, which can be set to the following predefined constants:
Tabela 1. Valid values for "whence" parameter
Value | Constant | Meaning |
---|---|---|
0 | SESAM_SEEK_NEXT | read sequentially |
1 | SESAM_SEEK_PRIOR | read sequentially backwards |
2 | SESAM_SEEK_FIRST | fetch first row (after fetch, the default is set to SESAM_SEEK_NEXT) |
3 | SESAM_SEEK_LAST | fetch last row (after fetch, the default is set to SESAM_SEEK_PRIOR) |
4 | SESAM_SEEK_ABSOLUTE | fetch absolute row number given as offset (Zero-based. After fetch, the default is set to SESAM_SEEK_ABSOLUTE, and the offset value is auto-incremented) |
5 | SESAM_SEEK_RELATIVE | fetch relative to current scroll position, where offset can be a positive or negative offset value (this also sets the default "offset" value for subsequent fetches). |
offset is an optional parameter which is only evaluated (and required) if whence is either SESAM_SEEK_RELATIVE or SESAM_SEEK_ABSOLUTE.
Obsługa sesji w PHP ma na celu zapewnienie sposobu na zachowanie pewnych danych w trakcie następujących po sobie wywołań strony. Pozwala to na budowanie bardziej spersonalizowanych aplikacji i zwiększenie atrakcyjności twojej strony internetowej.
Jeśli jesteś zaznajomiony z zarządzaniem sesją w PHPLIB, zauważysz że pewnie koncepcje są podobne w obłudze sesji PHP.
Gość wchodzący na twoją stronę WWW otrzymuje unikalny identyfikator, tzw. id sesji. Jest ono przechowywane albo jako ciasteczko po stronie użytkownika lub propagowane w URL'u.
Obsługa sesji pozwala ci na rejestrowanie dowolnej ilości zmiennych, które mają być przekazywane pomiędzy stronami. Kiedy gość wchodzi na twoją strone, PHP automatycznie sprawdzi (jeśli session.auto_start jest ustawione na 1) lub na twoje życzenie (jawnie przez wywołanie session_start() lub niejawnie przez wywołanie session_register()) czy specyficzne id sesji zostało przypisane. Jeśli tak, poprzednio zachowane środowisko jest odtwarzane.
Wszystkie zarejestrowane zmienne są serializowane po wykonaniu całego kodu strony. Zarejestrowane zmienne, które są niezdefiniowane, są zaznaczane jako niezdefijiowane. Nie są one definiowane przez moduł sesji w następujących po sobie wywołaniach, chyba że użytkownik zdefiniuje je później.
Opcje konfiguracyjne track_vars i register_globals wpływają na to, jak zmienne sesyjne są przechowywane i odtwarzane.
Notatka: Od PHP w wersji 4.0.3 opcja track_vars jest zawsze włączona.
Jeśli włączona jest opcja track_vars a register_globals jest wyłączona, tylko pozycje należące do zmiennej asocjacyjnej $HTTP_SESSION_VARS mogą być zarejestrowane jako zmienne sesyjne. Odtworzone zmienne sesyjne będą dostępne tylko w zmiennej $HTTP_SESSION_VARS.
Przykład 1. Rejestracja zmiennej z włączoną opcją track_vars
|
Jeśli włączona jest opcja register_globals, wszystkie globalne zmienne mogą być zarejestrowane jako zmienne sesyjne a zmienne sesyjne będą odtworzone do odpowiadających im zmiennych globalnych.
Przykład 2. Rejestracja zminnych z włączoną opcją register_globals
|
Jeśli włączone są obie opcje, track_vars i register_globals, globalne zmienne i wpisy w $HTTP_SESSION_VARS będą referencjami do tej samej wartości.
Istnieją dwie metody propagacji identyfikatora sesji:
Ciasteczka
Parametry URL'a
Moduł sesji obsługuje obie metody. Ciasteczka są metodą optymalną, ale ponieważ nie są one pewne (klienci nie muszą ich akceptować), nie możemy na nich polegać. Druga metora wstawia identyfikatory sesji bezpośrednio do URL'i.
PHP może to robić 'przezroczyście' jeśli został skompilowany z opcją --enable-trans-sid. Jeśli włączysz tą opcję, względne URI zostaną automatycznie podmienione tak, aby zawierały identyfikator sesji. Możesz także użyć stałej SID która jest definiowana jeśli klient nie wysłał odpowiedniego ciastka. SID jest albo w postaci nazwa_sesji=id_sesji lub pustym stringiem.
Poniższy przykład demonstruje jak zarejestrować zmienną i jak prawidłowo wstawić link do kolejnej strony korzystając ze stałej SID.
Przykład 3. Zliczanie ilości odwiedzin pojedyńczego użytkownika
|
<?=SID?> nie jest konieczne jeśli przy kompilacji PHP użyta została opcja --enable-trans-sid.
Notatka: PHP zakłada, że bezwzględne URLe odnoszą się do zewnętrznych serwisów, więc nie trzeba przekazywać SID, ponieważ istniałoby niebezpieczeństwo podkradania SIDów przez inny serwer.
Aby zaimplementować przechowywanie danych sesyjnych w bazie danych lub w dowolnej innej postaci, musisz użyć session_set_save_handler() do stworzenia zestawu funkcji przechowujących dane.
System zarządzania sesją obsługuje wiele opcji konfiguracyjnych, które możesz wstawić do swojego pliku php.ini. Oto ich krótki przegląd.
session.save_handler definiuje nazwę procedury obsługi, która jest używana do przechowywania i odczytu danych skojarzonych z sesją. Domyślnie files.
session.save_path definiuje argument, który jest przekazywany procedurze obsługi zapisu danych. Jeśli wybierzesz domyślną procedurę obsługi, jest to ścieżka gdzie tworzone będą pliki z danymi. Domyślnie /tmp.
Ostrze¿enie |
Jeśli w tej opcji ustawisz katalog, który jest ogólnie dostępny, jak na przykład /tmp (domyślna wartość), inni użytkownicy serwera będą w stanie przechwycić sesję przez pobranie listy plików z tego katalogu. |
session.name określa nazwę sesji, która jest używana jako nazwa ciastka. Powinna zawierać tylko znaki alfanumeryczne. Domyślnie PHPSESSID.
session.auto_start określa, czy moduł sesji rozpoczyna sesję na początku wywołania. Domyślnie 0 (wyłączony).
session.cookie_lifetime określa długość życia w sekundach ciastka przesyłanego do przeglądarki. Wartość 0 oznacza "dopóki przeglądarka nie została zamknięta". Domyślnie 0.
session.serialize_handler określa nazwę procedury obsługi, która zostanie użyta do serializacji/odserializacji danych. Obecnie obsługiwany jest wewnętrzny format PHP (nazwa php i WDDX (nazwa wddx). WDDX jest jedynym dostępnym formatem jeśli PHP zostało skompilowane z obsługą WDDX. Domyślnie php.
session.gc_probability określa prawdopodobieństwo w procentach rozpoczęcia procedury gc (garbage collection - zbieranie śmieci) przy każdym wywołaniu. Domyślnie 1.
session.gc_maxlifetime określa ilość sekund, po jakich dane będą rozpoznawane jako 'śmieci' i usuwane.
session.referer_check zawiera podciąg, z którym HTTP_REFERER ma być sprawdzany. Jeśli HTTP_REFERER został wysłany przez klienta i nie zawierał podanego podciągu, identyfikator sesji podany przez takiego klienta zostanie uznany za nieważny. Domyślnie jest to ciąg pusty.
session.entropy_file podaje ścieżkę do zewnętrznego zasobu (pliku), który będzie użyty jako dodatkowe źródło entropii w procesie tworzenia identyfikatora sesji. Przykłady to /dev/random lub /dev/urandom, które są dostępne na wielu systemach Unix.
session.entropy_length określa liczbę bajtów, która będzie odczytana z pliku podanego powyżej. Domyślnie 0 (wyłączona).
session.use_cookies określa czy moduł będzie używał ciasteczek do przechowywania identyfikatora sesji po stronie klienta. Domyślnie 1 (włączona).
session.cookie_path określa ścieżkę która będzie podana w session_cookie. Domyślnie /.
session.cookie_domain określa domenę która ma być podana w session_cookie. Domyślnie - pusta.
session.cache_limiter określa metodę używaną do przechowywania stron sesyjnych w pamięci podręcznej (nocache/private/private_no_expire/public). Domyślnie nocache.
session.cache_expire określa czas życia w minutach stron sesyjnych zachowanych w pamięci podręcznej. Nie ma to efektu dla metody nocache. Domyślnie 180
session.use_trans_sid określa czy będzie używana obsługa przezroczystego przekazywania identyfikatora sesji. Opcja brana pod uwagę tylko jeśli PHP zostało skompilowane z opcją --enable-trans-sid. Domyślnie 1 (włączona).
url_rewriter.tags określa które tagi HTML zostają przepisane w celu dopisania identyfikatora sesji jeśli włączona została opcja przezroczystego przekazywania identyfikatora sesji. Domyślnie a=href,area=href,frame=src,input=src,form=fakeentry
Notatka: Obsługa sesji została dodana w PHP 4.0.
session_start() tworzy sesję (lub odtwarza bieżącą w oparciu o identyfikator sesji przekazywany przez zmienne GET lub ciasteczko).
Jeśli chcesz, aby sesja była nazwana, przed wywołaniem session_start() musisz wywołać session_name().
Ta funkcja zawsze zwraca warotść TRUE.
Notatka: Jeśli używasz sesji opartych o ciasteczka, to session_start() musi być wywołane przed wysłaniem jakichkolwiek danych do przeglądarki.
session_destroy() niszczy wszystkie dane skojarzone z bieżącą sesją. Nie usuwa żadnych globalnych zmiennych związanych z sesją. Nie usuwa też ciasteczka sesyjnego.
Funkcja ta zawraca TRUE w przypadku sukcesu w niszczeniu danych sesji. W przeciwnym przypadku zwracana jest wartość FALSE.
session_name() zwraca nazwę bieżącej sesji. Jeśli podano parametr name, nazwa bieżącej sesji zostanie zmieniona na tą wartość.
Nazwa sesji jest używana w identyfikatorze sesji w ciasteczkach i URLach. Powinna zawierać tylko znaki alfanumeryczne; powinna być krótka i treściwa (np. dla użytkowników z włączonymi ostrzeżeniami o ciasteczkach). Nazwa sesji jest przywracana do domyślnej wartości określonej w session.name na początku wywołania strony, a więc musisz wywołać session_name() dla każdej strony (przed wywołaniem w niej session_start() i session_register()).
session_module_name() zwraca nazwę bieżącego modułu sesji. Jeśli podany został parametr moduł, użyty zostanie nowo podany moduł.
session_save_path() zwraca ścieżkę do katalogu, który aktualnie jest używany do zapisu danych sesji. Jeśli podany został parametr ścieżka, zmieniona zostanie ścieżka zapisu danych.
Notatka: Na niektórych systemach operacyjnych możesz chciać podać ścieżkę do systemu plików, który lepiej obsługuje duże ilości małych plików. Na przykład na Linuksie reiserfs w takich warunkach ma lepszą wydajność niż ext2fs.
session_id() zwraca identyfikator sesji dla bieżącej sesji. Jeśli podany został parametr id, zostanie on użyty do zmiany identyfikatora bieżącej sesji.
Do pobrania nazwy i identyfikatora bieżącej sesji moża być użyta także stała SID, która zawiera string odpowiedni do dodawania go do URLi.
session_register() jest funkcją o zmiennej liczbie argumentów, z których każdy może być albo stringiem zawierającym nazwę zmiennej lub tablicą zawierającą nazwy zmiennych lub inne tablice. Dla każdej napotkanej nazwy zmiennej, session_register() rejestruje w bieżącej sesji globalną zmienną o danej nazwie.
Uwaga! |
Funkcja ta rejestruje globalną zmienną. Jeśli chcesz zarejestrować zmienną w sesji z wnętrza funkcji, musisz się upewnić że jest ona globalna prez użycie global() lub używając tablic sesyjnych, tak jak to opisano poniżej. |
Funkcja ta zwraca wartość TRUE jeśli wszystkie zmienne zostały pomyślnie zarejestrowane w sesji.
Jeśli przed wywołaniem tej funkcji nie wywołano session_start(), dokonane zostanie niejawne wywołanie session_start() bez żadnych parametrów.
Możesz tworzyć zmienne sesyjne poprostu przez dopisywanie odpowiednicz wpisów do tablic $HTTP_SESSION_VARS lub $_SESSION (PHP >= 4.1.0).
$barney = "Duży fioletowy dinozaur."; session_register("barney"); $HTTP_SESSION_VARS["zim"] = "Najeźdźca z innej planety."; # tablica $_SESSION typu auto-global została wprowadzona w PHP 4.1.0 #_SESSION["spongebob"] = "Ma kwadratowe spodnie."; |
Notatka: W chwili obecnej niemożliwe jest zarejestrowanie w sesji zmiennych zawierających zasoby. Na przykład, nie możesz stworzyć połączenia do bazy danych i zachować identyfikator połączenia jako zmienną sesyjną i oczekować, że połączenie ciągle będzie aktywne po odtworzeniu danych sesji. Funkcję PHP, która zwraca zasoby, identyfikuje się przez zwracanie typu resource w definicji funkcji. Listę funkcji, które zwracają zasoby, można znaleźć w załączniku typy zasobów.
Patrz także session_is_registered() i session_unregister().
session_unregister() wyrejestrowuje (zapomina) globalną zmienną o nazwie nazwa z bieżącej sesji.
Funkcja ta zwraca wartość TRUE jeśli zmienna została pomyślnie wyrejestrowana z sesji.
Uwaga! |
Ta funkcja nie usuwa zmiennej globalnej o nazwie nazwa, a jedynie zapobiega zapisaniu tej zmiennej jako części sesji. Jeśli chcesz usunąć odpowiednią zmienną globalną, musisz użyć funkcji unset(). |
Funkcja session_unset() zwalnia wszystkie zmienne sesyjne, które są aktualnie zarejestrowane.
session_is_registered() zwraca wartość TRUE jeśli w bieżącej sesji zarejestrowana jest zmienna o nazwie nazwa.
Funkcja session_get_cookie_params() zwraca tablicę zawierającą informacje o bieżącym ciasteczku sesyjnym. Tablica zawiera poniższe informacje:
"lifetime" - Czas życia ciasteczka.
"path" - Ścieżka na której przechowywane są informacje.
"domain" - Domena ciasteczka.
"secure" - Ciasteczko powinno być przesłane tylko przez bezpieczne połączenie. (Ten element został dodany w PHP 4.0.4.)
Ustaw parametry ciasteczka pierwotnie zdefiniowane w pliku php.ini. Efekt działania tej funkcji widoczny jest tylko do końca działania skryptu.
session_decode() dekofuje dane sesji zawarte w parametrze dane, ustawiając zmienne zachowane w sesji.
session_encode() zwraca string zawierający zakodowane dane bieżącej sesji.
session_set_save_handler() ustawia funkcje użytkownika do obsługi przechowywania sesji, które używane sa do zapisywania i odtwarzania danych skojarzonych z sesją. Jest to bardzo przydatne jeśli preferowany jest sposób przechowywania sesji inny niż ten, który jest dostarczany z PHP, np. przechowywanie danych sesji w lokalnej bazie danych.
Notatka: W swoim pliku php.ini musisz ustawić opcję konfiguracji session.save_handler na user aby session_set_save_handler() zadziałało.
Notatka: Procedura obsługi "zapisz" nie będzie wywołana dopóki strumień wyjściowy jest otwarty. W związku z tym, wyjście instrukcji debugowania zawartych w procedurze "zapisz" nigdy nie będzie widoczne w oknie przeglądarki. Jeśli konieczne jest wyjście debugowania, sugerowane jest zapisanie tego wyjścia do pliku.
Poniższy przykład opisuje metodę przechowywania danych sesyjnych w plikach, podobną do tej obsługiwanej wewnętrznie przez PHP. Przykład ten może być łatwo rozszerzony aby móc użyć go z twoją ulubioną bazą danych obsługiwaną przez PHP.
Przykład 1. Przykład session_set_save_handler()
|
session_cache_limiter() zwraca nazwę bieżącego ogranicznika pamięci podręcznej. Jeśli podany został parametr ogranicznik, nazwa bieżącego ogranicznego zostanie zmieniona na nową wartość.
Ogranicznik pamięci podręcznej kontroluje nagłówki HTTP wysyłane do klienta. Nagłówki te ustalają zasady, według których zawartość strony może być przechowywana w pamięci podręcznej przeglądarki. Ustawiając ogranicznik pamięci podręcznej na przykład nanocache, zabronimy jakiekolwiek zachowywanie strony po stronie klienta. Wartość public pozwoli na takie przechywanie. Ogranicznikiem może być też private, który jest troszkę bardziej restrykcyjny niż public.
W trybie private, nagłówek Expire, który jest wysyłany do klienta, może spowodować nieoczekiwane działanie niektórych przeglądarem, między innymi Mozilli. Możesz uniknąć tego problemu używając trybu private_no_expire. Nagłówek Expire nie jest w tym wypadku wysyłany do klienta.
Notatka: private_no_expire zostało dodane w PHP 4.2.0dev.
Ogranicznik pamięci podręcznej w momencie wywołania skryptu jest zerowany do wartości domyślnej przechowywanej w session.cache_limiter. W związku z tym niezbędne jest wywołanie session_cache_limiter() dla każdego wywołania skryptu (i przed wywołaniem session_start()).
session_cache_expire() zwraca aktualny czas przedawnienia pamięci podręcznej. Jeśli podany zostanie nowy_czas, to bieżący czas zostanie zastąpiony przez ten podany w parametrze.
Zakończ bieżącą sesję i zachowaj dane sesji.
Dane sesji są zazwyczaj przechowywane do czasu zakończenie działania skryptu bez konieczności wywołania session_write_close (), ale ponieważ dane sesji są blokowane w celu zapobieżenia równoległym zapisom, tylko jeden skrypt może operować na sesji w danej chwili. Używając ramek HTMLowych razem z sesjami napotkasz problemy związane z jednoczesnym korzystaniem z jednej sesji przez kilka skryptów. Możesz zmniejszyć czas niezbędny do wczytania wszystkich ramek przez kończenie sesji jak tylko wykonane są wszystkie zmiany w zmiennych sesyjnych.
Shmop is an easy to use set of functions that allows php to read, write, create and delete UNIX shared memory segments. The functions will not work on windows, as it does not support shared memory. To use shmop you will need to compile php with the --enable-shmop parameter in your configure line.
Notatka: This module is experimental. API and others are subject to be changed without notice.
In PHP 4.0.3, there functions were prefixed by shm rather than shmop.
Przykład 1. Shared Memory Operations Overview
|
shmop_open() can create or open a shared memory block.
shmop_open() takes 4 parameters: key, which is the system's id for the shared memory block, this parameter can be passed as a decimal or hex. The second parameter are the flags that you can use:
"a" for access (sets SHM_RDONLY for shmat) use this flag when you need to open an existing shared memory segment for read only
"c" for create (sets IPC_CREATE) use this flag when you need to create a new shared memory segment or if a segment with the same key exists, try to open it for read and write
"w" for read & write access use this flag when you need to read and write to a shared memory segment, use this flag in most cases.
"n" create a new memory segment (sets IPC_CREATE|IPC_EXCL) use this flag when you want to create a new shared memory segment but if one already exists with the same flag, fail. This is useful for security purposes, using this you can prevent race condition exploits.
Notatka: Note: the 3rd and 4th should be entered as 0 if you are opening an existing memory segment. On success shmop_open() will return an id that you can use to access the shared memory segment you've created.
This example opened a shared memory block with a system id of 0x0fff.
shmop_read() will read a string from shared memory block.
shmop_read() takes 3 parameters: shmid, which is the shared memory block identifier created by shmop_open(), offset from which to start reading and count on the number of bytes to read.
This example will read 50 bytes from shared memory block and place the data inside $shm_data.
shmop_write() will write a string into shared memory block.
shmop_write() takes 3 parameters: shmid, which is the shared memory block identifier created by shmop_open(), data, a string that you want to write into shared memory block and offset, which specifies where to start writing data inside the shared memory segment.
This example will write data inside $my_string into shared memory block, $shm_bytes_written will contain the number of bytes written.
shmop_size() is used to get the size, in bytes of the shared memory block.
shmop_size() takes the shmid, which is the shared memory block identifier created by shmop_open(), the function will return and int, which represents the number of bytes the shared memory block occupies.
This example will put the size of shared memory block identified by $shm_id into $shm_size.
shmop_delete() is used to delete a shared memory block.
shmop_delete() takes the shmid, which is the shared memory block identifier created by shmop_open(). On success 1 is returned, on failure 0 is returned.
This example will delete shared memory block identified by $shm_id.
shmop_close() is used to close a shared memory block.
shmop_close() takes the shmid, which is the shared memory block identifier created by shmop_open().
This example will close shared memory block identified by $shm_id.
PHP offers the ability to create Shockwave Flash files via Paul Haeberli's libswf module. You can download libswf at http://reality.sgi.com/grafica/flash/. Once you have libswf all you need to do is to configure --with-swf[=DIR] where DIR is a location containing the directories include and lib. The include directory has to contain the swf.h file and the lib directory has to contain the libswf.a file. If you unpack the libswf distribution the two files will be in one directory. Consequently you will have to copy the files to the proper location manually.
Once you've successfully installed PHP with Shockwave Flash support you can then go about creating Shockwave files from PHP. You would be surprised at what you can do, take the following code:
Przykład 1. SWF example
|
Notatka: SWF support was added in PHP 4 RC2.
The libswf does not have support for Windows. The development of that library has been stopped, and the source is not available to port it to another systems.
The swf_openfile() function opens a new file named filename with a width of width and a height of height a frame rate of framerate and background with a red color of r a green color of g and a blue color of b.
The swf_openfile() must be the first function you call, otherwise your script will cause a segfault. If you want to send your output to the screen make the filename: "php://stdout" (support for this is in 4.0.1 and up).
Close a file that was opened by the swf_openfile() function. If the return_file parameter is set then the contents of the SWF file are returned from the function.
Przykład 1. Creating a simple flash file based on user input and outputting it and saving it in a database
|
Label the current frame with the name given by the name parameter.
The swf_setframe() changes the active frame to the frame specified by framenumber.
The swf_getframe() function gets the number of the current frame.
The swf_mulcolor() function sets the global multiply color to the rgba color specified. This color is then used (implicitly) by the swf_placeobject(), swf_modifyobject() and the swf_addbuttonrecord() functions. The color of the object will be multiplied by the rgba values when the object is written to the screen.
Notatka: The rgba values can be either positive or negative.
The swf_addcolor() function sets the global add color to the rgba color specified. This color is then used (implicitly) by the swf_placeobject(), swf_modifyobject() and the swf_addbuttonrecord() functions. The color of the object will be add by the rgba values when the object is written to the screen.
Notatka: The rgba values can be either positive or negative.
Places the object specified by objid in the current frame at a depth of depth. The objid parameter and the depth must be between 1 and 65535.
This uses the current mulcolor (specified by swf_mulcolor()) and the current addcolor (specified by swf_addcolor()) to color the object and it uses the current matrix to position the object.
Notatka: Full RGBA colors are supported.
Updates the position and/or color of the object at the specified depth, depth. The parameter how determines what is updated. how can either be the constant MOD_MATRIX or MOD_COLOR or it can be a combination of both (MOD_MATRIX|MOD_COLOR).
MOD_COLOR uses the current mulcolor (specified by the function swf_mulcolor()) and addcolor (specified by the function swf_addcolor()) to color the object. MOD_MATRIX uses the current matrix to position the object.
The swf_startdoaction() function starts the description of an action list for the current frame. This must be called before actions are defined for the current frame.
The swf_actionGotoFrame() function will go to the frame specified by framenumber, play it, and then stop.
The swf_actionGetUrl() function gets the URL specified by the parameter url with the target target.
Toggle the flash movie between high and low quality.
The swf_actionWaitForFrame() function will check to see if the frame, specified by the framenumber parameter has been loaded, if not it will skip the number of actions specified by the skipcount parameter. This can be useful for "Loading..." type animations.
The swf_actionSetTarget() function sets the context for all actions. You can use this to control other flash movies that are currently playing.
The swf_actionGotoLabel() function displays the frame with the label given by the label parameter and then stops.
Ends the current action started by the swf_startdoaction() function.
The swf_defineline() defines a line starting from the x coordinate given by x1 and the y coordinate given by y1 parameter. Up to the x coordinate given by the x2 parameter and the y coordinate given by the y2 parameter. It will have a width defined by the width parameter.
The swf_definerect() defines a rectangle with an upper left hand coordinate given by the x, x1, and the y, y1. And a lower right hand coordinate given by the x coordinate, x2, and the y coordinate, y2 . Width of the rectangles border is given by the width parameter, if the width is 0.0 then the rectangle is filled.
The swf_definepoly() function defines a polygon given an array of x, y coordinates (the coordinates are defined in the parameter coords). The parameter npoints is the number of overall points that are contained in the array given by coords. The width is the width of the polygon's border, if set to 0.0 the polygon is filled.
The swf_startshape() function starts a complex shape, with an object id given by the objid parameter.
The swf_shapeLineSolid() function sets the current line style to the color of the rgba parameters and width to the width parameter. If 0.0 is given as a width then no lines are drawn.
The swf_shapeFillOff() function turns off filling for the current shape.
The swf_shapeFillSolid() function sets the current fill style to solid, and then sets the fill color to the values of the rgba parameters.
Sets the fill to bitmap clipped, empty spaces will be filled by the bitmap given by the bitmapid parameter.
Sets the fill to bitmap tile, empty spaces will be filled by the bitmap given by the bitmapid parameter (tiled).
The swf_shapeMoveTo() function moves the current position to the x coordinate given by the x parameter and the y position given by the y parameter.
The swf_shapeLineTo() draws a line to the x,y coordinates given by the x parameter & the y parameter. The current position is then set to the x,y parameters.
The swf_shapecurveto() function draws a quadratic bezier curve from the current location, though the x coordinate given by x1 and the y coordinate given by y1 to the x coordinate given by x2 and the y coordinate given by y2. The current position is then set to the x,y coordinates given by the x2 and y2 parameters
Draw a cubic bezier curve using the x,y coordinate pairs x1, y1 and x2,y2 as off curve control points and the x,y coordinate x3, y3 as an endpoint. The current position is then set to the x,y coordinate pair given by x3,y3.
The swf_shapeArc() function draws a circular arc from angle A given by the ang1 parameter to angle B given by the ang2 parameter. The center of the circle has an x coordinate given by the x parameter and a y coordinate given by the y, the radius of the circle is given by the r parameter.
The swf_endshape() completes the definition of the current shape.
The swf_definefont() function defines a font given by the fontname parameter and gives it the id specified by the fontid parameter. It then sets the font given by fontname to the current font.
The swf_setfont() sets the current font to the value given by the fontid parameter.
The swf_fontsize() function changes the font size to the value given by the size parameter.
Set the current font slant to the angle indicated by the slant parameter. Positive values create a foward slant, negative values create a negative slant.
Set the font tracking to the value specified by the tracking parameter. This function is used to increase the spacing between letters and text, positive values increase the space and negative values decrease the space between letters.
The swf_getfontinfo() function returns an associative array with the following parameters:
Aheight - The height in pixels of a capital A.
xheight - The height in pixels of a lowercase x.
Define a text string (the str parameter) using the current font and font size. The docenter is where the word is centered, if docenter is 1, then the word is centered in x.
The swf_textwidth() function gives the width of the string, str, in pixels, using the current font and font size.
The swf_definebitmap() function defines a bitmap given a GIF, JPEG, RGB or FI image. The image will be converted into a Flash JPEG or Flash color map format.
The swf_getbitmapinfo() function returns an array of information about a bitmap given by the bitmapid parameter. The returned array has the following elements:
"size" - The size in bytes of the bitmap.
"width" - The width in pixels of the bitmap.
"height" - The height in pixels of the bitmap.
Define an object id as a symbol. Symbols are tiny flash movies that can be played simultaneously. The objid parameter is the object id you want to define as a symbol.
The swf_endsymbol() function ends the definition of a symbol that was started by the swf_startsymbol() function.
The swf_startbutton() function starts off the definition of a button. The type parameter can either be TYPE_MENUBUTTON or TYPE_PUSHBUTTON. The TYPE_MENUBUTTON constant allows the focus to travel from the button when the mouse is down, TYPE_PUSHBUTTON does not allow the focus to travel when the mouse is down.
(PHP 4 >= 4.0.0)
swf_addbuttonrecord -- Controls location, appearance and active area of the current buttonThe swf_addbuttonrecord() function allows you to define the specifics of using a button. The first parameter, states, defines what states the button can have, these can be any or all of the following constants: BSHitTest, BSDown, BSOver or BSUp. The second parameter, the shapeid is the look of the button, this is usually the object id of the shape of the button. The depth parameter is the placement of the button in the current frame.
Przykład 1. swf_addbuttonrecord() function example
|
The swf_onCondition() function describes a transition that will trigger an action list. There are several types of possible transitions, the following are for buttons defined as TYPE_MENUBUTTON:
IdletoOverUp
OverUptoIdle
OverUptoOverDown
OverDowntoOverUp
IdletoOverDown
OutDowntoIdle
MenuEnter (IdletoOverUp|IdletoOverDown)
MenuExit (OverUptoIdle|OverDowntoIdle)
IdletoOverUp
OverUptoIdle
OverUptoOverDown
OverDowntoOverUp
OverDowntoOutDown
OutDowntoOverDown
OutDowntoIdle
ButtonEnter (IdletoOverUp|OutDowntoOverDown)
ButtonExit (OverUptoIdle|OverDowntoOutDown)
The swf_endButton() function ends the definition of the current button.
The swf_viewport() function selects an area for future drawing for xmin to xmax and ymin to ymax, if this function is not called the area defaults to the size of the screen.
The swf_ortho() funcion defines a orthographic mapping of user coordinates onto the current viewport.
(PHP 4 >= 4.0.0)
swf_ortho2 -- Defines 2D orthographic mapping of user coordinates onto the current viewportThe swf_ortho2() function defines a two dimensional orthographic mapping of user coordinates onto the current viewport, this defaults to one to one mapping of the area of the Flash movie. If a perspective transformation is desired, the swf_perspective () function can be used.
The swf_perspective() function defines a perspective projection transformation. The fovy parameter is field-of-view angle in the y direction. The aspect parameter should be set to the aspect ratio of the viewport that is being drawn onto. The near parameter is the near clipping plane and the far parameter is the far clipping plane.
Notatka: Various distortion artifacts may appear when performing a perspective projection, this is because Flash players only have a two dimensional matrix. Some are not to pretty.
The swf_polarview() function defines the viewer's position in polar coordinates. The dist parameter gives the distance between the viewpoint to the world space origin. The azimuth parameter defines the azimuthal angle in the x,y coordinate plane, measured in distance from the y axis. The incidence parameter defines the angle of incidence in the y,z plane, measured in distance from the z axis. The incidence angle is defined as the angle of the viewport relative to the z axis. Finally the twist specifies the amount that the viewpoint is to be rotated about the line of sight using the right hand rule.
The swf_lookat() function defines a viewing transformation by giving the viewing position (the parameters view_x, view_y, and view_z) and the coordinates of a reference point in the scene, the reference point is defined by the reference_x, reference_y , and reference_z parameters. The twist controls the rotation along with viewer's z axis.
The swf_pushmatrix() function pushes the current transformation matrix back onto the stack.
The swf_popmatrix() function pushes the current transformation matrix back onto the stack.
The swf_scale() scales the x coordinate of the curve by the value of the x parameter, the y coordinate of the curve by the value of the y parameter, and the z coordinate of the curve by the value of the z parameter.
The swf_translate() function translates the current transformation by the x, y, and z values given.
The swf_rotate() rotates the current transformation by the angle given by the angle parameter around the axis given by the axis parameter. Valid values for the axis are 'x' (the x axis), 'y' (the y axis) or 'z' (the z axis).
(PHP 4 >= 4.0.0)
swf_posround -- Enables or Disables the rounding of the translation when objects are placed or movedThe swf_posround() function enables or disables the rounding of the translation when objects are placed or moved, there are times when text becomes more readable because rounding has been enabled. The round is whether to enable rounding or not, if set to the value of 1, then rounding is enabled, if set to 0 then rounding is disabled.
In order to use the SNMP functions on Unix you need to install the UCD SNMP package. On Windows these functions are only available on NT and not on Win95/98.
Important: In order to use the UCD SNMP package, you need to define NO_ZEROLENGTH_COMMUNITY to 1 before compiling it. After configuring UCD SNMP, edit config.h and search for NO_ZEROLENGTH_COMMUNITY. Uncomment the #define line. It should look like this afterwards:
#define NO_ZEROLENGTH_COMMUNITY 1 |
If you see strange segmentation faults in combination with SNMP commands, you did not follow the above instructions. If you do not want to recompile UCD SNMP, you can compile PHP with the --enable-ucd-snmp-hack switch which will work around the misfeature.
Returns SNMP object value on success and FALSE on error.
The snmpget() function is used to read the value of an SNMP object specified by the object_id. SNMP agent is specified by the hostname and the read community is specified by the community parameter.
Sets the specified SNMP object value, returning TRUE on success and FALSE on error.
The snmpset() function is used to set the value of an SNMP object specified by the object_id. SNMP agent is specified by the hostname and the read community is specified by the community parameter.
Returns an array of SNMP object values starting from the object_id() as root and FALSE on error.
snmpwalk() function is used to read all the values from an SNMP agent specified by the hostname. Community specifies the read community for that agent. A NULL object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array. If object_id is specified, all the SNMP objects below that object_id are returned.
Above function call would return all the SNMP objects from the SNMP agent running on localhost. One can step through the values with a loop
(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)
snmpwalkoid -- Query for a tree of information about a network entityReturns an associative array with object ids and their respective object value starting from the object_id as root and FALSE on error.
snmpwalkoid() function is used to read all object ids and their respective values from an SNMP agent specified by the hostname. Community specifies the read community for that agent. A NULL object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array. If object_id is specified, all the SNMP objects below that object_id are returned.
The existence of snmpwalkoid() and snmpwalk() has historical reasons. Both functions are provided for backward compatibility.
Above function call would return all the SNMP objects from the SNMP agent running on localhost. One can step through the values with a loop
(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)
snmp_get_quick_print -- Fetch the current value of the UCD library's quick_print settingReturns the current value stored in the UCD Library for quick_print. quick_print is off by default.
Above function call would return FALSE if quick_print is off, and TRUE if quick_print is on.
snmp_get_quick_print() is only available when using the UCD SNMP library. This function is not available when using the Windows SNMP library.
See: snmp_set_quick_print() for a full description of what quick_print does.
(PHP 3>= 3.0.8, PHP 4 >= 4.0.0)
snmp_set_quick_print -- Set the value of quick_print within the UCD SNMP library.Sets the value of quick_print within the UCD SNMP library. When this is set (1), the SNMP library will return 'quick printed' values. This means that just the value will be printed. When quick_print is not enabled (default) the UCD SNMP library prints extra information including the type of the value (i.e. IpAddress or OID). Additionally, if quick_print is not enabled, the library prints additional hex values for all strings of three characters or less.
Setting quick_print is often used when using the information returned rather then displaying it.
snmp_set_quick_print(0); $a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1"); echo "$a<BR>\n"; snmp_set_quick_print(1); $a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1"); echo "$a<BR>\n"; |
The first value printed might be: 'Timeticks: (0) 0:00:00.00', whereas with quick_print enabled, just '0:00:00.00' would be printed.
By default the UCD SNMP library returns verbose values, quick_print is used to return only the value.
Currently strings are still returned with extra quotes, this will be corrected in a later release.
snmp_set_quick_print() is only available when using the UCD SNMP library. This function is not available when using the Windows SNMP library.
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. |
The socket extension implements a low-level interface to the socket communication functions, providing the possibility to act as a socket server as well as a client.
The socket functions described here are part of an extension to PHP which must be enabled at compile time by giving the --enable-sockets option to configure.
For a more generic client-side socket interface, see fsockopen() and pfsockopen().
When using these functions, it is important to remember that while many of them have identical names to their C counterparts, they often have different declarations. Please be sure to read the descriptions to avoid confusion.
That said, those unfamiliar with socket programming can still find a lot of useful material in the appropriate Unix man pages, and there is a great deal of tutorial information on socket programming in C on the web, much of which can be applied, with slight modifications, to socket programming in PHP.
Przykład 1. Socket example: Simple TCP/IP server This example shows a simple talkback server. Change the address and port variables to suit your setup and execute. You may then connect to the server with a command similar to: telnet 192.168.1.53 10000 (where the address and port match your setup). Anything you type will then be output on the server side, and echoed back to you. To disconnect, enter 'quit'.
|
Przykład 2. Socket example: Simple TCP/IP client This example shows a simple, one-shot HTTP client. It simply connects to a page, submits a HEAD request, echoes the reply, and exits.
|
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. |
After the socket socket has been created using socket_create(), bound to a name with socket_bind(), and told to listen for connections with socket_listen(), this function will accept incoming connections on that socket. Once a successful connection is made, a new socket descriptor is returned, which may be used for communication. If there are multiple connections queued on the socket, the first will be used. If there are no pending connections, socket_accept() will block until a connection becomes present. If socket has been made non-blocking using socket_set_blocking() or socket_set_nonblock(), an error code will be returned.
The socket descriptor returned by socket_accept() may not be used to accept new connections. The original listening socket socket, however, remains open and may be reused.
Returns a new socket descriptor on success, or a negative error code on failure. This code may be passed to socket_strerror() to get a textual explanation of the error.
See also socket_bind(), socket_connect(), socket_listen(), socket_create(), socket_get_status(), and socket_strerror().
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. |
socket_bind() binds the name given in address to the socket described by socket, which must be a valid socket descriptor created with socket_create().
The address parameter is either an IP address in dotted-quad notation (e.g. 127.0.0.1), if the socket is of the AF_INET family; or the pathname of a Unix-domain socket, if the socket family is AF_UNIX.
The port parameter is only used when connecting to an AF_INET socket, and designates the port on the remote host to which a connection should be made.
Returns zero on success, or a negative error code on failure. This code may be passed to socket_strerror() to get a textual explanation of the error.
See also socket_connect(), socket_listen(), socket_create(), socket_get_status(), and socket_strerror().
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. |
socket_close() closes the file (or socket) descriptor given by socket.
Note that socket_close() should not be used on PHP file descriptors created with fopen(), popen(), fsockopen(), or psockopen(); it is meant for sockets created with socket_create() or socket_accept().
Returns TRUE on success, or FALSE if an error occurs (i.e., socket is invalid).
See also socket_bind(), socket_listen(), socket_create(), socket_get_status(), and socket_strerror().
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. |
Initiates a connection using the socket descriptor socket, which must be a valid socket descriptor created with socket_create().
The address parameter is either an IP address in dotted-quad notation (e.g. 127.0.0.1), if the socket is of the AF_INET family; or the pathname of a Unix-domain socket, if the socket family is AF_UNIX.
The port parameter is only used when connecting to an AF_INET socket, and designates the port on the remote host to which a connection should be made.
Returns zero on success, or a negative error code on failure. This code may be passed to socket_strerror() to get a textual explanation of the error.
See also socket_bind(), socket_listen(), socket_create(), socket_get_status(), and socket_strerror().
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. |
After the socket socket has been created using socket_create() and bound to a name with socket_bind(), it may be told to listen for incoming connections on socket. A maximum of backlog incoming connections will be queued for processing.
socket_listen() is applicable only to sockets with type SOCK_STREAM or SOCK_SEQPACKET.
Returns zero on success, or a negative error code on failure. This code may be passed to socket_strerror() to get a textual explanation of the error.
See also socket_accept(), socket_bind(), socket_connect(), socket_create(), socket_get_status(), and socket_strerror().
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 socket_read() reads from socket socket_des created by the socket_accept() function the number of bytes set by length. Otherwise you can use \n, \t or \0 to end reading. Returns data, or FALSE if socket_read() failed.
Optional type parameter is a named constant:
PHP_BINARY_READ - use the system socket_read() (Default in PHP >= 4.1.0)
PHP_NORMAL_READ - reading stops at \n or \r. (Default in PHP <= 4.0.6)
See also socket_accept(), socket_bind(), socket_connect(), socket_listen(), socket_strerror(), socket_get_status() and socket_write().
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 communication endpoint (a socket), and returns a descriptor to the socket.
The domain parameter sets the domain. Currently, AF_INET and AF_UNIX are understood.
The type parameter selects the socket type. This is one of SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET, SOCK_RAW, SOCK_RDM, or SOCK_PACKET.
protocol sets the protocol.
Returns a valid socket descriptor on success, or a negative error code on failure. This code may be passed to socket_strerror() to get a textual explanation of the error.
For more information on the usage of socket_create(), as well as on the meanings of the various parameters, see the Unix man page socket (2).
See also socket_accept(), socket_bind(), socket_connect(), socket_listen(), socket_strerror(), and socket_get_status().
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. |
socket_strerror() takes as its errno parameter the return value of one of the socket functions, and returns the corresponding explanatory text. This makes it a bit more pleasant to figure out why something didn't work; for instance, instead of having to track down a system include file to find out what '-111' means, you just pass it to socket_strerror(), and it tells you what happened.
Przykład 1. socket_strerror() example
The expected output from the above example (assuming the script is not run with root privileges):
|
See also socket_accept(), socket_bind(), socket_connect(), socket_listen(), socket_create(), and socket_get_status().
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 socket_write() writes to the socket socket_des from &buffer the number of bytes set by length.
See also socket_accept(), socket_bind(), socket_connect(), socket_listen(), socket_read(), socket_strerror(), and socket_get_status().
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. |
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. |
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. |
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. |
(PHP 4 >= 4.1.0)
socket_fd_isset -- Checks to see if a file descriptor is set within the file descrirptor setOstrze¿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. |
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. |
(PHP 4 >= 4.1.0)
socket_select -- Runs the select() system call on the sets mentioned with a timeout specified by tv_sec and tv_usecOstrze¿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. |
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. |
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. |
(PHP 4 >= 4.1.0)
socket_getsockname -- Given an fd, stores a string representing sa.sin_addr and the value of sa.sin_port into addr and port describing the local side of a socketOstrze¿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. |
(PHP 4 >= 4.1.0)
socket_getpeername -- Given an fd, stores a string representing sa.sin_addr and the value of sa.sin_port into addr and port describing the remote side of a socketOstrze¿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. |
(PHP 4 >= 4.1.0)
socket_iovec_alloc -- ...]) Builds a 'struct iovec' for use with sendmsg, recvmsg, writev, and readvOstrze¿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. |
(PHP 4 >= 4.1.0)
socket_iovec_fetch -- Returns the data held in the iovec specified by iovec_id[iovec_position]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. |
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. |
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. |
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. |
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. |
(PHP 4 >= 4.1.0)
socket_readv -- Reads from an fd, using the scatter-gather array defined by iovec_idOstrze¿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. |
(PHP 4 >= 4.1.0)
socket_writev -- Writes to a file descriptor, fd, using the scatter-gather array defined by iovec_idOstrze¿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. |
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. |
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. |
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. |
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. |
(PHP 4 >= 4.1.0)
socket_recvmsg -- Used to receive messages on a socket, whether connection-oriented or notOstrze¿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. |
(PHP 4 >= 4.1.0)
socket_sendmsg -- Sends a message to a socket, regardless of whether it is connection-oriented or notOstrze¿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. |
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. |
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. |
(PHP 4 >= 4.1.0)
socket_create_pair -- Creates a pair of indistinguishable sockets and stores them in fds.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. |
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. |
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. |
These functions all manipulate strings in various ways. Some more specialized sections can be found in the regular expression and URL handling sections.
For information on how strings behave, especially with regard to usage of single quotes, double quotes, and escape sequences, see the Strings entry in the Types section of the manual.
Returns a string with backslashes before characters that are listed in charlist parameter. It escapes \n, \r etc. in C-like style, characters with ASCII code lower than 32 and higher than 126 are converted to octal representation.
Be careful if you choose to escape characters 0, a, b, f, n, r, t and v. They will be converted to \0, \a, \b, \f, \n, \r, \t and \v. In PHP \0 (NULL), \r (carriage return), \n (newline) and \t (tab) are predefined escape sequences, while in C all of these are predefined escape sequences.
charlist like "\0..\37", which would escape all characters with ASCII code between 0 and 31.
When you define a sequence of characters in the charlist argument make sure that you know what characters come between the characters that you set as the start and end of the range.
echo addcslashes('foo[ ]', 'A..z'); // output: \f\o\o\[ \] // All upper and lower-case letters will be escaped // ... but so will the [\]^_` and any tabs, line // feeds, carriage returns, etc. |
See also stripcslashes(), stripslashes(), htmlspecialchars(), and quotemeta().
Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).
Notatka: magic_quotes_gpc is ON by default.
See also stripslashes(), htmlspecialchars(), and quotemeta().
Returns an ASCII string containing the hexadecimal representation of str. The conversion is done byte-wise with the high-nibble first.
This function is an alias of rtrim().
Notatka: chop() is different than the Perl chop() function, which removes the last character in the string.
Returns a one-character string containing the character specified by ascii.
You can find an ASCII-table over here: http://www.mindspring.com/~jc1/serial/Resources/ASCII.html.
This function complements ord(). See also sprintf() with a format string of %c.
Can be used to split a string into smaller chunks which is useful for e.g. converting base64_encode output to match RFC 2045 semantics. It inserts end (defaults to "\r\n") every chunklen characters (defaults to 76). It returns the new string leaving the original string untouched.
See also explode(), split() and wordwrap().
(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)
convert_cyr_string -- Convert from one Cyrillic character set to anotherThis function returns the given string converted from one Cyrillic character set to another. The from and to arguments are single characters that represent the source and target Cyrillic character sets. The supported types are:
k - koi8-r
w - windows-1251
i - iso8859-5
a - x-cp866
d - x-cp866
m - x-mac-cyrillic
Counts the number of occurrences of every byte-value (0..255) in string and returns it in various ways. The optional parameter Mode default to 0. Depending on mode count_chars() returns one of the following:
0 - an array with the byte-value as key and the frequency of every byte as value.
1 - same as 0 but only byte-values with a frequency greater than zero are listed.
2 - same as 0 but only byte-values with a frequency equal to zero are listed.
3 - a string containing all used byte-values is returned.
4 - a string containing all not used byte-values is returned.
Generates the cyclic redundancy checksum polynomial of 32-bit lengths of the str. This is usually used to validate the integrity of data being transmitted.
See also: md5()
crypt() will return an encrypted string using the standard Unix DES-based encryption algorithm or alternative algorithms that may be available on the system. Arguments are a string to be encrypted and an optional salt string to base the encryption on. See the Unix man page for your crypt function for more information.
If the salt argument is not provided, one will be randomly generated by PHP.
Some operating systems support more than one type of encryption. In fact, sometimes the standard DES-based encryption is replaced by an MD5-based encryption algorithm. The encryption type is triggered by the salt argument. At install time, PHP determines the capabilities of the crypt function and will accept salts for other encryption types. If no salt is provided, PHP will auto-generate a standard two character salt by default, unless the default encryption type on the system is MD5, in which case a random MD5-compatible salt is generated. PHP sets a constant named CRYPT_SALT_LENGTH which tells you whether a regular two character salt applies to your system or the longer twelve character salt is applicable.
If you are using the supplied salt, you should be aware that the salt is generated once. If you are calling this function recursively, this may impact both appearance and security.
The standard DES-based encryption crypt() returns the salt as the first two characters of the output. It also only uses the first eight characters of str, so longer strings that start with the same eight characters will generate the same result (when the same salt is used).
On systems where the crypt() function supports multiple encryption types, the following constants are set to 0 or 1 depending on whether the given type is available:
CRYPT_STD_DES - Standard DES-based encryption with a two character salt
CRYPT_EXT_DES - Extended DES-based encryption with a nine character salt
CRYPT_MD5 - MD5 encryption with a twelve character salt starting with $1$
CRYPT_BLOWFISH - Blowfish encryption with a sixteen character salt starting with $2$
Notatka: There is no decrypt function, since crypt() uses a one-way algorithm.
Przykład 1. crypt() examples
|
See also md5() and the Mcrypt extension.
Outputs all parameters.
echo() is not actually a function (it is a language construct) so you are not required to use parentheses with it. In fact, if you want to pass more than one parameter to echo, you must not enclose the parameters within parentheses.
Przykład 1. echo() examples
|
echo() also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign.
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string separator. If limit is set, the returned array will contain a maximum of limit elements with the last element containing the rest of string.
If separator is an empty string (""), explode() will return FALSE. If separator contains a value that is not contained in string, then explode() will return an array containing string.
Notatka: The limit parameter was added in PHP 4.0.1
Notatka: Although implode() can for historical reasons accept its parameters in either order, explode() cannot. You must ensure that the separator argument comes before the string argument.
See also preg_split(), spliti(), split(), and implode().
(PHP 4 >= 4.0.0)
get_html_translation_table -- Returns the translation table used by htmlspecialchars() and htmlentities()get_html_translation_table() will return the translation table that is used internally for htmlspecialchars() and htmlentities(). There are two new defines (HTML_ENTITIES, HTML_SPECIALCHARS) that allow you to specify the table you want. And as in the htmlspecialchars() and htmlentities() functions you can optionally specify the quote_style you are working with. The default is ENT_COMPAT mode. See the description of these modes in htmlspecialchars().
The cool thing is using array_flip() to change the direction of the translation.
The content of $original would be: "Hallo & <Frau> & Krämer".See also: htmlspecialchars(), htmlentities(), strtr(), and array_flip().
(PHP 3>= 3.0.4, PHP 4 >= 4.0.0)
get_meta_tags -- Extracts all meta tag content attributes from a file and returns an arrayOpens filename and parses it line by line for <meta> tags of the form
The value of the name property becomes the key, the value of the content property becomes the value of the returned array, so you can easily use standard array functions to traverse it or access single values. Special characters in the value of the name property are substituted with '_', the rest is converted to lower case.
Setting use_include_path to 1 will result in PHP trying to open the file along the standard include path.
The optional parameter max_chars_per_line indicates maximum number of characters per line will be output. The function tries to avoid breaking words.
See also hebrevc()
(PHP 3, PHP 4 >= 4.0.0)
hebrevc -- Convert logical Hebrew text to visual text with newline conversionThis function is similar to hebrev() with the difference that it converts newlines (\n) to "<br>\n". The optional parameter max_chars_per_line indicates maximum number of characters per line will be output. The function tries to avoid breaking words.
See also hebrev()
This function is identical to htmlspecialchars() in all ways, except that all characters which have HTML character entity equivalents are translated into these entities. Like htmlspecialchars(), it takes an optional second argument which indicates what should be done with single and double quotes. ENT_COMPAT (the default) will only convert double-quotes and leave single-quotes alone. ENT_QUOTES will convert both double and single quotes, and ENT_NOQUOTES will leave both double and single quotes unconverted.
At present, the ISO-8859-1 character set is used as default. Support for the optional second argument was added in PHP 3.0.17 and PHP 4.0.3.
Like htmlspecialchars(), it takes an optional third argument which defines character set used in conversion. Support for this argument was added in PHP 4.1.0.
See also htmlspecialchars() and nl2br().
Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead.
This function is useful in preventing user-supplied text from containing HTML markup, such as in a message board or guest book application. The optional second argument, quote_style, tells the function what to do with single and double quote characters. The default mode, ENT_COMPAT, is the backwards compatible mode which only translates the double-quote character and leaves the single-quote untranslated. If ENT_QUOTES is set, both single and double quotes are translated and if ENT_NOQUOTES is set neither single nor double quotes are translated.
The translations performed are:
'&' (ampersand) becomes '&'
'"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
''' (single quote) becomes ''' only when ENT_QUOTES is set.
'<' (less than) becomes '<'
'>' (greater than) becomes '>'
Note that this function does not translate anything beyond what is listed above. For full entity translation, see htmlentities(). Support for the optional second argument was added in PHP 3.0.17 and PHP 4.0.3.
The third argument defines character set used in conversion. The default character set is ISO-8859-1. Support for this third argument was added in PHP 4.1.0.
See also htmlentities() and nl2br().
Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.
Notatka: implode() can, for historical reasons, accept its parameters in either order. For consistency with explode(), however, it may be less confusing to use the documented order of arguments.
join() is an alias to implode(), and is identical in every way.
This function returns the Levenshtein-Distance between the two argument strings or -1, if one of the argument strings is longer than the limit of 255 characters (255 should be more than enough for name or dictionary comparison, and nobody serious would be doing genetic analysis with PHP).
The Levenshtein distance is defined as the minimal number of characters you have to replace, insert or delete to transform str1 into str2. The complexity of the algorithm is O(m*n), where n and m are the length of str1 and str2 (rather good when compared to similar_text(), which is O(max(n,m)**3), but still expensive).
In its simplest form the function will take only the two strings as parameter and will calculate just the number of insert, replace and delete operations needed to transform str1 into str2.
A second variant will take three additional parameters that define the cost of insert, replace and delete operations. This is more general and adaptive than variant one, but not as efficient.
The third variant (which is not implemented yet) will be the most general and adaptive, but also the slowest alternative. It will call a user-supplied function that will determine the cost for every possible operation.
The user-supplied function will be called with the following arguments:
operation to apply: 'I', 'R' or 'D'
actual character in string 1
actual character in string 2
position in string 1
position in string 2
remaining characters in string 1
remaining characters in string 2
The user-supplied function approach offers the possibility to take into account the relevance of and/or difference between certain symbols (characters) or even the context those symbols appear in to determine the cost of insert, replace and delete operations, but at the cost of losing all optimizations done regarding cpu register utilization and cache misses that have been worked into the other two variants.
See also soundex(), similar_text(), and metaphone().
Returns an associative array containing localized numeric and monetary formatting information.
localeconv() returns data based upon the current locale as set by setlocale(). The associative array that is returned contains the following fields:
Array element | Description | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
decimal_point | Decimal point character | ||||||||||
thousands_sep | Thousands separator | ||||||||||
grouping | Array containing numeric groupings | ||||||||||
int_curr_symbol | International currency symbol (i.e. USD) | ||||||||||
currency_symbol | Local currency symbol (i.e. $) | ||||||||||
mon_decimal_point | Monetary decimal point character | ||||||||||
mon_thousands_sep | Monetary thousands separator | ||||||||||
mon_grouping | Array containing monetary groupings | ||||||||||
positive_sign | Sign for positive values | ||||||||||
negative_sign | Sign for negative values | ||||||||||
int_frac_digits | International fractional digits | ||||||||||
frac_digits | Local fractional digits | ||||||||||
p_cs_precedes | TRUE if currency_symbol precedes a positive value, FALSE if it succeeds one | ||||||||||
p_sep_by_space | TRUE if a space separates currency_symbol from a positive value, FALSE otherwise | ||||||||||
n_cs_precedes | TRUE if currency_symbol precedes a negative value, FALSE if it succeeds one | ||||||||||
n_sep_by_space | TRUE if a space separates currency_symbol from a negative value, FALSE otherwise | ||||||||||
p_sign_posn |
| ||||||||||
n_sign_posn |
|
The grouping fields contain arrays that define the way numbers should be grouped. For example, the grouping field for the en_US locale, would contain a 2 item array with the values 3 and 3. The higher the index in the array, the farther left the grouping is. If an array element is equal to CHAR_MAX, no further grouping is done. If an array element is equal to 0, the previous element should be used.
Przykład 1. localeconv() example
|
The constant CHAR_MAX is also defined for the use mentioned above.
See also: setlocale().
Notatka: The second parameter was added in PHP 4.1.0
This function returns a string with whitespace stripped from the beginning of str. Without the second parameter, ltrim() will strip these characters:
" " (ASCII 32 (0x20)), an ordinary space.
"\t" (ASCII 9 (0x09)), a tab.
"\n" (ASCII 10 (0x0A)), a new line (line feed).
"\r" (ASCII 13 (0x0D)), a carriage return.
"\0" (ASCII 0 (0x00)), the NUL-byte.
"\x0B" (ASCII 11 (0x0B)), a vertical tab.
You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.
Przykład 1. Usage example of ltrim()
|
Calculates the MD5 hash of str using the RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. The hash is a 32-character hexadecimal number.
See also: crc32() and md5_file()
Calculates the MD5 hash of the specified filename using the RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash.
This function has the same purpose of the command line utility md5sum.
Calculates the metaphone key of str.
Similar to soundex() metaphone creates the same key for similar sounding words. It's more accurate than soundex() as it knows the basic rules of English pronunciation. The metaphone generated keys are of variable length.
Metaphone was developed by Lawrence Philips <lphilips@verity.com>. It is described in ["Practical Algorithms for Programmers", Binstock & Rex, Addison Wesley, 1995].
Returns string with '<br />' inserted before all newlines.
Notatka: Starting with PHP 4.0.5, nl2br() is now XHTML compliant. All versions before 4.0.5 will return string with '<br>' inserted before newlines instead of '<br />'.
See also htmlspecialchars(), htmlentities() and wordwrap().
Returns the ASCII value of the first character of string. This function complements chr().
You can find an ASCII-table over here: http://www.mindspring.com/~jc1/serial/Resources/ASCII.html.
See also chr().
Parses str as if it were the query string passed via an URL and sets variables in the current scope. If the second parameter arr is present, variables are stored in this variable as an array elements instead.
Notatka: Support for the optional second parameter was added in PHP 4.0.3.
See also set_magic_quotes_runtime() and urldecode().
Outputs arg. Zwraca TRUE w przypadku sukcesu, FALSE w przypadku porażki.
print() is not actually a function (it is a language construct) so you are not required to use parentheses with it.
Przykład 1. print() examples
|
Produces output according to format, which is described in the documentation for sprintf().
See also: print(), sprintf(), sscanf(), fscanf(), and flush().
(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)
quoted_printable_decode -- Convert a quoted-printable string to an 8 bit stringThis function returns an 8-bit binary string corresponding to the decoded quoted printable string. This function is similar to imap_qprint(), except this one does not require the IMAP module to work.
Returns a version of str with a backslash character (\) before every character that is among these:
. \\ + * ? [ ^ ] ( $ ) |
See also addslashes(), htmlentities(), htmlspecialchars(), nl2br(), and stripslashes().
This function performs the ROT13 encoding on the str argument and returns the resulting string. The ROT13 encoding simply shifts every letter by 13 places in the alphabet while leaving non-alpha characters untouched. Encoding and decoding are done by the same function, passing an encoded string as argument will return the original version.
Notatka: The second parameter was added in PHP 4.1.0
This function returns a string with whitespace stripped from the end of str. Without the second parameter, rtrim() will strip these characters:
" " (ASCII 32 (0x20)), an ordinary space.
"\t" (ASCII 9 (0x09)), a tab.
"\n" (ASCII 10 (0x0A)), a new line (line feed).
"\r" (ASCII 13 (0x0D)), a carriage return.
"\0" (ASCII 0 (0x00)), the NUL-byte.
"\x0B" (ASCII 11 (0x0B)), a vertical tab.
You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.
Przykład 1. Usage example of rtrim()
|
The function sscanf() is the input analog of printf(). sscanf() reads from the string str and interprets it according to the specified format. If only two parameters were passed to this function, the values parsed will be returned as an array.
Category is a named constant (or string) specifying the category of the functions affected by the locale setting:
LC_ALL for all of the below
LC_COLLATE for string comparison, see strcoll()
LC_CTYPE for character classification and conversion, for example strtoupper()
LC_MONETARY for localeconv()
LC_NUMERIC for decimal separator (See also: localeconv())
LC_TIME for date and time formatting with strftime()
If locale is the empty string "", the locale names will be set from the values of environment variables with the same names as the above categories, or from "LANG".
If locale is zero or "0", the locale setting is not affected, only the current setting is returned.
Setlocale returns the new current locale, or FALSE if the locale functionality is not implemented in the platform, the specified locale does not exist or the category name is invalid. An invalid category name also causes a warning message.
This calculates the similarity between two strings as described in Oliver [1993]. Note that this implementation does not use a stack as in Oliver's pseudo code, but recursive calls which may or may not speed up the whole process. Note also that the complexity of this algorithm is O(N**3) where N is the length of the longest string.
By passing a reference as third argument, similar_text() will calculate the similarity in percent for you. It returns the number of matching chars in both strings.
Calculates the soundex key of str.
Soundex keys have the property that words pronounced similarly produce the same soundex key, and can thus be used to simplify searches in databases where you know the pronunciation but not the spelling. This soundex function returns a string 4 characters long, starting with a letter.
This particular soundex function is one described by Donald Knuth in "The Art Of Computer Programming, vol. 3: Sorting And Searching", Addison-Wesley (1973), pp. 391-392.
Przykład 1. Soundex Examples
|
See also levenshtein(), metaphone(), and similar_text().
Returns a string produced according to the formatting string format.
The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result, and conversion specifications, each of which results in fetching its own parameter. This applies to both sprintf() and printf().
Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order:
An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote ('). See the examples below.
An optional alignment specifier that says if the result should be left-justified or right-justified. The default is right-justified; a - character here will make it left-justified.
An optional number, a width specifier that says how many characters (minimum) this conversion should result in.
An optional precision specifier that says how many decimal digits should be displayed for floating-point numbers. This option has no effect for other types than float. (Another function useful for formatting numbers is number_format().)
A type specifier that says what type the argument data should be treated as. Possible types:
% - a literal percent character. No argument is required. |
b - the argument is treated as an integer, and presented as a binary number. |
c - the argument is treated as an integer, and presented as the character with that ASCII value. |
d - the argument is treated as an integer, and presented as a (signed) decimal number. |
u - the argument is treated as an integer, and presented as an unsigned decimal number. |
f - the argument is treated as a float, and presented as a floating-point number. |
o - the argument is treated as an integer, and presented as an octal number. |
s - the argument is treated as and presented as a string. |
x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters). |
X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters). |
As of PHP version 4.0.6 the format string supports argument numbering/swapping. Here is an example:
See also: printf(), sscanf(), fscanf(), and number_format().
(PHP 4 >= 4.0.2)
strncasecmp -- Binary safe case-insensitive string comparison of the first n charactersThis function is similar to strcasecmp(), with the difference that you can specify the (upper limit of the) number of characters (len) from each string to be used in the comparison. If any of the strings is shorter than len, then the length of that string will be used for the comparison.
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
See also ereg(), strcasecmp(), strcmp(), substr(), stristr(), and strstr().
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
See also ereg(), strcmp(), substr(), stristr(), strncasecmp(), and strstr().
This function is an alias for strstr(), and is identical in every way.
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
Note that this comparison is case sensitive.
See also ereg(), strcasecmp(), substr(), stristr(), strncasecmp(), strncmp(), and strstr().
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. strcoll() uses the current locale for doing the comparisons. If the current locale is C or POSIX, this function is equivalent to strcmp().
Note that this comparison is case sensitive, and unlike strcmp() this function is not binary safe.
See also ereg(), strcmp(), strcasecmp(), substr(), stristr(), strncasecmp(), strncmp(), strstr(), and setlocale().
Returns the length of the initial segment of str1 which does not contain any of the characters in str2.
See also strspn().
This function tries to return a string with all HTML and PHP tags stripped from a given str. It errors on the side of caution in case of incomplete or bogus tags. It uses the same tag stripping state machine as the fgetss() function.
You can use the optional second parameter to specify tags which should not be stripped.
Notatka: allowable_tags was added in PHP 3.0.13 and PHP 4.0b3.
Ostrze¿enie |
This function does not modify any attributes on the tags that you allow using allowable_tags, including the style and onmouseover attributes that a mischievous user may abuse when posting text that will be shown to other users. |
Returns a string with backslashes stripped off. Recognizes C-like \n, \r ..., octal and hexadecimal representation.
See also addcslashes().
Returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes are made into a single backslash.
See also addslashes().
Returns all of haystack from the first occurrence of needle to the end. needle and haystack are examined in a case-insensitive manner.
If needle is not found, returns FALSE.
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
This function implements a comparison algorithm that orders alphanumeric strings in the way a human being would, this is described as a "natural ordering". An example of the difference between this algorithm and the regular computer string sorting algorithms (used in strcmp()) can be seen below:
$arr1 = $arr2 = array("img12.png","img10.png","img2.png","img1.png"); echo "Standard string comparison\n"; usort($arr1,"strcmp"); print_r($arr1); echo "\nNatural order string comparison\n"; usort($arr2,"strnatcmp"); print_r($arr2); |
Standard string comparison Array ( [0] => img1.png [1] => img10.png [2] => img12.png [3] => img2.png ) Natural order string comparison Array ( [0] => img1.png [1] => img2.png [2] => img10.png [3] => img12.png ) |
Similar to other string comparison functions, this one returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
Note that this comparison is case sensitive.
See also ereg(), strcasecmp(), substr(), stristr(), strcmp(), strncmp(), strncasecmp(), strnatcasecmp(), strstr(), natsort() and natcasesort().
(PHP 4 >= 4.0.0)
strnatcasecmp -- Case insensitive string comparisons using a "natural order" algorithmThis function implements a comparison algorithm that orders alphanumeric strings in the way a human being would. The behaviour of this function is similar to strnatcmp(), except that the comparison is not case sensitive. For more infomation see: Martin Pool's Natural Order String Comparison page.
Similar to other string comparison functions, this one returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
See also ereg(), strcasecmp(), substr(), stristr(), strcmp(), strncmp(), strncasecmp(), strnatcmp(), and strstr().
This function is similar to strcmp(), with the difference that you can specify the (upper limit of the) number of characters (len) from each string to be used in the comparison. If any of the strings is shorter than len, then the length of that string will be used for the comparison.
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
Note that this comparison is case sensitive.
See also ereg(), strncasecmp(), strcasecmp(), substr(), stristr(), strcmp(), and strstr().
This functions returns the input string padded on the left, the right, or both sides to the specified padding length. If the optional argument pad_string is not supplied, the input is padded with spaces, otherwise it is padded with characters from pad_string up to the limit.
Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not specified it is assumed to be STR_PAD_RIGHT.
If the value of pad_length is negative or less than the length of the input string, no padding takes place.
Returns the numeric position of the first occurrence of needle in the haystack string. Unlike the strrpos(), this function can take a full string as the needle parameter and the entire string will be used.
If needle is not found, returns FALSE.
Notatka: It is easy to mistake the return values for "character found at position 0" and "character not found". Here's how to detect the difference:
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
The optional offset parameter allows you to specify which character in haystack to start searching. The position returned is still relative to the the beginning of haystack.
See also strrpos(), strrchr(), substr(), stristr(), and strstr().
This function returns the portion of haystack which starts at the last occurrence of needle and goes until the end of haystack.
Returns FALSE if needle is not found.
If needle contains more than one character, the first is used.
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
Returns input_str repeated multiplier times. multiplier has to be greater than 0.
This will output "-=-=-=-=-=-=-=-=-=-=".
See also substr_count().
Returns the numeric position of the last occurrence of needle in the haystack string. Note that the needle in this case can only be a single character. If a string is passed as the needle, then only the first character of that string will be used.
If needle is not found, returns FALSE.
Notatka: It is easy to mistake the return values for "character found at position 0" and "character not found". Here's how to detect the difference:
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
See also strpos(), strrchr(), substr(), stristr(), and strstr().
Returns the length of the initial segment of str1 which consists entirely of characters in str2.
The line of code:
will assign 2 to $var, because the string "42" will be the longest segment containing characters from "1234567890".See also strcspn().
Returns part of haystack string from the first occurrence of needle to the end of haystack.
If needle is not found, returns FALSE.
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
Notatka: This function is case-sensitive. For case-insensitive searches, use stristr().
See also ereg(), preg_match(), strchr(), stristr(), strpos(), strrchr(), and substr().
strtok() splits a string (arg1) into smaller strings (tokens), with each token being delimited by any character from arg2. That is, if you have a string like "This is an example string" you could tokenize this string into its individual words by using the space character as the token.
Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use, as it keeps track of where it is in the current string. To start over, or to tokenize a new string you simply call strtok with the string argument again to initialize it. Note that you may put multiple tokens in the token parameter. The string will be tokenized when any one of the characters in the argument are found.
The behavior when an empty part was found changed with PHP 4.1.0. The old behavior returned an empty string, while the new, correct, behavior simply skips the part of the string:
Also be careful that your tokens may be equal to "0". This evaluates to FALSE in conditional expressions.
Returns string with all alphabetic characters converted to lowercase.
Note that 'alphabetic' is determined by the current locale. This means that in i.e. the default "C" locale, characters such as umlaut-A (Ä) will not be converted.
See also strtoupper(), ucfirst(), and ucwords().
Returns string with all alphabetic characters converted to uppercase.
Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.
See also strtolower(), ucfirst(), and ucwords().
(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)
str_replace -- Replace all occurrences of the search string with the replacement stringThis function returns a string or an array with all occurences of search in subject replaced with the given replace value. If you don't need fancy replacing rules, you should always use this function instead of ereg_replace() or preg_replace().
In PHP 4.0.5 and later, every parameter to str_replace() can be an array.
If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.
If search and replace are arrays, then str_replace() takes a value from each array and uses them to do search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string; then this replacement string is used for every value of search. The converse would not make sense, though.
This function is binary safe.
Notatka: str_replace() was added in PHP 3.0.6, but was buggy up until PHP 3.0.8.
See also ereg_replace(), preg_replace(), and strtr().
This function returns a copy of str, translating all occurrences of each character in from to the corresponding character in to and returning the result.
If from and to are different lengths, the extra characters in the longer of the two are ignored.
strtr() can be called with only two arguments. If called with two arguments it behaves in a new way: from then has to be an array that contains string -> string pairs that will be replaced in the source string. strtr() will always look for the longest possible match first and will *NOT* try to replace stuff that it has already worked on.
Examples:
$trans = array("hello" => "hi", "hi" => "hello"); echo strtr("hi all, I said hello", $trans) . "\n"; |
Notatka: This optional to and from parameters were added in PHP 4.0.0
See also ereg_replace().
Substr returns the portion of string specified by the start and length parameters.
If start is positive, the returned string will start at the start'th position in string, counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth.
If start is negative, the returned string will start at the start'th character from the end of string.
If length is given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of string. If string is less than start characters long, FALSE will be returned.
If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative). If start denotes a position beyond this truncation, an empty string will be returned.
substr_count() returns the number of times the needle substring occurs in the haystack string.
substr_replace() replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement. The result is returned.
If start is positive, the replacing will begin at the start'th offset into string.
If start is negative, the replacing will begin at the start'th character from the end of string.
If length is given and is positive, it represents the length of the portion of string which is to be replaced. If it is negative, it represents the number of characters from the end of string at which to stop replacing. If it is not given, then it will default to strlen( string ); i.e. end the replacing at the end of string.
Przykład 1. substr_replace() example
|
See also str_replace() and substr().
Notatka: The optional charlist parameter was added in PHP 4.1.0
This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:
" " (ASCII 32 (0x20)), an ordinary space.
"\t" (ASCII 9 (0x09)), a tab.
"\n" (ASCII 10 (0x0A)), a new line (line feed).
"\r" (ASCII 13 (0x0D)), a carriage return.
"\0" (ASCII 0 (0x00)), the NUL-byte.
"\x0B" (ASCII 11 (0x0B)), a vertical tab.
You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.
Przykład 1. Usage example of trim()
|
Returns a string with the first character of str capitalized, if that character is alphabetic.
Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.
See also strtolower(), strtoupper(), and ucwords().
Returns a string with the first character of each word in str capitalized, if that character is alphabetic.
Notatka: The definition of a word is any string of characters that is immediately after a whitespace (These are: space, form-feed, newline, carriage return, horizontal tab, and vertical tab).
See also strtoupper(), strtolower() and ucfirst().
Display array values as a formatted string according to format (which is described in the documentation for sprintf()).
Operates as printf() but accepts an array of arguments, rather than a variable number of arguments.
See also: printf(), sprintf(), vsprintf()
Return array values as a formatted string according to format (which is described in the documentation for sprintf()).
Operates as sprintf() but accepts an array of arguments, rather than a variable number of arguments.
(PHP 4 >= 4.0.2)
wordwrap -- Wraps a string to a given number of characters using a string break character.Returns a string with str wrapped at the column number specified by the (optional) width parameter. The line is broken using the (optional) break parameter.
wordwrap() will automatically wrap at column 75 and break using '\n' (newline) if width or break are not given.
If the cut is set to 1, the string is always wrapped at the specified width. So if you have a word that is larger than the given width, it is broken apart. (See second example).
Notatka: The optional cut parameter was added in PHP 4.0.3
This example would display:
This example would display:
See also nl2br().
Returns: The number of affected rows by the last query.
sybase_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or DELETE query on the server associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.
This command is not effective for SELECT statements, only on statements which modify records. To retrieve the number of rows returned from a SELECT, use sybase_num_rows().
Notatka: This function is only available using the CT library interface to Sybase, and not the DB library.
Returns: TRUE on success, FALSE on error
sybase_close() closes the link to a Sybase database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.
Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
sybase_close() will not close persistent links generated by sybase_pconnect().
See also: sybase_connect(), sybase_pconnect().
Returns: A positive Sybase link identifier on success, or FALSE on error.
sybase_connect() establishes a connection to a Sybase server. The servername argument has to be a valid servername that is defined in the 'interfaces' file.
In case a second call is made to sybase_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.
The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling sybase_close().
See also sybase_pconnect(), sybase_close().
Returns: TRUE on success, FALSE on failure
sybase_data_seek() moves the internal row pointer of the Sybase result associated with the specified result identifier to pointer to the specifyed row number. The next call to sybase_fetch_row() would return that row.
See also: sybase_data_seek().
Returns: An array that corresponds to the fetched row, or FALSE if there are no more rows.
sybase_fetch_array() is an extended version of sybase_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.
An important thing to note is that using sybase_fetch_array() is NOT significantly slower than using sybase_fetch_row(), while it provides a significant added value.
For further details, also see sybase_fetch_row().
Returns an object containing field information.
sybase_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retreived by sybase_fetch_field() is retreived.
The properties of the object are:
name - column name. if the column is a result of a function, this property is set to computed#N, where #N is a serial number.
column_source - the table from which the column was taken
max_length - maximum length of the column
numeric - 1 if the column is numeric
type - datatype of the column
See also sybase_field_seek()
Returns: An object with properties that correspond to the fetched row, or FALSE if there are no more rows.
sybase_fetch_object() is similar to sybase_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).
Speed-wise, the function is identical to sybase_fetch_array(), and almost as quick as sybase_fetch_row() (the difference is insignificant).
See also: sybase_fetch_array() and sybase_fetch_row().
Returns: An array that corresponds to the fetched row, or FALSE if there are no more rows.
sybase_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
Subsequent call to sybase_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.
See also: sybase_fetch_array(), sybase_fetch_object(), sybase_data_seek(), sybase_fetch_lengths(), and sybase_result().
Seeks to the specified field offset. If the next call to sybase_fetch_field() won't include a field offset, this field would be returned.
See also: sybase_fetch_field().
sybase_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script ends. You may call sybase_free_result() with the result identifier as an argument and the associated result memory will be freed.
sybase_get_last_message() returns the last message reported by the server.
sybase_min_client_severity() sets the minimum client severity level.
Notatka: This function is only available using the CT library interface to Sybase, and not the DB library.
See also: sybase_min_server_severity().
sybase_min_error_severity() sets the minimum error severity level.
See also: sybase_min_message_severity().
sybase_min_message_severity() sets the minimum message severity level.
See also: sybase_min_error_severity().
sybase_min_server_severity() sets the minimum server severity level.
Notatka: This function is only available using the CT library interface to Sybase, and not the DB library.
See also: sybase_min_client_severity().
sybase_num_fields() returns the number of fields in a result set.
See also: sybase_db_query(), sybase_query(), sybase_fetch_field(), sybase_num_rows().
sybase_num_rows() returns the number of rows in a result set.
See also: sybase_db_query(), sybase_query() and, sybase_fetch_row().
Returns: A positive Sybase persistent link identifier on success, or FALSE on error
sybase_pconnect() acts very much like sybase_connect() with two major differences.
First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (sybase_close() will not close links established by sybase_pconnect()()).
This type of links is therefore called 'persistent'.
Returns: A positive Sybase result identifier on success, or FALSE on error.
sybase_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if sybase_connect() was called, and use it.
See also: sybase_db_query(), sybase_select_db(), and sybase_connect().
Returns: The contents of the cell at the row and offset in the specified Sybase result set.
sybase_result() returns the contents of one cell from a Sybase result set. The field argument can be the field's offset, or the field's name, or the field's table dot field's name (tablename.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 sybase_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.
Recommended high-performance alternatives: sybase_fetch_row(), sybase_fetch_array(), and sybase_fetch_object().
Returns: TRUE on success, FALSE on error
sybase_select_db() sets the current active database on the server that's associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if sybase_connect() was called, and use it.
Every subsequent call to sybase_query() will be made on the active database.
See also: sybase_connect(), sybase_pconnect(), and sybase_query()
base64_decode() dekoduje dane_zakodowane i zwraca oryginalną postać danych. Dane wynikowe mogą być binarne.
Patrz także: base64_encode(), RFC2045 sekcja 6.8.
base64_encode() zwraca dane zakodowane za pomocą algorytmu base64. Ten sposób kodowania został zaprojektowany, aby móc bezpiecznie przesyłać dane binarne, poprzez warstwy transportujące nie zaprojektowane do obsługi 8 bitowego przesyłania informacji, np. treść email'i.
Dane zakodowane tą funkcją zajmują ok 33% więcej miejsca niż dane oryginalne.
Patrz także: base64_decode(), chunk_split(), RFC2045 sekcja 6.8.
Funkcja ta zwraca w tablicy asocjacyjnej wszystkie składowe przetwarzanego URL'a. Dostępne są następujące klucze tablicy: "scheme" (protokół), "host", "port", "user" (użytkownik), "pass" (hasło), "path" (ścieżka), "query" (zapytanie) i "fragment" (treść kotwicy, po #).
Patrz także pathinfo().
Zwraca łańcuch w którym sekwencje dwóch cyfr szesnastkowych poprzedzone znakiem procenta (%), zastąpione są przez ich odpowiednik znakowy. Na przykład, łańcuch
foo%20bar%40baz |
foo bar@baz |
Notatka: rawurldecode() nie zamienia znaków plusa ('+') na spacje. Robi to urldecode().
Patrz także rawurlencode(), urldecode(), urlencode().
Zwraca łańcuch w którym wszystkie nie alfanumeryczne znaki z wyjątkiem
-_. |
Lub, jeśli podajesz informację w części PATH_INFO (ścieżka) URL'a:
Patrz także rawurldecode(), urldecode(), urlencode().
Odkodowuje każdy %## kod z danego łańcucha. Zwracany jest zdekodowany łańcuch.
Patrz także urlencode(), rawurlencode(), rawurldecode().
Zwraca łańcuch w którym wszystkie nie alfanumeryczne znaki z wyjątkiem
-_. |
Notka: Uważaj na zmienne, które mogą zawierać HTML'owe encje. Rzeczy jak &, © i £ są przetwarzane przez przeglądarkę i ich aktualna postać jest używana dalej zamiast porządanej nazwy zmiennej. To jest oczywisty problem, o którym W3C informuje ludzi od lat. Referencje są tutaj: http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.2 PHP obsługuje zmianę separatora argumentów na zalecany przez W3C średnik poprzez dyrektywę arg_separator .ini. Niestety większość przeglądarek nie wysyła danych z formularza w formacie używającym średnik jako separator. Bardziej przenośnym rozwiązaniem jest użycie & jako separatora zamiast &. Nie musisz zmieniać PHP'owego arg_separator aby to uzyskać. Zostaw separator jako &, ale koduj swoje URL'e używając htmlentities()(urlencode($data)).
Patrz także urldecode(), htmlentities(), rawurldecode(), rawurlencode().
For information on how variables behave, see the Variables entry in the Language Reference section of the manual.
This function is an alias of floatval().
Notatka: This alias is a left-over from a function-renaming. In older versions of PHP you'll need to use this alias of the floatval() function, because floatval() wasn't yet available in that version.
Notatka: empty() is a language construct.
This is the opposite of (boolean) var, except that no warning is generated when the variable is not set. See converting to boolean for more information.
$var = 0; if (empty($var)) { // evaluates true echo '$var is either 0 or not set at all'; } if (!isset($var)) { // evaluates false echo '$var is not set at all'; } |
Note that this is meaningless when used on anything which isn't a variable; i.e. empty (addslashes ($name)) has no meaning since it would be checking whether something which isn't a variable is a variable with a FALSE value.
Returns the float value of var.
Var may be any scalar type. You cannot use floatval() on arrays or objects.
$var = '122.34343The'; $float_value_of_var = floatval ($var); print $float_value_of_var; // prints 122.34343 |
See also intval(), strval(), settype() and Type juggling.
Returns the type of the PHP variable var.
Ostrze¿enie |
Never use gettype() to test for a certain type, since the returned string may be subject to change in a future version. In addition, it is slow too, as it involves string comparision . Instead, use the is_* functions. |
Possibles values for the returned string are:
"boolean" (since PHP 4)
"integer"
"double" (for historical reasons "double" is returned in case of a float, and not simply "float")
"string"
"array"
"object"
"resource" (since PHP 4)
"NULL" (since PHP 4)
"user function" (PHP 3 only, deprecated)
"unknown type"
For PHP 4, you should use function_exists() and method_exists() to replace the prior usage of gettype() on a function.
See also settype(), is_array(), is_bool(), is_float(), is_integer(), is_null(), is_numeric(), is_object(), is_resource(), is_scalar() and is_string().
This function returns an multidimensional array containing a list of all defined variables, be them environment, server or user-defined variables.
$b = array(1,1,2,3,5,8); $arr = get_defined_vars(); // print $b print_r($arr["b"]); // print path to the PHP interpreter (if used as a CGI) // e.g. /usr/local/bin/php echo $arr["_"]; // print the command-line paramaters if any print_r($arr["argv"]); // print all the server vars print_r($arr["HTTP_SERVER_VARS"]); // print all the available keys for the arrays of variables print_r(array_keys(get_defined_vars())); |
See also get_defined_functions().
This function returns a string representing the type of the resource passed to it. If the paramater is not a valid resource, it generates an error.
Imports GET/POST/Cookie variables into the global scope. It is useful if you disabled register_globals, but would like to see some variables in the global scope.
Using the types parameter, you can specify, which request variables to import. You can use 'G', 'P' and 'C' characters respectively for GET, POST and Cookie. These characters are not case sensitive, so you can also use any combination of 'g', 'p' and 'c'. POST includes the uploaded file informations. Note, that the order of the letters matters, as using "gp", the POST variables will overwrite GET variables with the same name. Any other other letters then GPC are discarded.
Notatka: Although the prefix argument is optional, you will get a notice level error, if you specify no prefix, or specify an empty string as a prefix. This is a possible security hazard. Notice level errors are not displayed using the default error reporting level.
// This will import GET and POST vars // with an "rvar_" prefix import_request_variables("gP", "rvar_"); |
See also register_globals and track_vars.
Returns the integer value of var, using the specified base for the conversion (the default is base 10).
var may be any scalar type. You cannot use intval() on arrays or objects.
Notatka: The base argument for intval() has no effect unless the var argument is a string.
See also floatval(), strval(), settype() and Type juggling.
Returns TRUE if var is an array, FALSE otherwise.
See also is_float(), is_int(), is_integer(), is_string(), and is_object().
Returns TRUE if the var parameter is a boolean.
See also is_array(), is_float(), is_int(), is_integer(), is_string(), and is_object().
Returns TRUE if var is a float, FALSE otherwise.
Notatka: To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().
See also is_bool(), is_int(), is_integer(), is_numeric(), is_string(), is_array(), and is_object(),
Returns TRUE if var is an integer FALSE otherwise.
Notatka: To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().
See also is_bool(), is_float(), is_integer(), is_numeric(), is_string(), is_array(), and is_object().
Returns TRUE if var is null, FALSE otherwise.
See also is_bool(), is_numeric(), is_float(), is_int(), is_string(), is_object(), is_array(), and
Returns TRUE if var is a number or a numeric string, FALSE otherwise.
See also is_bool(), is_float(), is_int(), is_string(), is_object(), is_array(), and is_integer().
Returns TRUE if var is an object, FALSE otherwise.
See also is_bool(), is_int(), is_integer(), is_float(), is_string(), and is_array().
is_resource() returns TRUE if the variable given by the var parameter is a resource, otherwise it returns FALSE.
See the documentation on the resource-type for more information.
is_scalar() returns TRUE if the variable given by the var parameter is a scalar, otherwise it returns FALSE.
Scalar variables are those containing an integer, float, string or boolean. Types array, object and resource or not scalar.
function show_var($var) { if (is_scalar($var)) { echo $var; } else { var_dump($var); } } $pi = 3.1416; $proteins = array("hemoglobin", "cytochrome c oxidase", "ferredoxin"); show_var($pi); // prints: 3.1416 show_var($proteins) // prints: // array(3) { // [0]=> // string(10) "hemoglobin" // [1]=> // string(20) "cytochrome c oxidase" // [2]=> // string(10) "ferredoxin" // } |
Notatka: is_scalar() does not consider resource type values to be scalar as resources are abstract datatypes which are currently based on integers. This implementation detail should not be relied upon, as it may change.
See also is_bool(), is_numeric(), is_float(), is_int(), is_real(), is_string(), is_object(), is_array(), and is_integer().
Returns TRUE if var is a string, FALSE otherwise.
See also is_bool(), is_int(), is_integer(), is_float(), is_real(), is_object(), and is_array().
Returns TRUE if var exists; FALSE otherwise.
If a variable has been unset with unset(), it will no longer be isset(). isset() will return FALSE if testing a variable that has been set to NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP NULL constant.
print_r() displays information about a variable in a way that's readable by humans. If given a string, integer or float, the value itself will be printed. If given an array, values will be presented in a format that shows keys and elements. Similar notation is used for objects.
Remember that print_r() will move the array pointer to the end. Use reset() to bring it back to beginning.
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.
<pre> <?php $a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x','y','z')); print_r ($a); ?> </pre> |
Which will output:
<pre> Array ( [a] => apple [b] => banana [c] => Array ( [0] => x [1] => y [2] => z ) ) </pre> |
Notatka: Prior to PHP 4.0.4, print_r() will continue forever if given an array or object that contains a direct or indirect reference to itself. An example is print_r($GLOBALS) because $GLOBALS is itself a global variable that contains a reference to itself.
See also ob_start(), var_dump(), and var_export().
serialize() returns a string containing a byte-stream representation of value that can be stored anywhere.
This is useful for storing or passing PHP values around without losing their type and structure.
To make the serialized string into a PHP value again, use unserialize(). serialize() handles all types, except the resource-type. You can even serialize() arrays that contain references to itself. References inside the array/object you are serialize()ing will also be stored.
Notatka: In PHP 3, object properties will be serialized, but methods are lost. PHP 4 removes that limitation and restores both properties and methods. Please see the Serializing Objects section of Classes and Objects for more information.
Przykład 1. serialize() example
|
See Also: unserialize().
Set the type of variable var to type.
Possibles values of type are:
"boolean" (or, since PHP 4.2.0, "bool")
"integer" (or, since PHP 4.2.0, "int")
"float" (only possible since PHP 4.2.0, for older versions use the deprecated variant "double")
"string"
"array"
"object"
"null" (since PHP 4.0.8)
Returns TRUE if successful; otherwise returns FALSE.
See also gettype(), type-casting and type-juggling.
Returns the string value of var. See the documentation on string for more information on converting to string.
var may be any scalar type. You cannot use strval() on arrays or objects.
See also floatval(), intval(), settype() and Type juggling.
unserialize() takes a single serialized variable (see serialize()) and converts it back into a PHP value. The converted value is returned, and can be an integer, float, string, array or object. If an object was serialized, its methods are not preserved in the returned value.
Notatka: It's possible to set a callback-function which will be called, if an undefined class should be instanciated during unserializing. (to prevent getting an incomplete object "__PHP_Incomplete_Class".) Use your php.ini, ini_set() or .htaccess-file to define 'unserialize_callback_func'. Everytime an undefined class should be instanciated, it'll be called. To disable this feature just empty this global variable.
Przykład 1. unserialize_callback_func example
|
Notatka: In PHP 3, methods are not preserved when unserializing a serialized object. PHP 4 removes that limitation and restores both properties and methods. Please see the Serializing Objects section of Classes and Objects or more information.
Przykład 2. unserialize() example
|
See Also: serialize().
unset() destroys the specified variables. Note that in PHP 3, unset() will always return TRUE (actually, the integer value 1). In PHP 4, however, unset() is no longer a true function: it is now a statement. As such no value is returned, and attempting to take the value of unset() results in a parse error.
The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy.
If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.
The above example would output:If a variable that is PASSED BY REFERENCE is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.
function foo(&$bar) { unset($bar); $bar = "blah"; } $bar = 'something'; echo "$bar\n"; foo($bar); echo "$bar\n"; |
If a static variable is unset() inside of a function, unset() destroyes the variable and all its references.
The above example would output:If you would like to unset() a global variable inside of a function, you can use the $GLOBALS array to do so:
Notatka: unset() is a language construct.
This function returns structured information about one or more expressions that includes its type and value. Arrays are explored recursively with values indented to show structure.
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.
Compare var_dump() to print_r().
This function returns structured information about the variable that is passed to this function. It is similar to var_dump() with the exception that the returned representation is valid PHP code.
You can also return the variable representation by using TRUE as second parameter to this function.
Compare var_export() to var_dump().
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. |
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. |
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. |
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. |
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. |
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. |
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. |
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. |
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. |
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. |
(PHP 4 >= 4.0.5)
vpopmail_auth_user -- Attempt to validate a username/domain/password. Returns true/falseOstrze¿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. |
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. |
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. |
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. |
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. |
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. |
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. |
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. |
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. |
(unknown)
w32api_invoke_function -- ....) Invokes function funcname with the arguments passed after the function nameOstrze¿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. |
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. |
(PHP 4 CVS only)
w32api_init_dtype -- ; Creates an instance to the data type typename and fills it with the values val1, val2, the functionOstrze¿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. |
These functions are intended for work with WDDX.
In order to use WDDX, you will need to install the expat library (which comes with apache 1.3.7 or higher) and recompile PHP with --with-xml and --enable-wddx.
Notatka: If you want to serialize non-ASCII characters you have to set the appropriate locale before doing so (see setlocale()).
All the functions that serialize variables use the first element of an array to determine whether the array is to be serialized into an array or structure. If the first element has string key, then it is serialized into a structure, otherwise, into an array.
This example will produce:
<wddxPacket version='1.0'><header comment='PHP packet'/><data> <string>PHP to WDDX packet example</string></data></wddxPacket> |
Przykład 2. Using incremental packets
|
This example will produce:
wddx_serialize_value() is used to create a WDDX packet from a single given value. It takes the value contained in var, and an optional comment string that appears in the packet header, and returns the WDDX packet.
wddx_serialize_vars() is used to create a WDDX packet with a structure that contains the serialized representation of the passed variables.
wddx_serialize_vars() takes a variable number of arguments, each of which can be either a string naming a variable or an array containing strings naming the variables or another array, etc.
The above example will produce:
<wddxPacket version='1.0'><header/><data><struct><var name='a'><number>1</number></var> <var name='b'><number>5.5</number></var><var name='c'><array length='3'> <string>blue</string><string>orange</string><string>violet</string></array></var> <var name='d'><string>colors</string></var></struct></data></wddxPacket> |
(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)
wddx_packet_start -- Starts a new WDDX packet with structure inside itUse wddx_packet_start() to start a new WDDX packet for incremental addition of variables. It takes an optional comment string and returns a packet ID for use in later functions. It automatically creates a structure definition inside the packet to contain the variables.
wddx_packet_end() ends the WDDX packet specified by the packet_id and returns the string with the packet.
(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)
wddx_add_vars -- Add variables to a WDDX packet with the specified IDwddx_add_vars() is used to serialize passed variables and add the result to the packet specified by the packet_id. The variables to be serialized are specified in exactly the same way as wddx_serialize_vars().
XML (eXtensible Markup Language) is a data format for structured document interchange on the Web. It is a standard defined by The World Wide Web consortium (W3C). Information about XML and related technologies can be found at http://www.w3.org/XML/.
This extension uses expat, which can be found at http://www.jclark.com/xml/. The Makefile that comes with expat does not build a library by default, you can use this make rule for that:
libexpat.a: $(OBJS) ar -rc $@ $(OBJS) ranlib $@ |
Note that if you are using Apache-1.3.7 or later, you already have the required expat library. Simply configure PHP using --with-xml (without any additional path) and it will automatically use the expat library built into Apache.
On UNIX, run configure with the --with-xml option. The expat library should be installed somewhere your compiler can find it. If you compile PHP as a module for Apache 1.3.9 or later, PHP will automatically use the bundled expat library from Apache. You may need to set CPPFLAGS and LDFLAGS in your environment before running configure if you have installed expat somewhere exotic.
Build PHP. Tada! That should be it.
This PHP extension implements support for James Clark's expat in PHP. This toolkit lets you parse, but not validate, XML documents. It supports three source character encodings also provided by PHP: US-ASCII, ISO-8859-1 and UTF-8. UTF-16 is not supported.
This extension lets you create XML parsers and then define handlers for different XML events. Each XML parser also has a few parameters you can adjust.
The XML event handlers defined are:
Tabela 1. Supported XML handlers
PHP function to set handler | Event description |
---|---|
xml_set_element_handler() | Element events are issued whenever the XML parser encounters start or end tags. There are separate handlers for start tags and end tags. |
xml_set_character_data_handler() | Character data is roughly all the non-markup contents of XML documents, including whitespace between tags. Note that the XML parser does not add or remove any whitespace, it is up to the application (you) to decide whether whitespace is significant. |
xml_set_processing_instruction_handler() | PHP programmers should be familiar with processing instructions (PIs) already. <?php ?> is a processing instruction, where php is called the "PI target". The handling of these are application-specific, except that all PI targets starting with "XML" are reserved. |
xml_set_default_handler() | What goes not to another handler goes to the default handler. You will get things like the XML and document type declarations in the default handler. |
xml_set_unparsed_entity_decl_handler() | This handler will be called for declaration of an unparsed (NDATA) entity. |
xml_set_notation_decl_handler() | This handler is called for declaration of a notation. |
xml_set_external_entity_ref_handler() | This handler is called when the XML parser finds a reference to an external parsed general entity. This can be a reference to a file or URL, for example. See the external entity example for a demonstration. |
The element handler functions may get their element names case-folded. Case-folding is defined by the XML standard as "a process applied to a sequence of characters, in which those identified as non-uppercase are replaced by their uppercase equivalents". In other words, when it comes to XML, case-folding simply means uppercasing.
By default, all the element names that are passed to the handler functions are case-folded. This behaviour can be queried and controlled per XML parser with the xml_parser_get_option() and xml_parser_set_option() functions, respectively.
The following constants are defined for XML error codes (as returned by xml_parse()):
XML_ERROR_NONE |
XML_ERROR_NO_MEMORY |
XML_ERROR_SYNTAX |
XML_ERROR_NO_ELEMENTS |
XML_ERROR_INVALID_TOKEN |
XML_ERROR_UNCLOSED_TOKEN |
XML_ERROR_PARTIAL_CHAR |
XML_ERROR_TAG_MISMATCH |
XML_ERROR_DUPLICATE_ATTRIBUTE |
XML_ERROR_JUNK_AFTER_DOC_ELEMENT |
XML_ERROR_PARAM_ENTITY_REF |
XML_ERROR_UNDEFINED_ENTITY |
XML_ERROR_RECURSIVE_ENTITY_REF |
XML_ERROR_ASYNC_ENTITY |
XML_ERROR_BAD_CHAR_REF |
XML_ERROR_BINARY_ENTITY_REF |
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF |
XML_ERROR_MISPLACED_XML_PI |
XML_ERROR_UNKNOWN_ENCODING |
XML_ERROR_INCORRECT_ENCODING |
XML_ERROR_UNCLOSED_CDATA_SECTION |
XML_ERROR_EXTERNAL_ENTITY_HANDLING |
PHP's XML extension supports the Unicode character set through different character encodings. There are two types of character encodings, source encoding and target encoding. PHP's internal representation of the document is always encoded with UTF-8.
Source encoding is done when an XML document is parsed. Upon creating an XML parser, a source encoding can be specified (this encoding can not be changed later in the XML parser's lifetime). The supported source encodings are ISO-8859-1, US-ASCII and UTF-8. The former two are single-byte encodings, which means that each character is represented by a single byte. UTF-8 can encode characters composed by a variable number of bits (up to 21) in one to four bytes. The default source encoding used by PHP is ISO-8859-1.
Target encoding is done when PHP passes data to XML handler functions. When an XML parser is created, the target encoding is set to the same as the source encoding, but this may be changed at any point. The target encoding will affect character data as well as tag names and processing instruction targets.
If the XML parser encounters characters outside the range that its source encoding is capable of representing, it will return an error.
If PHP encounters characters in the parsed XML document that can not be represented in the chosen target encoding, the problem characters will be "demoted". Currently, this means that such characters are replaced by a question mark.
Here are some example PHP scripts parsing XML documents.
This first example displays the stucture of the start elements in a document with indentation.
Przykład 1. Show XML Element Structure
|
Przykład 2. Map XML to HTML This example maps tags in an XML document directly to HTML tags. Elements not found in the "map array" are ignored. Of course, this example will only work with a specific XML document type.
|
This example highlights XML code. It illustrates how to use an external entity reference handler to include and parse other documents, as well as how PIs can be processed, and a way of determining "trust" for PIs containing code.
XML documents that can be used for this example are found below the example (xmltest.xml and xmltest2.xml.)
Przykład 3. External Entity Example
|
Przykład 4. xmltest.xml
|
This file is included from xmltest.xml:
Which character encoding the parser should use. The following character encodings are supported:
ISO-8859-1 (default) |
US-ASCII |
UTF-8 |
This function allows to use parser inside object. All callback functions could be set with xml_set_element_handler() etc and assumed to be methods of object.
<?php class xml { var $parser; function xml() { $this->parser = xml_parser_create(); xml_set_object($this->parser,&$this); xml_set_element_handler($this->parser,"tag_open","tag_close"); xml_set_character_data_handler($this->parser,"cdata"); } function parse($data) { xml_parse($this->parser,$data); } function tag_open($parser,$tag,$attributes) { var_dump($parser,$tag,$attributes); } function cdata($parser,$cdata) { var_dump($parser,$cdata); } function tag_close($parser,$tag) { var_dump($parser,$tag); } } // end of class xml $xml_parser = new xml(); $xml_parser->parse("<A ID=\"hallo\">PHP</A>"); ?> |
Sets the element handler functions for the XML parser parser. startElementHandler and endElementHandler are strings containing the names of functions that must exist when xml_parse() is called for parser.
The function named by startElementHandler must accept three parameters: startElementHandler ( int parser, string name, array attribs)
The first parameter, parser, is a reference to the XML parser calling the handler.
The second parameter, name, contains the name of the element for which this handler is called. If case-folding is in effect for this parser, the element name will be in uppercase letters.
The third parameter, attribs, contains an associative array with the element's attributes (if any). The keys of this array are the attribute names, the values are the attribute values. Attribute names are case-folded on the same criteria as element names. Attribute values are not case-folded.
The original order of the attributes can be retrieved by walking through attribs the normal way, using each(). The first key in the array was the first attribute, and so on.
The function named by endElementHandler must accept two parameters: endElementHandler ( int parser, string name)
The first parameter, parser, is a reference to the XML parser calling the handler.
The second parameter, name, contains the name of the element for which this handler is called. If case-folding is in effect for this parser, the element name will be in uppercase letters.
If a handler function is set to an empty string, or FALSE, the handler in question is disabled.
TRUE is returned if the handlers are set up, FALSE if parser is not a parser.
Notatka: Zamiast nazwy funkcji może zostać przekazana
Sets the character data handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
The function named by handler must accept two parameters: handler ( int parser, string data)
The first parameter, parser, is a reference to the XML parser calling the handler.
The second parameter, data, contains the character data as a string.
If a handler function is set to an empty string, or FALSE, the handler in question is disabled.
TRUE is returned if the handler is set up, FALSE if parser is not a parser.
Notatka: Zamiast nazwy funkcji może zostać przekazana
(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)
xml_set_processing_instruction_handler -- Set up processing instruction (PI) handlerSets the processing instruction (PI) handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
A processing instruction has the following format:
You can put PHP code into such a tag, but be aware of one limitation: in an XML PI, the PI end tag (?>) can not be quoted, so this character sequence should not appear in the PHP code you embed with PIs in XML documents. If it does, the rest of the PHP code, as well as the "real" PI end tag, will be treated as character data.The function named by handler must accept three parameters: handler ( int parser, string target, string data)
The first parameter, parser, is a reference to the XML parser calling the handler.
The second parameter, target, contains the PI target.
The third parameter, data, contains the PI data.
If a handler function is set to an empty string, or FALSE, the handler in question is disabled.
TRUE is returned if the handler is set up, FALSE if parser is not a parser.
Notatka: Zamiast nazwy funkcji może zostać przekazana
Sets the default handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
The function named by handler must accept two parameters: handler ( int parser, string data)
The first parameter, parser, is a reference to the XML parser calling the handler.
The second parameter, data, contains the character data. This may be the XML declaration, document type declaration, entities or other data for which no other handler exists.
If a handler function is set to an empty string, or FALSE, the handler in question is disabled.
TRUE is returned if the handler is set up, FALSE if parser is not a parser.
Notatka: Zamiast nazwy funkcji może zostać przekazana
(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)
xml_set_unparsed_entity_decl_handler -- Set up unparsed entity declaration handlerSets the unparsed entity declaration handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
This handler will be called if the XML parser encounters an external entity declaration with an NDATA declaration, like the following:
<!ENTITY name {publicId | systemId} NDATA notationName> |
See section 4.2.2 of the XML 1.0 spec for the definition of notation declared external entities.
The function named by handler must accept six parameters: handler ( int parser, string entityName, string base, string systemId, string publicId, string notationName)
The first parameter, parser, is a reference to the XML parser calling the handler.
The name of the entity that is about to be defined.
This is the base for resolving the system identifier (systemId) of the external entity. Currently this parameter will always be set to an empty string.
System identifier for the external entity.
Public identifier for the external entity.
Name of the notation of this entity (see xml_set_notation_decl_handler()).
If a handler function is set to an empty string, or FALSE, the handler in question is disabled.
TRUE is returned if the handler is set up, FALSE if parser is not a parser.
Notatka: Zamiast nazwy funkcji może zostać przekazana
Sets the notation declaration handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
A notation declaration is part of the document's DTD and has the following format:
<!NOTATION name {systemId | publicId}> |
The function named by handler must accept five parameters: handler ( int parser, string notationName, string base, string systemId, string publicId)
The first parameter, parser, is a reference to the XML parser calling the handler.
This is the notation's name, as per the notation format described above.
This is the base for resolving the system identifier (systemId) of the notation declaration. Currently this parameter will always be set to an empty string.
System identifier of the external notation declaration.
Public identifier of the external notation declaration.
If a handler function is set to an empty string, or FALSE, the handler in question is disabled.
TRUE is returned if the handler is set up, FALSE if parser is not a parser.
Notatka: Zamiast nazwy funkcji może zostać przekazana
(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)
xml_set_external_entity_ref_handler -- set up external entity reference handlerSets the notation declaration handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
The function named by handler must accept five parameters, and should return an integer value. If the value returned from the handler is FALSE (which it will be if no value is returned), the XML parser will stop parsing and xml_get_error_code() will return XML_ERROR_EXTERNAL_ENTITY_HANDLING. int handler ( int parser, string openEntityNames, string base, string systemId, string publicId)
The first parameter, parser, is a reference to the XML parser calling the handler.
The second parameter, openEntityNames, is a space-separated list of the names of the entities that are open for the parse of this entity (including the name of the referenced entity).
This is the base for resolving the system identifier (systemid) of the external entity. Currently this parameter will always be set to an empty string.
The fourth parameter, systemId, is the system identifier as specified in the entity declaration.
The fifth parameter, publicId, is the public identifier as specified in the entity declaration, or an empty string if none was specified; the whitespace in the public identifier will have been normalized as required by the XML spec.
If a handler function is set to an empty string, or FALSE, the handler in question is disabled.
TRUE is returned if the handler is set up, FALSE if parser is not a parser.
Notatka: Zamiast nazwy funkcji może zostać przekazana
A reference to the XML parser to use.
Chunk of data to parse. A document may be parsed piece-wise by calling xml_parse() several times with new data, as long as the isFinal parameter is set and TRUE when the last data is parsed.
If set and TRUE, data is the last piece of data sent in this parse.
When the XML document is parsed, the handlers for the configured events are called as many times as necessary, after which this function returns TRUE or FALSE.
TRUE is returned if the parse was successful, FALSE if it was not successful, or if parser does not refer to a valid parser. For unsuccessful parses, error information can be retrieved with xml_get_error_code(), xml_error_string(), xml_get_current_line_number(), xml_get_current_column_number() and xml_get_current_byte_index().
A reference to the XML parser to get error code from.
This function returns FALSE if parser does not refer to a valid parser, or else it returns one of the error codes listed in the error codes section.
An error code from xml_get_error_code().
Returns a string with a textual description of the error code code, or FALSE if no description was found.
(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)
xml_get_current_line_number -- get current line number for an XML parser
A reference to the XML parser to get line number from.
This function returns FALSE if parser does not refer to a valid parser, or else it returns which line the parser is currently at in its data buffer.
(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)
xml_get_current_column_number -- Get current column number for an XML parser
A reference to the XML parser to get column number from.
This function returns FALSE if parser does not refer to a valid parser, or else it returns which column on the current line (as given by xml_get_current_line_number()) the parser is currently at.
(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)
xml_get_current_byte_index -- get current byte index for an XML parser
A reference to the XML parser to get byte index from.
This function returns FALSE if parser does not refer to a valid parser, or else it returns which byte index the parser is currently at in its data buffer (starting at 0).
This function parses an XML file into 2 parallel array structures, one (index) containing pointers to the location of the appropriate values in the values array. These last two parameters must be passed by reference.
Below is an example that illustrates the internal structure of the arrays being generated by the function. We use a simple note tag embeded inside a para tag, and then we parse this an print out the structures generated:
$simple = "<para><note>simple note</note></para>"; $p = xml_parser_create(); xml_parse_into_struct($p,$simple,$vals,$index); xml_parser_free($p); echo "Index array\n"; print_r($index); echo "\nVals array\n"; print_r($vals); |
Index array Array ( [PARA] => Array ( [0] => 0 [1] => 2 ) [NOTE] => Array ( [0] => 1 ) ) Vals array Array ( [0] => Array ( [tag] => PARA [type] => open [level] => 1 ) [1] => Array ( [tag] => NOTE [type] => complete [level] => 2 [value] => simple note ) [2] => Array ( [tag] => PARA [type] => close [level] => 1 ) ) |
Event-driven parsing (based on the expat library) can get complicated when you have an XML document that is complex. This function does not produce a DOM style object, but it generates structures amenable of being transversed in a tree fashion. Thus, we can create objects representing the data in the XML file easily. Let's consider the following XML file representing a small database of aminoacids information:
Przykład 1. moldb.xml - small database of molecular information
|
Przykład 2. parsemoldb.php - parses moldb.xml into and array of molecular objects
|
A reference to the XML parser to free.
This function returns FALSE if parser does not refer to a valid parser, or else it frees the parser and returns TRUE.
A reference to the XML parser to set an option in.
Which option to set. See below.
The option's new value.
This function returns FALSE if parser does not refer to a valid parser, or if the option could not be set. Else the option is set and TRUE is returned.
The following options are available:
Tabela 1. XML parser options
Option constant | Data type | Description |
---|---|---|
XML_OPTION_CASE_FOLDING | integer | Controls whether case-folding is enabled for this XML parser. Enabled by default. |
XML_OPTION_TARGET_ENCODING | string | Sets which target encoding to use in this XML parser. By default, it is set to the same as the source encoding used by xml_parser_create(). Supported target encodings are ISO-8859-1, US-ASCII and UTF-8. |
A reference to the XML parser to get an option from.
Which option to fetch. See xml_parser_set_option() for a list of options.
This function returns FALSE if parser does not refer to a valid parser, or if the option could not be set. Else the option's value is returned.
See xml_parser_set_option() for the list of options.
(PHP 3>= 3.0.6, PHP 4 >= 4.0.0)
utf8_decode -- Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1.This function decodes data, assumed to be UTF-8 encoded, to ISO-8859-1.
See utf8_encode() for an explaination of UTF-8 encoding.
This function encodes the string data to UTF-8, and returns the encoded version. UTF-8 is a standard mechanism used by Unicodefor encoding wide character values into a byte stream. UTF-8 is transparent to plain ASCII characters, is self-synchronized (meaning it is possible for a program to figure out where in the bytestream characters start) and can be used with normal string comparison functions for sorting and such. PHP encodes UTF-8 characters in up to four bytes, like this:
Each b represents a bit that can be used to store character data.
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
Notatka: Zamiast nazwy funkcji może zostać przekazana
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. |
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. |
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. |
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. |
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. |
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. |
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. |
(PHP 4 >= 4.1.0)
xmlrpc_server_register_method -- Register a PHP function to resource method matching method_nameOstrze¿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. |
(PHP 4 >= 4.1.0)
xmlrpc_server_register_introspection_callback -- Register a PHP function to generate documentationOstrze¿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. |
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. |
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. |
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. |
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. |
(PHP 4 >= 4.1.0)
xmlrpc_get_type -- Gets xmlrpc type for a PHP value. Especially useful for base64 and datetime stringsOstrze¿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. |
XSLT (Extensible Stylesheet Language (XSL) Transformations) is a language for transforming XML documents into other XML documents. It is a standard defined by The World Wide Web consortium (W3C). Information about XSLT and related technologies can be found at http://www.w3.org/TR/xslt.
This extension uses Sablotron and expat, which can both be found at http://www.gingerall.com/. Binaries are provided as well as source.
On UNIX, run configure with the --enable-xslt --with-xslt-sablot options. The Sablotron library should be installed somewhere your compiler can find it.
This PHP extension provides a processor independent API to XSLT transformations. Currently this extension only supports the Sablotron library from the Ginger Alliance. Support is planned for other libraries, such as the Xalan library or the libxslt library.
Notatka: This extension is different than the sablotron extension distributed with versions of PHP prior to PHP 4.1, currently only the new XSLT extension in PHP 4.1 is supported. If you need support for the old extension, please ask your questions on the php-general@lists.php.net mailing list.
A reference to the XSLT parser.
This parameter is either a boolean value which toggles logging on and off, or a string containing the logfile in which log errors too.
This function allows you to set the file in which you want XSLT log messages to, XSLT log messages are different than error messages, in that log messages are not actually error messages but rather messages related to the state of the XSLT processor. They are useful for debugging XSLT, when something goes wrong.
By default logging is disabled, in order to enable logging you must first call xslt_set_log() with a boolean parameter which enables logging, then if you want to set the log file to debug to, you must then pass it a string containing the filename:
Create and return a new XSLT processor resource for manipulation by the other XSLT functions.
Return an error code describing the last error that occured on the passed XSLT processor.
Return a string describing the last error that occured on the passed XSLT processor.
Przykład 1. Handling errors using the xslt_error() and xslt_errno() functions.
|
The xslt_process() function is the crux of the new XSLT extension. It allows you to perform an XSLT transformation using almost any type of input source. This is accomplished through the use of argument buffers -- a concept taken from the Sablotron XSLT processor (currently the only XSLT processor this extension supports).
The simplest type of transformation with the xslt_process()() function is the transformation of an XML file with an XSLT file, placing the result in a third file containing the new XML (or HTML) document. Doing this with sablotron is really quite easy...
Przykład 1. Using the xslt_process() to transform an XML file and a XSL file to a new XML file
|
While this functionality is great, many times, especially in a web environment, you want to be able to print out your results directly. Therefore, if you omit the third argument to the xslt_process() function (or provide a NULL value for the argument), it will automatically return the value of the XSLT transformation, instead of writing it to a file...
Przykład 2. Using the xslt_process() to transform an XML file and a XSL file to a variable containing the resulting XML data
|
The above two cases are the two simplest cases there are when it comes to XSLT transformation and I'd dare say that they are the most common cases, however, sometimes you get your XML and XSLT code from external sources, such as a database or a socket. In these cases you'll have the XML and/or XSLT data in a variable -- and in production applications the overhead of dumping these to file may be too much. This is where XSLT's "argument" syntax, comes to the rescue. Instead of files as the XML and XSLT arguments to the xslt_process() function, you can specify "argument place holders" which are then subsituted by values given in the arguments array (5th parameter to the xslt_process() function). The following is an example of processing XML and XSLT into a result variable without the use of files at all.
Przykład 3. Using the xslt_process() to transform a variable containing XML data and a variable containing XSL data into a variable containing the resulting XML data
|
Finally, the last argument to the xslt_process() function is any parameters that you want to pass to the XSLT document. These parameters can then be accessed within your XSL files using the <xsl:param name="parameter_name"> instruction.
Set SAX handlers on the resource handle given by xh. SAX handlers should be a two dimensional array with the format (all top level elements are optional):
array( [document] => array( start document handler, end document handler ), [element] => array( start element handler, end element handler ), [namespace] => array( start namespace handler, end namespace handler ), [comment] => comment handler, [pi] => processing instruction handler, [character] => character data handler ) |
Set Scheme handlers on the resource handle given by xh. Scheme handlers should be an array with the format (all elements are optional):
Set an error handler function for the XSLT processor given by xh, this function will be called whenever an error occurs in the XSLT transformation (this function is also called for notices).
Sets the base URI for all XSLT transformations, the base URI is used with Xpath instructions to resolve document() and other commands which access external resources.
Set the output encoding for the XSLT transformations. When using the Sablotron backend this option is only available when you compile Sablotron with encoding support.
(PHP 4 >= 4.0.6)
xslt_set_sax_handlers -- Set the SAX handlers to be called when the XML document gets processed
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
This extension offers a PHP interface to the YAZ toolkit that implements the Z39.50 protocol for information retrieval. With this extension you can easily implement a Z39.50 origin (client) that searches or scans Z39.50 targets (servers) in parallel.
YAZ is available at http://www.indexdata.dk/yaz/. You can find news information, example scripts, etc. for this extension at http://www.indexdata.dk/phpyaz/.
The module hides most of the complexity of Z39.50 so it should be fairly easy to use. It supports persistent stateless connections very similar to those offered by the various SQL APIs that are available for PHP. This means that sessions are stateless but shared amongst users, thus saving the connect and initialize phase steps in most cases.
Compile YAZ and install it. Build PHP with your favourite modules and add option --with-yaz. Your task is roughly the following:
PHP/YAZ keeps track of connections with targets (Z-Associations). A positive integer represents the ID of a particular association.
Przykład 1. Parallel searching using YAZ() The script below demonstrates the parallel searching feature of the API. When invoked with no arguments it prints a query form; else (arguments are supplied) it searches the targets as given in in array host.
|
Returns additional error message for target (last request). An empty string is returned if last operation was a success or if no additional information was provided by the target.
Closes the Z-association given by id. The id is a target ID as returned by a previous yaz_connect() command.
This function returns a positive ID on success; zero on failure.
yaz_connect() prepares for a connection to a Z39.50 target. The zurl argument takes the form host[:port][/database]. If port is omitted 210 is used. If database is omitted Default is used. This function is non-blocking and doesn't attempt to establish a socket - it merely prepares a connect to be performed later when yaz_wait() is called.
If the second argument, options, is given as a string it is treated as the Z39.50 V2 authentication string (OpenAuth).
If options is given as an array the contents of the array serves as options. Note that array options are only supported for PHP 4.1.0 and later.
yaz_connect() options
Username for authentication.
Group for authentication.
Password for authentication.
Cookie for session (YAZ proxy).
Proxy for connection (YAZ proxy).
A boolean. If TRUE the connection is persistent; If FALSE the connection is not persistent. By default connections are persistent.
A boolean. If TRUE piggyback is enabled for searches; If FALSE piggyback is disabled. By default piggyback is enabled. Enabling piggyback is more efficient and usually saves a network-round-trip for first time fetches of records. However, a few Z39.50 targets doesn't support piggyback or they ignore element set names. For those, piggyback should be disabled.
Returns error for target (last request). A positive value is returned if the target returned a diagnostic code; a value of zero is returned if no errors occurred (success); negative value is returned for other errors (such as when the target closed connection, etc).
yaz_errno() should be called after network activity for each target - (after yaz_wait() returns) to determine the success or failure of the last operation (e.g. search).
Returns error message for target (last request). An empty string is returned if last operation was a success.
yaz_error() returns an english text message corresponding to the last error number as returned by yaz_errno().
This function is used in conjunction with yaz_search() and yaz_present() to specify the element set name for records to be retrieved. Most servers support F (full) and B (brief).
Returns TRUE on success; FALSE on error.
This function specifies one or more databases to be used in search, retrieval, etc. - overriding databases specified in call to yaz_connect(). Multiple databases are separated by a plus sign +.
This function allows you to use different sets of databases within a session.
Returns TRUE on success; FALSE on error.
This function is used in conjunction with yaz_search() to specify the maximum number of records to retrieve (number) and the first record position (start). If this function is not invoked (only yaz_search()) start is set to 1 and number is set to 10.
Returns TRUE on success; FALSE on error.
Returns record at position or empty string if no record exists at given position.
The yaz_record() function inspects a record in the current result set at the position specified. If no database record exists at the given position an empty string is returned. The argument, type, specifies the form of the returned record. If type is "string" the record is returned in a string representation suitable for printing (for XML and SUTRS). If type is "array" the record is returned as an array representation (for structured records).
yaz_search() prepares for a search on the target with given id. The type represents the query type - only "rpn" is supported now in which case the third argument specifies a Type-1 query (RPN). Like yaz_connect() this function is non-blocking and only prepares for a search to be executed later when yaz_wait() is called.
The RPN query is a textual represenation of the Type-1 query as defined by the Z39.50 standard. However, in the text representation as used by YAZ a prefix notation is used, that is the operater precedes the operands. The query string is a sequence of tokens where white space is ignored is ignored unless surrounded by double quotes. Tokens beginning with an at-character (@) are considered operators, otherwise they are treated as search terms.
Tabela 1. RPN Operators
Syntax | Description |
---|---|
@and query1 query2 | intersection of query1 and query2 |
@or query1 query2 | union of query1 and query2 |
@not query1 query2 | query1 and not query2 |
@set name | result set reference |
@attrset set query | specifies attribute-set for query. This construction is only allowed once - in the beginning of the whole query |
@attr set type=value query | applies attribute to query. The type and value are integers specifying the attribute-type and attribute-value respectively. The set, if given, specifies the attribute-set. |
Przykład 1. Query Examples Query
The Query
For the query
Another more complex one:
|
This function prepares for retrieval of records after a successful search. The yaz_range() should be called prior to this function to specify the range of records to be retrieved.
The syntax is specified as an OID (Object Identifier) in a raw dot-notation (like 1.2.840.10003.5.10) or as one of the known registered record syntaxes (sutrs, usmarc, grs1, xml, etc.). This function is used in conjunction with yaz_search() and yaz_present() to specify the preferred record syntax for retrieval.
This function prepares for a Z39.50 Scan Request. Argument id specifies target ID. Starting term point for the scan is given by startterm. The form in which is the starting term is specified is given by type. Currently type rpn is supported. The optional flags specifies additional information to control the behaviour of the scan request. Three indexes are currently read from the flags: number (number of terms requested), position (preferred position of term) and stepSize (preferred step size). To actually tranfer the Scan Request to the target and receive the Scan Response, yaz_wait() must be called. Upon completion of yaz_wait() call yaz_error() and yaz_scan_result() to handle the response.
The syntax of startterm is similar to the RPN query as described in yaz_search(). The startterm consists of zero or more @attr-operator specifications, then followed by exactly one token.
Przykład 1. PHP function that scans titles
|
Given a target ID this function returns and array with terms as received from the target in the last Scan Response. This function returns an array (0..n-1) where n is the number of terms returned. Each value is a pair where first item is term, second item is result-count. If the result is given it will be modified to hold additional information taken from the Scan Response: number (number of entries returned), stepsize (Step-size), position (position of term), status (Scan Status).
This function configures the CCL query parser for a target with definitions of access points (CCL qualifiers) and their mapping to RPN. To map a specific CCL query to RPN afterwards call the yaz_ccl_parse() function. Each index of the array config is the name of a CCL field and the corresponding value holds a string that specifies a mapping to RPN. The mapping is a sequence of attribute-type, attribute-value pairs. Attribute-type and attribute-value is separated by an equal sign (=). Each pair is separated by white space.
Przykład 1. CCL configuration In the example below, the CCL parser is configured to support three CCL fields: ti, au and isbn. Each field is mapped to their BIB-1 equivalent. It is assumed that variable $id is a target ID.
|
This function invokes the CCL parser. It converts a given CCL FIND query to an RPN query which may be passed to the yaz_search() function to perform a search. To define a set of valid CCL fields call yaz_ccl_conf() prior to this function. If the supplied query was successfully converted to RPN, this function returns TRUE, and the index rpn of the supplied array result holds a valid RPN query. If the query could not be converted (because of invalid syntax, unknown field, etc.) this function returns FALSE and three indexes are set in the resulting array to indicate the cause of failure: errorcodeCCL error code (integer), errorstringCCL error string, and errorposapproximate position in query of failure (integer is character position).
This function prepares for an Extended Services request using the Profile for the Use of Z39.50 Item Order Extended Service to Transport ILL (Profile/1). See this and the specification. The args parameter must be a hash array with information about the Item Order request to be sent. The key of the hash is the name of the corresponding ASN.1 tag path. For example, the ISBN below the Item-ID has the key item-id,ISBN.
The ILL-Request parameters are:
protocol-version-num
transaction-id,initial-requester-id,person-or-institution-symbol,person
transaction-id,initial-requester-id,person-or-institution-symbol,institution
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-person
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-institution
transaction-id,transaction-group-qualifier
transaction-id,transaction-qualifier
transaction-id,sub-transaction-qualifier
service-date-time,this,date
service-date-time,this,time
service-date-time,original,date
service-date-time,original,time
requester-id,person-or-institution-symbol,person
requester-id,person-or-institution-symbol,institution
requester-id,name-of-person-or-institution,name-of-person
requester-id,name-of-person-or-institution,name-of-institution
responder-id,person-or-institution-symbol,person
responder-id,person-or-institution-symbol,institution
responder-id,name-of-person-or-institution,name-of-person
responder-id,name-of-person-or-institution,name-of-institution
transaction-type
delivery-address,postal-address,name-of-person-or-institution,name-of-person
delivery-address,postal-address,name-of-person-or-institution,name-of-institution
delivery-address,postal-address,extended-postal-delivery-address
delivery-address,postal-address,street-and-number
delivery-address,postal-address,post-office-box
delivery-address,postal-address,city
delivery-address,postal-address,region
delivery-address,postal-address,country
delivery-address,postal-address,postal-code
delivery-address,electronic-address,telecom-service-identifier
delivery-address,electronic-address,telecom-service-addreess
billing-address,postal-address,name-of-person-or-institution,name-of-person
billing-address,postal-address,name-of-person-or-institution,name-of-institution
billing-address,postal-address,extended-postal-delivery-address
billing-address,postal-address,street-and-number
billing-address,postal-address,post-office-box
billing-address,postal-address,city
billing-address,postal-address,region
billing-address,postal-address,country
billing-address,postal-address,postal-code
billing-address,electronic-address,telecom-service-identifier
billing-address,electronic-address,telecom-service-addreess
ill-service-type
requester-optional-messages,can-send-RECEIVED
requester-optional-messages,can-send-RETURNED
requester-optional-messages,requester-SHIPPED
requester-optional-messages,requester-CHECKED-IN
search-type,level-of-service
search-type,need-before-date
search-type,expiry-date
search-type,expiry-flag
place-on-hold
client-id,client-name
client-id,client-status
client-id,client-identifier
item-id,item-type
item-id,call-number
item-id,author
item-id,title
item-id,sub-title
item-id,sponsoring-body
item-id,place-of-publication
item-id,publisher
item-id,series-title-number
item-id,volume-issue
item-id,edition
item-id,publication-date
item-id,publication-date-of-component
item-id,author-of-article
item-id,title-of-article
item-id,pagination
item-id,ISBN
item-id,ISSN
item-id,additional-no-letters
item-id,verification-reference-source
copyright-complicance
retry-flag
forward-flag
requester-note
forward-note
There are also a few parameters that are part of the Extended Services Request package and the ItemOrder package:
package-name
user-id
contact-name
contact-phone
contact-email
itemorder-item
This function carries out networked (blocked) activity for outstanding requests which have been prepared by the functions yaz_connect(), yaz_search(), yaz_present(), yaz_scan() and yaz_itemorder(). yaz_wait() returns when all targets have either completed all requests or aborted (in case of errors).
If the options array is given that holds options that change the behaviour of yaz_wait().
Sets timeout in seconds. If a target hasn't responded within the timeout it is considered dead and yaz_wait() returns. The default value for timeout is 15 seconds.
This function sets sorting criteria and enables Z39.50 Sort. Use this function together with yaz_search() or yaz_present(). Using this function alone doesn't have any effect. If used in conjunction with yaz_search() a Z39.50 Sort will be sent after a search response has been received and before any records are retrieved with Z39.50 Present. The criteria takes the form
field1 flags1 field2 flags2 ...
where field1 specifies primary attributes for sort, field2 seconds, etc.. The field specifies either numerical attribute combinations consisting of type=value pairs separated by comma (e.g. 1=4,2=1) ; or the field may specify a plain string criteria (e.g. title. The flags is a sequnce of the following characters which may not be separated by any white space.
Sort Flags
Sort ascending
Sort descending
Case insensitive sorting
Case sensitive sorting
NIS (formerly called Yellow Pages) allows network management of important administrative files (e.g. the password file). For more information refer to the NIS manpage and Introduction to YP/NIS. There is also a book called Managing NFS and NIS by Hal Stern.
To get these functions to work, you have to configure PHP with --with-yp(PHP 3) or --enable-yp(PHP 4).
yp_get_default_domain() returns the default domain of the node or FALSE. Can be used as the domain parameter for successive NIS calls.
A NIS domain can be described a group of NIS maps. Every host that needs to look up information binds itself to a certain domain. Refer to the documents mentioned at the beginning for more detailed information.
yp_order() returns the order number for a map or FALSE.
See also yp-get-default-domain().
(PHP 3>= 3.0.7, PHP 4 >= 4.0.0)
yp_master -- Returns the machine name of the master NIS server for a mapyp_master() returns the machine name of the master NIS server for a map.
See also yp-get-default-domain().
yp_match() returns the value associated with the passed key out of the specified map or FALSE. This key must be exact.
In this case this could be: joe:##joe:11111:100:Joe User:/home/j/joe:/usr/local/bin/bash
See also yp-get-default-domain()
yp_first() returns the first key-value pair from the named map in the named domain, otherwise FALSE.
See also yp-get-default-domain()
yp_next() returns the next key-value pair in the named map after the specified key or FALSE.
See also yp-get-default-domain().
yp_errno() returns the error code of the previous operation.
Possible errors are:
1 args to function are bad |
2 RPC failure - domain has been unbound |
3 can't bind to server on this domain |
4 no such map in server's domain |
5 no such key in map |
6 internal yp server or client error |
7 resource allocation failure |
8 no more records in map database |
9 can't communicate with portmapper |
10 can't communicate with ypbind |
11 can't communicate with ypserv |
12 local domain name not set |
13 yp database is bad |
14 yp version mismatch |
15 access violation |
16 database busy |
See also yp_err_string().
yp_err_string() returns the error message associated with the previous operation. Useful to indicate what exactly went wrong.
See also yp_errno().
Ostrze¿enie |
Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów. |
This module uses the functions of the ZZIPlib library by Guido Draheim to transparently read ZIP compressed archives and the files inside them.
Please note that ZZIPlib only provides a subset of functions provided in a full implementation of the ZIP compression algorithm and can only read ZIP file archives. A normal ZIP utility is needed to create the ZIP file archives read by this library.
Zip support in PHP is not enabled by default. You will need to use the --with-zip configuration option when compiling PHP to enable zip support. This module requires ZZIPlib version >= 0.10.6.
Notatka: Zip support before PHP 4.1.0 is experimental. This section reflects the Zip extension as it exists in PHP 4.1.0 and later.
This example opens a ZIP file archive, reads each file in the archive and prints out its contents. The test2.zip archive used in this example is one of the test archives in the ZZIPlib source distribution.
Przykład 1. Zip Usage Example
|
Closes a zip file archive. The parameter zip must be a zip archive previously opened by zip_open().
This function has no return value.
See also zip_open() and zip_read().
Closes a directory entry specified by zip_entry. The parameter zip_entry must be a valid directory entry opened by zip_entry_open().
This function has no return value.
See also zip_entry_open() and zip_entry_read().
Returns the compressed size of the directory entry specified by zip_entry. The parameter zip_entry is a valid directory entry returned by zip_read().
See also zip_open() and zip_read().
Returns the compression method of the directory entry specified by zip_entry. The parameter zip_entry is a valid directory entry returned by zip_read().
See also zip_open() and zip_read().
Returns the actual size of the directory entry specified by zip_entry. The parameter zip_entry is a valid directory entry returned by zip_read().
See also zip_open() and zip_read().
Returns the name of the directory entry specified by zip_entry. The parameter zip_entry is a valid directory entry returned by zip_read().
See also zip_open() and zip_read().
Opens a directory entry in a zip file for reading. The parameter zip is a valid resource handle returned by zip_open(). The parameter zip_entry is a directory entry resource returned by zip_read(). The optional parameter mode can be any of the modes specified in the documentaion for fopen().
Notatka: Currently, mode is ignored and is always "rb". This is due to the fact that zip support in PHP is read only access. Please see fopen() for an explanation of various modes, including "rb".
Returns TRUE on succes or FALSE on failure.
Notatka: Unlike fopen() and other similar functions, the return value of zip_entry_open() only indicates the result of the operation and is not needed for reading or closing the directory entry.
See also zip_entry_read() and zip_entry_close().
Reads up to length bytes from an open directory entry. If length is not specified, then zip_entry_read() will attempt to read 1024 bytes. The parameter zip_entry is a valid directory entry returned by zip_read().
Notatka: The length parameter should be the uncompressed length you wish to read.
Returns the data read, or FALSE if the end of the file is reached.
See also zip_entry_open(), zip_entry_close() and zip_entry_filesize().
Opens a new zip archive for reading. The filename parameter is the filename of the zip archive to open.
Returns a resource handle for later use with zip_read() and zip_close() or returns FALSE if filename does not exist.
See also zip_read() and zip_close().
Reads the next entry in a zip file archive. The parameter zip must be a zip archive previously opened by zip_open().
Returns a directory entry resource for later use with the zip_entry_...() functions.
See also zip_open(), zip_close(), zip_entry_open(), and zip_entry_read().
This module uses the functions of zlib by Jean-loup Gailly and Mark Adler to transparently read and write gzip (.gz) compressed files. You have to use a zlib version >= 1.0.9 with this module.
This module contains versions of most of the filesystem functions which work with gzip-compressed files (and uncompressed files, too, but not with sockets).
Notatka: The current CVS version 4.0.4-dev introduces a fopen-wrapper for .gz-files, so that you can use a special 'zlib:' URL to access compressed files transparently using the normal f*() file access functions if you prepend the filename or path with a 'zlib:' prefix when calling fopen().
This feature requires a C runtime library that provides the fopencookie() function. To my current knowledge the GNU libc is the only library that provides this feature.
Opens a temporary file and writes a test string to it, then it prints out the content of this file twice.
Przykład 1. Small Zlib Example
|
The gz-file pointed to by zp is closed.
Returns TRUE on success and FALSE on failure.
The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().
Returns TRUE if the gz-file pointer is at EOF or an error occurs; otherwise returns FALSE.
The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().
Identical to readgzfile(), except that gzfile() returns the file in an array.
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 readgzfile(), and gzopen().
Returns a string containing a single (uncompressed) character read from the file pointed to by zp. Returns FALSE on EOF (as does gzeof()).
The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().
Returns a (uncompressed) string of up to length - 1 bytes read from the file pointed to by fp. Reading ends when length - 1 bytes have been read, on a newline, or on EOF (whichever comes first).
If an error occurs, returns FALSE.
The file pointer must be valid, and must point to a file successfully opened by gzopen().
Identical to gzgets(), except that gzgetss() attempts to strip any HTML and PHP tags from the text it reads.
You can use the optional third parameter to specify tags which should not be stripped.
Notatka: Allowable_tags was added in PHP 3.0.13, PHP4B3.
See also gzgets(), gzopen(), and strip_tags().
Opens a gzip (.gz) file for reading or writing. The mode parameter is as in fopen() ("rb" or "wb") but can also include a compression level ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman only compression as in "wb1h". (See the description of deflateInit2 in zlib.h for more information about the strategy parameter.)
gzopen() can be used to read a file which is not in gzip format; in this case gzread() will directly read from the file without decompression.
gzopen() returns a file pointer to the file opened, after that, everything you read from this file descriptor will be transparently decompressed and what you write gets compressed.
If the open fails, the function returns FALSE.
You can use the optional third parameter and set it to "1", if you want to search for the file in the include_path, too.
See also gzclose().
Reads to EOF on the given gz-file pointer and writes the (uncompressed) results to standard output.
If an error occurs, returns FALSE.
The file pointer must be valid, and must point to a file successfully opened by gzopen().
The gz-file is closed when gzpassthru() is done reading it (leaving zp useless).
gzputs() is an alias to gzwrite(), and is identical in every way.
gzread() reads up to length bytes from the gz-file pointer referenced by zp. Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first.
// get contents of a gz-file into a string $filename = "/usr/local/something.txt.gz"; $zd = gzopen ($filename, "r"); $contents = gzread ($zd, 10000); gzclose ($zd); |
See also gzwrite(), gzopen(), gzgets(), gzgetss(), gzfile(), and gzpassthru().
Sets the file position indicator for zp to the beginning of the file stream.
If an error occurs, returns 0.
The file pointer must be valid, and must point to a file successfully opened by gzopen().
Sets the file position indicator for the file referenced by zp to offset bytes into the file stream. Equivalent to calling (in C) gzseek( zp, offset, SEEK_SET ).
If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; gzseek then compresses a sequence of zeroes up to the new starting position.
Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.
See also gztell() and gzrewind().
Returns the position of the file pointer referenced by zp; i.e., its offset into the file stream.
If an error occurs, returns FALSE.
The file pointer must be valid, and must point to a file successfully opened by gzopen().
See also gzopen(), gzseek() and gzrewind().
gzwrite() writes the contents of string to the gz-file stream pointed to by zp. If the length argument is given, writing will stop after length (uncompressed) bytes have been written or the end of string is reached, whichever comes first.
Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.
Reads a file, decompresses it and writes it to standard output.
readgzfile() can be used to read a file which is not in gzip format; in this case readgzfile() will directly read from the file without decompression.
Returns the number of (uncompressed) bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readgzfile, an error message is printed.
The file filename will be opened from the filesystem and its contents written to standard output.
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 gzpassthru(), gzfile(), and gzopen().
This function returns a compressed version of the input data using the ZLIB data format, or FALSE if an error is encountered. The optional parameter level can be given as 0 for no compression up to 9 for maximum compression.
For details on the ZLIB compression algorithm see the document "ZLIB Compressed Data Format Specification version 3.3" (RFC 1950).
Notatka: This is not the same as gzip compression, which includes some header data. See gzencode() for gzip compression.
See also gzdeflate(), gzinflate(), gzuncompress(), gzencode().
This function takes data compressed by gzcompress() and returns the original uncompressed data or FALSE on error. The function will return an error if the uncompressed data is more than 256 times the length of the compressed input data or more than the optional parameter length.
See also gzdeflate(), gzinflate(), gzcompress(), gzencode().
This function returns a compressed version of the input data using the DEFLATE data format, or FALSE if an error is encountered. The optional parameter level can be given as 0 for no compression up to 9 for maximum compression.
For details on the DEFLATE compression algorithm see the document "DEFLATE Compressed Data Format Specification version 1.3" (RFC 1951).
See also gzinflate(), gzcompress(), gzuncompress(), gzencode().
This function takes data compressed by gzdeflate() and returns the original uncompressed data or FALSE on error. The function will return an error if the uncompressed data is more than 256 times the length of the compressed input data or more than the optional parameter length.
See also gzcompress(). gzuncompress(), gzdeflate(), gzencode().
This function returns a compressed version of the input data compatible with the output of the gzip program, or FALSE if an error is encountered. The optional parameter level can be given as 0 for no compression up to 9 for maximum compression, if not given the default compression level will be 1.
The resulting data contains the appropriate headers and data structure to make a standard .gz file, e.g.:
For more information on the GZIP file format, see the document: GZIP file format specification version 4.3 (RFC 1952).
See also gzcompress(). gzuncompress(), gzdeflate(), gzinflate().
Sometimes, PHP "as is" simply isn't enough. Although these cases are rare for the average user, professional applications will soon lead PHP to the edge of its capabilities, in terms of either speed or functionality. New functionality cannot always be implemented natively due to language restrictions and inconveniences that arise when having to carry around a huge library of default code appended to every single script, so another method needs to be found for overcoming these eventual lacks in PHP.
As soon as this point is reached, it's time to touch the heart of PHP and take a look at its core, the C code that makes PHP go.
"Extending PHP" is easier said than done. PHP has evolved to a full-fledged tool consisting of a few megabytes of source code, and to hack a system like this quite a few things have to be learned and considered. When structuring this chapter, we finally decided on the "learn by doing" approach. This is not the most scientific and professional approach, but the method that's the most fun and gives the best end results. In the following sections, you'll learn quickly how to get the most basic extensions to work almost instantly. After that, you'll learn about Zend's advanced API functionality. The alternative would have been to try to impart the functionality, design, tips, tricks, etc. as a whole, all at once, thus giving a complete look at the big picture before doing anything practical. Although this is the "better" method, as no dirty hacks have to be made, it can be very frustrating as well as energy- and time-consuming, which is why we've decided on the direct approach.
Note that even though this chapter tries to impart as much knowledge as possible about the inner workings of PHP, it's impossible to really give a complete guide to extending PHP that works 100% of the time in all cases. PHP is such a huge and complex package that its inner workings can only be understood if you make yourself familiar with it by practicing, so we encourage you to work with the source.
The name Zend refers to the language engine, PHP's core. The term PHP refers to the complete system as it appears from the outside. This might sound a bit confusing at first, but it's not that complicated (see Figure 9.1). To implement a Web script interpreter, you need three parts:
The interpreter part analyzes the input code, translates it, and executes it.
The functionality part implements the functionality of the language (its functions, etc.).
The interface part talks to the Web server, etc.
The following sections discuss where PHP can be extended and how it's done.
As shown in Figure 9.1 above, PHP can be extended primarily at three points: external modules, built-in modules, and the Zend engine. The following sections discuss these options.
External modules can be loaded at script runtime using the function dl(). This function loads a shared object from disk and makes its functionality available to the script to which it's being bound. After the script is terminated, the external module is discarded from memory. This method has both advantages and disadvantages, as described in the following table:
Advantages | Disadvantages |
External modules don't require recompiling of PHP. | The shared objects need to be loaded every time a script is being executed (every hit), which is very slow. |
The size of PHP remains small by "outsourcing" certain functionality. | External additional files clutter up the disk. |
Every script that wants to use an external module's functionality has to specifically include a call to dl(), or the extension tag in php.ini needs to be modified (which is not always a suitable solution). |
Third parties might consider using the extension tag in php.ini to create additional external modules to PHP. These external modules are completely detached from the main package, which is a very handy feature in commercial environments. Commercial distributors can simply ship disks or archives containing only their additional modules, without the need to create fixed and solid PHP binaries that don't allow other modules to be bound to them.
Built-in modules are compiled directly into PHP and carried around with every PHP process; their functionality is instantly available to every script that's being run. Like external modules, built-in modules have advantages and disadvantages, as described in the following table:
Built-in modules are best when you have a solid library of functions that remains relatively unchanged, requires better than poor-to-average performance, or is used frequently by many scripts on your site. The need to recompile PHP is quickly compensated by the benefit in speed and ease of use. However, built-in modules are not ideal when rapid development of small additions is required.Of course, extensions can also be implemented directly in the Zend engine. This strategy is good if you need a change in the language behavior or require special functions to be built directly into the language core. In general, however, modifications to the Zend engine should be avoided. Changes here result in incompatibilities with the rest of the world, and hardly anyone will ever adapt to specially patched Zend engines. Modifications can't be detached from the main PHP sources and are overridden with the next update using the "official" source repositories. Therefore, this method is generally considered bad practice and, due to its rarity, is not covered in this book.
Notatka: Prior to working through the rest of this chapter, you should retrieve clean, unmodified source trees of your favorite Web server. We're working with Apache (available at http://www.apache.org/) and, of course, with PHP (available at http://www.php.net/ - does it need to be said?).
Make sure that you can compile a working PHP environment by yourself! We won't go into this issue here, however, as you should already have this most basic ability when studying this chapter.
Before we start discussing code issues, you should familiarize yourself with the source tree to be able to quickly navigate through PHP's files. This is a must-have ability to implement and debug extensions.
After extracting the PHP archive, you'll see a directory layout similar to that in Figure 9.2.
The following table describes the contents of the major directories.
Directory | Contents |
php-4 | Main PHP source files and main header files; here you'll find all of PHP's API definitions, macros, etc. (important). |
ext | Repository for dynamic and built-in modules; by default, these are the "official" PHP modules that have been integrated into the main source tree. In PHP 4.0, it's possible to compile these standard extensions as dynamic loadable modules (at least, those that support it). |
pear | Directory for the PHP class repository. At the time of this writing, this is still in the design phase, but it's being tried to establish something similar to CPAN for Perl here. |
sapi | Contains the code for the different server abstraction layers. |
TSRM | Location of the "Thread Safe Resource Manager" (TSRM) for Zend and PHP. |
Zend | Location of Zend's file; here you'll find all of Zend's API definitions, macros, etc. (important). |
Discussing all the files included in the PHP package is beyond the scope of this chapter. However, you should take a close look at the following files:
php.h, located in the main PHP directory. This file contains most of PHP's macro and API definitions.
zend.h, located in the main Zend directory. This file contains most of Zend's macros and definitions.
zend_API.h, also located in the Zend directory, which defines Zend's API.
Zend is built using certain conventions; to avoid breaking its standards, you should follow the rules described in the following sections.
For almost every important task, Zend ships predefined macros that are extremely handy. The tables and figures in the following sections describe most of the basic functions, structures, and macros. The macro definitions can be found mainly in zend.h and zend_API.h. We suggest that you take a close look at these files after having studied this chapter. (Although you can go ahead and read them now, not everything will make sense to you yet.)
Resource management is a crucial issue, especially in server software. One of the most valuable resources is memory, and memory management should be handled with extreme care. Memory management has been partially abstracted in Zend, and you should stick to this abstraction for obvious reasons: Due to the abstraction, Zend gets full control over all memory allocations. Zend is able to determine whether a block is in use, automatically freeing unused blocks and blocks with lost references, and thus prevent memory leaks. The functions to be used are described in the following table:
Function | Description |
emalloc() | Serves as replacement for malloc(). |
efree() | Serves as replacement for free(). |
estrdup() | Serves as replacement for strdup(). |
estrndup() | Serves as replacement for strndup(). Faster than estrdup() and binary-safe. This is the recommended function to use if you know the string length prior to duplicating it. |
ecalloc() | Serves as replacement for calloc(). |
erealloc() | Serves as replacement for realloc(). |
Ostrze¿enie |
To allocate resident memory that survives termination of the current script, you can use malloc() and free(). This should only be done with extreme care, however, and only in conjunction with demands of the Zend API; otherwise, you risk memory leaks. |
The following directory and file functions should be used in Zend modules. They behave exactly like their C counterparts, but provide virtual working directory support on the thread level.
Strings are handled a bit differently by the Zend engine than other values such as integers, Booleans, etc., which don't require additional memory allocation for storing their values. If you want to return a string from a function, introduce a new string variable to the symbol table, or do something similar, you have to make sure that the memory the string will be occupying has previously been allocated, using the aforementioned e*() functions for allocation. (This might not make much sense to you yet; just keep it somewhere in your head for now - we'll get back to it shortly.)
Complex types such as arrays and objects require different treatment. Zend features a single API for these types - they're stored using hash tables.
Notatka: To reduce complexity in the following source examples, we're only working with simple types such as integers at first. A discussion about creating more advanced types follows later in this chapter.
PHP 4 features an automatic build system that's very flexible. All modules reside in a subdirectory of the ext directory. In addition to its own sources, each module consists of an M4 file (for example, see http://www.gnu.org/manual/m4/html_mono/m4.html) for configuration and a Makefile.in file, which is responsible for compilation (the results of autoconf and automake; for example, see http://sourceware.cygnus.com/autoconf/autoconf.html and http://sourceware.cygnus.com/automake/automake.html).
Both files are generated automatically, along with .cvsignore, by a little shell script named ext_skel that resides in the ext directory. As argument it takes the name of the module that you want to create. The shell script then creates a directory of the same name, along with the appropriate config.m4 and Makefile.in files.
Step by step, the process looks like this:
root@dev:/usr/local/src/php4/ext > ./ext_skel my_module Creating directory Creating basic files: config.m4 Makefile.in .cvsignore [done]. To use your new extension, you will have to execute the following steps: $ cd .. $ ./buildconf $ ./configure # (your extension is automatically enabled) $ vi ext/my_module/my_module.c $ make Repeat the last two steps as often as necessary. |
Finally, running configure parses all configuration options and generates a makefile based on those options and the options you specify in Makefile.in.
Listing 9.1 shows the previously generated Makefile.in:
Rysunek 27-1. Listing 9.1. The default Makefile.in.
# $Id: Extending_Zend_Build.xml,v 1.5 2002/02/11 10:10:33 hholzgra Exp $ LTLIBRARY_NAME = libmy_module.la LTLIBRARY_SOURCES = my_module.c LTLIBRARY_SHARED_NAME = my_module.la include $(top_srcdir)/build/dynlib.mk |
There's not much to tell about this one: It contains the names of the input and output files. You could also specify build instructions for other files if your module is built from multiple source files.
The default config.m4 shown in Listing 9.2 is a bit more complex:
Rysunek 27-2. Listing 9.2. The default config.m4.
dnl $Id: Extending_Zend_Build.xml,v 1.5 2002/02/11 10:10:33 hholzgra Exp $ dnl config.m4 for extension my_module dnl don't forget to call PHP_EXTENSION(my_module) dnl If your extension references something external, use with: PHP_ARG_WITH(my_module, for my_module support, dnl Make sure that the comment is aligned: [ --with-my_module Include my_module support]) dnl Otherwise use enable: PHP_ARG_ENABLE(my_module, whether to enable my_module support, dnl Make sure that the comment is aligned: [ --enable-my_module Enable my_module support]) if test "$PHP_MY_MODULE" != "no"; then dnl Action.. PHP_EXTENSION(my_module, $ext_shared) fi |
If you're unfamiliar with M4 files (now is certainly a good time to get familiar), this might be a bit confusing at first; but it's actually quite easy.
Note: Everything prefixed with dnl is treated as a comment and is not parsed.
The config.m4 file is responsible for parsing the command-line options passed to configure at configuration time. This means that it has to check for required external files and do similar configuration and setup tasks.
The default file creates two configuration directives in the configure script: --with-my_module and --enable-my_module. Use the first option when referring external files (such as the --with-apache directive that refers to the Apache directory). Use the second option when the user simply has to decide whether to enable your extension. Regardless of which option you use, you should uncomment the other, unnecessary one; that is, if you're using --enable-my_module, you should remove support for --with-my_module, and vice versa.
By default, the config.m4 file created by ext_skel accepts both directives and automatically enables your extension. Enabling the extension is done by using the PHP_EXTENSION macro. To change the default behavior to include your module into the PHP binary when desired by the user (by explicitly specifying --enable-my_module or --with-my_module), change the test for $PHP_MY_MODULE to == "yes":
if test "$PHP_MY_MODULE" == "yes"; then dnl Action.. PHP_EXTENSION(my_module, $ext_shared) fi |
Note: Be sure to run buildconf every time you change config.m4!
We'll go into more details on the M4 macros available to your configuration scripts later in this chapter. For now, we'll simply use the default files. The sample sources on the CD-ROM all have working config.m4 files. To include them into the PHP build process, simply copy the source directories to your PHP ext directory, run buildconf, and then include the sample modules you want by using the appropriate --enable-* directives with configure.
We'll start with the creation of a very simple extension at first, which basically does nothing more than implement a function that returns the integer it receives as parameter. Listing 9.3 shows the source.
Rysunek 28-1. Listing 9.3. A simple extension.
/* include standard header */ #include "php.h" /* declaration of functions to be exported */ ZEND_FUNCTION(first_module); /* compiled function list so Zend knows what's in this module */ zend_function_entry firstmod_functions[] = { ZEND_FE(first_module, NULL) {NULL, NULL, NULL} }; /* compiled module information */ zend_module_entry firstmod_module_entry = { STANDARD_MODULE_HEADER, "First Module", firstmod_functions, NULL, NULL, NULL, NULL, NULL, NO_VERSION_YET, STANDARD_MODULE_PROPERTIES }; /* implement standard "stub" routine to introduce ourselves to Zend */ #if COMPILE_DL_FIRST_MODULE ZEND_GET_MODULE(firstmod) #endif /* implement function that is meant to be made available to PHP */ ZEND_FUNCTION(first_module) { long parameter; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", ¶meter) == FAILURE) { return; } RETURN_LONG(parmeter); } |
This code contains a complete PHP module. We'll explain the source code in detail shortly, but first we'd like to discuss the build process. (This will allow the impatient to experiment before we dive into API discussions.)
Notatka: The example source makes use of some features introduced with the Zend version used in PHP 4.1.0 and above, it won't compile with older PHP 4.0.x versions.
There are basically two ways to compile modules:
Use the provided "make" mechanism in the ext directory, which also allows building of dynamic loadable modules.
Compile the sources manually.
The second method is good for those who (for some reason) don't have the full PHP source tree available, don't have access to all files, or just like to juggle with their keyboard. These cases should be extremely rare, but for the sake of completeness we'll also describe this method.
Compiling Using Make. To compile the sample sources using the standard mechanism, copy all their subdirectories to the ext directory of your PHP source tree. Then run buildconf, which will create an updated configure script containing appropriate options for the new extension. By default, all the sample sources are disabled, so you don't have to fear breaking your build process.
After you run buildconf, configure --help shows the following additional modules:
--enable-array_experiments BOOK: Enables array experiments --enable-call_userland BOOK: Enables userland module --enable-cross_conversion BOOK: Enables cross-conversion module --enable-first_module BOOK: Enables first module --enable-infoprint BOOK: Enables infoprint module --enable-reference_test BOOK: Enables reference test module --enable-resource_test BOOK: Enables resource test module --enable-variable_creation BOOK: Enables variable-creation module |
The module shown earlier in Listing 9.3 can be enabled with --enable-first_module or --enable-first_module=yes.
Compiling Manually. To compile your modules manually, you need the following commands:
The command to compile the module simply instructs the compiler to generate position-independent code (-fpic shouldn't be omitted) and additionally defines the constant COMPILE_DL to tell the module code that it's compiled as a dynamically loadable module (the test module above checks for this; we'll discuss it shortly). After these options, it specifies a number of standard include paths that should be used as the minimal set to compile the source files.Note: All include paths in the example are relative to the directory ext. If you're compiling from another directory, change the pathnames accordingly. Required items are the PHP directory, the Zend directory, and (if necessary), the directory in which your module resides.
The link command is also a plain vanilla command instructing linkage as a dynamic module.
You can include optimization options in the compilation command, although these have been omitted in this example (but some are included in the makefile template described in an earlier section).
Note: Compiling and linking manually as a static module into the PHP binary involves very long instructions and thus is not discussed here. (It's not very efficient to type all those commands.)
Depending on the build process you selected, you should either end up with a new PHP binary to be linked into your Web server (or run as CGI), or with an .so (shared object) file. If you compiled the example file first_module.c as a shared object, your result file should be first_module.so. To use it, you first have to copy it to a place from which it's accessible to PHP. For a simple test procedure, you can copy it to your htdocs directory and try it with the source in Listing 9.4. If you compiled it into the PHP binary, omit the call to dl(), as the module's functionality is instantly available to your scripts.
Ostrze¿enie |
For security reasons, you should not put your dynamic modules into publicly accessible directories. Even though it can be done and it simplifies testing, you should put them into a separate directory in production environments. |
Rysunek 29-1. Listing 9.4. A test file for first_module.so.
<?php // remove next comment if necessary // dl("first_module.so"); $param = 2; $return = first_module($param); print("We sent '$param' and got '$return'"); ?> |
Calling this PHP file in your Web browser should give you the output shown in Figure 9.3.
If required, the dynamic loadable module is loaded by calling the dl() function. This function looks for the specified shared object, loads it, and makes its functions available to PHP. The module exports the function first_module(), which accepts a single parameter, converts it to an integer, and returns the result of the conversion.
If you've gotten this far, congratulations! You just built your first extension to PHP.
Actually, not much troubleshooting can be done when compiling static or dynamic modules. The only problem that could arise is that the compiler will complain about missing definitions or something similar. In this case, make sure that all header files are available and that you specified their path correctly in the compilation command. To be sure that everything is located correctly, extract a clean PHP source tree and use the automatic build in the ext directory with the fresh files from the CD-ROM; this will guarantee a safe compilation environment. If this fails, try manual compilation.
PHP might also complain about missing functions in your module. (This shouldn't happen with the sample sources if you didn't modify them.) If the names of external functions you're trying to access from your module are misspelled, they'll remain as "unlinked symbols" in the symbol table. During dynamic loading and linkage by PHP, they won't resolve because of the typing errors - there are no corresponding symbols in the main binary. Look for incorrect declarations in your module file or incorrectly written external references. Note that this problem is specific to dynamic loadable modules; it doesn't occur with static modules. Errors in static modules show up at compile time.
Now that you've got a safe build environment and you're able to include the modules into PHP files, it's time to discuss how everything works.
All PHP modules follow a common structure:
Header file inclusions (to include all required macros, API definitions, etc.)
C declaration of exported functions (required to declare the Zend function block)
Declaration of the Zend function block
Declaration of the Zend module block
Implementation of get_module()
Implementation of all exported functions
The only header file you really have to include for your modules is php.h, located in the PHP directory. This file makes all macros and API definitions required to build new modules available to your code.
Tip: It's good practice to create a separate header file for your module that contains module-specific definitions. This header file should contain all the forward definitions for exported functions and include php.h. If you created your module using ext_skel you already have such a header file prepared.
To declare functions that are to be exported (i.e., made available to PHP as new native functions), Zend provides a set of macros. A sample declaration looks like this:
ZEND_FUNCTION ( my_function ); |
ZEND_FUNCTION declares a new C function that complies with Zend's internal API. This means that the function is of type void and accepts INTERNAL_FUNCTION_PARAMETERS (another macro) as parameters. Additionally, it prefixes the function name with zif. The immediately expanded version of the above definitions would look like this:
void zif_my_function ( INTERNAL_FUNCTION_PARAMETERS ); |
void zif_my_function( int ht , zval * return_value , zval * this_ptr , int return_value_used , zend_executor_globals * executor_globals ); |
Since the interpreter and executor core have been separated from the main PHP package, a second API defining macros and function sets has evolved: the Zend API. As the Zend API now handles quite a few of the responsibilities that previously belonged to PHP, a lot of PHP functions have been reduced to macros aliasing to calls into the Zend API. The recommended practice is to use the Zend API wherever possible, as the old API is only preserved for compatibility reasons. For example, the types zval and pval are identical. zval is Zend's definition; pval is PHP's definition (actually, pval is an alias for zval now). As the macro INTERNAL_FUNCTION_PARAMETERS is a Zend macro, the above declaration contains zval. When writing code, you should always use zval to conform to the new Zend API.
The parameter list of this declaration is very important; you should keep these parameters in mind (see Table 9.1 for descriptions).
Rysunek 31-1. Table 9.1. Zend's Parameters to Functions Called from PHP
Parameter | Description |
ht | The number of arguments passed to the Zend function. You should not touch this directly, but instead use ZEND_NUM_ARGS() to obtain the value. |
return_value | This variable is used to pass any return values of your function back to PHP. Access to this variable is best done using the predefined macros. For a description of these see below. |
this_ptr | Using this variable, you can gain access to the object in which your function is contained, if it's used within an object. Use the function getThis() to obtain this pointer. |
return_value_used | This flag indicates whether an eventual return value from this function will actually be used by the calling script. 0 indicates that the return value is not used; 1 indicates that the caller expects a return value. Evaluation of this flag can be done to verify correct usage of the function as well as speed optimizations in case returning a value requires expensive operations (for an example, see how array.c makes use of this). |
executor_globals | This variable points to global settings of the Zend engine. You'll find this useful when creating new variables, for example (more about this later). The executor globals can also be introduced to your function by using the macro ELS_FETCH(). |
Now that you have declared the functions to be exported, you also have to introduce them to Zend. Introducing the list of functions is done by using an array of zend_function_entry. This array consecutively contains all functions that are to be made available externally, with the function's name as it should appear in PHP and its name as defined in the C source. Internally, zend_function_entry is defined as shown in Listing 9.5.
Rysunek 31-2. Listing 9.5. Internal declaration of zend_function_entry.
typedef struct _zend_function_entry { char *fname; void (*handler)(INTERNAL_FUNCTION_PARAMETERS); unsigned char *func_arg_types; } zend_function_entry; |
Entry | Description |
fname | Denotes the function name as seen in PHP (for example, fopen, mysql_connect, or, in our example, first_module). |
handler | Pointer to the C function responsible for handling calls to this function. For example, see the standard macro INTERNAL_FUNCTION_PARAMETERS discussed earlier. |
func_arg_types | Allows you to mark certain parameters so that they're forced to be passed by reference. You usually should set this to NULL. |
zend_function_entry firstmod_functions[] = { ZEND_FE(first_module, NULL) {NULL, NULL, NULL} }; |
Notatka: You cannot use the predefined macros for the end marker, as these would try to refer to a function named "NULL"!
The macro ZEND_FE (short for 'Zend Function Entry') simply expands to a structure entry in zend_function_entry. Note that these macros introduce a special naming scheme to your functions - your C functions will be prefixed with zif_, meaning that ZEND_FE(first_module) will refer to a C function zif_first_module(). If you want to mix macro usage with hand-coded entries (not a good practice), keep this in mind.
Tip: Compilation errors that refer to functions named zif_*() relate to functions defined with ZEND_FE.
Table 9.2 shows a list of all the macros that you can use to define functions.
Rysunek 31-3. Table 9.2. Macros for Defining Functions
Macro Name | Description |
ZEND_FE(name, arg_types) | Defines a function entry of the name name in zend_function_entry. Requires a corresponding C function. arg_types needs to be set to NULL. This function uses automatic C function name generation by prefixing the PHP function name with zif_. For example, ZEND_FE("first_module", NULL) introduces a function first_module() to PHP and links it to the C function zif_first_module(). Use in conjunction with ZEND_FUNCTION. |
ZEND_NAMED_FE(php_name, name, arg_types) | Defines a function that will be available to PHP by the name php_name and links it to the corresponding C function name. arg_types needs to be set to NULL. Use this function if you don't want the automatic name prefixing introduced by ZEND_FE. Use in conjunction with ZEND_NAMED_FUNCTION. |
ZEND_FALIAS(name, alias, arg_types) | Defines an alias named alias for name. arg_types needs to be set to NULL. Doesn't require a corresponding C function; refers to the alias target instead. |
PHP_FE(name, arg_types) | Old PHP API equivalent of ZEND_FE. |
PHP_NAMED_FE(runtime_name, name, arg_types) | Old PHP API equivalent of ZEND_NAMED_FE. |
Note: You can't use ZEND_FE in conjunction with PHP_FUNCTION, or PHP_FE in conjunction with ZEND_FUNCTION. However, it's perfectly legal to mix ZEND_FE and ZEND_FUNCTION with PHP_FE and PHP_FUNCTION when staying with the same macro set for each function to be declared. But mixing is not recommended; instead, you're advised to use the ZEND_* macros only.
This block is stored in the structure zend_module_entry and contains all necessary information to describe the contents of this module to Zend. You can see the internal definition of this module in Listing 9.6.
Rysunek 31-4. Internal declaration of zend_module_entry.
typedef struct _zend_module_entry zend_module_entry; struct _zend_module_entry { unsigned short size; unsigned int zend_api; unsigned char zend_debug; unsigned char zts; char *name; zend_function_entry *functions; int (*module_startup_func)(INIT_FUNC_ARGS); int (*module_shutdown_func)(SHUTDOWN_FUNC_ARGS); int (*request_startup_func)(INIT_FUNC_ARGS); int (*request_shutdown_func)(SHUTDOWN_FUNC_ARGS); void (*info_func)(ZEND_MODULE_INFO_FUNC_ARGS); char *version; int (*global_startup_func)(void); int (*global_shutdown_func)(void); [ Rest of the structure is not interesting here ] }; |
Entry | Description |
---|---|
size, zend_api, zend_debug and zts | Usually filled with the "STANDARD_MODULE_HEADER", which fills these four members with the size of the whole zend_module_entry, the ZEND_MODULE_API_NO, whether it is a debug build or normal build (ZEND_DEBUG) and if ZTS is enabled (USING_ZTS). |
name | Contains the module name (for example, "File functions", "Socket functions", "Crypt", etc.). This name will show up in phpinfo(), in the section "Additional Modules." |
functions | Points to the Zend function block, discussed in the preceding section. |
module_startup_func | This function is called once upon module initialization and can be used to do one-time initialization steps (such as initial memory allocation, etc.). To indicate a failure during initialization, return FAILURE; otherwise, SUCCESS. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_MINIT. |
module_shutdown_func | This function is called once upon module shutdown and can be used to do one-time deinitialization steps (such as memory deallocation). This is the counterpart to module_startup_func(). To indicate a failure during deinitialization, return FAILURE; otherwise, SUCCESS. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_MSHUTDOWN. |
request_startup_func | This function is called once upon every page request and can be used to do one-time initialization steps that are required to process a request. To indicate a failure here, return FAILURE; otherwise, SUCCESS. Note: As dynamic loadable modules are loaded only on page requests, the request startup function is called right after the module startup function (both initialization events happen at the same time). To mark this field as unused, use NULL. To declare a function, use the macro ZEND_RINIT. |
request_shutdown_func | This function is called once after every page request and works as counterpart to request_startup_func(). To indicate a failure here, return FAILURE; otherwise, SUCCESS. Note: As dynamic loadable modules are loaded only on page requests, the request shutdown function is immediately followed by a call to the module shutdown handler (both deinitialization events happen at the same time). To mark this field as unused, use NULL. To declare a function, use the macro ZEND_RSHUTDOWN. |
info_func | When phpinfo() is called in a script, Zend cycles through all loaded modules and calls this function. Every module then has the chance to print its own "footprint" into the output page. Generally this is used to dump environmental or statistical information. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_MINFO. |
version | The version of the module. You can use NO_VERSION_YET if you don't want to give the module a version number yet, but we really recommend that you add a version string here. Such a version string can look like this (in chronological order): "2.5-dev", "2.5RC1", "2.5" or "2.5pl3". |
Remaining structure elements | These are used internally and can be prefilled by using the macro STANDARD_MODULE_PROPERTIES_EX. You should not assign any values to them. Use STANDARD_MODULE_PROPERTIES_EX only if you use global startup and shutdown functions; otherwise, use STANDARD_MODULE_PROPERTIES directly. |
In our example, this structure is implemented as follows:
zend_module_entry firstmod_module_entry = { STANDARD_MODULE_HEADER, "First Module", firstmod_functions, NULL, NULL, NULL, NULL, NULL, NO_VERSION_YET, STANDARD_MODULE_PROPERTIES, }; |
For reference purposes, you can find a list of the macros involved in declared startup and shutdown functions in Table 9.3. These are not used in our basic example yet, but will be demonstrated later on. You should make use of these macros to declare your startup and shutdown functions, as these require special arguments to be passed (INIT_FUNC_ARGS and SHUTDOWN_FUNC_ARGS), which are automatically included into the function declaration when using the predefined macros. If you declare your functions manually and the PHP developers decide that a change in the argument list is necessary, you'll have to change your module sources to remain compatible.
Rysunek 31-5. Macros to Declare Startup and Shutdown Functions
Macro | Description |
ZEND_MINIT(module) | Declares a function for module startup. The generated name will be zend_minit_<module> (for example, zend_minit_first_module). Use in conjunction with ZEND_MINIT_FUNCTION. |
ZEND_MSHUTDOWN(module) | Declares a function for module shutdown. The generated name will be zend_mshutdown_<module> (for example, zend_mshutdown_first_module). Use in conjunction with ZEND_MSHUTDOWN_FUNCTION. |
ZEND_RINIT(module) | Declares a function for request startup. The generated name will be zend_rinit_<module> (for example, zend_rinit_first_module). Use in conjunction with ZEND_RINIT_FUNCTION. |
ZEND_RSHUTDOWN(module) | Declares a function for request shutdown. The generated name will be zend_rshutdown_<module> (for example, zend_rshutdown_first_module). Use in conjunction with ZEND_RSHUTDOWN_FUNCTION. |
ZEND_MINFO(module) | Declares a function for printing module information, used when phpinfo() is called. The generated name will be zend_info_<module> (for example, zend_info_first_module). Use in conjunction with ZEND_MINFO_FUNCTION. |
This function is special to all dynamic loadable modules. Take a look at the creation via the ZEND_GET_MODULE macro first:
#if COMPILE_DL_FIRSTMOD ZEND_GET_MODULE(firstmod) #endif |
The function implementation is surrounded by a conditional compilation statement. This is needed since the function get_module() is only required if your module is built as a dynamic extension. By specifying a definition of COMPILE_DL_FIRSTMOD in the compiler command (see above for a discussion of the compilation instructions required to build a dynamic extension), you can instruct your module whether you intend to build it as a dynamic extension or as a built-in module. If you want a built-in module, the implementation of get_module() is simply left out.
get_module() is called by Zend at load time of the module. You can think of it as being invoked by the dl() call in your script. Its purpose is to pass the module information block back to Zend in order to inform the engine about the module contents.
If you don't implement a get_module() function in your dynamic loadable module, Zend will compliment you with an error message when trying to access it.
Implementing the exported functions is the final step. The example function in first_module looks like this:
ZEND_FUNCTION(first_module) { long parameter; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", ¶meter) == FAILURE) { return; } RETURN_LONG(parameter); } |
After the declaration, code for checking and retrieving the function's arguments, argument conversion, and return value generation follows (more on this later).
That's it, basically - there's nothing more to implementing PHP modules. Built-in modules are structured similarly to dynamic modules, so, equipped with the information presented in the previous sections, you'll be able to fight the odds when encountering PHP module source files.
Now, in the following sections, read on about how to make use of PHP's internals to build powerful extensions.
One of the most important issues for language extensions is accepting and dealing with data passed via arguments. Most extensions are built to deal with specific input data (or require parameters to perform their specific actions), and function arguments are the only real way to exchange data between the PHP level and the C level. Of course, there's also the possibility of exchanging data using predefined global values (which is also discussed later), but this should be avoided by all means, as it's extremely bad practice.
PHP doesn't make use of any formal function declarations; this is why call syntax is always completely dynamic and never checked for errors. Checking for correct call syntax is left to the user code. For example, it's possible to call a function using only one argument at one time and four arguments the next time - both invocations are syntactically absolutely correct.
Since PHP doesn't have formal function definitions with support for call syntax checking, and since PHP features variable arguments, sometimes you need to find out with how many arguments your function has been called. You can use the ZEND_NUM_ARGS macro in this case. In previous versions of PHP, this macro retrieved the number of arguments with which the function has been called based on the function's hash table entry, ht, which is passed in the INTERNAL_FUNCTION_PARAMETERS list. As ht itself now contains the number of arguments that have been passed to the function, ZEND_NUM_ARGS has been stripped down to a dummy macro (see its definition in zend_API.h). But it's still good practice to use it, to remain compatible with future changes in the call interface. Note: The old PHP equivalent of this macro is ARG_COUNT.
The following code checks for the correct number of arguments:
if(ZEND_NUM_ARGS() != 2) WRONG_PARAM_COUNT; |
This macro prints a default error message and then returns to the caller. Its definition can also be found in zend_API.h and looks like this:
ZEND_API void wrong_param_count(void); #define WRONG_PARAM_COUNT { wrong_param_count(); return; } |
New parameter parsing API: This chapter documents the new Zend parameter parsing API introduced by Andrei Zmievski. It was introduced in the development stage between PHP 4.0.6 and 4.1.0 .
Parsing parameters is a very common operation and it may get a bit tedious. It would also be nice to have standardized error checking and error messages. Since PHP 4.1.0, there is a way to do just that by using the new parameter parsing API. It greatly simplifies the process of receiving parameteres, but it has a drawback in that it can't be used for functions that expect variable number of parameters. But since the vast majority of functions do not fall into those categories, this parsing API is recommended as the new standard way.
The prototype for parameter parsing function looks like this:
int zend_parse_parameters(int num_args TSRMLS_DC, char *type_spec, ...); |
zend_parse_parameters() also performs type conversions whenever possible, so that you always receive the data in the format you asked for. Any type of scalar can be converted to another one, but conversions between complex types (arrays, objects, and resources) and scalar types are not allowed.
If the parameters could be obtained successfully and there were no errors during type conversion, the function will return SUCCESS, otherwise it will return FAILURE. The function will output informative error messages, if the number of received parameters does not match the requested number, or if type conversion could not be performed.
Here are some sample error messages:
Warning - ini_get_all() requires at most 1 parameter, 2 given Warning - wddx_deserialize() expects parameter 1 to be string, array given |
Here is the full list of type specifiers:
l - long
d - double
s - string (with possible null bytes) and its length
b - boolean
r - resource, stored in zval*
a - array, stored in zval*
o - object (of any class), stored in zval*
O - object (of class specified by class entry), stored in zval*
z - the actual zval*
| - indicates that the remaining parameters are optional. The storage variables corresponding to these parameters should be initialized to default values by the extension, since they will not be touched by the parsing function if the parameters are not passed.
/ - the parsing function will call SEPARATE_ZVAL_IF_NOT_REF() on the parameter it follows, to provide a copy of the parameter, unless it's a reference.
! - the parameter it follows can be of specified type or NULL (only applies to a, o, O, r, and z). If NULL value is passed by the user, the storage pointer will be set to NULL.
The best way to illustrate the usage of this function is through examples:
/* Gets a long, a string and its length, and a zval. */ long l; char *s; int s_len; zval *param; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lsz", &l, &s, &s_len, ¶m) == FAILURE) { return; } /* Gets an object of class specified by my_ce, and an optional double. */ zval *obj; double d = 0.5; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|d", &obj, my_ce, &d) == FAILURE) { return; } /* Gets an object or null, and an array. If null is passed for object, obj will be set to NULL. */ zval *obj; zval *arr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O!a", &obj, &arr) == FAILURE) { return; } /* Gets a separated array. */ zval *arr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a/", &arr) == FAILURE) { return; } /* Get only the first three parameters (useful for varargs functions). */ zval *z; zend_bool b; zval *r; if (zend_parse_parameters(3, "zbr!", &z, &b, &r) == FAILURE) { return; } |
Note that in the last example we pass 3 for the number of received parameters, instead of ZEND_NUM_ARGS(). What this lets us do is receive the least number of parameters if our function expects a variable number of them. Of course, if you want to operate on the rest of the parameters, you will have to use zend_get_parameters_array_ex() to obtain them.
The parsing function has an extended version that allows for an additional flags argument that controls its actions.
int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC, char *type_spec, ...); |
The only flag you can pass currently is ZEND_PARSE_PARAMS_QUIET, which instructs the function to not output any error messages during its operation. This is useful for functions that expect several sets of completely different arguments, but you will have to output your own error messages.
For example, here is how you would get either a set of three longs or a string:
long l1, l2, l3; char *s; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "lll", &l1, &l2, &l3) == SUCCESS) { /* manipulate longs */ } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "s", &s, &s_len) == SUCCESS) { /* manipulate string */ } else { php_error(E_WARNING, "%s() takes either three long values or a string as argument", get_active_function_name(TSRMLS_C)); return; } |
With all the abovementioned ways of receiving function parameters you should have a good handle on this process. For even more example, look through the source code for extensions that are shipped with PHP - they illustrate every conceivable situation.
Deprecated parameter parsing API: This API is deprecated and superseded by the new ZEND parameter parsing API.
After having checked the number of arguments, you need to get access to the arguments themselves. This is done with the help of zend_get_parameters_ex():
zval **parameter; if(zend_get_parameters_ex(1, ¶meter) != SUCCESS) WRONG_PARAM_COUNT; |
zend_get_parameters_ex() accepts at least two arguments. The first argument is the number of arguments to retrieve (which should match the number of arguments with which the function has been called; this is why it's important to check for correct call syntax). The second argument (and all following arguments) are pointers to pointers to pointers to zvals. (Confusing, isn't it?) All these pointers are required because Zend works internally with **zval; to adjust a local **zval in our function,zend_get_parameters_ex() requires a pointer to it.
The return value of zend_get_parameters_ex() can either be SUCCESS or FAILURE, indicating (unsurprisingly) success or failure of the argument processing. A failure is most likely related to an incorrect number of arguments being specified, in which case you should exit with WRONG_PARAM_COUNT.
To retrieve more than one argument, you can use a similar snippet:
zval **param1, **param2, **param3, **param4; if(zend_get_parameters_ex(4, ¶m1, ¶m2, ¶m3, ¶m4) != SUCCESS) WRONG_PARAM_COUNT; |
zend_get_parameters_ex() only checks whether you're trying to retrieve too many parameters. If the function is called with five arguments, but you're only retrieving three of them with zend_get_parameters_ex(), you won't get an error but will get the first three parameters instead. Subsequent calls of zend_get_parameters_ex() won't retrieve the remaining arguments, but will get the same arguments again.
If your function is meant to accept a variable number of arguments, the snippets just described are sometimes suboptimal solutions. You have to create a line calling zend_get_parameters_ex() for every possible number of arguments, which is often unsatisfying.
For this case, you can use the function zend_get_parameters_array_ex(), which accepts the number of parameters to retrieve and an array in which to store them:
zval **parameter_array[4]; /* get the number of arguments */ argument_count = ZEND_NUM_ARGS(); /* see if it satisfies our minimal request (2 arguments) */ /* and our maximal acceptance (4 arguments) */ if(argument_count < 2 || argument_count > 5) WRONG_PARAM_COUNT; /* argument count is correct, now retrieve arguments */ if(zend_get_parameters_array_ex(argument_count, parameter_array) != SUCCESS) WRONG_PARAM_COUNT; |
A very clever implementation of this can be found in the code handling PHP's fsockopen() located in ext/standard/fsock.c, as shown in Listing 9.7. Don't worry if you don't know all the functions used in this source yet; we'll get to them shortly.
Rysunek 32-2. Listing 9.7. PHP's implementation of variable arguments in fsockopen().
pval **args[5]; int *sock=emalloc(sizeof(int)); int *sockp; int arg_count=ARG_COUNT(ht); int socketd = -1; unsigned char udp = 0; struct timeval timeout = { 60, 0 }; unsigned short portno; unsigned long conv; char *key = NULL; FLS_FETCH(); if (arg_count > 5 || arg_count < 2 || zend_get_parameters_array_ex(arg_count,args)==FAILURE) { CLOSE_SOCK(1); WRONG_PARAM_COUNT; } switch(arg_count) { case 5: convert_to_double_ex(args[4]); conv = (unsigned long) (Z_DVAL_P(args[4]) * 1000000.0); timeout.tv_sec = conv / 1000000; timeout.tv_usec = conv % 1000000; /* fall-through */ case 4: if (!PZVAL_IS_REF(*args[3])) { php_error(E_WARNING,"error string argument to fsockopen not passed by reference"); } pval_copy_constructor(*args[3]); ZVAL_EMPTY_STRING(*args[3]); /* fall-through */ case 3: if (!PZVAL_IS_REF(*args[2])) { php_error(E_WARNING,"error argument to fsockopen not passed by reference"); return; } ZVAL_LONG(*args[2], 0); break; } convert_to_string_ex(args[0]); convert_to_long_ex(args[1]); portno = (unsigned short) Z_LVAL_P(args[1]); key = emalloc(Z_STRLEN_P(args[0]) + 10); |
fsockopen() accepts two, three, four, or five parameters. After the obligatory variable declarations, the function checks for the correct range of arguments. Then it uses a fall-through mechanism in a switch() statement to deal with all arguments. The switch() statement starts with the maximum number of arguments being passed (five). After that, it automatically processes the case of four arguments being passed, then three, by omitting the otherwise obligatory break keyword in all stages. After having processed the last case, it exits the switch() statement and does the minimal argument processing needed if the function is invoked with only two arguments.
This multiple-stage type of processing, similar to a stairway, allows convenient processing of a variable number of arguments.
To access arguments, it's necessary for each argument to have a clearly defined type. Again, PHP's extremely dynamic nature introduces some quirks. Because PHP never does any kind of type checking, it's possible for a caller to pass any kind of data to your functions, whether you want it or not. If you expect an integer, for example, the caller might pass an array, and vice versa - PHP simply won't notice.
To work around this, you have to use a set of API functions to force a type conversion on every argument that's being passed (see Table 9.4).
Note: All conversion functions expect a **zval as parameter.
Rysunek 32-3. Table 9.4. Argument Conversion Functions
Function | Description |
convert_to_boolean_ex() | Forces conversion to a Boolean type. Boolean values remain untouched. Longs, doubles, and strings containing 0 as well as NULL values will result in Boolean 0 (FALSE). Arrays and objects are converted based on the number of entries or properties, respectively, that they have. Empty arrays and objects are converted to FALSE; otherwise, to TRUE. All other values result in a Boolean 1 (TRUE). |
convert_to_long_ex() | Forces conversion to a long, the default integer type. NULL values, Booleans, resources, and of course longs remain untouched. Doubles are truncated. Strings containing an integer are converted to their corresponding numeric representation, otherwise resulting in 0. Arrays and objects are converted to 0 if empty, 1 otherwise. |
convert_to_double_ex() | Forces conversion to a double, the default floating-point type. NULL values, Booleans, resources, longs, and of course doubles remain untouched. Strings containing a number are converted to their corresponding numeric representation, otherwise resulting in 0.0. Arrays and objects are converted to 0.0 if empty, 1.0 otherwise. |
convert_to_string_ex() | Forces conversion to a string. Strings remain untouched. NULL values are converted to an empty string. Booleans containing TRUE are converted to "1", otherwise resulting in an empty string. Longs and doubles are converted to their corresponding string representation. Arrays are converted to the string "Array" and objects to the string "Object". |
convert_to_array_ex(value) | Forces conversion to an array. Arrays remain untouched. Objects are converted to an array by assigning all their properties to the array table. All property names are used as keys, property contents as values. NULL values are converted to an empty array. All other values are converted to an array that contains the specific source value in the element with the key 0. |
convert_to_object_ex(value) | Forces conversion to an object. Objects remain untouched. NULL values are converted to an empty object. Arrays are converted to objects by introducing their keys as properties into the objects and their values as corresponding property contents in the object. All other types result in an object with the property scalar , having the corresponding source value as content. |
convert_to_null_ex(value) | Forces the type to become a NULL value, meaning empty. |
Notatka: You can find a demonstration of the behavior in cross_conversion.php on the accompanying CD-ROM. Figure 9.5 shows the output.
Using these functions on your arguments will ensure type safety for all data that's passed to you. If the supplied type doesn't match the required type, PHP forces dummy contents on the resulting value (empty strings, arrays, or objects, 0 for numeric values, FALSE for Booleans) to ensure a defined state.
Following is a quote from the sample module discussed previously, which makes use of the conversion functions:
zval **parameter; if((ZEND_NUM_ARGS() != 1) || (zend_get_parameters_ex(1, ¶meter) != SUCCESS)) { WRONG_PARAM_COUNT; } convert_to_long_ex(parameter); RETURN_LONG(Z_LVAL_P(parameter)); |
Rysunek 32-5. Listing 9.8. PHP/Zend zval type definition.
typedef pval zval; typedef struct _zval_struct zval; typedef union _zvalue_value { long lval; /* long value */ double dval; /* double value */ struct { char *val; int len; } str; HashTable *ht; /* hash table value */ struct { zend_class_entry *ce; HashTable *properties; } obj; } zvalue_value; struct _zval_struct { /* Variable information */ zvalue_value value; /* value */ unsigned char type; /* active type */ unsigned char is_ref; short refcount; }; |
Actually, pval (defined in php.h) is only an alias of zval (defined in zend.h), which in turn refers to _zval_struct. This is a most interesting structure. _zval_struct is the "master" structure, containing the value structure, type, and reference information. The substructure zvalue_value is a union that contains the variable's contents. Depending on the variable's type, you'll have to access different members of this union. For a description of both structures, see Tables 9.5, 9.6, and 9.7.
Rysunek 32-6. Table 9.5. Zend zval Structure
Entry | Description |
value | Union containing this variable's contents. See Table 9.6 for a description. |
type | Contains this variable's type. For a list of available types, see Table 9.7. |
is_ref | 0 means that this variable is not a reference; 1 means that this variable is a reference to another variable. |
refcount | The number of references that exist for this variable. For every new reference to the value stored in this variable, this counter is increased by 1. For every lost reference, this counter is decreased by 1. When the reference counter reaches 0, no references exist to this value anymore, which causes automatic freeing of the value. |
Rysunek 32-7. Table 9.6. Zend zvalue_value Structure
Entry | Description |
lval | Use this property if the variable is of the type IS_LONG, IS_BOOLEAN, or IS_RESOURCE. |
dval | Use this property if the variable is of the type IS_DOUBLE. |
str | This structure can be used to access variables of the type IS_STRING. The member len contains the string length; the member val points to the string itself. Zend uses C strings; thus, the string length contains a trailing 0x00. |
ht | This entry points to the variable's hash table entry if the variable is an array. |
obj | Use this property if the variable is of the type IS_OBJECT. |
Rysunek 32-8. Table 9.7. Zend Variable Type Constants
Constant | Description |
IS_NULL | Denotes a NULL (empty) value. |
IS_LONG | A long (integer) value. |
IS_DOUBLE | A double (floating point) value. |
IS_STRING | A string. |
IS_ARRAY | Denotes an array. |
IS_OBJECT | An object. |
IS_BOOL | A Boolean value. |
IS_RESOURCE | A resource (for a discussion of resources, see the appropriate section below). |
IS_CONSTANT | A constant (defined) value. |
To access a long you access zval.value.lval, to access a double you use zval.value.dval, and so on. Because all values are stored in a union, trying to access data with incorrect union members results in meaningless output.
Accessing arrays and objects is a bit more complicated and is discussed later.
If your function accepts arguments passed by reference that you intend to modify, you need to take some precautions.
What we didn't say yet is that under the circumstances presented so far, you don't have write access to any zval containers designating function parameters that have been passed to you. Of course, you can change any zval containers that you created within your function, but you mustn't change any zvals that refer to Zend-internal data!
We've only discussed the so-called *_ex() API so far. You may have noticed that the API functions we've used are called zend_get_parameters_ex() instead of zend_get_parameters(), convert_to_long_ex() instead of convert_to_long(), etc. The *_ex() functions form the so-called new "extended" Zend API. They give a minor speed increase over the old API, but as a tradeoff are only meant for providing read-only access.
Because Zend works internally with references, different variables may reference the same value. Write access to a zval container requires this container to contain an isolated value, meaning a value that's not referenced by any other containers. If a zval container were referenced by other containers and you changed the referenced zval, you would automatically change the contents of the other containers referencing this zval (because they'd simply point to the changed value and thus change their own value as well).
zend_get_parameters_ex() doesn't care about this situation, but simply returns a pointer to the desired zval containers, whether they consist of references or not. Its corresponding function in the traditional API, zend_get_parameters(), immediately checks for referenced values. If it finds a reference, it creates a new, isolated zval container; copies the referenced data into this newly allocated space; and then returns a pointer to the new, isolated value.
This action is called zval separation (or pval separation). Because the *_ex() API doesn't perform zval separation, it's considerably faster, while at the same time disabling write access.
To change parameters, however, write access is required. Zend deals with this situation in a special way: Whenever a parameter to a function is passed by reference, it performs automatic zval separation. This means that whenever you're calling a function like this in PHP, Zend will automatically ensure that $parameter is being passed as an isolated value, rendering it to a write-safe state:
my_function(&$parameter); |
But this is not the case with regular parameters! All other parameters that are not passed by reference are in a read-only state.
This requires you to make sure that you're really working with a reference - otherwise you might produce unwanted results. To check for a parameter being passed by reference, you can use the macro PZVAL_IS_REF. This macro accepts a zval* to check if it is a reference or not. Examples are given in in Listing 9.6 and Figure 9.9 (see the CD-ROM for the full source).
Rysunek 32-9. Listing 9.6. Testing for referenced parameter passing.
zval *parameter; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", ¶meter) == FAILURE) return; /* check for parameter being passed by reference */ if (!PZVAL_IS_REF(*parameter)) { { zend_error(E_WARNING, "Parameter wasn't passed by reference"); RETURN_NULL(); } /* make changes to the parameter */ ZVAL_LONG(*parameter, 10); |
You might run into a situation in which you need write access to a parameter that's retrieved with zend_get_parameters_ex() but not passed by reference. For this case, you can use the macro SEPARATE_ZVAL, which does a zval separation on the provided container. The newly generated zval is detached from internal data and has only a local scope, meaning that it can be changed or destroyed without implying global changes in the script context:
zval **parameter; /* retrieve parameter */ zend_get_parameters_ex(1, ¶meter); /* at this stage, <parameter> still is connected */ /* to Zend's internal data buffers */ /* make <parameter> write-safe */ SEPARATE_ZVAL(parameter); /* now we can safely modify <parameter> */ /* without implying global changes */ |
Note: As you can easily work around the lack of write access in the "traditional" API (with zend_get_parameters() and so on), this API seems to be obsolete, and is not discussed further in this chapter.
When exchanging data from your own extensions with PHP scripts, one of the most important issues is the creation of variables. This section shows you how to deal with the variable types that PHP supports.
To create new variables that can be seen "from the outside" by the executing script, you need to allocate a new zval container, fill this container with meaningful values, and then introduce it to Zend's internal symbol table. This basic process is common to all variable creations:
zval *new_variable; /* allocate and initialize new container */ MAKE_STD_ZVAL(new_variable); /* set type and variable contents here, see the following sections */ /* introduce this variable by the name "new_variable_name" into the symbol table */ ZEND_SET_SYMBOL(EG(active_symbol_table), "new_variable_name", new_variable); /* the variable is now accessible to the script by using $new_variable_name */ |
The macro MAKE_STD_ZVAL allocates a new zval container using ALLOC_ZVAL and initializes it using INIT_ZVAL. As implemented in Zend at the time of this writing, initializing means setting the reference count to 1 and clearing the is_ref flag, but this process could be extended later - this is why it's a good idea to keep using MAKE_STD_ZVAL instead of only using ALLOC_ZVAL. If you want to optimize for speed (and you don't have to explicitly initialize the zval container here), you can use ALLOC_ZVAL, but this isn't recommended because it doesn't ensure data integrity.
ZEND_SET_SYMBOL takes care of introducing the new variable to Zend's symbol table. This macro checks whether the value already exists in the symbol table and converts the new symbol to a reference if so (with automatic deallocation of the old zval container). This is the preferred method if speed is not a crucial issue and you'd like to keep memory usage low.
Note that ZEND_SET_SYMBOL makes use of the Zend executor globals via the macro EG. By specifying EG(active_symbol_table), you get access to the currently active symbol table, dealing with the active, local scope. The local scope may differ depending on whether the function was invoked from within a function.
If you need to optimize for speed and don't care about optimal memory usage, you can omit the check for an existing variable with the same value and instead force insertion into the symbol table by using zend_hash_update():
zval *new_variable; /* allocate and initialize new container */ MAKE_STD_ZVAL(new_variable); /* set type and variable contents here, see the following sections */ /* introduce this variable by the name "new_variable_name" into the symbol table */ zend_hash_update( EG(active_symbol_table), "new_variable_name", strlen("new_variable_name") + 1, &new_variable, sizeof(zval *), NULL ); |
The variables generated with the snippet above will always be of local scope, so they reside in the context in which the function has been called. To create new variables in the global scope, use the same method but refer to another symbol table:
zval *new_variable; // allocate and initialize new container MAKE_STD_ZVAL(new_variable); // // set type and variable contents here // // introduce this variable by the name "new_variable_name" into the global symbol table ZEND_SET_SYMBOL(&EG(symbol_table), "new_variable_name", new_variable); |
Note: The active_symbol_table variable is a pointer, but symbol_table is not. This is why you have to use EG(active_symbol_table) and &EG(symbol_table) as parameters to ZEND_SET_SYMBOL - it requires a pointer.
Similarly, to get a more efficient version, you can hardcode the symbol table update:
zval *new_variable; // allocate and initialize new container MAKE_STD_ZVAL(new_variable); // // set type and variable contents here // // introduce this variable by the name "new_variable_name" into the global symbol table zend_hash_update( &EG(symbol_table), "new_variable_name", strlen("new_variable_name") + 1, &new_variable, sizeof(zval *), NULL ); |
Note: You can see that the global variable is actually not accessible from within the function. This is because it's not imported into the local scope using global $global_variable; in the PHP source.
Rysunek 33-1. Listing 9.10. Creating variables with different scopes.
ZEND_FUNCTION(variable_creation) { zval *new_var1, *new_var2; MAKE_STD_ZVAL(new_var1); MAKE_STD_ZVAL(new_var2); ZVAL_LONG(new_var1, 10); ZVAL_LONG(new_var2, 5); ZEND_SET_SYMBOL(EG(active_symbol_table), "local_variable", new_var1); ZEND_SET_SYMBOL(&EG(symbol_table), "global_variable", new_var2); RETURN_NULL(); } |
Now let's get to the assignment of data to variables, starting with longs. Longs are PHP's integers and are very simple to store. Looking at the zval.value container structure discussed earlier in this chapter, you can see that the long data type is directly contained in the union, namely in the lval field. The corresponding type value for longs is IS_LONG (see Listing 9.11).
Rysunek 33-2. Listing 9.11. Creation of a long.
zval *new_long; MAKE_STD_ZVAL(new_long); new_long->type = IS_LONG; new_long->value.lval = 10; |
zval *new_long; MAKE_STD_ZVAL(new_long); ZVAL_LONG(new_long, 10); |
Doubles are PHP's floats and are as easy to assign as longs, because their value is also contained directly in the union. The member in the zval.value container is dval; the corresponding type is IS_DOUBLE.
zval *new_double; MAKE_STD_ZVAL(new_double); new_double->type = IS_DOUBLE; new_double->value.dval = 3.45; |
zval *new_double; MAKE_STD_ZVAL(new_double); ZVAL_DOUBLE(new_double, 3.45); |
Strings need slightly more effort. As mentioned earlier, all strings that will be associated with Zend's internal data structures need to be allocated using Zend's own memory-management functions. Referencing of static strings or strings allocated with standard routines is not allowed. To assign strings, you have to access the structure str in the zval.value container. The corresponding type is IS_STRING:
zval *new_string; char *string_contents = "This is a new string variable"; MAKE_STD_ZVAL(new_string); new_string->type = IS_STRING; new_string->value.str.len = strlen(string_contents); new_string->value.str.val = estrdup(string_contents); |
zval *new_string; char *string_contents = "This is a new string variable"; MAKE_STD_ZVAL(new_string); ZVAL_STRING(new_string, string_contents, 1); |
If you want to truncate the string at a certain position or you already know its length, you can use ZVAL_STRINGL(zval, string, length, duplicate), which accepts an explicit string length to be set for the new string. This macro is faster than ZVAL_STRING and also binary-safe.
To create empty strings, set the string length to 0 and use empty_string as contents:
new_string->type = IS_STRING; new_string->value.str.len = 0; new_string->value.str.val = empty_string; |
MAKE_STD_ZVAL(new_string); ZVAL_EMPTY_STRING(new_string); |
Booleans are created just like longs, but have the type IS_BOOL. Allowed values in lval are 0 and 1:
zval *new_bool; MAKE_STD_ZVAL(new_bool); new_bool->type = IS_BOOL; new_bool->value.lval = 1; |
Arrays are stored using Zend's internal hash tables, which can be accessed using the zend_hash_*() API. For every array that you want to create, you need a new hash table handle, which will be stored in the ht member of the zval.value container.
There's a whole API solely for the creation of arrays, which is extremely handy. To start a new array, you call array_init().
zval *new_array; MAKE_STD_ZVAL(new_array); if(array_init(new_array) != SUCCESS) { // do error handling here } |
To add new elements to the array, you can use numerous functions, depending on what you want to do. Tables 9.8, 9.9, and 9.10 describe these functions. All functions return FAILURE on failure and SUCCESS on success.
Rysunek 33-3. Table 9.8. Zend's API for Associative Arrays
Note: The functions in Table 9.8 all operate on the array "array" with the key "key". The key string doesn't have to reside in Zend internal memory; it will be duplicated by the API. |
Function | Description |
add_assoc_long(zval *array, char *key, long n);() | Adds an element of type long. |
add_assoc_unset(zval *array, char *key);() | Adds an unset element. |
add_assoc_bool(zval *array, char *key, int b);() | Adds a Boolean element. |
add_assoc_resource(zval *array, char *key, int r);() | Adds a resource to the array. |
add_assoc_double(zval *array, char *key, double d);() | Adds a floating-point value. |
add_assoc_string(zval *array, char *key, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory. |
add_assoc_stringl(zval *array, char *key, char *str, uint length, int duplicate); () | Adds a string with the desired length length to the array. Otherwise, behaves like add_assoc_string(). |
Rysunek 33-4. Table 9.9. Zend's API for Indexed Arrays, Part 1
Note: The functions in Table 9.9 all operate on the array "array" with the index "idx". The index is always an integer. |
Function | Description |
add_index_long(zval *array, uint idx, long n);() | Adds an element of type long. |
add_index_unset(zval *array, uint idx);() | Adds an unset element. |
add_index_bool(zval *array, uint idx, int b);() | Adds a Boolean element. |
add_index_resource(zval *array, uint idx, int r);() | Adds a resource to the array. |
add_index_double(zval *array, uint idx, double d);() | Adds a floating-point value. |
add_index_string(zval *array, uint idx, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory. |
add_index_stringl(zval *array, uint idx, char *str, uint length, int duplicate);() | Adds a string with the desired length length to the array. This function is faster and binary-safe. Otherwise, behaves like add_index_string()(). |
Rysunek 33-5. Table 9.10. Zend's API for Indexed Arrays, Part 2
Note: The functions in Table 9.10 all operate on the array "array". These functions automatically generate a new index based on the highest index found in the array. |
Function | Description |
add_next_index_long(zval *array, long n);() | Adds an element of type long. |
add_next_index_unset(zval *array);() | Adds an unset element. |
add_next_index_bool(zval *array, int b);() | Adds a Boolean element. |
add_next_index_resource(zval *array, int r);() | Adds a resource to the array. |
add_next_index_double(zval *array, double d);() | Adds a floating-point value. |
add_next_index_string(zval *array, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory. |
add_next_index_stringl(zval *array, char *str, uint length, int duplicate);() | Adds a string with the desired length length to the array. This function is faster and binary-safe. Otherwise, behaves like add_index_string()(). |
All these functions provide a handy abstraction to Zend's internal hash API. Of course, you can also use the hash functions directly - for example, if you already have a zval container allocated that you want to insert into an array. This is done using zend_hash_update()() for associative arrays (see Listing 9.12) and zend_hash_index_update() for indexed arrays (see Listing 9.13):
Rysunek 33-6. Listing 9.12. Adding an element to an associative array.
zval *new_array, *new_element; char *key = "element_key"; MAKE_STD_ZVAL(new_array); MAKE_STD_ZVAL(new_element); if(array_init(new_array) == FAILURE) { // do error handling here } ZVAL_LONG(new_element, 10); if(zend_hash_update(new_array->value.ht, key, strlen(key) + 1, (void *)&new_element, sizeof(zval *), NULL) == FAILURE) { // do error handling here } |
Rysunek 33-7. Listing 9.13. Adding an element to an indexed array.
zval *new_array, *new_element; int key = 2; MAKE_STD_ZVAL(new_array); MAKE_STD_ZVAL(new_element); if(array_init(new_array) == FAILURE) { // do error handling here } ZVAL_LONG(new_element, 10); if(zend_hash_index_update(new_array->value.ht, key, (void *)&new_element, sizeof(zval *), NULL) == FAILURE) { // do error handling here } |
To emulate the functionality of add_next_index_*(), you can use this:
zend_hash_next_index_insert(ht, zval **new_element, sizeof(zval *), NULL) |
Note: To return arrays from a function, use array_init() and all following actions on the predefined variable return_value (given as argument to your exported function; see the earlier discussion of the call interface). You do not have to use MAKE_STD_ZVAL on this.
Tip: To avoid having to write new_array->value.ht every time, you can use HASH_OF(new_array), which is also recommended for compatibility and style reasons.
Since objects can be converted to arrays (and vice versa), you might have already guessed that they have a lot of similarities to arrays in PHP. Objects are maintained with the same hash functions, but there's a different API for creating them.
To initialize an object, you use the function object_init():
zval *new_object; MAKE_STD_ZVAL(new_object); if(object_init(new_object) != SUCCESS) { // do error handling here } |
Rysunek 33-8. Table 9.11. Zend's API for Object Creation
Note: All functions in Table 9.11 work on the object "object" with the key "key". The key forms the member name, so the resulting member can be accessed via $object->key. |
Function | Description |
add_property_long(zval *object, char *key, long l);() | Adds a long to the object. |
add_property_unset(zval *object, char *key);() | Adds an unset property to the object. |
add_property_bool(zval *object, char *key, int b);() | Adds a Boolean to the object. |
add_property_resource(zval *object, char *key, long r);() | Adds a resource to the object. |
add_property_double(zval *object, char *key, double d);() | Adds a double to the object. |
add_property_string(zval *object, char *key, char *str, int duplicate);() | Adds a string to the object. |
add_property_stringl(zval *object, char *key, char *str, uint length, int duplicate);() | Adds a string of the specified length to the object. This function is faster than add_property_string() and also binary-safe. |
add_property_zval(zval *obect, char *key, zval *container):() | Adds a zval container to the object. This is useful if you have to add properties which aren't simple types like integers or strings but arrays or other objects. |
Resources are a special kind of data type in PHP. The term resources doesn't really refer to any special kind of data, but to an abstraction method for maintaining any kind of information. Resources are kept in a special resource list within Zend. Each entry in the list has a correspondending type definition that denotes the kind of resource to which it refers. Zend then internally manages all references to this resource. Access to a resource is never possible directly - only via a provided API. As soon as all references to a specific resource are lost, a corresponding shutdown function is called.
For example, resources are used to store database links and file descriptors. The de facto standard implementation can be found in the MySQL module, but other modules such as the Oracle module also make use of resources.
Notatka: In fact, a resource can be a pointer to anything you need to handle in your functions (e.g. pointer to a structure) and the user only has to pass a single resource variable to your function.
To create a new resource you need to register a resource destruction handler for it. Since you can store any kind of data as a resource, Zend needs to know how to free this resource if its not longer needed. This works by registering your own resource destruction handler to Zend which in turn gets called by Zend whenever your resource can be freed (whether manually or automatically). Registering your resource handler within Zend returns you the resource type handle for that resource. This handle is needed whenever you want to access a resource of this type later and is most of time stored in a global static variable within your extension. There is no need to worry about thread safety here because you only register your resource handler once during module initialization.
The Zend function to register your resource handler is defined as:
ZEND_API int zend_register_list_destructors_ex(rsrc_dtor_func_t ld, rsrc_dtor_func_t pld, char *type_name, int module_number); |
There are two different kinds of resource destruction handlers you can pass to this function: a handler for normal resources and a handler for persistent resources. Persistent resources are for example used for database connection. When registering a resource, either of these handlers must be given. For the other handler just pass NULL.
zend_register_list_destructors_ex() accepts the following parameters:
ld | Normal resource destruction handler callback |
pld | Pesistent resource destruction handler callback |
type_name | A string specifying the name of your resource. It's always a good thing to specify an unique name within PHP for the resource type so when the user for example calls var_dump($resource); he also gets the name of the resource. |
module_number | The module_number is automatically available in your PHP_MINIT_FUNCTION function and therefore you just pass it over. |
The resource destruction handler (either normal or persistent resources) has the following prototype:
void resource_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC); |
typedef struct _zend_rsrc_list_entry { void *ptr; int type; int refcount; } zend_rsrc_list_entry; |
Now we know how to start things, we define our own resource we want register within Zend. It is only a simple structure with two integer members:
typedef struct { int resource_link; int resource_type; } my_resource; |
void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) { // You most likely cast the void pointer to your structure type my_resource *my_rsrc = (my_resource *) rsrc->ptr; // Now do whatever needs to be done with you resource. Closing // Files, Sockets, freeing additional memory, etc. // Also, don't forget to actually free the memory for your resource too! do_whatever_needs_to_be_done_with_the_resource(my_rsrc); } |
Notatka: One important thing to mention: If your resource is a rather complex structure which also contains pointers to memory you allocated during runtime you have to free them before freeing the resource itself!
Now that we have defined
what our resource is and
our resource destruction handler
create a global variable within the extension holding the resource ID so it can be accessed from every function which needs it
define the resource name
write the resource destruction handler
and finally register the handler
// Somewhere in your extension, define the variable for your registered resources. // If you wondered what 'le' stands for: it simply means 'list entry'. static int le_myresource; // It's nice to define your resource name somewhere #define le_myresource_name "My type of resource" [...] // Now actually define our resource destruction handler void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) { my_resource *my_rsrc = (my_resource *) rsrc->ptr; do_whatever_needs_to_be_done_with_the_resource(my_rsrc); } [...] PHP_MINIT_FUNCTION(my_extension) { // Note that 'module_number' is already provided through the // PHP_MINIT_FUNCTION() function definition. le_myresource = zend_register_resource_destructors_ex(my_destruction_handler, NULL, le_myresource_name, module_number); // You can register additional resources, initialize // your global vars, constants, whatever. } |
To actually register a new resource you use can either use the zend_register_resource() function or the ZEND_REGISTER_RESOURE() macro, both defined in zend_list.h . Although the arguments for both map 1:1 it's a good idea to always use macros to be upwards compatible:
int ZEND_REGISTER_RESOURCE(zval *rsrc_result, void *rsrc_pointer, int rsrc_type); |
rsrc_result | This is an already initialized zval * container. |
rsrc_pointer | Your resource pointer you want to store. |
rsrc_type | The type which you received when you registered the resource destruction handler. If you followed the naming scheme this would be le_myresource. |
What is really going on when you register a new resource is it gets inserted in an internal list in Zend and the result is just stored in the given zval * container:
rsrc_id = zend_list_insert(rsrc_pointer, rsrc_type); if (rsrc_result) { rsrc_result->value.lval = rsrc_id; rsrc_result->type = IS_RESOURCE; } return rsrc_id; |
RETURN_RESOURCE(rsrc_id) |
Notatka: It is common practice that if you want to return the resource immidiately to the user you specify the return_value as the zval * container.
Zend now keeps track of all references to this resource. As soon as all references to the resource are lost, the destructor that you previously registered for this resource is called. The nice thing about this setup is that you don't have to worry about memory leakages introduced by allocations in your module - just register all memory allocations that your calling script will refer to as resources. As soon as the script decides it doesn't need them anymore, Zend will find out and tell you.
Now that the user got his resource, at some point he is passing it back to one of your functions. The value.lval inside the zval * container contains the key to your resource and thus can be used to fetch the resource with the following macro: ZEND_FETCH_RESOURCE:
ZEND_FETCH_RESOURCE(rsrc, rsrc_type, rsrc_id, default_rsrc_id, resource_type_name, resource_type) |
rsrc | This is your pointer which will point to your previously registered resource. |
rsrc_type | This is the typecast argument for your pointer, e.g. myresource *. |
rsrc_id | This is the address of the zval *container the user passed to your function, e.g. &z_resource if zval *z_resource is given. |
default_rsrc_id | This integer specifies the default resource ID if no resource could be fetched or -1. |
resource_type_name | This is the name of the requested resource. It's a string and is used when the resource can't be found or is invalid to form a meaningful error message. |
resource_type | The resource_type you got back when registering the resource destruction handler. In our example this was le_myresource. |
To force removal of a resource from the list, use the function zend_list_delete(). You can also force the reference count to increase if you know that you're creating another reference for a previously allocated value (for example, if you're automatically reusing a default database link). For this case, use the function zend_list_addref(). To search for previously allocated resource entries, use zend_list_find(). The complete API can be found in zend_list.h.
In addition to the macros discussed earlier, a few macros allow easy creation of simple global variables. These are nice to know in case you want to introduce global flags, for example. This is somewhat bad practice, but Table 9.12 describes macros that do exactly this task. They don't need any zval allocation; you simply have to supply a variable name and value.
Rysunek 33-9. Table 9.12. Macros for Global Variable Creation
Note: All macros in Table 9.12 create a global variable of the name "name" with the value "value". |
Macro | Description |
SET_VAR_STRING(name, value) | Creates a new string. |
SET_VAR_STRINGL(name, value, length) | Creates a new string of the specified length. This macro is faster than SET_VAR_STRING and also binary-safe. |
SET_VAR_LONG(name, value) | Creates a new long. |
SET_VAR_DOUBLE(name, value) | Creates a new double. |
Zend supports the creation of true constants (as opposed to regular variables). Constants are accessed without the typical dollar sign ($) prefix and are available in all scopes. Examples include TRUE and FALSE, to name just two.
To create your own constants, you can use the macros in Table 9.13. All the macros create a constant with the specified name and value.
You can also specify flags for each constant:
CONST_CS - This constant's name is to be treated as case sensitive.
CONST_PERSISTENT - This constant is persistent and won't be "forgotten" when the current process carrying this constant shuts down.
// register a new constant of type "long" REGISTER_LONG_CONSTANT("NEW_MEANINGFUL_CONSTANT", 324, CONST_CS | CONST_PERSISTENT); |
Rysunek 33-10. Table 9.13. Macros for Creating Constants
Macro | Description |
REGISTER_LONG_CONSTANT(name, value, flags) REGISTER_MAIN_LONG_CONSTANT(name, value, flags) | Registers a new constant of type long. |
REGISTER_DOUBLE_CONSTANT(name, value, flags) REGISTER_MAIN_DOUBLE_CONSTANT(name, value, flags) | Registers a new constant of type double. |
REGISTER_STRING_CONSTANT(name, value, flags) REGISTER_MAIN_STRING_CONSTANT(name, value, flags) | Registers a new constant of type string. The specified string must reside in Zend's internal memory. |
REGISTER_STRINGL_CONSTANT(name, value, length, flags) REGISTER_MAIN_STRINGL_CONSTANT(name, value, length, flags) | Registers a new constant of type string. The string length is explicitly set to length. The specified string must reside in Zend's internal memory. |
Sooner or later, you may need to assign the contents of one zval container to another. This is easier said than done, since the zval container doesn't contain only type information, but also references to places in Zend's internal data. For example, depending on their size, arrays and objects may be nested with lots of hash table entries. By assigning one zval to another, you avoid duplicating the hash table entries, using only a reference to them (at most).
To copy this complex kind of data, use the copy constructor. Copy constructors are typically defined in languages that support operator overloading, with the express purpose of copying complex types. If you define an object in such a language, you have the possibility of overloading the "=" operator, which is usually responsible for assigning the contents of the lvalue (result of the evaluation of the left side of the operator) to the rvalue (same for the right side).
Overloading means assigning a different meaning to this operator, and is usually used to assign a function call to an operator. Whenever this operator would be used on such an object in a program, this function would be called with the lvalue and rvalue as parameters. Equipped with that information, it can perform the operation it intends the "=" operator to have (usually an extended form of copying).
This same form of "extended copying" is also necessary for PHP's zval containers. Again, in the case of an array, this extended copying would imply re-creation of all hash table entries relating to this array. For strings, proper memory allocation would have to be assured, and so on.
Zend ships with such a function, called zend_copy_ctor() (the previous PHP equivalent was pval_copy_constructor()).
A most useful demonstration is a function that accepts a complex type as argument, modifies it, and then returns the argument:
zval *parameter; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", ¶meter) == FAILURE) return; } // do modifications to the parameter here // now we want to return the modified container: *return_value == *parameter; zval_copy_ctor(return_value); |
The first part of the function is plain-vanilla argument retrieval. After the (left out) modifications, however, it gets interesting: The container of parameter is assigned to the (predefined) return_value container. Now, in order to effectively duplicate its contents, the copy constructor is called. The copy constructor works directly with the supplied argument, and the standard return values are FAILURE on failure and SUCCESS on success.
If you omit the call to the copy constructor in this example, both parameter and return_value would point to the same internal data, meaning that return_value would be an illegal additional reference to the same data structures. Whenever changes occurred in the data that parameter points to, return_value might be affected. Thus, in order to create separate copies, the copy constructor must be used.
The copy constructor's counterpart in the Zend API, the destructor zval_dtor(), does the opposite of the constructor.
Returning values from your functions to PHP was described briefly in an earlier section; this section gives the details. Return values are passed via the return_value variable, which is passed to your functions as argument. The return_value argument consists of a zval container (see the earlier discussion of the call interface) that you can freely modify. The container itself is already allocated, so you don't have to run MAKE_STD_ZVAL on it. Instead, you can access its members directly.
To make returning values from functions easier and to prevent hassles with accessing the internal structures of the zval container, a set of predefined macros is available (as usual). These macros automatically set the correspondent type and value, as described in Tables 9.14 and 9.15.
Rysunek 35-1. Table 9.14. Predefined Macros for Returning Values from a Function
Note: The macros in Table 9.14 automatically return from your function. |
Macro | Description |
RETURN_RESOURCE(resource) | Returns a resource. |
RETURN_BOOL(bool) | Returns a Boolean. |
RETURN_NULL() | Returns nothing (a NULL value). |
RETURN_LONG(long) | Returns a long. |
RETURN_DOUBLE(double) | Returns a double. |
RETURN_STRING(string, duplicate) | Returns a string. The duplicate flag indicates whether the string should be duplicated using estrdup(). |
RETURN_STRINGL(string, length, duplicate) | Returns a string of the specified length; otherwise, behaves like RETURN_STRING. This macro is faster and binary-safe, however. |
RETURN_EMPTY_STRING() | Returns an empty string. |
RETURN_FALSE | Returns Boolean false. |
RETURN_TRUE | Returns Boolean true. |
Rysunek 35-2. Table 9.15. Predefined Macros for Setting the Return Value of a Function
Note: The macros in Table 9.15 only set the
return value; they don't return from your function. |
Macro | Description |
RETVAL_RESOURCE(resource) | Sets the return value to the specified resource. |
RETVAL_BOOL(bool) | Sets the return value to the specified Boolean value. |
RETVAL_NULL | Sets the return value to NULL. |
RETVAL_LONG(long) | Sets the return value to the specified long. |
RETVAL_DOUBLE(double) | Sets the return value to the specified double. |
RETVAL_STRING(string, duplicate) | Sets the return value to the specified string and duplicates it to Zend internal memory if desired (see also RETURN_STRING). |
RETVAL_STRINGL(string, length, duplicate) | Sets the return value to the specified string and forces the length to become length (see also RETVAL_STRING). This macro is faster and binary-safe, and should be used whenever the string length is known. |
RETVAL_EMPTY_STRING | Sets the return value to an empty string. |
RETVAL_FALSE | Sets the return value to Boolean false. |
RETVAL_TRUE | Sets the return value to Boolean true. |
Complex types such as arrays and objects can be returned by using array_init() and object_init(), as well as the corresponding hash functions on return_value. Since these types cannot be constructed of trivial information, there are no predefined macros for them.
Often it's necessary to print messages to the output stream from your module, just as print() would be used within a script. PHP offers functions for most generic tasks, such as printing warning messages, generating output for phpinfo(), and so on. The following sections provide more details. Examples of these functions can be found on the CD-ROM.
zend_printf() works like the standard printf(), except that it prints to Zend's output stream.
zend_error() can be used to generate error messages. This function accepts two arguments; the first is the error type (see zend_errors.h), and the second is the error message.
zend_error(E_WARNING, "This function has been called with empty arguments"); |
Rysunek 36-1. Table 9.16. Zend's Predefined Error Messages.
Error | Description |
E_ERROR | Signals an error and terminates execution of the script immediately . |
E_WARNING | Signals a generic warning. Execution continues. |
E_PARSE | Signals a parser error. Execution continues. |
E_NOTICE | Signals a notice. Execution continues. Note that by default the display of this type of error messages is turned off in php.ini. |
E_CORE_ERROR | Internal error by the core; shouldn't be used by user-written modules. |
E_COMPILE_ERROR | Internal error by the compiler; shouldn't be used by user-written modules. |
E_COMPILE_WARNING | Internal warning by the compiler; shouldn't be used by user-written modules. |
After creating a real module, you'll want to show information about the module in phpinfo() (in addition to the module name, which appears in the module list by default). PHP allows you to create your own section in the phpinfo() output with the ZEND_MINFO() function. This function should be placed in the module descriptor block (discussed earlier) and is always called whenever a script calls phpinfo().
PHP automatically prints a section in phpinfo() for you if you specify the ZEND_MINFO function, including the module name in the heading. Everything else must be formatted and printed by you.
Typically, you can print an HTML table header using php_info_print_table_start() and then use the standard functions php_info_print_table_header() and php_info_print_table_row(). As arguments, both take the number of columns (as integers) and the column contents (as strings). Listing 9.14 shows a source example; Figure 9.9 shows the output. To print the table footer, use php_info_print_table_end().
Rysunek 36-3. Listing 9.14. Source code and screenshot for output in phpinfo().
php_info_print_table_start(); php_info_print_table_header(2, "First column", "Second column"); php_info_print_table_row(2, "Entry in first row", "Another entry"); php_info_print_table_row(2, "Just to fill", "another row here"); php_info_print_table_end(); |
You can also print execution information, such as the current file being executed. The name of the function currently being executed can be retrieved using the function get_active_function_name(). This function returns a pointer to the function name and doesn't accept any arguments. To retrieve the name of the file currently being executed, use zend_get_executed_filename(). This function accesses the executor globals, which are passed to it using the ELS_C macro. The executor globals are automatically available to every function that's called directly by Zend (they're part of the INTERNAL_FUNCTION_PARAMETERS described earlier in this chapter). If you want to access the executor globals in another function that doesn't have them available automatically, call the macro ELS_FETCH() once in that function; this will introduce them to your local scope.
Finally, the line number currently being executed can be retrieved using the function zend_get_executed_lineno(). This function also requires the executor globals as arguments. For examples of these functions, see Listing 9.15 and Figure 9.10. Of course, all the examples are also available on the CD-ROM.
Rysunek 36-4. Listing 9.15. Printing execution information.
zend_printf("The name of the current function is %s<br>", get_active_function_name()); zend_printf("The file currently executed is %s<br>", zend_get_executed_filename(ELS_C)); zend_printf("The current line being executed is %i<br>", zend_get_executed_lineno(ELS_C)); |
Startup and shutdown functions can be used for one-time initialization and deinitialization of your modules. As discussed earlier in this chapter (see the description of the Zend module descriptor block), there are global, module, and request startup and shutdown events.
The global startup functions are called once when PHP starts up; similarly, the global shutdown functions are called once when PHP shuts down. Please note that they're really only called once, not when a new Apache process is being created!
The module startup and shutdown functions are called whenever a module is loaded and needs initialization; the request startup and shutdown functions are called every time a request is processed (meaning that a file is being executed).
For dynamic extensions, module and request startup/shutdown events happen at the same time.
Declaration and implementation of these functions can be done with macros; see the earlier section "Declaration of the Zend Module Block" for details.
You can call user functions from your own modules, which is very handy when implementing callbacks; for example, for array walking, searching, or simply for event-based programs.
User functions can be called with the function call_user_function_ex(). It requires a hash value for the function table you want to access, a pointer to an object (if you want to call a method), the function name, return value, number of arguments, argument array, and a flag indicating whether you want to perform zval separation.
ZEND_API int call_user_function_ex(HashTable *function_table, zval *object, zval *function_name, zval **retval_ptr_ptr, int param_count, zval **params[], int no_separation); |
Note that you don't have to specify both function_table and object; either will do. If you want to call a method, you have to supply the object that contains this method, in which case call_user_function()automatically sets the function table to this object's function table. Otherwise, you only need to specify function_table and can set object to NULL.
Usually, the default function table is the "root" function table containing all function entries. This function table is part of the compiler globals and can be accessed using the macro CG. To introduce the compiler globals to your function, call the macro CLS_FETCH once.
The function name is specified in a zval container. This might be a bit surprising at first, but is quite a logical step, since most of the time you'll accept function names as parameters from calling functions within your script, which in turn are contained in zval containers again. Thus, you only have to pass your arguments through to this function. This zval must be of type IS_STRING.
The next argument consists of a pointer to the return value. You don't have to allocate memory for this container; the function will do so by itself. However, you have to destroy this container (using zval_dtor()) afterward!
Next is the parameter count as integer and an array containing all necessary parameters. The last argument specifies whether the function should perform zval separation - this should always be set to 0. If set to 1, the function consumes less memory but fails if any of the parameters need separation.
Listing 9.16 and Figure 9.11 show a small demonstration of calling a user function. The code calls a function that's supplied to it as argument and directly passes this function's return value through as its own return value. Note the use of the constructor and destructor calls at the end - it might not be necessary to do it this way here (since they should be separate values, the assignment might be safe), but this is bulletproof.
Rysunek 38-1. Listing 9.16. Calling user functions.
zval **function_name; zval *retval; if((ZEND_NUM_ARGS() != 1) || (zend_get_parameters_ex(1, &function_name) != SUCCESS)) { WRONG_PARAM_COUNT; } if((*function_name)->type != IS_STRING) { zend_error(E_ERROR, "Function requires string argument"); } CLS_FETCH(); if(call_user_function_ex(CG(function_table), NULL, *function_name, &retval, 0, NULL, 0) != SUCCESS) { zend_error(E_ERROR, "Function call failed"); } zend_printf("We have %i as type<br>", retval->type); *return_value = *retval; zval_copy_ctor(return_value); zval_ptr_dtor(&retval); |
<?php dl("call_userland.so"); function test_function() { print("We are in the test function!<br>"); return("hello"); } $return_value = call_userland("test_function"); print("Return value: \"$return_value\"<br>"); ?> |
PHP 4 features a redesigned initialization file support. It's now possible to specify default initialization entries directly in your code, read and change these values at runtime, and create message handlers for change notifications.
To create an .ini section in your own module, use the macros PHP_INI_BEGIN() to mark the beginning of such a section and PHP_INI_END() to mark its end. In between you can use PHP_INI_ENTRY() to create entries.
PHP_INI_BEGIN() PHP_INI_ENTRY("first_ini_entry", "has_string_value", PHP_INI_ALL, NULL) PHP_INI_ENTRY("second_ini_entry", "2", PHP_INI_SYSTEM, OnChangeSecond) PHP_INI_ENTRY("third_ini_entry", "xyz", PHP_INI_USER, NULL) PHP_INI_END() |
The permissions are grouped into three sections:PHP_INI_SYSTEM allows a change only directly in the php3.ini file; PHP_INI_USER allows a change to be overridden by a user at runtime using additional configuration files, such as .htaccess; and PHP_INI_ALL allows changes to be made without restrictions. There's also a fourth level, PHP_INI_PERDIR, for which we couldn't verify its behavior yet.
The fourth parameter consists of a pointer to a change-notification handler. Whenever one of these initialization entries is changed, this handler is called. Such a handler can be declared using the PHP_INI_MH macro:
PHP_INI_MH(OnChangeSecond); // handler for ini-entry "second_ini_entry" // specify ini-entries here PHP_INI_MH(OnChangeSecond) { zend_printf("Message caught, our ini entry has been changed to %s<br>", new_value); return(SUCCESS); } |
#define PHP_INI_MH(name) int name(php_ini_entry *entry, char *new_value, uint new_value_length, void *mh_arg1, void *mh_arg2, void *mh_arg3) |
The change-notification handlers should be used to cache initialization entries locally for faster access or to perform certain tasks that are required if a value changes. For example, if a constant connection to a certain host is required by a module and someone changes the hostname, automatically terminate the old connection and attempt a new one.
Access to initialization entries can also be handled with the macros shown in Table 9.17.
Rysunek 39-1. Table 9.17. Macros to Access Initialization Entries in PHP
Macro | Description |
INI_INT(name) | Returns the current value of entry name as integer (long). |
INI_FLT(name) | Returns the current value of entry name as float (double). |
INI_STR(name) | Returns the current value of entry name as string. Note: This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory. |
INI_BOOL(name) | Returns the current value of entry name as Boolean (defined as zend_bool, which currently means unsigned char). |
INI_ORIG_INT(name) | Returns the original value of entry name as integer (long). |
INI_ORIG_FLT(name) | Returns the original value of entry name as float (double). |
INI_ORIG_STR(name) | Returns the original value of entry name as string. Note: This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory. |
INI_ORIG_BOOL(name) | Returns the original value of entry name as Boolean (defined as zend_bool, which currently means unsigned char). |
Finally, you have to introduce your initialization entries to PHP. This can be done in the module startup and shutdown functions, using the macros REGISTER_INI_ENTRIES() and UNREGISTER_INI_ENTRIES():
ZEND_MINIT_FUNCTION(mymodule) { REGISTER_INI_ENTRIES(); } ZEND_MSHUTDOWN_FUNCTION(mymodule) { UNREGISTER_INI_ENTRIES(); } |
You've learned a lot about PHP. You now know how to create dynamic loadable modules and statically linked extensions. You've learned how PHP and Zend deal with internal storage of variables and how you can create and access these variables. You know quite a set of tool functions that do a lot of routine tasks such as printing informational texts, automatically introducing variables to the symbol table, and so on.
Even though this chapter often had a mostly "referential" character, we hope that it gave you insight on how to start writing your own extensions. For the sake of space, we had to leave out a lot; we suggest that you take the time to study the header files and some modules (especially the ones in the ext/standard directory and the MySQL module, as these implement commonly known functionality). This will give you an idea of how other people have used the API functions - particularly those that didn't make it into this chapter.
The file config.m4 is processed by buildconf and must contain all the instructions to be executed during configuration. For example, these can include tests for required external files, such as header files, libraries, and so on. PHP defines a set of macros that can be used in this process, the most useful of which are described in Table 9.18.
Rysunek 41-1. Table 9.18. M4 Macros for config.m4
Macro | Description |
AC_MSG_CHECKING(message) | Prints a "checking <message>" text during configure. |
AC_MSG_RESULT(value) | Gives the result to AC_MSG_CHECKING; should specify either yes or no as value. |
AC_MSG_ERROR(message) | Prints message as error message during configure and aborts the script. |
AC_DEFINE(name,value,description) | Adds #define to php_config.h with the value of value and a comment that says description (this is useful for conditional compilation of your module). |
AC_ADD_INCLUDE(path) | Adds a compiler include path; for example, used if the module needs to add search paths for header files. |
AC_ADD_LIBRARY_WITH_PATH(libraryname,librarypath) | Specifies an additional library to link. |
AC_ARG_WITH(modulename,description,unconditionaltest,conditionaltest) | Quite a powerful macro, adding the module with description to the configure --help output. PHP checks whether the option --with-<modulename> is given to the configure script. If so, it runs the script unconditionaltest (for example, --with-myext=yes), in which case the value of the option is contained in the variable $withval. Otherwise, it executes conditionaltest. |
PHP_EXTENSION(modulename, [shared]) | This macro is a must to call for PHP to configure your extension. You can supply a second argument in addition to your module name, indicating whether you intend compilation as a shared module. This will result in a definition at compile time for your source as COMPILE_DL_<modulename>. |
A set of macros was introduced into Zend's API that simplify access to zval containers (see Table 9.19).
Rysunek 42-1. Table 9.19. API Macros for Accessing zval Containers
Macro | Refers to |
Z_LVAL(zval) | (zval).value.lval |
Z_DVAL(zval) | (zval).value.dval |
Z_STRVAL(zval) | (zval).value.str.val |
Z_STRLEN(zval) | (zval).value.str.len |
Z_ARRVAL(zval) | (zval).value.ht |
Z_LVAL_P(zval) | (*zval).value.lval |
Z_DVAL_P(zval) | (*zval).value.dval |
Z_STRVAL_P(zval_p) | (*zval).value.str.val |
Z_STRLEN_P(zval_p) | (*zval).value.str.len |
Z_ARRVAL_P(zval_p) | (*zval).value.ht |
Z_LVAL_PP(zval_pp) | (**zval).value.lval |
Z_DVAL_PP(zval_pp) | (**zval).value.dval |
Z_STRVAL_PP(zval_pp) | (**zval).value.str.val |
Z_STRLEN_PP(zval_pp) | (**zval).value.str.len |
Z_ARRVAL_PP(zval_pp) | (**zval).value.ht |
This section holds the most general questions about PHP: what it is and what it does.
From the preface of the manual:
PHP is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly.
A nice introduction to PHP by Stig Sæther Bakken can be found here on the Zend website. Also, much of the PHP Conference Material is freely available.
PHP stands for PHP: Hypertext Preprocessor. This confuses many people because the first word of the acronym is the acronym. This type of acronym is called a recursive acronym. The curious can visit Free On-Line Dictionary of Computing for more information on recursive acronyms.
PHP/FI 2.0 is an early and no longer supported version of PHP. PHP 3 is the successor to PHP/FI 2.0 and is a lot nicer. PHP 4 is the latest generation of PHP, which uses the Zend engine under the hood.
Yes. See the INSTALL file that is included in the PHP 4 source distribution. Also, read the related appendix.
There are a couple of articles written on this by the authors of PHP 4. Here's a list of some of the more important new features:
Extended API module
Generalized build process under UNIX
Generic web server interface that also supports multi-threaded web servers
Improved syntax highlighter
Native HTTP session support
Output buffering support
More powerful configuration system
Reference counting
You should go to the PHP Bug Database and make sure the bug isn't a known bug. If you don't see it in the database, use the reporting form to report the bug. It is important to use the bug database instead of just sending an email to one of the mailing lists because the bug will have a tracking number assigned and it will then be possible for you to go back later and check on the status of the bug. The bug database can be found at http://bugs.php.net/.
This section holds questions abuot how to get in touch with the PHP community. The best way is the mailing lists.
Of course! There are many mailing lists for several subjects. A whole list of mailing lists can be found on our Support page.
The most general mailing list is php-general. To subscribe, send mail to php-general-subscribe@lists.php.net. You don't need to include anything special in the subject or body of the message. To unsubscribe, send mail to php-general-unsubscribe@lists.php.net.
You can also subscribe and unsubscribe usging the web interface on our Support page.
There are countless of them around the world. We have links for example to some IRC servers and foreign language mailing lists on our Support page.
If you have problems subscribing to or unsubscribing from the php-general mailing list, it may be because the mailing list software can't figure out the correct mailing address to use. If your email address was joeblow@example.com, you can send your subscription request to php-general-subscribe-joeblow=example.com@lists.php.net, or your unsubscription request to php-general-unsubscribe-joeblow=example.com@lists.php.net. Use similar addresses for the other mailing lists.
Yes, you will find a list of archive sites on the Support page. The mailing list articles are also archived as news messages. You can access the news server at news://news.php.net/ with a news client. There is also an experimental web interface for the news server at http://news.php.net/
Since PHP is growing more and more popular by the day the traffic has increased on the php-general mailing list and as of now the list gets about 150 to 200 posts a day. Because of this it is in everyones interest that you use the list as a last resort when you have looked everywhere else.
Before you post to the list please have a look in this FAQ and the manual to see if you can find the help there. If there is nothing to be found there try out the mailing list archives (see above). If you're having problem with installing or configuring PHP please read through all included documentation and README's. If you still can't find any information that helps you out you're more than welcome to use the mailing list.
Posts like "I can't get PHP up and running! Help me! What is wrong?" are of absolutely no use to anyone. If you're having problems getting PHP up and running you must include what operating system you are running on, what version of PHP you're trying to set up, how you got it (pre-compiled, CVS, RPMs and so on), what you have done so far, where you got stuck and the exact error message.
This goes for any other problem as well. You have to include information on what you have done, where you got stuck, what you're trying to do and, if applicable, exact error messages. If you're having problems with your source code you need to include the part of the code that isn't working. Do not include more code than necessary though! It makes the post hard to read and a lot of people might just skip it all together because of this. If you're unsure about how much information to include in the mail it's better that you include to much than to little.
Another important thing to remember is to summarize your problem on the subject line. A subject like "HELP MEEEE!!!" or "What is the problem here?" will be ignored by the majority of the readers.
This section has details about PHP download locations, and OS issues.
You can download PHP from any of the members of the PHP network of sites. These can be found at http://www.php.net/. You can also use anonymous CVS to get the absolute latest version of the source. For more information, go to http://cvs.php.net/.
We only distribute precompiled binaries for Windows systems, as we are not able to compile PHP for every major Linux/Unix platform with every extension combination. Also note, that many Linux distributions come with PHP built in these days. Windows binaries can be downloaded from our Downloads page, for Linux binaries, please visit your distributions website.
Notatka: Those marked with * are not thread-safe libraries, and should not be used with PHP as a server module in the multi-threaded Windows web servers (IIS, Netscape). This does not matter in Unix environments, yet.
LDAP (unix/win) : Netscape Directory (LDAP) SDK 1.1.
Berkeley DB2 (Unix/Win) : http://www.sleepycat.com/.
Sybase-CT* (Linux, libc5) : Available locally.
You will need to follow instructions provided with the library. Some of these libraries are detected automatically when you run the 'configure' script of PHP (such as the GD library), and others you will have to enable using '--with-EXTENSION' options to 'configure'. Run 'configure --help' for a listing of these.
5. I got the latest version of the PHP source code from the CVS repository on my Windows machine, what do I need to compile it?
First, you will need Microsoft Visual C++ v6 (v5 may do it also, but we do it with v6), and you will need some support files. See the manual section about building PHP from source on Windows.
You can find a browscap.ini file at http://www.cyscape.com/asp/browscap/.
This section holds common questions about relation between PHP and databases. Yes, PHP can access virtually any database available today.
On Windows machines, you can simply use the included ODBC support and the correct ODBC driver.
On Unix machines, you can use the Sybase-CT driver to access Microsoft SQL Servers because they are (at least mostly) protocol-compatible. Sybase has made a free version of the necessary libraries for Linux systems. For other Unix operating systems, you need to contact Sybase for the correct libraries. Also see the answer to the next question.
Yes. You already have all the tools you need if you are running entirely under Windows 9x/Me, or NT/2000, where you can use ODBC and Microsoft's ODBC drivers for Microsoft Access databases.
If you are running PHP on a Unix box and want to talk to MS Access on a Windows box you will need Unix ODBC drivers. OpenLink Software has Unix-based ODBC drivers that can do this. There is a free pilot program where you can download an evaluation copy that doesn't expire and prices start at $675 for the commercial supported version.
Another alternative is to use an SQL server that has Windows ODBC drivers and use that to store the data, which you can then access from Microsoft Access (using ODBC) and PHP (using the built in drivers), or to use an intermediary file format that Access and PHP both understand, such as flat files or dBase databases. On this point Tim Hayes from OpenLink software writes:
Using another database as an intermediary is not a good idea, when you can use ODBC from PHP straight to your database - i.e. with OpenLink's drivers. If you do need to use an intermediary file format, OpenLink have now released Virtuoso (a virtual database engine) for NT, Linux and other unix platforms. Please visit our website for a free download. |
One option that has proven successful is to use MySQL and its MyODBC drivers on Windows and synchronizing the databases. Steve Lawrence writes:
Install MySQL on your platform according to instructions with MySQL. Latest available from www.mysql.com (get it from your mirror!). No special configuration required except when you set up a database, and configure the user account, you should put % in the host field, or the host name of the Windows computer you wish to access MySQL with. Make a note of your server name, username, and password.
Download the MyODBC for Windows driver from the MySQL site. Latest release is myodbc-2_50_19-win95.zip (NT available too, as well as source code). Install it on your Windows machine. You can test the operation with the utilities included with this program.
Create a user or system dsn in your ODBC administrator, located in the control panel. Make up a dsn name, enter your hostname, user name, password, port, etc for you MySQL database configured in step 1.
Install Access with a full install, this makes sure you get the proper add-ins.. at the least you will need ODBC support and the linked table manager.
Now the fun part! Create a new access database. In the table window right click and select Link Tables, or under the file menu option, select Get External Data and then Link Tables. When the file browser box comes up, select files of type: ODBC. Select System dsn and the name of your dsn created in step 3. Select the table to link, press ok, and presto! You can now open the table and add/delete/edit data on your MySQL server! You can also build queries, import/export tables to MySQL, build forms and reports, etc.
Tips and Tricks:
You can construct your tables in access and export them to MySQL, then link them back in. That makes table creation quick.
When creating tables in access, you must have a primary key defined in order to have write access to the table in access. Make sure you create a primary key in MySQL before linking in access
If you change a table in MySQL, you have to re-link it in Access. Go to tools>add-ins>linked table manager, cruise to your ODBC DSN, and select the table to re-link from there. you can also move your dsn source around there, just hit the always prompt for new location checkbox before pressing ok.
3. I upgraded to PHP 4, and now mysql keeps telling me "Warning: MySQL: Unable to save result set in ...". What's up?
Most likely what has happened is, PHP 4 was compiled with the '--with-mysql' option, without specifying the path to MySQL. This means PHP is using its built-in MySQL client library. If your system is running applications, such as PHP 3 as a concurrent Apache module, or auth-mysql, that use other versions of MySQL clients, then there is a conflict between the two differing versions of those clients.
Recompiling PHP 4, and adding the path to MySQL to the flag, '--with-mysql=/your/path/to/mysql' usually solves the problem.
4. After installing shared MySQL support, Apache dumps core as soon as libphp4.so is loaded. Can this be fixed?
If your MySQL libs are linked against pthreads this will happen. Check using ldd. If they are, grab the MySQL tarball and compile from source, or recompile from the source rpm and remove the switch in the spec file that turns on the threaded client code. Either of these suggestions will fix this. Then recompile PHP with the new MySQL libs.
5. Why do I get an error that looks something like this: "Warning: 0 is not a MySQL result index in <file> on line <x>" or "Warning: Supplied argument is not a valid MySQL result resource in <file> on line <x>?
You are trying to use a result identifier that is 0. The 0 indicates that your query failed for some reason. You need to check for errors after submitting a query and before you attempt to use the returned result identifier. The proper way to do this is with code similar to the following:
$result = mysql_query("SELECT * FROM tables_priv"); if (!$result) { echo mysql_error(); exit; } |
$result = mysql_query("SELECT * FROM tables_priv") or die("Bad query: ".mysql_error()); |
This section holds common questions about the way to install PHP. PHP is available for almost any OS (except maybe for MacOS before OSX), and almost any web server.
To install PHP, follow the instructions in the INSTALL file located in the distribution. Windows users should also read the install.txt file. There are also some helpful hints for Windows users here.
[mybox:user /src/php4] root# apachectl configtest apachectl: /usr/local/apache/bin/httpd Undefined symbols: _compress _uncompress |
cgi error: The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are: |
By default on UNIX it should be in /usr/local/lib. Most people will want to change this at compile-time with the --with-config-file-path flag. You would, for example, set it with something like:
--with-config-file-path=/etc |
On Windows the default path for the php.ini file is the Windows directory.
2. Unix: I installed PHP, but every time I load a document, I get the message 'Document Contains No Data'! What's going on here?
This probably means that PHP is having some sort of problem and is core-dumping. Look in your server error log to see if this is the case, and then try to reproduce the problem with a small test case. If you know how to use 'gdb', it is very helpful when you can provide a backtrace with your bug report to help the developers pinpoint the problem. If you are using PHP as an Apache module try something like:
Stop your httpd processes
gdb httpd
Stop your httpd processes
> run -X -f /path/to/httpd.conf
Then fetch the URL causing the problem with your browser
> run -X -f /path/to/httpd.conf
If you are getting a core dump, gdb should inform you of this now
type: bt
You should include your backtrace in your bug report. This should be submitted to http://bugs.php.net/
If your script uses the regular expression functions (ereg() and friends), you should make sure that you compiled PHP and Apache with the same regular expression package. This should happen automatically with PHP and Apache 1.3.x
3. Unix: I installed PHP using RPMS, but Apache isn't processing the PHP pages! What's going on here?
Assuming you installed both Apache and PHP from RPM packages, you need to uncomment or add some or all of the following lines in your http.conf file:
# Extra Modules AddModule mod_php.c AddModule mod_php3.c AddModule mod_perl.c # Extra Modules LoadModule php_module modules/mod_php.so LoadModule php3_module modules/libphp3.so /* for PHP 3 */ LoadModule php4_module modules/libphp4.so /* for PHP 4 */ LoadModule perl_module modules/libperl.so |
AddType application/x-httpd-php3 .php3 /* for PHP 3 */ AddType application/x-httpd-php .php /* for PHP 4 */ |
4. Unix: I installed PHP 3 using RPMS, but it doesn't compile with the database support I need! What's going on here?
Due to the way PHP 3 built, it is not easy to build a complete flexible PHP RPM. This issue is addressed in PHP 4. For PHP 3, we currently suggest you use the mechanism described in the INSTALL.REDHAT file in the PHP distribution. If you insist on using an RPM version of PHP 3, read on...
The RPM packagers are setting up the RPMS to install without database support to simplify installations and because RPMS use /usr/ instead of the standard /usr/local/ directory for files. You need to tell the RPM spec file which databases to support and the location of the top-level of your database server.
This example will explain the process of adding support for the popular MySQL database server, using the mod installation for Apache.
Of course all of this information can be adjusted for any database server that PHP supports. We will assume you installed MySQL and Apache completely with RPMS for this example as well.
First remove mod_php3 :
rpm -e mod_php3 |
Then get the source rpm and INSTALL it, NOT --rebuild
rpm -Uvh mod_php3-3.0.5-2.src.rpm |
Then edit the /usr/src/redhat/SPECS/mod_php3.spec file
In the %build section add the database support you want, and the path.
For MySQL you would add
--with-mysql=/usr \ |
./configure --prefix=/usr \ --with-apxs=/usr/sbin/apxs \ --with-config-file-path=/usr/lib \ --enable-debug=no \ --enable-safe-mode \ --with-exec-dir=/usr/bin \ --with-mysql=/usr \ --with-system-regex |
Once this modification is made then build the binary rpm as follows:
rpm -bb /usr/src/redhat/SPECS/mod_php3.spec |
Then install the rpm
rpm -ivh /usr/src/redhat/RPMS/i386/mod_php3-3.0.5-2.i386.rpm |
5. Unix: I patched Apache with the FrontPage extensions patch, and suddenly PHP stopped working. Is PHP incompatible with the Apache FrontPage extensions?
No, PHP works fine with the FrontPage extensions. The problem is that the FrontPage patch modifies several Apache structures, that PHP relies on. Recompiling PHP (using 'make clean ; make') after the FP patch is applied would solve the problem.
6. Unix/Windows: I have installed PHP, but when I try to access a PHP script file via my browser, I get a blank screen.
Do a 'view source' in the web browser and you will probably find that you can see the source code of your PHP script. This means that the web server did not send the script to PHP for interpretation. Something is wrong with the server configuration - double check the server configuration against the PHP installation instructions.
7. Unix/Windows: I have installed PHP, but when try to access a PHP script file via my browser, I get a server 500 error.
Something went wrong when the server tried to run PHP. To get to see a sensible error message, from the command line, change to the directory containing the PHP executable (php.exe on Windows) and run php -i. If PHP has any problems running, then a suitable error message will be displayed which will give you a clue as to what needs to be done next. If you get a screen full of html codes (the output of the phpinfo() function) then PHP is working, and your problem may be related to your server configuration which you should double check.
8. Some operating systems: I have installed PHP without errors, but when I try to start apache I get undefined symbol errors:
[mybox:user /src/php4] root# apachectl configtest apachectl: /usr/local/apache/bin/httpd Undefined symbols: _compress _uncompress |
This has actually nothing to do with PHP, but with the MySQL client libraries. Some need --with-zlib, others do not. This is also covered in the MySQL FAQ.
9. Windows: I have installed PHP, but when I to access a PHP script file via my browser, I get the error:
cgi error: The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are: |
This error message means that PHP failed to output anything at all. To get to see a sensible error message, from the command line, change to the directory containing the PHP executable (php.exe on Windows) and run php -i. If PHP has any problems running, then a suitable error message will be displayed which will give you a clue as to what needs to be done next. If you get a screen full of html codes (the output of the phpinfo() function) then PHP is working.
Once PHP is working at the command line, try accessing the script via the browser again. If it still fails then it could be one of the following:
File permissions on your PHP script, php.exe, php4ts.dll, php.ini or any PHP extensions you are trying to load are such that the anonymous internet user ISUR_<machinename> cannot access them.
The script file does not exist (or possibly isn't where you think it is relative to your web root directory). Note that for IIS you can trap this error by ticking the 'check file exists' box when setting up the script mappings in the Internet Services Manager. If a script file does not exist then the server will return a 404 error instead. There is also the additional benefit that IIS will do any authentication required for you based on the NTLanMan permissions on your script file.
Make sure any user who needs to run a PHP script has the rights to run php.exe! IIS uses an anonymous user which is added at the time IIS is installed. This user needs rights to php.exe. Also, any authenticated user will also need rights to execute php.exe. And for IIS4 you need to tell it that PHP is a script engine.
This section gathers most common errors that occur at build time.
1. I got the latest version of PHP using the anonymous CVS service, but there's no configure script!
You have to have the GNU autoconf package installed so you can generate the configure script from configure.in. Just run ./buildconf in the top-level directory after getting the sources from the CVS server. (Also, unless you run configure with the --enable-maintainer-mode option, the configure script will not automatically get rebuilt when the configure.in file is updated, so you should make sure to do that manually when you notice configure.in has changed. One symptom of this is finding things like @VARIABLE@ in your Makefile after configure or config.status is run.)
2. I'm having problems configuring PHP to work with Apache. It says it can't find httpd.h, but it's right where I said it is!
You need to tell the configure/setup script the location of the top-level of your Apache source tree. This means that you want to specify '--with-apache=/path/to/apache' and not '--with-apache=/path/to/apache/src'.
3. When I run configure, it says that it can't find the include files or library for GD, gdbm, or some other package!
You can make the configure script looks for header files and libraries in non-standard locations by specifying additional flags to pass to the C preprocessor and linker, such as:
CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure |
env CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure |
4. When it is compiling the file language-parser.tab.c, it gives me errors that say 'yytname undeclared'.
You need to update your version of Bison. You can find the latest version at ftp://ftp.gnu.org/pub/gnu/bison/.
5. When I run 'make', it seems to run fine but then fails when it tries to link the final application complaining that it can't find some files.
Some old versions of make that don't correctly put the compiled versions of the files in the functions directory into that same directory. Try running "cp *.o functions" and then re-running 'make' to see if that helps. If it does, you should really upgrade to a recent version of GNU make.
Take a look at the link line and make sure that all of the appropriate libraries are being included at the end. Common ones that you might have missed are '-ldl' and any libraries required for any database support you included.
If you're linking with Apache 1.2.x, did you remember to add the appropriate information to the EXTRA_LIBS line of the Configuration file and re-rerun Apache's Configure script? See the INSTALL file that comes with the distribution for more information.
Some people have also reported that they had to add '-ldl' immediately following 'libphp4.a' when linking with Apache.
This is actually quite easy. Follow these steps carefully:
Grab the latest Apache 1.3 distribution from http://www.apache.org/dist/.
Ungzip and untar it somewhere, for example /usr/local/src/apache-1.3.
Compile PHP by first running ./configure --with-apache=/<path>/apache-1.3 (substitute <path> for the actual path to your apache-1.3 directory.
Type 'make' followed by 'make install' to build PHP and copy the necessary files to the Apache distribution tree.
Change directories into to your /<path>/apache-1.3/src directory and edit the Configuration file. Add to the file: AddModule modules/php4/libphp4.a.
Type: './Configure' followed by 'make'.
You should now have a PHP-enabled httpd binary!
Note: : You can also use the new Apache ./configure script. See the instructions in the README.configure file which is part of your Apache distribution. Also have a look at the INSTALL file in the PHP distribution.
8. I have followed all the steps to install the Apache module version on UNIX, and my PHP scripts show up in my browser or I am being asked to save the file.
This means that the PHP module is not getting invoked for some reason. Three things to check before asking for further help:
Make sure that the httpd binary you are running is the actual new httpd binary you just built. To do this, try running: /path/to/binary/httpd -l
If you don't see mod_php4.c listed then you are not running the right binary. Find and install the correct binary.
Make sure you have added the correct Mime Type to one of your Apache .conf files. It should be: AddType application/x-httpd-php3 .php3 (for PHP 3)
or AddType application/x-httpd-php .php (for PHP 4)
Also make sure that this AddType line is not hidden away inside a <Virtualhost> or <Directory> block which would prevent it from applying to the location of your test script.
Finally, the default location of the Apache configuration files changed between Apache 1.2 and Apache 1.3. You should check to make sure that the configuration file you are adding the AddType line to is actually being read. You can put an obvious syntax error into your httpd.conf file or some other obvious change that will tell you if the file is being read correctly.
9. It says to use: --activate-module=src/modules/php4/libphp4.a, but that file doesn't exist, so I changed it to --activate-module=src/modules/php4/libmodphp4.a and it doesn't work!? What's going on?
Note that the libphp4.a file is not supposed to exist. The apache process will create it!
10. When I try to build Apache with PHP as a static module using --activate-module=src/modules/php4/libphp4.a it tells me that my compiler is not ANSI compliant.
This is a misleading error message from Apache that has been fixed in more recent versions.
There are three things to check here. First, for some reason when Apache builds the apxs Perl script, it sometimes ends up getting built without the proper compiler and flags variables. Find your apxs script (try the command 'which apxs', it's sometimes found in /usr/local/apache/bin/apxs or /usr/sbin/apxs. Open it and check for lines similar to these:
my $CFG_CFLAGS_SHLIB = ' '; # substituted via Makefile.tmpl my $CFG_LD_SHLIB = ' '; # substituted via Makefile.tmpl my $CFG_LDFLAGS_SHLIB = ' '; # substituted via Makefile.tmpl |
my $CFG_CFLAGS_SHLIB = '-fpic -DSHARED_MODULE'; # substituted via Makefile.tmpl my $CFG_LD_SHLIB = 'gcc'; # substituted via Makefile.tmpl my $CFG_LDFLAGS_SHLIB = q(-shared); # substituted via Makefile.tmpl |
my $CFG_LIBEXECDIR = 'modules'; # substituted via APACI install |
my $CFG_LIBEXECDIR = '/usr/lib/apache'; # substituted via APACI install |
During the 'make' portion of installation, if you encounter problems that look similar to this:
microtime.c: In function `php_if_getrusage': microtime.c:94: storage size of `usg' isn't known microtime.c:97: `RUSAGE_SELF' undeclared (first use in this function) microtime.c:97: (Each undeclared identifier is reported only once microtime.c:97: for each function it appears in.) microtime.c:103: `RUSAGE_CHILDREN' undeclared (first use in this function) make[3]: *** [microtime.lo] Error 1 make[3]: Leaving directory `/home/master/php-4.0.1/ext/standard' make[2]: *** [all-recursive] Error 1 make[2]: Leaving directory `/home/master/php-4.0.1/ext/standard' make[1]: *** [all-recursive] Error 1 make[1]: Leaving directory `/home/master/php-4.0.1/ext' make: *** [all-recursive] Error 1 |
Your system is broken. You need to fix your /usr/include files either by making sure your /usr/include/linux symlink is pointing to the right place in your kernel sources or by installing a glibc-devel package that matches your glibc. This has absolutely nothing to do with PHP. To prove this to yourself, try this simple test:
$ cat >test.c <<X #include <sys/resource.h> X $ gcc -E test.c >/dev/null |
This section gathers most common errors you can face, while writing PHP scripts.
function myfunc($argument) { echo $argument + 10; } $variable = 10; echo "myfunc($variable) = " . myfunc($variable); |
<pre> <?php echo "This should be the first line."; ?> <?php echo "This should show up after the new line above."; ?> </pre> |
1. I would like to write a generic PHP script that can handle data coming from any form. How do I know which POST method variables are available?
Make sure that the track_vars feature is enabled in your php.ini file. Since PHP 4.0.3, this feature is always on. When track_vars is on, it creates some associative arrays, the most important here is: $HTTP_POST_VARS. So, to write a generic script to handle POST method variables you would need something similar to the following:
foreach ($HTTP_POST_VARS as $var => $value) { echo "$var = $value<br>\n"; } |
2. I need to convert all single-quotes (') to a backslash followed by a single-quote. How can I do this with a regular expression?
First off, take a look at the addslashes() function. It will do exactly what you want. You should also have a look at the magic_quotes_gpc directive in your php.ini file.
3. When I do the following, the output is printed in the wrong order:
function myfunc($argument) { echo $argument + 10; } $variable = 10; echo "myfunc($variable) = " . myfunc($variable); |
To be able to use the results of your function in an expression (such as concatenating it with other strings in the example above), you need to return the value, not echo() it.
4. Hey, what happened to my newlines?
<pre> <?php echo "This should be the first line."; ?> <?php echo "This should show up after the new line above."; ?> </pre> |
In PHP, the ending for a block of code is either "?>" or "?>\n" (where \n means a newline). So in the example above, the echoed sentences will be on one line, because PHP ommits the newlines after the block ending. This means that you need to insert an extra newline after each block of PHP code to make it print out one newline.
Why does PHP do this? Because when formatting normal HTML, this usually makes your life easier because you don't want that newline, but you'd have to create extremely long lines or otherwise make the raw page source unreadable to achieve that effect.
The getallheaders() function will do this if you are running PHP as an Apache module. So, the following bit of code will show you all the request headers:
$headers = getallheaders(); foreach ($headers as $name => $content) { echo "headers[$name] = $content<br>\n"; } |
The security model of IIS is at fault here. This is a problem common to all CGI programs running under IIS. A workaround is to create a plain HTML file (not parsed by PHP) as the entry page into an authenticated directory. Then use a META tag to redirect to the PHP page, or have a link to the PHP page. PHP will then recognize the authentication correctly. With the ISAPI module, this is not a problem. This should not effect other NT web servers. For more information, see: http://support.microsoft.com/support/kb/articles/q160/4/22.asp.
7. My PHP script works on IE and Lynx, but on Netscape some of my output is missing. When I do a "View Source" I see the content in IE but not in Netscape.
Netscape is more strict regarding html tags (such as tables) then IE. Running your html output through a html validator, such as validator.w3.org, might be helpful. For example, a missing </table> might cause this.
Also, both IE and Lynx ignore any NULs (\0) in the HTML stream, Netscape does not. The best way to check for this is to compile the command line version of PHP (also known as the CGI version) and run your script from the command line. In *nix, pipe it through od -c and look for any \0 characters. If you are on Windows you need to find an editor or some other program that lets you look at binary files. When Netscape sees a NUL in a file it will typically not output anything else on that line whereas both IE and Lynx will.
You need to turn off the short tags by setting short_tags to 0 in your php.ini file, or by using the appropriate Apache directive. You could even use a <File> section to do this selectively.
9. How can I use PHP with FrontPage or some other HTML editor that insists on moving my code around?
One of the easiest things to do is to enable using ASP tags in your PHP code. This allows you to use the ASP-style <% and %> code delimiters. Some of the popular HTML editors handle those more intelligently (for now). To enable the ASP-style tags, you need to set the asp_tags php.ini variable, or use the appropriate Apache directive.
10. Where can I find a complete list of pre-set variables available to me, and why are these not documented in the PHP documentation?
The best way is to stick a <?php phpinfo(); ?> part on a page and load it up. This will show you all sorts of information about your PHP setup, including a list of both environment variables and also special variables set by your web server. This list can't really be documented in the PHP documentation because it will change from one server to another.
11. I'm trying to access one of the standard CGI variables (such as $DOCUMENT_ROOT or $HTTP_REFERER) in a user-defined function, and it can't seem to find it. What's wrong?
Environment variables are normal global variables, so you must either declare them as global variables in your function (by using "global $DOCUMENT_ROOT;", for example) or by using the global variable array (ie, "$GLOBALS["DOCUMENT_ROOT"]".
PHP and HTML interact a lot: PHP generate HTML, and HTML has informations that will be sent to PHP.
There are several stages for which encoding is important. Assuming that you have a string $data, which contains the string you want to pass on in a non-encoded way, these are the relevant stages:
HTML interpretation. In order to specify a random string, you must include it in double quotes, and htmlspecialchars the the whole value.
URL: A URL consists of several parts. If you want your data to be interpreted as one item, you must encode it with urlencode().
Notatka: It is wrong to urlencode() $data, because it's the browsers reposability to urlencode() the data. All popular browsers do that correctly. Note that this will happen regardless of the method (i.e., GET or POST). You'll only notice this in case of GET request though, because POST requests are usually hidden.
Notatka: The data is shown in the browser as intended, because the browser will interpret the html escaped symbols.
Upon submitting, either via GET or POST, the data will be urlencoded by the browser for transferring, and directly urldecoded by PHP. So in the end, you don't need to do any urlencoding/urldecoding yourself, everything is handeled automagically.
Notatka: In fact you are faking a HTML GET request, therefore it's necessary to manually urlencode() the data.
Notatka: You need to htmlspecialchars() the whole URL, because the URL occurs as value of an HTML-attribute. In this case, the browser will first un-htmlspecialchars() the value, and then pass the URL on. PHP will understand the URL correcly, because you urlencoded() the data.
You'll notice that the & in the URL is replaced by &. Although most browsers will recover if you forget this, this isn't always possible. So even if your URL is not dynamic, you need to htmlspecialchars() the URL.
2. I'm trying to use an <input type="image"> tag, but the $foo.x and $foo.y variables aren't available. Where are they?
When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:
<input type="image" src="image.gif" name="foo"> |
Because $foo.x and $foo.y are invalid variable names in PHP, they are automagically converted to $foo_x and $foo_y. That is, the periods are replaced with underscores.
To get your <form> result sent as an array to your PHP script you name the <input>, <select> or <textarea> elements like this:
<input name="MyArray[]"> <input name="MyArray[]"> <input name="MyArray[]"> <input name="MyArray[]"> |
<input name="MyArray[]"> <input name="MyArray[]"> <input name="MyOtherArray[]"> <input name="MyOtherArray[]"> |
<input name="AnotherArray[]"> <input name="AnotherArray[]"> <input name="AnotherArray[email]"> <input name="AnotherArray[phone]"> |
Notatka: Specifying an arrays key is optional in HTML. If you do not specify the keys, the array gets filled in the order the elements appear in the form. Our first example will contain keys 0, 1, 2 and 3.
See also Array Functions and Variables from outside PHP.
The select multiple tag in an HTML construct allows users to select multiple items from a list. These items are then passed to the action handler for the form. The problem is that they are all passed with the same widget name. ie.
<select name="var" multiple> |
var=option1 var=option2 var=option3 |
<select name="var[]" multiple> |
Note that if you are using JavaScript the [] on the element name might cause you problems when you try to refer to the element by name. Use it's numerical form element id instead, or enclose the variable name in single quotes and use that as the index to the elements array, for example:
variable = documents.forms[0].elements['var[]']; |
PHP can be used to access COM and DCOM objects on Win32 platforms.
If this is a simple DLL there is no way yet to run it from PHP. If the DLL contains a COM server you may be able to access it if it implements the IDispatch interface.
There are dozens of VARIANT types and combinations of them. Most of them are already supported but a few still have to be implemented. Arrays are not completely supported. Only single dimensional indexed only arrays can be passed between PHP and COM. If you find other types that aren't supported, please report them as a bug (if not already reported) and provide as much information as available.
Generally it is, but as PHP is mostly used as a web scripting language it runs in the web servers context, thus visual objects will never appear on the servers desktop. If you use PHP for application scripting e.g. in conjunction with PHP-GTK there is no limitation in accessing and manipulating visual objects through COM.
No, you can't. COM instances are treated as resources and therefore they are only available in a single script's context.
Currently it's not possible to trap COM errors beside the ways provided by PHP itself (@, track_errors, ..), but we are thinking of a way to implement this.
No, unfortunatelly there is no such tool available for PHP.
7. What does 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}' mean ?
This error can have multiple reasons:
the CLSID is wrong
the requested DLL is missing
the requested component doesn't implement the IDispatch interface
Exactly like you run local objects. You only have to pass the ip of the remote machine as second parameter to the COM constructor.
Make sure that you have set com.allow_dcom=true in your php.ini.
Edit your php.ini and set com.allow_dcom=true.
This has nothing to do with PHP. ActiveX objects are loaded on client side if they are requested by the HTML document. There is no relation to the PHP script and therefore there is no direct server side interaction possible.
This is possible with the help of monikers. If you want to get multiple references to the same word instance you can create that instance like shown:
$word = new COM("C:\docs\word.doc"); |
This will create a new instance if there is no running instance available or it will return a handle to the running instance, if available.
13. I'm having problems when trying to invoke a method of a COM object wich exposes more than one interface. What can I do ?
The answer is as simple as unsatisfying. I don't know exactly but i think you can do nothing. If someone has specific information about this, please let me know :)
COM+ extends COM by a framework for managing components through MTS and MSMQ but there is nothing special that PHP has to support to use such components.
15. If PHP can manipulate COM objects, can we imagine to use MTS to manage components resources, in conjunction with PHP ?
PHP itself doesn't handle transactions yet. Thus if an error occours no rollback is initiated. If you use components that support transactions you will have to implement the transaction management yourself.
PHP is the best language for web programing, but what about other languages?
ASP is not really a language in itself, it's an acronym for Active Server Pages, the actual language used to program ASP with is Visual Basic Script or JScript. The biggest drawback of ASP is that it's a proprietary system that is natively used only on Microsoft Internet Information Server (IIS). This limits it's availability to Win32 based servers. There are a couple of projects in the works that allows ASP to run in other environments and webservers: InstantASP from Halcyon (commercial), Chili!Soft ASP from Chili!Soft (commercial) and OpenASP from ActiveScripting.org (free). ASP is said to be a slower and more cumbersome language than PHP, less stable as well. Some of the pros of ASP is that since it primarily uses VBScript it's relatively easy to pick up the language if you're already know how to program in Visual Basic. ASP support is also enabled by default in the IIS server making it easy to get up and running. The components built in ASP are really limited, so if you need to use "advanced" features like interacting with FTP servers, you need to buy additional components.
Yes, asp2php is the one most often referred to.
PHP is commonly said to be faster and more efficient for complex programming tasks and trying out new ideas. PHP is generally referred to as more stable and less resource intensive as well. Cold Fusion has better error handling, database abstraction and date parsing although database abstraction is addressed in PHP 4. Another thing that is listed as one of Cold Fusion's strengths is its excellent search engine, but it has been mentioned that a search engine is not something that should be included in a web scripting language. PHP runs on almost every platform there is; Cold Fusion is only available on Win32, Solaris, Linux and HP/UX. Cold Fusion has a good IDE and is generally easier to get started with, whereas PHP initially requires more programming knowledge. Cold Fusion is designed with non-programmers in mind, while PHP is focused on programmers.
A great summary by Michael J Sheldon on this topic has been posted to the PHP mailing list. A copy can be found here.
The biggest advantage of PHP over Perl is that PHP was designed for scripting for the web where Perl was designed to do a lot more and can because of this get very complicated. The flexibility / complexity of Perl makes it easier to write code that another author / coder has a hard time reading. PHP has a less confusing and stricter format without losing flexibility. PHP is easier to integrate into existing HTML than Perl. PHP has pretty much all the 'good' functionality of Perl: constructs, syntax and so on, without making it as complicated as Perl can be. Perl is a very tried and true language, it's been around since the late eighties, but PHP is maturing very quickly.
PHP ma już za sobą długą historię: Legendarne PHP 1.0, PHP/FI, PHP 3.0 and PHP 4.0.
PHP/FI 2.0 już nie jest obsługiwane. Zobacz właściwy rozdział podręcznika aby uzystać informację o migracji z PHP/FI 2.0.
Jeśli ciągle pracujesz na PHP 2, mocno zalecamy uaktualnienie bezpośrednio na PHP 4.
PHP ma już za sobą długą historię: Legendarne PHP 1.0, PHP/FI, PHP 3.0 and PHP 4.0.
PHP 4 było projektowane tak, aby zapewnić największą możliwą kompatybilność z wcześniejszymi wersjami PHP i w tym procesie bardzo niewiele zostało utracone. Jeśli nie jesteś pewien co do kompatybilności, powinieneś zainstalować PHP 4 w środowisku testowym i uruchomić tam swoje skrypty.
Zobacz także dodatek o migracji znajdujący się w tym podręczniku.
There can be some questions we can't put into other categories. Here you can find them.
The yellow pop-up windows on the old site were pretty cool, but were very difficult to maintain (since some companies seem to enjoy changing the way their browsers work with every new release).
All the code for previous versions of the website is still available through CVS. Specifically, the last version of shared.inc (that had all the Javascript and DHTML to do the popups) is available here.
PHP has come a long way in the last few years. Growing to be one of the most prominent languages powering the Web was not an easy task. Those of you interested in briefly seeing how PHP grew out to what it is today, read on.
PHP succeeds an older product, named PHP/FI. PHP/FI was created by Rasmus Lerdorf in 1995, initially as a simple set of Perl scripts for tracking accesses to his online resume. He named this set of scripts 'Personal Home Page Tools'. As more functionality was required, Rasmus wrote a much larger C implementation, which was able to communicate with databases, and enabled users to develop simple dynamic Web applications. Rasmus chose to release the source code for PHP/FI for everybody to see, so that anybody can use it, as well as fix bugs in it and improve the code.
PHP/FI, which stood for Personal Home Page / Forms Interpreter, included some of the basic functionality of PHP as we know it today. It had Perl-like variables, automatic interpretation of form variables and HTML embedded syntax. The syntax itself was similar to that of Perl, albeit much more limited, simple, and somewhat inconsistent.
By 1997, PHP/FI 2.0, the second write-up of the C implementation, had a cult of several thousand users around the world (estimated), with approximately 50,000 domains reporting as having it installed, accounting for about 1% of the domains on the Internet. While there were several people contributing bits of code to this project, it was still at large a one-man project.
PHP/FI 2.0 was officially released only in November 1997, after spending most of its life in beta releases. It was shortly afterwards succeeded by the first alphas of PHP 3.0.
PHP 3.0 was the first version that closely resembles PHP as we know it today. It was created by Andi Gutmans and Zeev Suraski in 1997 as a complete rewrite, after they found PHP/FI 2.0 severely underpowered for developing their own eCommerce application. In an effort to cooperate and start building upon PHP/FI's existing user-base, Andi, Rasmus and Zeev decided to cooperate and announce PHP 3.0 as the official successor of PHP/FI 2.0, and development of PHP/FI 2.0 was mostly halted.
One of the biggest strengths of PHP 3.0 was its strong extensibility features. In addition to providing end users with a solid infrastructure for lots of different databases, protocols and APIs, PHP 3.0's extensibility features attracted dozens of developers to join in and submit new extension modules. Arguably, this was the key to PHP 3.0's tremendous success. Other key features introduced in PHP 3.0 were the object oriented syntax support and the much more powerful and consistent language syntax.
The whole new language was released under a new name, that removed the implication of limited personal use that the PHP/FI 2.0 name held. It was named plain 'PHP', with the meaning being a recursive acronym - PHP: Hypertext Preprocessor.
By the end of 1998, PHP grew to an install base of tens of thousands of users (estimated) and hundreds of thousands of Web sites reporting it installed. At its peak, PHP 3.0 was installed on approximately 10% of the Web servers on the Internet.
PHP 3.0 was officially released in June 1998, after having spent about 9 months in public testing.
By the winter of 1998, shortly after PHP 3.0 was officially released, Andi Gutmans and Zeev Suraski had begun working on a rewrite of PHP's core. The design goals were to improve performance of complex applications, and improve the modularity of PHP's code base. Such applications were made possible by PHP 3.0's new features and support for a wide variety of third party databases and APIs, but PHP 3.0 was not designed to handle such complex applications efficiently.
The new engine, dubbed 'Zend Engine' (comprised of their first names, Zeev and Andi), met these design goals successfully, and was first introduced in mid 1999. PHP 4.0, based on this engine, and coupled with a wide range of additional new features, was officially released in May 2000, almost two years after its predecessor, PHP 3.0. In addition to the highly improved performance of this version, PHP 4.0 included other key features such as support for many more Web servers, HTTP sessions, output buffering, more secure ways of handling user input and several new language constructs.
PHP 4 is currently the latest released version of PHP. Work has already begun on modifying and improving the Zend Engine to integrate the features which were designed for PHP 5.0.
Today, PHP is being used by hundreds of thousands of developers (estimated), and several million sites report as having it installed, which accounts for over 20% of the domains on the Internet.
PHP's development team includes dozens of developers, as well as dozens others working on PHP-related projects such as PEAR and the documentation project.
PEAR, the PHP Extension and Application Repository (originally, PHP Extension and Add-on Repository) is PHP's version of foundation classes, and may grow in the future to be one of the key ways to distribute both PHP and C-based PHP extensions among developers.
PEAR was born in discussions held in the PHP Developers' Meeting (PDM) held in January 2000 in Tel Aviv. It was created by Stig S. Bakken, and is dedicated to his first-born daughter, Malin Bakken.
Since early 2000, PEAR has grown to be a big, significant project with a large number of developers working on implementing common, reusable functionality for the benefit of the entire PHP community. PEAR today includes a wide variety of infrastructure foundation classes for database access, content caching, mathematical calculations, eCommerce and much more.
The PHP Quality Assurance Initiative was set up in the summer of 2000 in response to criticism that PHP releases were not being tested well enough for production environments. The team now consists of a core group of developers with a good understanding of the PHP code base. These developers spend a lot of their time localizing and fixing bugs within PHP. In addition there are many other team members who test and provide feedback on these fixes using a wide variety of platforms.
PHP-GTK is the PHP solution for writing client side GUI applications. Andrei Zmievski remembers the planing and creation process of PHP-GTK:
GUI programming has always been of my interests, and I found that Gtk+ is a very nice toolkit, except that programming with it in C is somewhat tedious. After witnessing PyGtk and GTK-Perl implementations, I decided to see if PHP could be made to interface with Gtk+, even minimally. Starting in August of 2000, I began to have a bit more free time so that is when I started experimenting. My main guideline was the PyGtk implementation as it was fairly feature complete and had a nice object-oriented interface. James Henstridge, the author of PyGtk, provided very helpful advice during those initial stages.
Hand-writing the interfaces to all the Gtk+ functions was out of the question, so I seized upon the idea of code-generator, similar to how PyGtk did it. The code generator is a PHP program that reads a set of .defs file containing the Gtk+ classes, constants, and methods information and generates C code that interfaces PHP with them. What cannot be generated automatically can be written by hand in .overrides file.
Working on the code generator and the infrastructure took some time, because I could spend little time on PHP-GTK during the fall of 2000. After I showed PHP-GTK to Frank Kromann, he got interested and started helping me out with code generator work and Win32 implementation. When we wrote the first Hello World program and fired it up, it was extremely exciting. It took a couple more months to get the project to a presentable condition and the initial version was released on March 1, 2001. The story promptly hit SlashDot.
Sensing that PHP-GTK might be extensive, I set up separate mailing lists and CVS repositories for it, as well as the gtk.php.net website with the help of Colin Viebrock. The documentation would also need to be done and James Moore came in to help with that.
Since its release PHP-GTK has been gaining popularity. We have our own documentation team, the manual keeps improving, people start writing extensions for PHP-GTK, and more and more exciting applications with it.
As PHP grew, it began to be recognized as a world-wide popular development platform. One of the most interesting ways of seeing this trend was by observing the books about PHP that came out throughout the years.
To the best of our knowledge, the first book dedicated to PHP was 'php- dynamische webauftritte professionell realisieren' - a German book published in 1999, authored by Egon Schmid, Christian Cartus and Richard Blume. The first book in English about PHP was published shortly afterwards, and was 'Core PHP Programming' by Leon Atkinson. Both of these books covered PHP 3.0.
While these two books were the first of their kind - they were followed by a large number of books from a host of authors and publishers. There are over 40 books in English, 50 books in German, and over 20 books in French! In addition, you can find books about PHP in many other languages, including Spanish, Korean, Japanese and Hebrew.
Clearly, this large number of books, written by different authors, published by many publishers, and their availability in so many languages - are a strong testimony for PHP's world-wide success.
To the best of our knowledge, the first article about PHP in a hard-copy magazine was published in the French Informatiques Magazine, towards the end of 1998, and covered PHP 3.0. As with books, this was the first in a series of many articles published about PHP in various prominent magazines.
Articles about PHP appeared in Dr. Dobbs, Linux Enterprise, Linux Magazine and many more. Articles about migrating ASP-based applications to PHP under Windows even appear on Microsoft's very own MSDN!
The command line options of the PHP executable are useful if you would like to debug or test your PHP setup, but they can also be handy, if you would like to use PHP for a different purpose than web scripting.
Note, that you can always direct the output of the PHP executable to an external file with the > character, so php -q test.php > test.html will print out the output of test.php without HTTP headers to the test.html file in the same directory.
You can only use these command line options if you have the PHP executable. If you built the server module version, and you have no CGI version available on your machine, than you have no chance to use these options. For Windows users both the PHP executable and the server modules are in the binary package, the executable is named php.exe.
This list of command line options is consistent with PHP 4.0.6. You can get the actual list and some one line descriptions with the -h option. The output of php -h should be something like this:
Usage: php [-q] [-h] [-s [-v] [-i] [-f <file>] | {<file> [args...]} -q Quiet-mode. Suppress HTTP Header output. -s Display colour syntax highlighted source. -f <file> Parse <file>. Implies `-q' -v Version number -C Do not chdir to the script's directory -c <path> Look for php.ini file in this directory -d foo[=bar] Define INI entry foo with value 'bar' -e Generate extended information for debugger/profiler -z <file> Load Zend extension <file>. -l Syntax check only (lint) -m Show compiled in modules -i PHP information -h This help |
Here we list some of the most important command line options with detailed explanations.
Tabela B-1. Command line options
Option | Description |
---|---|
-q | Suppress HTTP headers output. Normally PHP prints out HTTP headers for the calling program (ie. webserver) to hand on to the browser. When writing command line applications these headers are useless. |
-s | Display the color highlighted source of the file given with its name. This is the same as if you were printing out the source using the highlight_file() function in a PHP script. |
-f | Parse the file given, and search for syntactical and fatal errors. This option implies -q. Use for debugging purposes. |
-v | By calling PHP with this option, you can ask it to print out its version number, ie: 4.0.6. |
-C | Normally PHP changes the working directory to the running scripts directory. This makes it possible for example, to open files in the same directory, with only specifying the name of the file. If you would like to disable this directory change, use this option. |
-c | Using this option, you can specify an alternative php.ini path, so PHP will search your configurations file in this path instead of the default one. |
-d | With this option, you can set individual php.ini settings in the time of running a script. |
-l | Check the file given for syntax errors. This option implies -q. Use for debugging purposes. This option won't find fatal errors (like undefined functions). Use -f if you would like to test for fatal errors too. |
-m | Using this option, PHP prints out the built in (and loaded) PHP and Zend modules, the PHP and Zend version numbers, and a short Zend copyright notice. |
-i | This command line option calls phpinfo(), and prints out the results. If PHP is not working well, it is advisable to make a php -i and see if any error messages are printed out before or in place of the information tables. |
-h | With this option, you can get information about the actual list of command line options and some one line descriptions about what they do. |
The PHP executable can be used to run PHP scripts absolutely independent from the web server. If you are on a Unix system, you should add a special first line to your PHP script, and make it executable, so the system will know, what program should run the script. On a Windows platform you can associate php.exe -q with the double click option of the .php files, or you can make a batch file to run the script through PHP. The first line added to the script to work on Unix won't hurt on Windows, so you can write cross platform programs this way. A simple example of writing a command line PHP program can be found below.
Przykład B-1. Script intended to be run from command line (script.php)
|
In the script above, we used the special first line to indicate, that this file should be run by PHP and should not print out HTTP headers. There are two variables you can use while writing command line applications with PHP: $argc and $argv. The first is the number of arguments plus one (the name of the script running). The second is an array containing the arguments, starting with the script name as number zero ($argv[0]).
In the program above we checked if there are less or more than one arguments. Also if the argument was --help, -help, -h or -?, we printed out the help message, printing the script name dynamically. If we received some other argument we echoed that out.
If you would like to run the above script on Unix, you need to make it executable, and simply call it as script.php echothis or script.php -h. On Windows, you can make a batch file for this task:
Assuming, you named the above program as script.php, and you have your php.exe in c:\php\php.exe this batch file will run it for you with your added options: script.bat echothis or script.bat -h.
See also the Readline extension documentation for more functions you can use to enhance your command line applications in PHP.
PHP 4 and the integrated Zend engine have greatly improved PHPs performance and capabilities, but great care has been taken to break as little existing code as possible. So migrating your code from PHP 3 to 4 should be much easier than migrating from PHP/FI 2 to PHP 3. A lot of existing PHP 3 code should be ready to run without changes, but you should still know about the few differences and take care to test your code before switching versions in production environments. The following should give you some hints about what to look for.
Recent operating systems provide the ability to perform versioning and scoping. This features make it possible to let PHP 3 and PHP 4 run as concurrent modules in one Apache server.
This feature is known to work on the following platforms:
Linux with recent binutils (binutils 2.9.1.0.25 tested)
Solaris 2.5 or better
FreeBSD (3.2, 4.0 tested)
To enable it, configure PHP3 and PHP4 to use APXS (--with-apxs) and the necessary link extensions (--enable-versioning). Otherwise, all standard installations instructions apply. For example:
The global configuration file, php3.ini, has changed its name to php.ini.
For the Apache configuration file, there are slightly more changes. The MIME types recognized by the PHP module have changed.
application/x-httpd-php3 --> application/x-httpd-php application/x-httpd-php3-source --> application/x-httpd-php-source |
You can make your configuration files work with both versions of PHP (depending on which one is currently compiled into the server), using the following syntax:
AddType application/x-httpd-php3 .php3 AddType application/x-httpd-php3-source .php3s AddType application/x-httpd-php .php AddType application/x-httpd-php-source .phps |
In addition, the PHP directive names for Apache have changed.
Starting with PHP 4.0, there are only four Apache directives that relate to PHP:
php_value [PHP directive name] [value] php_flag [PHP directive name] [On|Off] php_admin_value [PHP directive name] [value] php_admin_flag [PHP directive name] [On|Off] |
There are two differences between the Admin values and the non admin values:
Admin values (or flags) can only appear in the server-wide apache configuration files (e.g., httpd.conf).
Standard values (or flags) cannot control certain PHP directives, for example - safe mode (if you could override safe mode settings in .htaccess files, it would defeat safe-mode's purpose). In contrast, Admin values can modify the value of any PHP directive.
To make the transition process easier, PHP 4 is bundled with scripts that automatically convert your Apache configuration and .htaccess files to work with both PHP 3 and PHP 4. These scripts do NOT convert the mime type lines! You have to convert these yourself.
To convert your Apache configuration files, run the apconf-conv.sh script (available in the scripts/apache/ directory). For example:
Your original configuration file will be saved in httpd.conf.orig.
To convert your .htaccess files, run the aphtaccess-conv.sh script (available in the scripts/apache/ directory as well):
Likewise, your old .htaccess files will be saved with an .orig prefix.
The conversion scripts require awk to be installed.
Parsing and execution are now two completely separated steps, no execution of a files code will happen until the complete file and everything it requires has completely and successfully been parsed.
One of the new requirements introduced with this split is that required and included files now have to be syntactically complete. You can no longer spread the different controlling parts of a control structure across file boundaries. That is you cannot start a for or while loop, an if statement or a switch block in one file and have the end of loop, else, endif, case or break statements in a different file.
It still perfectly legal to include additional code within loops or other control structures, only the controlling keywords and corresponding curly braces {...} have to be within the same compile unit (file or eval()ed string).
This should not harm to much as spreading code like this should be considered as very bad style anyway.
Another thing no longer possible, though rarely seen in PHP 3 code is returning values from a required file. Returning a value from an included file is still possible.
With PHP 3 the error reporting level was set as a simple numeric value formed by summing up the numbers related to different error levels. Usual values where 15 for reporting all errors and warnings or 7 for reporting everything but simple notice messages reporting bad style and things like that.
PHP 4 has a larger set of error and warning levels and comes with a configuration parser that now allows for symbolic constants to be used for setting the intended behavior.
Error reporting level should now be configured by explicitly taking away the warning levels you do not want to generate error messages by x-oring them from the symbolic constant E_ALL. Sounds complicated? Well, lets say you want the error reporting system to report all but the simple style warnings that are categorized by the symbolic constant E_NOTICE. Then you'll put the following into your php.ini: error_reporting = E_ALL & ~ ( E_NOTICE ). If you want to suppress warnings too you add up the appropriate constant within the braces using the binary or operator '|': error_reporting= E_ALL & ~ ( E_NOTICE | E_WARNING ).
Ostrze¿enie |
Using the old values 7 and 15 for setting up error reporting is a very bad idea as this suppresses some of the newly added error classes including parse errors. This may lead to very strange behavior as scripts might no longer work without error messages showing up anywhere. This has lead to a lot of unreproducible bug reports in the past where people reported script engine problems they were not capable to track down while the TRUE case was usually some missing '}' in a required file that the parser was not able to report due to a misconfigured error reporting system. So checking your error reporting setup should be the first thing to do whenever your scripts silently die. The Zend engine can be considered mature enough nowadays to not cause this kind of strange behavior. |
A lot of existing PHP 3 code uses language constructs that should be considered as very bad style as this code, while doing the intended thing now, could easily be broken by changes in other places. PHP 4 will output a lot of notice messages in such situations where PHP 3 didn't. The easy fix is to just turn off E_NOTICE messages, but it is usually a good idea to fix the code instead.
The most common case that will now produce notice messages is the use of unquoted string constants as array indices. Both PHP 3 and 4 will fall back to interpret these as strings if no keyword or constant is known by that name, but whenever a constant by that name had been defined anywhere else in the code it might break your script. This can even become a security risk if some intruder manages to redefine string constants in a way that makes your script give him access rights he wasn't intended to have. So PHP 4 will now warn you whenever you use unquoted string constants as for example in $HTTP_SERVER_VARS[REQUEST_METHOD]. Changing it to $HTTP_SERVER_VARS['REQUEST_METHOD'] will make the parser happy and greatly improve the style and security of your code.
Another thing PHP 4 will now tell you about is the use of uninitialized variables or array elements.
Static variable and class member initializers only accept scalar values while in PHP 3 they accepted any valid expression. This is, once again, due to the split between parsing and execution as no code has yet been executed when the parser sees the initializer.
For classes you should use constructors to initialize member variables instead. For static variables anything but a simple static value rarely makes sense anyway.
The perhaps most controversial change in behavior has happened to the behavior of the empty(). A String containing only the character '0' (zero) is now considered empty while it wasn't in PHP 3.
This new behavior makes sense in web applications, with all input fields returning strings even if numeric input is requested, and with PHP's capabilities of automatic type conversion. But on the other had it might break your code in a rather subtle way, leading to misbehavior that is hard to track down if you do not know about what to look for.
While PHP 4 comes with a lot of new features, functions and extensions, you may still find some functions from version 3 missing. A small number of core functions has vanished because they do not work with the new scheme of splitting parsing and execution as introduced into 4 with the Zend engine. Other functions and even complete extensions have become obsolete as newer functions and extensions serve the same task better and/or in a more general way. Some functions just simply haven't been ported yet and finally some functions or extensions may be missing due to license conflicts.
As PHP 4 now separates parsing from execution it is no longer possible to change the behavior of the parser (now embedded in the Zend engine) at runtime as parsing already happened by then. So the function short_tags() no longer exists. You can still change the parsers behavior by setting appropriate values in the php.ini file.
Another feature of PHP 3 that is not a part of PHP 4 is the bundled debugging interface. There are third-party add-ons for the Zend engine which add similar functionality.
The Adabas and Solid database extensions are no more. Long live the unified ODBC extension instead.
unset(), although still available, is implemented as a language construct rather than a function.
This does not have any consequences on the behavior of unset(), but testing for "unset" using function_exists() will return FALSE as it would with other language constructs that look like functions such as echo().
Another more practical change is that it is no longer possible to call unset() indirectly, that is $func="unset"; $func($somevar) won't work anymore.
Extensions written for PHP 3 will not work with PHP 4, neither as binaries nor at the source level. It is not difficult to port extensions to PHP 4 if you have access to the original source. A detailed description of the actual porting process is not part of this text.
PHP 4 adds a new mechanism to variable substitution in strings. You can now finally access object member variables and elements from multidimensional arrays within strings.
To do so you have to enclose your variables with curly braces with the dollar sign immediately following the opening brace: {$...}
To embed the value of an object member variable into a string you simply write "text {$obj->member} text" while in PHP 3 you had to use something like "text ".$obj->member." text".
This should lead to more readable code, while it may break existing scripts written for PHP 3. But you can easily check for this kind of problem by checking for the character combination {$ in your code and by replacing it with \{$ with your favorite search-and-replace tool.
PHP 3 had the bad habit of setting cookies in the reverse order of the setcookie() calls in your code. PHP 4 breaks with this habit and creates the cookie header lines in exactly the same order as you set the cookies in the code.
This might break some existing code, but the old behaviour was so strange to understand that it deserved a change to prevent further problems in the future.
PHP 3.0 is rewritten from the ground up. It has a proper parser that is much more robust and consistent than 2.0's. 3.0 is also significantly faster, and uses less memory. However, some of these improvements have not been possible without compatibility changes, both in syntax and functionality.
In addition, PHP's developers have tried to clean up both PHP's syntax and semantics in version 3.0, and this has also caused some incompatibilities. In the long run, we believe that these changes are for the better.
This chapter will try to guide you through the incompatibilities you might run into when going from PHP/FI 2.0 to PHP 3.0 and help you resolve them. New features are not mentioned here unless necessary.
A conversion program that can automatically convert your old PHP/FI 2.0 scripts exists. It can be found in the convertor subdirectory of the PHP 3.0 distribution. This program only catches the syntax changes though, so you should read this chapter carefully anyway.
The first thing you probably will notice is that PHP's start and end tags have changed. The old <? > form has been replaced by three new possible forms:
The `alternative' way to write if/elseif/else statements, using if(); elseif(); else; endif; cannot be efficiently implemented without adding a large amount of complexity to the 3.0 parser. Because of this, the syntax has been changed:
Just like with if..endif, the syntax of while..endwhile has changed as well:
Ostrze¿enie |
If you use the old while..endwhile syntax in PHP 3.0, you will get a never-ending loop. |
PHP/FI 2.0 used the left side of expressions to determine what type the result should be. PHP 3.0 takes both sides into account when determining result types, and this may cause 2.0 scripts to behave unexpectedly in 3.0.
Consider this example:
In PHP/FI 2.0, this would display both of $a's indices. In PHP 3.0, it wouldn't display anything. The reason is that in PHP 2.0, because the left argument's type was string, a string comparison was made, and indeed "" does not equal "0", and the loop went through. In PHP 3.0, when a string is compared with an integer, an integer comparison is made (the string is converted to an integer). This results in comparing atoi("") which is 0, and variablelist which is also 0, and since 0==0, the loop doesn't go through even once.The fix for this is simple. Replace the while statement with:
PHP 3.0's error messages are usually more accurate than 2.0's were, but you no longer get to see the code fragment causing the error. You will be supplied with a file name and a line number for the error, though.
In PHP 3.0 boolean evaluation is short-circuited. This means that in an expression like (1 || test_me()), the function test_me() would not be executed since nothing can change the result of the expression after the 1.
This is a minor compatibility issue, but may cause unexpected side-effects.
Most internal functions have been rewritten so they return TRUE when successful and FALSE when failing, as opposed to 0 and -1 in PHP/FI 2.0, respectively. The new behaviour allows for more logical code, like $fp = fopen("/your/file") or fail("darn!");. Because PHP/FI 2.0 had no clear rules for what functions should return when they failed, most such scripts will probably have to be checked manually after using the 2.0 to 3.0 convertor.
The PHP 3.0 Apache module no longer supports Apache versions prior to 1.2. Apache 1.2 or later is required.
echo() no longer supports a format string. Use the printf() function instead.
In PHP/FI 2.0, an implementation side-effect caused $foo[0] to have the same effect as $foo. This is not true for PHP 3.0.
Reading arrays with $array[] is no longer supported
That is, you cannot traverse an array by having a loop that does $data = $array[]. Use current() and next() instead.
Also, $array1[] = $array2 does not append the values of $array2 to $array1, but appends $array2 as the last entry of $array1. See also multidimensional array support.
"+" is no longer overloaded as a concatenation operator for strings, instead it converts it's arguments to numbers and performs numeric addition. Use "." instead.
PHP 3 includes support for a network-based debugger.
PHP 4 does not have an internal debugging facility. You can use one of the external debuggers though. The Zend IDE includes a debugger, and there are also some free debugger extensions like DBG at http://dd.cron.ru/dbg/ or the Advanced PHP Debugger (APD).
The internal debugger in PHP 3 is useful for tracking down evasive bugs. The debugger works by connecting to a TCP port for every time PHP 3 starts up. All error messages from that request will be sent to this TCP connection. This information is intended for "debugging server" that can run inside an IDE or programmable editor (such as Emacs).
How to set up the debugger:
Set up a TCP port for the debugger in the configuration file (debugger.port) and enable it (debugger.enabled).
Set up a TCP listener on that port somewhere (for example socket -l -s 1400 on UNIX).
In your code, run "debugger_on(host)", where host is the IP number or name of the host running the TCP listener.
The PHP 3 debugger protocol is line-based. Each line has a type, and several lines compose a message. Each message starts with a line of the type start and terminates with a line of the type end. PHP 3 may send lines for different messages simultaneously.
A line has this format:
Date in ISO 8601 format (yyyy-mm-dd)
Time including microseconds: hh:mm:uuuuuu
DNS name or IP address of the host where the script error was generated.
PID (process id) on host of the process with the PHP 3 script that generated this error.
Type of line. Tells the receiving program about what it should treat the following data as:
Tabela E-1. Debugger Line Types
Name | Meaning |
---|---|
start | Tells the receiving program that a debugger message starts here. The contents of data will be the type of error message, listed below. |
message | The PHP 3 error message. |
location | File name and line number where the error occurred. The first location line will always contain the top-level location. data will contain file:line. There will always be a location line after message and after every function. |
frames | Number of frames in the following stack dump. If there are four frames, expect information about four levels of called functions. If no "frames" line is given, the depth should be assumed to be 0 (the error occurred at top-level). |
function | Name of function where the error occurred. Will be repeated once for every level in the function call stack. |
end | Tells the receiving program that a debugger message ends here. |
Line data.
Tabela E-2. Debugger Error Types
Debugger | PHP 3 Internal |
---|---|
warning | E_WARNING |
error | E_ERROR |
parse | E_PARSE |
notice | E_NOTICE |
core-error | E_CORE_ERROR |
core-warning | E_CORE_WARNING |
unknown | (any other) |
Przykład E-1. Example Debugger Message
|
All functions look like this:
void php3_foo(INTERNAL_FUNCTION_PARAMETERS) { } |
Arguments are always of type pval. This type contains a union which has the actual type of the argument. So, if your function takes two arguments, you would do something like the following at the top of your function:
When you change any of the passed parameters, whether they are sent by reference or by value, you can either start over with the parameter by calling pval_destructor on it, or if it's an ARRAY you want to add to, you can use functions similar to the ones in internal_functions.h which manipulate return_value as an ARRAY.
Also if you change a parameter to IS_STRING make sure you first assign the new estrdup()'ed string and the string length, and only later change the type to IS_STRING. If you change the string of a parameter which already IS_STRING or IS_ARRAY you should run pval_destructor on it first.
A function can take a variable number of arguments. If your function can take either 2 or 3 arguments, use the following:
The type of each argument is stored in the pval type field. This type can be any of the following:
Tabela F-1. PHP Internal Types
IS_STRING | String |
IS_DOUBLE | Double-precision floating point |
IS_LONG | Long integer |
IS_ARRAY | Array |
IS_EMPTY | None |
IS_USER_FUNCTION | ?? |
IS_INTERNAL_FUNCTION | ?? (if some of these cannot be passed to a function - delete) |
IS_CLASS | ?? |
IS_OBJECT | ?? |
If you get an argument of one type and would like to use it as another, or if you just want to force the argument to be of a certain type, you can use one of the following conversion functions:
convert_to_long(arg1); convert_to_double(arg1); convert_to_string(arg1); convert_to_boolean_long(arg1); /* If the string is "" or "0" it becomes 0, 1 otherwise */ convert_string_to_number(arg1); /* Converts string to either LONG or DOUBLE depending on string */ |
These function all do in-place conversion. They do not return anything.
The actual argument is stored in a union; the members are:
IS_STRING: arg1->value.str.val
IS_LONG: arg1->value.lval
IS_DOUBLE: arg1->value.dval
Any memory needed by a function should be allocated with either emalloc() or estrdup(). These are memory handling abstraction functions that look and smell like the normal malloc() and strdup() functions. Memory should be freed with efree().
There are two kinds of memory in this program: memory which is returned to the parser in a variable, and memory which you need for temporary storage in your internal function. When you assign a string to a variable which is returned to the parser you need to make sure you first allocate the memory with either emalloc() or estrdup(). This memory should NEVER be freed by you, unless you later in the same function overwrite your original assignment (this kind of programming practice is not good though).
For any temporary/permanent memory you need in your functions/library you should use the three emalloc(), estrdup(), and efree() functions. They behave EXACTLY like their counterpart functions. Anything you emalloc() or estrdup() you have to efree() at some point or another, unless it's supposed to stick around until the end of the program; otherwise, there will be a memory leak. The meaning of "the functions behave exactly like their counterparts" is: if you efree() something which was not emalloc()'ed nor estrdup()'ed you might get a segmentation fault. So please take care and free all of your wasted memory.
If you compile with "-DDEBUG", PHP 3 will print out a list of all memory that was allocated using emalloc() and estrdup() but never freed with efree() when it is done running the specified script.
A number of macros are available which make it easier to set a variable in the symbol table:
SET_VAR_STRING(name,value)
SET_VAR_DOUBLE(name,value)
SET_VAR_LONG(name,value)
Ostrze¿enie |
Be careful with SET_VAR_STRING. The value part must be malloc'ed manually because the memory management code will try to free this pointer later. Do not pass statically allocated memory into a SET_VAR_STRING. |
Symbol tables in PHP 3.0 are implemented as hash tables. At any given time, &symbol_table is a pointer to the 'main' symbol table, and active_symbol_table points to the currently active symbol table (these may be identical like in startup, or different, if you're inside a function).
The following examples use 'active_symbol_table'. You should replace it with &symbol_table if you specifically want to work with the 'main' symbol table. Also, the same functions may be applied to arrays, as explained below.
If you want to define a new array in a symbol table, you should do the following.
First, you may want to check whether it exists and abort appropriately, using hash_exists() or hash_find().
Next, initialize the array:
Here's how to add new entries to it:
Przykład F-6. Adding entries to a new array
|
hash_next_index_insert() uses more or less the same logic as "$foo[] = bar;" in PHP 2.0.
If you are building an array to return from a function, you can initialize the array just like above by doing:
if (array_init(return_value) == FAILURE) { failed...; } |
...and then adding values with the helper functions:
add_next_index_long(return_value,long_value); add_next_index_double(return_value,double_value); add_next_index_string(return_value,estrdup(string_value)); |
Of course, if the adding isn't done right after the array initialization, you'd probably have to look for the array first:
pval *arr; if (hash_find(active_symbol_table,"foo",sizeof("foo"),(void **)&arr)==FAILURE) { can't find... } else { use arr->value.ht... } |
Note that hash_find receives a pointer to a pval pointer, and not a pval pointer.
Just about any hash function returns SUCCESS or FAILURE (except for hash_exists(), which returns a boolean truth value).
A number of macros are available to make returning values from a function easier.
The RETURN_* macros all set the return value and return from the function:
RETURN
RETURN_FALSE
RETURN_TRUE
RETURN_LONG(l)
RETURN_STRING(s,dup) If dup is TRUE, duplicates the string
RETURN_STRINGL(s,l,dup) Return string (s) specifying length (l).
RETURN_DOUBLE(d)
The RETVAL_* macros set the return value, but do not return.
RETVAL_FALSE
RETVAL_TRUE
RETVAL_LONG(l)
RETVAL_STRING(s,dup) If dup is TRUE, duplicates the string
RETVAL_STRINGL(s,l,dup) Return string (s) specifying length (l).
RETVAL_DOUBLE(d)
The string macros above will all estrdup() the passed 's' argument, so you can safely free the argument after calling the macro, or alternatively use statically allocated memory.
If your function returns boolean success/error responses, always use RETURN_TRUE and RETURN_FALSE respectively.
Your function can also return a complex data type such as an object or an array.
Returning an object:
Call object_init(return_value).
Fill it up with values. The functions available for this purpose are listed below.
Possibly, register functions for this object. In order to obtain values from the object, the function would have to fetch "this" from the active_symbol_table. Its type should be IS_OBJECT, and it's basically a regular hash table (i.e., you can use regular hash functions on .value.ht). The actual registration of the function can be done using:
add_method( return_value, function_name, function_ptr ); |
The functions used to populate an object are:
add_property_long( return_value, property_name, l ) - Add a property named 'property_name', of type long, equal to 'l'
add_property_double( return_value, property_name, d ) - Same, only adds a double
add_property_string( return_value, property_name, str ) - Same, only adds a string
add_property_stringl( return_value, property_name, str, l ) - Same, only adds a string of length 'l'
Returning an array:
Call array_init(return_value).
Fill it up with values. The functions available for this purpose are listed below.
The functions used to populate an array are:
add_assoc_long(return_value,key,l) - add associative entry with key 'key' and long value 'l'
add_assoc_double(return_value,key,d)
add_assoc_string(return_value,key,str,duplicate)
add_assoc_stringl(return_value,key,str,length,duplicate) specify the string length
add_index_long(return_value,index,l) - add entry in index 'index' with long value 'l'
add_index_double(return_value,index,d)
add_index_string(return_value,index,str)
add_index_stringl(return_value,index,str,length) - specify the string length
add_next_index_long(return_value,l) - add an array entry in the next free offset with long value 'l'
add_next_index_double(return_value,d)
add_next_index_string(return_value,str)
add_next_index_stringl(return_value,str,length) - specify the string length
PHP 3.0 has a standard way of dealing with various types of resources. This replaces all of the local linked lists in PHP 2.0.
Available functions:
php3_list_insert(ptr, type) - returns the 'id' of the newly inserted resource
php3_list_delete(id) - delete the resource with the specified id
php3_list_find(id,*type) - returns the pointer of the resource with the specified id, updates 'type' to the resource's type
Typical list code would look like this:
Przykład F-8. Using an existing resource
|
PHP 3.0 has a standard way of storing persistent resources (i.e., resources that are kept in between hits). The first module to use this feature was the MySQL module, and mSQL followed it, so one can get the general impression of how a persistent resource should be used by reading mysql.c. The functions you should look at are:
php3_mysql_do_connect |
php3_mysql_connect() |
php3_mysql_pconnect() |
The general idea of persistence modules is this:
Code all of your module to work with the regular resource list mentioned in section (9).
Code extra connect functions that check if the resource already exists in the persistent resource list. If it does, register it as in the regular resource list as a pointer to the persistent resource list (because of 1., the rest of the code should work immediately). If it doesn't, then create it, add it to the persistent resource list AND add a pointer to it from the regular resource list, so all of the code would work since it's in the regular resource list, but on the next connect, the resource would be found in the persistent resource list and be used without having to recreate it. You should register these resources with a different type (e.g. LE_MYSQL_LINK for non-persistent link and LE_MYSQL_PLINK for a persistent link).
If you read mysql.c, you'll notice that except for the more complex connect function, nothing in the rest of the module has to be changed.
The very same interface exists for the regular resource list and the persistent resource list, only 'list' is replaced with 'plist':
php3_plist_insert(ptr, type) - returns the 'id' of the newly inserted resource
php3_plist_delete(id) - delete the resource with the specified id
php3_plist_find(id,*type) - returns the pointer of the resource with the specified id, updates 'type' to the resource's type
However, it's more than likely that these functions would prove to be useless for you when trying to implement a persistent module. Typically, one would want to use the fact that the persistent resource list is really a hash table. For instance, in the MySQL/mSQL modules, when there's a pconnect() call (persistent connect), the function builds a string out of the host/user/passwd that were passed to the function, and hashes the SQL link with this string as a key. The next time someone calls a pconnect() with the same host/user/passwd, the same key would be generated, and the function would find the SQL link in the persistent list.
Until further documented, you should look at mysql.c or msql.c to see how one should use the plist's hash table abilities.
One important thing to note: resources going into the persistent resource list must *NOT* be allocated with PHP's memory manager, i.e., they should NOT be created with emalloc(), estrdup(), etc. Rather, one should use the regular malloc(), strdup(), etc. The reason for this is simple - at the end of the request (end of the hit), every memory chunk that was allocated using PHP's memory manager is deleted. Since the persistent list isn't supposed to be erased at the end of a request, one mustn't use PHP's memory manager for allocating resources that go to it.
When you register a resource that's going to be in the persistent list, you should add destructors to it both in the non-persistent list and in the persistent list. The destructor in the non-persistent list destructor shouldn't do anything. The one in the persistent list destructor should properly free any resources obtained by that type (e.g. memory, SQL links, etc). Just like with the non-persistent resources, you *MUST* add destructors for every resource, even it requires no destruction and the destructor would be empty. Remember, since emalloc() and friends aren't to be used in conjunction with the persistent list, you mustn't use efree() here either.
Many of the features of PHP 3 can be configured at runtime. These configuration directives can appear in either the designated php3.ini file, or in the case of the Apache module version in the Apache .conf files. The advantage of having them in the Apache .conf files is that they can be configured on a per-directory basis. This means that one directory may have a certain safemodeexecdir for example, while another directory may have another. This configuration granularity is especially handy when a server supports multiple virtual hosts.
The steps required to add a new directive:
Add directive to php3_ini_structure struct in mod_php3.h.
In main.c, edit the php3_module_startup function and add the appropriate cfg_get_string() or cfg_get_long() call.
Add the directive, restrictions and a comment to the php3_commands structure in mod_php3.c. Note the restrictions part. RSRC_CONF are directives that can only be present in the actual Apache .conf files. Any OR_OPTIONS directives can be present anywhere, include normal .htaccess files.
In either php3take1handler() or php3flaghandler() add the appropriate entry for your directive.
In the configuration section of the _php3_info() function in functions/info.c you need to add your new directive.
And last, you of course have to use your new directive somewhere. It will be addressable as php3_ini.directive.
To call user functions from an internal function, you should use the call_user_function() function.
call_user_function() returns SUCCESS on success, and FAILURE in case the function cannot be found. You should check that return value! If it returns SUCCESS, you are responsible for destroying the retval pval yourself (or return it as the return value of your function). If it returns FAILURE, the value of retval is undefined, and you mustn't touch it.
All internal functions that call user functions must be reentrant. Among other things, this means they must not use globals or static variables.
call_user_function() takes six arguments:
This is a pointer to an object on which the function is invoked. This should be NULL if a global function is called. If it's not NULL (i.e. it points to an object), the function_table argument is ignored, and instead taken from the object's hash. The object *may* be modified by the function that is invoked on it (that function will have access to it via $this). If for some reason you don't want that to happen, send a copy of the object instead.
The name of the function to call. Must be a pval of type IS_STRING with function_name.str.val and function_name.str.len set to the appropriate values. The function_name is modified by call_user_function() - it's converted to lowercase. If you need to preserve the case, send a copy of the function name instead.
A pointer to a pval structure, into which the return value of the invoked function is saved. The structure must be previously allocated - call_user_function() does NOT allocate it by itself.
An array of pointers to values that will be passed as arguments to the function, the first argument being in offset 0, the second in offset 1, etc. The array is an array of pointers to pval's; The pointers are sent as-is to the function, which means if the function modifies its arguments, the original values are changed (passing by reference). If you don't want that behavior, pass a copy instead.
To report errors from an internal function, you should call the php3_error() function. This takes at least two parameters -- the first is the level of the error, the second is the format string for the error message (as in a standard printf() call), and any following arguments are the parameters for the format string. The error levels are:
Notices are not printed by default, and indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script. For example, trying to access the value of a variable which has not been set, or calling stat() on a file that doesn't exist.
Warnings are printed by default, but do not interrupt script execution. These indicate a problem that should have been trapped by the script before the call was made. For example, calling ereg() with an invalid regular expression.
Errors are also printed by default, and execution of the script is halted after the function returns. These indicate errors that can not be recovered from, such as a memory allocation problem.
Parse errors should only be generated by the parser. The code is listed here only for the sake of completeness.
This is like an E_ERROR, except it is generated by the core of PHP. Functions should not generate this type of error.
This is like an E_WARNING, except it is generated by the core of PHP. Functions should not generate this type of error.
This is like an E_ERROR, except it is generated by the Zend Scripting Engine. Functions should not generate this type of error.
This is like an E_WARNING, except it is generated by the Zend Scripting Engine. Functions should not generate this type of error.
This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error(). Functions should not generate this type of error.
This is like an E_WARNING, except it is generated by using the PHP function trigger_error(). Functions should not generate this type of error.
This is like an E_NOTICE, except it is generated by using the PHP function trigger_error(). Functions should not generate this type of error.
Poniżej znajduje się lista wszystkich aliasów. Wykorzystywanie aliasów jest raczej złym rozwiązaniem, gdyż mogą zostać usunięte lub zmienione, co spowoduje że nie będzie można przenieść skryptu na inną platformę. Lista ta jest przeznaczona dla osób, które chcą zaktualizować skrypty do nowej składni.
Należy pamiętać, że niektóre funkcje po prostu mają dwie nazwy i nie ma żadnej różnicy w ich użyciu. Na przykład nazwy is_int() i is_integer() są równie dobre.
Ta lista jest zgodna z PHP 4.0.6.
Tabela G-1. Aliases
Alias | Funkcja macierzysta | Wykorzystywane rozszerzenie |
---|---|---|
add | swfmovie_add() | Ming (flash) |
add | swfsprite_add() | Ming (flash) |
add_root | domxml_add_root() | DOM XML |
addaction | swfbutton_addAction() | Ming (flash) |
addcolor | swfdisplayitem_addColor() | Ming (flash) |
addentry | swfgradient_addEntry() | Ming (flash) |
addfill | swfshape_addfill() | Ming (flash) |
addshape | swfbutton_addShape() | Ming (flash) |
addstring | swftext_addString() | Ming (flash) |
addstring | swftextfield_addString() | Ming (flash) |
align | swftextfield_align() | Ming (flash) |
attributes | domxml_attributes() | DOM XML |
children | domxml_children() | DOM XML |
chop | rtrim() | Podstawowa składnia |
close | closedir() | Podstawowa składnia |
com_get | com_propget() | COM |
com_propset | com_propput() | COM |
com_set | com_propput() | COM |
cv_add | ccvs_add() | CCVS |
cv_auth | ccvs_auth() | CCVS |
cv_command | ccvs_command() | CCVS |
cv_count | ccvs_count() | CCVS |
cv_delete | ccvs_delete() | CCVS |
cv_done | ccvs_done() | CCVS |
cv_init | ccvs_init() | CCVS |
cv_lookup | ccvs_lookup() | CCVS |
cv_new | ccvs_new() | CCVS |
cv_report | ccvs_report() | CCVS |
cv_return | ccvs_return() | CCVS |
cv_reverse | ccvs_reverse() | CCVS |
cv_sale | ccvs_sale() | CCVS |
cv_status | ccvs_status() | CCVS |
cv_textvalue | ccvs_textvalue() | CCVS |
cv_void | ccvs_void() | CCVS |
die | exit() | Różne funkcje |
dir | getdir() | Podstawowa składnia |
diskfreespace | disk_free_space() | System plików |
domxml_getattr | domxml_get_attribute() | DOM XML |
domxml_setattr | domxml_set_attribute() | DOM XML |
doubleval | floatval() | Podstawowa składnia |
drawarc | swfshape_drawarc() | Ming (flash) |
drawcircle | swfshape_drawcircle() | Ming (flash) |
drawcubic | swfshape_drawcubic() | Ming (flash) |
drawcubicto | swfshape_drawcubicto() | Ming (flash) |
drawcurve | swfshape_drawcurve() | Ming (flash) |
drawcurveto | swfshape_drawcurveto() | Ming (flash) |
drawglyph | swfshape_drawglyph() | Ming (flash) |
drawline | swfshape_drawline() | Ming (flash) |
drawlineto | swfshape_drawlineto() | Ming (flash) |
dtd | domxml_intdtd() | DOM XML |
dumpmem | domxml_dumpmem() | DOM XML |
fbsql | fbsql_db_query() | FrontBase |
fputs | fwrite() | Podstawowa składnia |
get_attribute | domxml_get_attribute() | DOM XML |
getascent | swffont_getAscent() | Ming (flash) |
getascent | swftext_getAscent() | Ming (flash) |
getattr | domxml_get_attribute() | DOM XML |
getdescent | swffont_getDescent() | Ming (flash) |
getdescent | swftext_getDescent() | Ming (flash) |
getheight | swfbitmap_getHeight() | Ming (flash) |
getleading | swffont_getLeading() | Ming (flash) |
getleading | swftext_getLeading() | Ming (flash) |
getshape1 | swfmorph_getShape1() | Ming (flash) |
getshape2 | swfmorph_getShape2() | Ming (flash) |
getwidth | swfbitmap_getWidth() | Ming (flash) |
getwidth | swffont_getWidth() | Ming (flash) |
getwidth | swftext_getWidth() | Ming (flash) |
gzputs | gzwrite() | Zlib |
i18n_convert | mb_convert_encoding() | Multi-bytes Strings |
i18n_discover_encoding | mb_detect_encoding() | Multi-bytes Strings |
i18n_http_input | mb_http_input() | Multi-bytes Strings |
i18n_http_output | mb_http_output() | Multi-bytes Strings |
i18n_internal_encoding | mb_internal_encoding() | Multi-bytes Strings |
i18n_ja_jp_hantozen | mb_convert_kana() | Multi-bytes Strings |
i18n_mime_header_decode | mb_decode_mimeheader() | Multi-bytes Strings |
i18n_mime_header_encode | mb_encode_mimeheader() | Multi-bytes Strings |
imap_create | imap_createmailbox() | IMAP |
imap_fetchtext | imap_body() | IMAP |
imap_getmailboxes | imap_list_full() | IMAP |
imap_getsubscribed | imap_lsub_full() | IMAP |
imap_header | imap_headerinfo() | IMAP |
imap_listmailbox | imap_list() | IMAP |
imap_listsubscribed | imap_lsub() | IMAP |
imap_rename | imap_renamemailbox() | IMAP |
imap_scan | imap_listscan() | IMAP |
imap_scanmailbox | imap_listscan() | IMAP |
ini_alter | ini_set() | Podstawowa składnia |
is_double | is_float() | Podstawowa składnia |
is_integer | is_int() | Podstawowa składnia |
is_long | is_int() | Podstawowa składnia |
is_real | is_float() | Podstawowa składnia |
is_writeable | is_writable() | Podstawowa składnia |
join | implode() | Podstawowa składnia |
labelframe | swfmovie_labelFrame() | Ming (flash) |
labelframe | swfsprite_labelFrame() | Ming (flash) |
last_child | domxml_last_child() | DOM XML |
lastchild | domxml_last_child() | DOM XML |
ldap_close | ldap_unbind() | LDAP |
magic_quotes_runtime | set_magic_quotes_runtime() | Podstawowa składnia |
mbstrcut | mb_strcut() | Multi-bytes Strings |
mbstrlen | mb_strlen() | Multi-bytes Strings |
mbstrpos | mb_strpos() | Multi-bytes Strings |
mbstrrpos | mb_strrpos() | Multi-bytes Strings |
mbsubstr | mb_substr() | Multi-bytes Strings |
ming_setcubicthreshold | ming_setCubicThreshold() | Ming (flash) |
ming_setscale | ming_setScale() | Ming (flash) |
move | swfdisplayitem_move() | Ming (flash) |
movepen | swfshape_movepen() | Ming (flash) |
movepento | swfshape_movepento() | Ming (flash) |
moveto | swfdisplayitem_moveTo() | Ming (flash) |
moveto | swffill_moveTo() | Ming (flash) |
moveto | swftext_moveTo() | Ming (flash) |
msql | msql_db_query() | mSQL |
msql_affected_rows | msql_affected_rows() | mSQL |
msql_createdb | msql_create_db() | mSQL |
msql_dbname | msql_result() | mSQL |
msql_dropdb | msql_drop_db() | mSQL |
msql_fieldflags | msql_field_flags() | mSQL |
msql_fieldlen | msql_field_len() | mSQL |
msql_fieldname | msql_field_name() | mSQL |
msql_fieldtable | msql_field_table() | mSQL |
msql_fieldtype | msql_field_type() | mSQL |
msql_freeresult | msql_free_result() | mSQL |
msql_listdbs | msql_list_dbs() | mSQL |
msql_listfields | msql_list_fields() | mSQL |
msql_listtables | msql_list_tables() | mSQL |
msql_numfields | msql_num_fields() | mSQL |
msql_numrows | msql_num_rows() | mSQL |
msql_regcase | sql_regcase() | mSQL |
msql_selectdb | msql_select_db() | mSQL |
msql_tablename | msql_result() | mSQL |
mssql_affected_rows | sybase_affected_rows() | Sybase |
mssql_affected_rows | sybase_affected_rows() | Sybase |
mssql_close | sybase_close() | Sybase |
mssql_close | sybase_close() | Sybase |
mssql_connect | sybase_connect() | Sybase |
mssql_connect | sybase_connect() | Sybase |
mssql_data_seek | sybase_data_seek() | Sybase |
mssql_data_seek | sybase_data_seek() | Sybase |
mssql_fetch_array | sybase_fetch_array() | Sybase |
mssql_fetch_array | sybase_fetch_array() | Sybase |
mssql_fetch_field | sybase_fetch_field() | Sybase |
mssql_fetch_field | sybase_fetch_field() | Sybase |
mssql_fetch_object | sybase_fetch_object() | Sybase |
mssql_fetch_object | sybase_fetch_object() | Sybase |
mssql_fetch_row | sybase_fetch_row() | Sybase |
mssql_fetch_row | sybase_fetch_row() | Sybase |
mssql_field_seek | sybase_field_seek() | Sybase |
mssql_field_seek | sybase_field_seek() | Sybase |
mssql_free_result | sybase_free_result() | Sybase |
mssql_free_result | sybase_free_result() | Sybase |
mssql_get_last_message | sybase_get_last_message() | Sybase |
mssql_get_last_message | sybase_get_last_message() | Sybase |
mssql_min_client_severity | sybase_min_client_severity() | Sybase |
mssql_min_error_severity | sybase_min_error_severity() | Sybase |
mssql_min_message_severity | sybase_min_message_severity() | Sybase |
mssql_min_server_severity | sybase_min_server_severity() | Sybase |
mssql_num_fields | sybase_num_fields() | Sybase |
mssql_num_fields | sybase_num_fields() | Sybase |
mssql_num_rows | sybase_num_rows() | Sybase |
mssql_num_rows | sybase_num_rows() | Sybase |
mssql_pconnect | sybase_pconnect() | Sybase |
mssql_pconnect | sybase_pconnect() | Sybase |
mssql_query | sybase_query() | Sybase |
mssql_query | sybase_query() | Sybase |
mssql_result | sybase_result() | Sybase |
mssql_result | sybase_result() | Sybase |
mssql_select_db | sybase_select_db() | Sybase |
mssql_select_db | sybase_select_db() | Sybase |
multcolor | swfdisplayitem_multColor() | Ming (flash) |
mysql | mysql_db_query() | MySQL |
mysql_createdb | mysql_create_db() | MySQL |
mysql_db_name | mysql_result() | MySQL |
mysql_dbname | mysql_result() | MySQL |
mysql_dropdb | mysql_drop_db() | MySQL |
mysql_fieldflags | mysql_field_flags() | MySQL |
mysql_fieldlen | mysql_field_len() | MySQL |
mysql_fieldname | mysql_field_name() | MySQL |
mysql_fieldtable | mysql_field_table() | MySQL |
mysql_fieldtype | mysql_field_type() | MySQL |
mysql_freeresult | mysql_free_result() | MySQL |
mysql_listdbs | mysql_list_dbs() | MySQL |
mysql_listfields | mysql_list_fields() | MySQL |
mysql_listtables | mysql_list_tables() | MySQL |
mysql_numfields | mysql_num_fields() | MySQL |
mysql_numrows | mysql_num_rows() | MySQL |
mysql_selectdb | mysql_select_db() | MySQL |
mysql_tablename | mysql_result() | MySQL |
name | domxml_attrname() | DOM XML |
new_child | domxml_new_child() | DOM XML |
new_xmldoc | domxml_new_xmldoc() | DOM XML |
nextframe | swfmovie_nextFrame() | Ming (flash) |
nextframe | swfsprite_nextFrame() | Ming (flash) |
node | domxml_node() | DOM XML |
oci8append | ocicollappend() | OCI8 |
oci8assign | ocicollassign() | OCI8 |
oci8assignelem | ocicollassignelem() | OCI8 |
oci8close | ocicloselob() | OCI8 |
oci8free | ocifreecoll() | OCI8 |
oci8free | ocifreedesc() | OCI8 |
oci8getelem | ocicollgetelem() | OCI8 |
oci8load | ociloadlob() | OCI8 |
oci8max | ocicollmax() | OCI8 |
oci8ocifreecursor | ocifreestatement() | OCI8 |
oci8save | ocisavelob() | OCI8 |
oci8savefile | ocisavelobfile() | OCI8 |
oci8size | ocicollsize() | OCI8 |
oci8trim | ocicolltrim() | OCI8 |
oci8writetemporary | ociwritetemporarylob() | OCI8 |
oci8writetofile | ociwritelobtofile() | OCI8 |
odbc_do | odbc_exec() | OCI8 |
odbc_field_precision | odbc_field_len() | OCI8 |
orbit_caught_exception | satellite_caught_exception() | Satellite |
orbit_exception_id | satellite_exception_id() | Satellite |
orbit_exception_value | satellite_exception_value() | Satellite |
orbit_get_repository_id | satellite_get_repository_id() | Satellite |
orbit_load_idl | satellite_load_idl() | Satellite |
output | swfmovie_output() | Ming (flash) |
parent | domxml_parent() | DOM XML |
pdf_add_outline | pdf_add_bookmark() | |
pg_clientencoding | pg_client_encoding() | PostgreSQL |
pg_setclientencoding | pg_set_client_encoding() | PostgreSQL |
pos | current() | Podstawowa składnia |
recode | recode_string() | Recode |
remove | swfmovie_remove() | Ming (flash) |
remove | swfsprite_remove() | Ming (flash) |
rewind | rewinddir() | Podstawowa składnia |
root | domxml_root() | DOM XML |
rotate | swfdisplayitem_rotate() | Ming (flash) |
rotateto | swfdisplayitem_rotateTo() | Ming (flash) |
rotateto | swffill_rotateTo() | Ming (flash) |
save | swfmovie_save() | Ming (flash) |
savetofile | swfmovie_saveToFile() | Ming (flash) |
scale | swfdisplayitem_scale() | Ming (flash) |
scaleto | swfdisplayitem_scaleTo() | Ming (flash) |
scaleto | swffill_scaleTo() | Ming (flash) |
set_attribute | domxml_set_attribute() | DOM XML |
set_content | domxml_set_content() | DOM XML |
setaction | swfbutton_setAction() | Ming (flash) |
setattr | domxml_set_attribute() | DOM XML |
setbackground | swfmovie_setBackground() | Ming (flash) |
setbounds | swftextfield_setBounds() | Ming (flash) |
setcolor | swftext_setColor() | Ming (flash) |
setcolor | swftextfield_setColor() | Ming (flash) |
setdepth | swfdisplayitem_setDepth() | Ming (flash) |
setdimension | swfmovie_setDimension() | Ming (flash) |
setdown | swfbutton_setDown() | Ming (flash) |
setfont | swftext_setFont() | Ming (flash) |
setfont | swftextfield_setFont() | Ming (flash) |
setframes | swfmovie_setFrames() | Ming (flash) |
setframes | swfsprite_setFrames() | Ming (flash) |
setheight | swftext_setHeight() | Ming (flash) |
setheight | swftextfield_setHeight() | Ming (flash) |
sethit | swfbutton_setHit() | Ming (flash) |
setindentation | swftextfield_setIndentation() | Ming (flash) |
setleftfill | swfshape_setleftfill() | Ming (flash) |
setleftmargin | swftextfield_setLeftMargin() | Ming (flash) |
setline | swfshape_setline() | Ming (flash) |
setlinespacing | swftextfield_setLineSpacing() | Ming (flash) |
setmargins | swftextfield_setMargins() | Ming (flash) |
setmatrix | swfdisplayitem_setMatrix() | Ming (flash) |
setname | swfdisplayitem_setName() | Ming (flash) |
setname | swftextfield_setName() | Ming (flash) |
setover | swfbutton_setOver() | Ming (flash) |
setrate | swfmovie_setRate() | Ming (flash) |
setratio | swfdisplayitem_setRatio() | Ming (flash) |
setrightfill | swfshape_setrightfill() | Ming (flash) |
setrightmargin | swftextfield_setRightMargin() | Ming (flash) |
setspacing | swftext_setSpacing() | Ming (flash) |
setup | swfbutton_setUp() | Ming (flash) |
show_source | highlight_file () | Podstawowa składnia |
sizeof | count() | Podstawowa składnia |
skewx | swfdisplayitem_skewX() | Ming (flash) |
skewxto | swfdisplayitem_skewXTo() | Ming (flash) |
skewxto | swffill_skewXTo() | Ming (flash) |
skewy | swfdisplayitem_skewY() | Ming (flash) |
skewyto | swfdisplayitem_skewYTo() | Ming (flash) |
skewyto | swffill_skewYTo() | Ming (flash) |
snmpwalkoid | snmprealwalk() | SNMP |
strchr | strstr() | Podstawowa składnia |
streammp3 | swfmovie_streamMp3() | Ming (flash) |
swfaction | swfaction_init() | Ming (flash) |
swfbitmap | swfbitmap_init() | Ming (flash) |
swfbutton | swfbutton_init() | Ming (flash) |
swfbutton_keypress | swfbutton_keypress() | Ming (flash) |
swffill | swffill_init() | Ming (flash) |
swffont | swffont_init() | Ming (flash) |
swfgradient | swfgradient_init() | Ming (flash) |
swfmorph | swfmorph_init() | Ming (flash) |
swfmovie | swfmovie_init() | Ming (flash) |
swfshape | swfshape_init() | Ming (flash) |
swfsprite | swfsprite_init() | Ming (flash) |
swftext | swftext_init() | Ming (flash) |
swftextfield | swftextfield_init() | Ming (flash) |
unlink | domxml_unlink_node() | DOM XML |
xpath_eval | xpath_eval() | DOM XML |
xpath_eval_expression | xpath_eval_expression() | DOM XML |
xpath_init | xpath_init() | DOM XML |
xpath_new_context | xpath_new_context() | DOM XML |
xptr_new_context | xpath_new_context() | DOM XML |
Poniżej znajduje się lista zarezerwowanych słów w PHP. Są to zwykle stałe i zmienne predefiniowane. Nie ma na tej liście żadnych funkcji, choć są konstrukcje językowe. Nie powinno się próbować używać tych słów jako nazw zmiennych, funkcji, stałych czy metod, gdyż z całą pewnością spowoduje to powstanie błędu.
and | E_PARSE | old_function |
$argv | E_ERROR | or |
as | E_WARNING | parent |
$argc | eval | PHP_OS |
break | exit() | $PHP_SELF |
case | extends | PHP_VERSION |
cfunction | FALSE | print() |
class | for | require() |
continue | foreach | require_once() |
declare | function | return() |
default | $HTTP_COOKIE_VARS | static |
do | $HTTP_GET_VARS | switch |
die() | $HTTP_POST_VARS | stdClass |
echo() | $HTTP_POST_FILES | $this |
else | $HTTP_ENV_VARS | TRUE |
elseif | $HTTP_SERVER_VARS | var |
empty() | if | xor |
enddeclare | include() | virtual() |
endfor | include_once() | while |
endforeach | global | __FILE__ |
endif | list() | __LINE__ |
endswitch | new | __sleep |
endwhile | not | __wakeup |
E_ALL | NULL |
The following is a list of functions which create, use or destroy PHP resources. The function is_resource() can be used to determine if a variable is a resource and get_resource_type() will return the type of resource it is.
Tabela I-1. Resource Types
Resource Type Name | Created By | Used By | Destroyed By | Definition |
---|---|---|---|---|
aspell | aspell_new() | aspell_check(), aspell_check_raw(), aspell_suggest() | None | Aspell dictionary |
bzip2 | bzopen() | bzerrno(), bzerror(), bzerrstr(), bzflush(), bzread(), bzwrite() | bzclose() | Bzip2 file |
COM | com_load() | com_invoke(), com_propget(), com_get(), com_propput(), com_set(), com_propput() | None | COM object reference |
VARIANT | ||||
cpdf | cpdf_open() | cpdf_page_init(), cpdf_finalize_page(), cpdf_finalize(), cpdf_output_buffer(), cpdf_save_to_file(), cpdf_set_current_page(), cpdf_begin_text(), cpdf_end_text(), cpdf_show(), cpdf_show_xy(), cpdf_text(), cpdf_set_font(), cpdf_set_leading(), cpdf_set_text_rendering(), cpdf_set_horiz_scaling(), cpdf_set_text_rise(), cpdf_set_text_matrix(), cpdf_set_text_pos(), cpdf_set_text_pos(), cpdf_set_word_spacing(), cpdf_continue_text(), cpdf_stringwidth(), cpdf_save(), cpdf_translate(), cpdf_restore(), cpdf_scale(), cpdf_rotate(), cpdf_setflat(), cpdf_setlinejoin(), cpdf_setlinecap(), cpdf_setmiterlimit(), cpdf_setlinewidth(), cpdf_setdash(), cpdf_moveto(), cpdf_rmoveto(), cpdf_curveto(), cpdf_lineto(), cpdf_rlineto(), cpdf_circle(), cpdf_arc(), cpdf_rect(), cpdf_closepath(), cpdf_stroke(), cpdf_closepath_fill_stroke(), cpdf_fill_stroke(), cpdf_clip(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray_stroke(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor(), cpdf_add_outline(), cpdf_set_page_animation(), cpdf_import_jpeg(), cpdf_place_inline_image(), cpdf_add_annotation() | cpdf_close() | PDF document with CPDF lib |
cpdf outline | ||||
curl | curl_init() | curl_init(), curl_exec() | curl_close() | Curl session |
dbm | dbmopen() | dbmexists(), dbmfetch(), dbminsert(), dbmreplace(), dbmdelete(), dbmfirstkey(), dbmnextkey() | dbmclose() | Link to DBM database |
dba | dba_popen() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | dba_close() | Link to DBA base |
dba persistent | dba_open() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | None | Persistent link to DBA base |
dbase | dbase_open() | dbase_pack(), dbase_add_record(), dbase_replace_record(), dbase_delete_record(), dbase_get_record(), dbase_get_record_with_names(), dbase_numfields(), dbase_numrecords() | dbase_close() | Link to Dbase base |
dbx_link_object | dbx_connect() | dbx_query() | dbx_close() | dbx connection |
dbx_result_object | dbx_query() | () | None | dbx result |
domxml attribute | ||||
domxml document | ||||
domxml node | ||||
xpath context | ||||
xpath object | ||||
fbsql database | fbsql_select_db() | () | None | fbsql database |
fbsql link | fbsql_change_user(), fbsql_connect() | fbsql_autocommit(), fbsql_change_user(), fbsql_create_db(), fbsql_data_seek(), fbsql_db_query(), fbsql_drop_db(), (), fbsql_select_db(), fbsql_errno(), fbsql_error(), fbsql_insert_id(), fbsql_list_dbs() | fbsql_close() | Link to fbsql database |
fbsql plink | fbsql_change_user(), fbsql_pconnect() | fbsql_autocommit(), fbsql_change_user(), fbsql_create_db(), fbsql_data_seek(), fbsql_db_query(), fbsql_drop_db(), (), fbsql_select_db(), fbsql_errno(), fbsql_error(), fbsql_insert_id(), fbsql_list_dbs() | None | Persistent link to fbsql database |
fbsql result | fbsql_db_query(), fbsql_list_dbs(), fbsql_query(), fbsql_list_fields(), fbsql_list_tables(), fbsql_tablename() | fbsql_affected_rows(), fbsql_fetch_array(), fbsql_fetch_assoc(), fbsql_fetch_field(), fbsql_fetch_lengths(), fbsql_fetch_object(), fbsql_fetch_row(), fbsql_field_flags(), fbsql_field_name(), fbsql_field_len(), fbsql_field_seek(), fbsql_field_table(), fbsql_field_type(), fbsql_next_result(), fbsql_num_fields(), fbsql_num_rows(), fbsql_result(), fbsql_num_rows() | fbsql_free_result() | fbsql result |
fdf | fdf_open() | fdf_create(), fdf_save(), fdf_get_value(), fdf_set_value(), fdf_next_field_name(), fdf_set_ap(), fdf_set_status(), fdf_get_status(), fdf_set_file(), fdf_get_file(), fdf_set_flags(), fdf_set_opt(), fdf_set_submit_form_action(), fdf_set_javascript_action() | fdf_close() | FDF File |
ftp | ftp_connect() | ftp_login(), ftp_pwd(), ftp_cdup(), ftp_chdir(), ftp_mkdir(), ftp_rmdir(), ftp_nlist(), ftp_rawlist(), ftp_systype(), ftp_pasv(), ftp_get(), ftp_fget(), ftp_put(), ftp_fput(), ftp_size(), ftp_mdtm(), ftp_rename(), ftp_delete(), ftp_site() | ftp_quit() | FTP stream |
gd | imagecreate(), imagecreatefromgif(), imagecreatefromjpeg(), imagecreatefrompng(), imagecreatefromwbmp(), imagecreatefromstring(), imagecreatetruecolor() | imagearc(), imagechar(), imagecharup(), imagecolorallocate(), imagecolorat(), imagecolorclosest(), imagecolorexact(), imagecolorresolve(), imagegammacorrect(), imagegammacorrect(), imagecolorset(), imagecolorsforindex(), imagecolorstotal(), imagecolortransparent(), imagecopy(), imagecopyresized(), imagedashedline(), imagefill(), imagefilledpolygon(), imagefilledrectangle(), imagefilltoborder(), imagegif(), imagepng(), imagejpeg(), imagewbmp(), imageinterlace(), imageline(), imagepolygon(), imagepstext(), imagerectangle(), imagesetpixel(), imagestring(), imagestringup(), imagesx(), imagesy(), imagettftext(), imagefilledarc(), imageellipse(), imagefilledellipse(), imagecolorclosestalpha(), imagecolorexactalpha(), imagecolorresolvealpha(), imagecopymerge(), imagecopymergegray(), imagecopyresampled(), imagetruecolortopalette(), imagesetbrush(), imagesettile(), imagesetthickness() | imagedestroy() | GD Image |
gd font | imageloadfont() | imagechar(), imagecharup(), imagefontheight() | None | Font for GD |
gd PS encoding | ||||
gd PS font | imagepsloadfont() | imagepstext(), imagepsslantfont(), imagepsextendfont(), imagepsencodefont(), imagepsbbox() | imagepsfreefont() | PS font for GD |
GMP integer | gmp_init() | gmp_intval(), gmp_strval(), gmp_add(), gmp_sub(), gmp_mul(), gmp_div_q(), gmp_div_r(), gmp_div_qr(), gmp_div(), gmp_mod(), gmp_divexact(), gmp_cmp(), gmp_neg(), gmp_abs(), gmp_sign(), gmp_fact(), gmp_sqrt(), gmp_sqrtrm(), gmp_perfect_square(), gmp_pow(), gmp_powm(), gmp_prob_prime(), gmp_gcd(), gmp_gcdext(), gmp_invert(), gmp_legendre(), gmp_jacobi(), gmp_random(), gmp_and(), gmp_or(), gmp_xor(), gmp_setbit(), gmp_clrbit(), gmp_scan0(), gmp_scan1(), gmp_popcount(), gmp_hamdist() | None | GMP Number |
hyperwave document | hw_cp(), hw_docbyanchor(), hw_getremote(), hw_getremotechildren() | hw_children(), hw_childrenobj(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getsrcbydestobj(), hw_getandlock(), hw_gettext(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_inscoll(), hw_pipedocument(), hw_unlock() | hw_deleteobject() | Hyperwave object |
hyperwave link | hw_connect() | hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() | hw_close(), hw_free_document() | Link to Hyperwave server |
hyperwave link persistent | hw_pconnect() | hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() | None | Persistent link to Hyperwave server |
icap | icap_open() | icap_fetch_event(), icap_list_events(), icap_store_event(), icap_snooze(), icap_list_alarms(), icap_delete_event() | icap_close() | Link to icap server |
imap | imap_open() | imap_append(), imap_body(), imap_check(), imap_createmailbox(), imap_delete(), imap_deletemailbox(), imap_expunge(), imap_fetchbody(), imap_fetchstructure(), imap_headerinfo(), imap_header(), imap_headers(), imap_listmailbox(), imap_getmailboxes(), imap_get_quota(), imap_status(), imap_listsubscribed(), imap_set_quota(), imap_set_quota(), imap_getsubscribed(), imap_mail_copy(), imap_mail_move(), imap_num_msg(), imap_num_recent(), imap_ping(), imap_renamemailbox(), imap_reopen(), imap_subscribe(), imap_undelete(), imap_unsubscribe(), imap_scanmailbox(), imap_mailboxmsginfo(), imap_fetchheader(), imap_uid(), imap_msgno(), imap_search(), imap_fetch_overview() | imap_close() | Link to IMAP, POP3 server |
imap chain persistent | ||||
imap persistent | ||||
ingres | ingres_connect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | ingres_close() | Link to ingresII base |
ingres persistent | ingres_pconnect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | None | Persistent link to ingresII base |
interbase blob | ||||
interbase link | ibase_connect() | ibase_query(), ibase_prepare(), ibase_trans() | ibase_close() | Link to Interbase database |
interbase link persistent | ibase_pconnect() | ibase_query(), ibase_prepare(), ibase_trans() | None | Persistent link to Interbase database |
interbase query | ibase_prepare() | ibase_execute() | ibase_free_query() | Interbase query |
interbase result | ibase_query() | ibase_fetch_row(), ibase_fetch_object(), ibase_field_info(), ibase_num_fields() | ibase_free_result() | Interbase Result |
interbase transaction | ibase_trans() | ibase_commit() | ibase_rollback() | Interbase transaction |
java | ||||
ldap link | ldap_connect(), ldap_search() | ldap_count_entries(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_next_attribute(), ldap_next_entry() | ldap_close() | ldap connection |
ldap result | ldap_read() | ldap_add(), ldap_compare(), ldap_bind(), ldap_count_entries(), ldap_delete(), ldap_errno(), ldap_error(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_get_option(), ldap_list(), ldap_modify(), ldap_mod_add(), ldap_mod_replace(), ldap_next_attribute(), ldap_next_entry(), ldap_mod_del(), ldap_set_option(), ldap_unbind() | ldap_free_result() | ldap search result |
ldap result entry | ||||
mcal | mcal_open(), mcal_popen() | mcal_create_calendar(), mcal_rename_calendar(), mcal_rename_calendar(), mcal_delete_calendar(), mcal_fetch_event(), mcal_list_events(), mcal_append_event(), mcal_store_event(), mcal_delete_event(), mcal_list_alarms(), mcal_event_init(), mcal_event_set_category(), mcal_event_set_title(), mcal_event_set_description(), mcal_event_set_start(), mcal_event_set_end(), mcal_event_set_alarm(), mcal_event_set_class(), mcal_next_recurrence(), mcal_event_set_recur_none(), mcal_event_set_recur_daily(), mcal_event_set_recur_weekly(), mcal_event_set_recur_monthly_mday(), mcal_event_set_recur_monthly_wday(), mcal_event_set_recur_yearly(), mcal_fetch_current_stream_event(), mcal_event_add_attribute(), mcal_expunge() | mcal_close() | Link to calendar server |
SWFAction | ||||
SWFBitmap | ||||
SWFButton | ||||
SWFDisplayItem | ||||
SWFFill | ||||
SWFFont | ||||
SWFGradient | ||||
SWFMorph | ||||
SWFMovie | ||||
SWFShape | ||||
SWFSprite | ||||
SWFText | ||||
SWFTextField | ||||
mnogosearch agent | ||||
mnogosearch result | ||||
msql link | msql_connect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | msql_close() | Link to mSQL database |
msql link persistent | msql_pconnect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | None | Persistent link to mSQL |
msql query | msql_query() | msql(), msql_affected_rows(), msql_data_seek(), msql_dbname(), msql_fetch_array(), msql_fetch_field(), msql_fetch_object(), msql_fetch_row(), msql_fieldname(), msql_field_seek(), msql_fieldtable(), msql_fieldtype(), msql_fieldflags(), msql_fieldlen(), msql_num_fields(), msql_num_rows(), msql_numfields(), msql_numrows(), msql_result() | msql_free_result(), msql_free_result() | mSQL result |
mssql link | mssql_connect() | mssql_query(), mssql_select_db() | mssql_close() | Link to Microsft SQL Server database |
mssql link persistent | mssql_pconnect() | mssql_query(), mssql_select_db() | None | Persistent link to Microsft SQL Server |
mssql result | mssql_query() | mssql_data_seek(), mssql_fetch_array(), mssql_fetch_field(), mssql_fetch_object(), mssql_fetch_row(), mssql_field_length(), mssql_field_name(), mssql_field_seek(), mssql_field_type(), mssql_num_fields(), mssql_num_rows(), mssql_result() | mssql_free_result() | Microsft SQL Server result |
mysql link | mysql_connect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | mysql_close() | Link to MySQL database |
mysql link persistent | mysql_pconnect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | None | Persistent link to MySQL database |
mysql result | mysql_db_query(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query() | mysql_data_seek(), mysql_db_name(), mysql_fetch_array(), mysql_fetch_assoc(), mysql_fetch_field(), mysql_fetch_lengths(), mysql_fetch_object(), mysql_fetch_row(), mysql_fetch_row(), mysql_field_flags(), mysql_field_name(), mysql_field_len(), mysql_field_seek(), mysql_field_table(), mysql_field_type(), mysql_num_fields(), mysql_num_rows(), mysql_result(), mysql_tablename() | mysql_free_result() | MySQL result |
oci8 collection | ||||
oci8 connection | ocilogon(), ociplogon(), ocinlogon() | ocicommit(), ociserverversion(), ocinewcursor(), ociparse(), ocierror() | ocilogoff() | Link to Oracle database |
oci8 descriptor | ||||
oci8 server | ||||
oci8 session | ||||
oci8 statement | ocinewdescriptor() | ocirollback(), ocinewdescriptor(), ocirowcount(), ocidefinebyname(), ocibindbyname(), ociexecute(), ocinumcols(), ociresult(), ocifetch(), ocifetchinto(), ocifetchstatement(), ocicolumnisnull(), ocicolumnname(), ocicolumnsize(), ocicolumntype(), ocistatementtype(), ocierror() | ocifreestatement() | Oracle Cursor |
odbc link | odbc_connect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | odbc_close() | Link to ODBC database |
odbc link persistent | odbc_connect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | None | Persistent link to ODBC database |
odbc result | odbc_prepare() | odbc_binmode(), odbc_cursor(), odbc_execute(), odbc_fetch_into(), odbc_fetch_row(), odbc_field_name(), odbc_field_num(), odbc_field_type(), odbc_field_len(), odbc_field_precision(), odbc_field_scale(), odbc_longreadlen(), odbc_num_fields(), odbc_num_rows(), odbc_result(), odbc_result_all(), odbc_setoption() | odbc_free_result() | ODBC result |
velocis link | ||||
velocis result | ||||
OpenSSL key | openssl_get_privatekey(), openssl_get_publickey() | openssl_sign(), openssl_seal(), openssl_open(), openssl_verify() | openssl_free_key() | OpenSSL key |
OpenSSL X.509 | openssl_x509_read() | openssl_x509_parse(), openssl_x509_checkpurpose() | openssl_x509_free() | Public Key |
oracle Cursor | ora_open() | ora_bind(), ora_columnname(), ora_columnsize(), ora_columntype(), ora_error(), ora_errorcode(), ora_exec(), ora_fetch(), ora_fetch_into(), ora_getcolumn(), ora_numcols(), ora_numrows(), ora_parse() | ora_close() | Oracle cursor |
oracle link | ora_logon() | ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() | ora_logoff() | Link to oracle database |
oracle link persistent | ora_plogon() | ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() | None | Persistent link to oracle database |
pdf document | pdf_new() | pdf_add_bookmark(), pdf_add_launchlink(), pdf_add_locallink(), pdf_add_note(), pdf_add_pdflink(), pdf_add_weblink(), pdf_arc(), pdf_attach_file(), pdf_begin_page(), pdf_circle(), pdf_clip(), pdf_closepath(), pdf_closepath_fill_stroke(), pdf_closepath_stroke(), pdf_concat(), pdf_continue_text(), pdf_curveto(), pdf_end_page(), pdf_endpath(), pdf_fill(), pdf_fill_stroke(), pdf_findfont(), pdf_get_buffer(), pdf_get_image_height(), pdf_get_image_width(), pdf_get_parameter(), pdf_get_value(), pdf_lineto(), pdf_moveto(), pdf_open_ccitt(), pdf_open_file(), pdf_open_image_file(), pdf_place_image(), pdf_rect(), pdf_restore(), pdf_rotate(), pdf_save(), pdf_scale(), pdf_setdash(), pdf_setflat(), pdf_setfont(), pdf_setgray(), pdf_setgray_fill(), pdf_setgray_stroke(), pdf_setlinecap(), pdf_setlinejoin(), pdf_setlinewidth(), pdf_setmiterlimit(), pdf_setpolydash(), pdf_setrgbcolor(), pdf_setrgbcolor_fill(), pdf_setrgbcolor_stroke(), pdf_set_border_color(), pdf_set_border_dash(), pdf_set_border_style(), pdf_set_char_spacing(), pdf_set_duration(), pdf_set_font(), pdf_set_horiz_scaling(), pdf_set_parameter(), pdf_set_text_pos(), pdf_set_text_rendering(), pdf_set_value(), pdf_set_word_spacing(), pdf_show(), pdf_show_boxed(), pdf_show_xy(), pdf_skew(), pdf_stringwidth(), pdf_stroke(), pdf_translate(), pdf_open_memory_image() | pdf_close(), pdf_delete() | PDF document |
pdf image | pdf_open_image(), pdf_open_image_file(), pdf_open_memory_image() | pdf_get_image_height(), pdf_get_image_width(), pdf_open_CCITT(), pdf_place_image() | pdf_close_image() | Image in PDF file |
pdf object | ||||
pdf outline | ||||
pgsql large object | pg_getlastoid(), pg_loimport(), pg_loimport() | pg_loopen(), pg_getlastoid(), pg_locreate(), pg_loexport(), pg_loread(), pg_loreadall(), pg_lounlink(), pg_lowrite() | pg_loclose() | PostGreSQL Large Object |
pgsql link | pg_connect() | pg_cmdtuples(), pg_dbname(), pg_end_copy(), pg_errormessage(), pg_host(), pg_locreate(), pg_loexport(), pg_loimport(), pg_loopen(), pg_lounlink(), pg_options(), pg_port(), pg_put_line(), pg_set_client_encoding(), pg_client_encoding(), pg_trace(), pg_untrace(), pg_tty() | pg_close() | Link to PostGreSQL database |
pgsql link persistent | pg_pconnect() | pg_cmdtuples(), pg_dbname(), pg_end_copy(), pg_errormessage(), pg_host(), pg_locreate(), pg_loexport(), pg_loimport(), pg_loopen(), pg_lounlink(), pg_options(), pg_port(), pg_put_line(), pg_set_client_encoding(), pg_client_encoding(), pg_trace(), pg_untrace(), pg_tty() | None | Persistent link to PostGreSQL database |
pgsql result | pg_exec() | pg_fetch_array(), pg_fetch_object(), pg_fieldisnull(), pg_fetch_row(), pg_fieldname(), pg_fieldnum(), pg_fieldprtlen(), pg_fieldsize(), pg_fieldtype(), pg_getlastoid(), pg_numfields(), pg_result(), pg_numrows() | pg_freeresult() | PostGreSQL result |
pgsql string | ||||
printer | ||||
printer brush | ||||
printer font | ||||
printer pen | ||||
pspell | pspell_new(), pspell_new_config(), pspell_new_personal() | pspell_add_to_personal(), pspell_add_to_session(), pspell_check(), pspell_clear_session(), pspell_config_ignore(), pspell_config_mode(), pspell_config_personal(), pspell_config_repl(), pspell_config_runtogether(), pspell_config_save_repl(), pspell_save_wordlist(), pspell_store_replacement(), pspell_suggest() | None | pspell dictionary |
pspell config | pspell_config_create() | pspell_new_config() | None | pspell configuration |
Sablotron XSLT | xslt_create() | xslt_closelog(), xslt_openlog(), xslt_run(), xslt_set_sax_handler(), xslt_errno(), xslt_error(), xslt_fetch_result(), xslt_free() | xslt_free() | XSLT parser |
shmop | shmop_open() | shmop_read(), shmop_write(), shmop_size(), shmop_delete() | shmop_close() | |
sockets file descriptor set | socket() | accept_connect(), bind(), connect(), listen(), read(), write() | close() | Socket |
sockets i/o vector | ||||
dir | dir() | readdir(), rewinddir() | closedir() | Dir handle |
file | fopen() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), flock(), fpassthru(), fputs(), fwrite(), fread(), fseek(), ftell(), fstat(), ftruncate(), set_file_buffer(), rewind() | fclose() | File handle |
pipe | popen() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | pclose() | Process handle |
socket | fsockopen() | fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | fclose() | Socket handle |
stream | ||||
sybase-db link | sybase_connect() | sybase_query(), sybase_select_db() | sybase_close() | Link to Sybase database using DB library |
sybase-db link persistent | sybase_pconnect() | sybase_query(), sybase_select_db() | None | Persistent link to Sybase database using DB library |
sybase-db result | sybase_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Sybase result using DB library |
sybase-ct link | sybase_connect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | sybase_close() | Link to Sybase database using CT library |
sybase-ct link persistent | sybase_pconnect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | None | Persistent link to Sybase database using CT library |
sybase-ct result | sybase_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Sybase result using CT library |
sysvsem | sem_get() | sem_acquire() | sem_release() | System V Semaphore |
sysvshm | shm_attach() | shm_remove(), shm_put_var(), shm_get_var(), shm_remove_var() | shm_detach() | System V Shared Memory |
wddx | wddx_packet_start() | wddx_add_vars() | wddx_packet_end() | WDDX packet |
xml | xml_parser_create() | xml_set_object(), xml_set_element_handler(), xml_set_character_data_handler(), xml_set_processing_instruction_handler(), xml_set_default_handler(), xml_set_unparsed_entity_decl_handler(), xml_set_notation_decl_handler(), xml_set_external_entity_ref_handler(), xml_parse(), xml_get_error_code(), xml_error_string(), xml_get_current_line_number(), xml_get_current_column_number(), xml_get_current_byte_index(), xml_parse_into_struct(), xml_parser_set_option(), xml_parser_get_option() | xml_parser_free() | XML parser |
zlib | gzopen() | gzeof(), gzgetc(), gzgets(), gzgetss(), gzpassthru(), gzputs(), gzread(), gzrewind(), gzseek(), gztell(), gzwrite() | gzclose() | gz-compressed file |
The PHP manual is provided in several formats. These formats can be divided into two groups: online readable formats, and downloadable packages.
Notatka: Some publishers have made available printed versions of this manual. We cannot recommend any of those, as they tend to become out-of-date very quickly.
You can read the manual online at http://www.php.net/ and on the numerous mirror sites. For best performance, you should choose the mirror site closest to you. You can view the manual in either its plain (print-friendly) HTML format or a an HTML format that integrates the manual into the look and feel of the PHP website itself.
An advantage of the online manual over most of the offline formats is the integration of user-contributed notes. An obvious disadvantage is that you have to be online to view the manual in the online formats.
There are several offline formats of the manual, and the most appropriate format for you depends on what operating system you use and your personal reading style. For information on how the manual is generated in so many formats, read the 'How we generate the formats' section of this appendix.
The most cross-platform formats of the manual are the HTML and plain-text versions. The HTML format is provided both as a single HTML file and as a package of individual files for each section (which results in a collection of several thousand files). The HTML and plaintext formats are provided as compressed tar files (using both gzip and bzip2) and ZIP archives.
Another popular cross-platform format, and the format most suited to printing, is PDF (also known as Adobe Acrobat). But before you rush to download this format and hit the Print button, be warned that the manual is nearly 2000 pages long, and constantly being revised.
Notatka: If you do not already have a program capable of viewing PDF format files, you may need to download Adobe Acrobat Reader.
For owners of Palm-compatible handhelds, the Palm document and iSilo formats are ideal for this platform. You can bring your handheld with you on your daily commute and use a DOC or iSilo reader to brush up on your PHP knowledge, or just use it as a quick reference.
For Windows platforms, the Windows HTML Help version of the manual soups up the HTML format for use with the Windows HTML Help application. This version provides full-text search, a full index, and bookmarking. Many popular Windows PHP development environments also integrate with this version of the documentation to provide easy access.
Notatka: A Visual Basic for Linux project is in the planning stage, which will include the development of a CHM Creator and Viewer for Linux. See their SourceForge.net page if you are interested in the progress.
The user-contributed notes play an important role in the development of this manual. By allowing readers of the manual to contribute examples, caveats, and further clarifications from their browser, we are able to incorporate that feedback into the main text of the manual. And until the notes have been incorporated, they can be viewed in their submitted form online and in some of the offline formats.
Notatka: The user-contributed notes are not moderated before they appear online, so the quality of the writing or code examples, and even the veracity of the contribution, cannot be guaranteed. (Not that there is any guarantee of the quality or accuracy of the manual text itself.)
This manual does not attempt to provide instruction about general programming practices. If you are a first-time, or even just a beginning, programmer, you may find it difficult to learn how to program in PHP using just this manual. You may want to seek out a text more oriented towards beginners. You can find a list of PHP-related books at http://www.php.net/books.php.
There are a number of active mailing lists for discussion of all aspects of programming with PHP. If you find yourself stuck on a problem for which you can't find your own solution, you may be able to get help from someone on these lists. You can find a list of the mailing lists at http://www.php.net/support.php, as well as links to the mailing list archives and other online support resources. Furthermore, at http://www.php.net/links.php there is a list of websites devoted to PHP articles, forums, and code galleries.
There are two ways you can help to improve this documentation.
If you find errors in this manual, in any language, please report them using the bug system at http://bugs.php.net/. Classify the bug as "Documentation Problem". You can also submit problems related to specific manual formats here.
Notatka: Please don't abuse the bug system by submitting requests for help. Use the mailing lists or community sites mentioned earlier, instead.
By contributing notes, you can provide additional examples, caveats, and clarifications for other readers. But do not submit bug reports using the annotation system please. You can read more about annotations in the 'About user notes' section of this appendix.
This manual is written in XML using the DocBook XML DTD, using DSSSL (Document Style and Semantics Specification Language) for formatting, and experimentally the XSLT (Extensible Stylesheet Language Transformations) for maintenance and formatting.
Using XML as a source format gives us the ability to generate many output formats from the source files, while only maintaining one source document for all formats. The tools used for formatting HTML and TeX versions are Jade, written by James Clark and The Modular DocBook Stylesheets written by Norman Walsh. We use Microsoft HTML Help Workshop to generate the Windows HTML Help format of the manual, and of course PHP itself to do some additional conversions and formatting.
You can download the manual in various languages and formats, including plain text, plain HTML, PDF, PalmPilot DOC, PalmPilot iSilo and Windows HTML Help, from http://www.php.net/docs.php. The manuals are updated automatically as the text is updated.
You can find more information about downloading the XML source code of this documentation at http://cvs.php.net/. The documentation is stored in the phpdoc module.