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.