2006-05-25
Copyright © 1997-2006 the PHP Documentation Group
Copyright
Prawa autorskie do tego podręcznika © 1997 - 2006 należą do PHP Documentation Group. Materiał ten może być rozprowadzany tylko pod warunkami określonymi w Open Publication License, v1.0 lub nowszych. Kopia Open Publication License jest dystrybuowana z tym podręcznikiem. Najnowsza wersja jest aktualnie dostępna pod adresem http://www.opencontent.org/openpub/.
Dystrybucja zmodyfikowanych wersji tego dokumentu jest zabroniona, chyba że jednostka będąca właścicielem praw autorskich jawnie udzieliła pozwolenia.
Dystrybucja tej pracy lub jej pochodnej w jakiejkolwiek standardowej (papierowej) formie jest możliwa tylko po udzieleniu jawnego pozwolenia przez jednostka będąca właścicielem praw autorskich.
W przypadku zainteresowania redystrybucją lub publikowaniem tego dokumentu w całości lub jego części, zmodyfikowanego czy niezmodyfikowanego, wszystkie pytania należy zadawać posiadaczom praw autorskich do niego pod adresem doc-license@lists.php.net. Adres ten jest podłączony do publicznie archiwizowanej listy dyskusyjnej.
Rozdział Rozdział 46 jest oparty o początkowy wkład firmy Zend Technologies.
PHP, co jest skrótem od "PHP: Hypertext Preprocessor", jest powszechnie używanym językiem skryptowym ogólnego przeznaczenia, który jest szczególnie przystosowany do tworzenia aplikacji Webowych, także poprzez zagnieżdżenie wewnątrz języka HTML. Składnia, wywodząca się z języków C, Java i Perl, jest łatwa do nauczenia się. Głównym celem języka jest umożliwienie programistom szybkiego tworzenia stron internetowych, ale PHP umożliwia znacznie więcej.
Podręcznik ten składa się głównie z opisu funkcji, ale zawiera także opis języka, objaśnienie niektórych z głównych cech PHP, jak również kilka dodatkowych informacji.
Podręcznik można pobrać w kilku formatach spod adresu http://www.php.net/download-docs.php. Więcej informacji na temat prac nad tym podręcznikiem można znaleźć w rozdziale 'O podręczniku'. Osobom zainteresowanym historią PHP polecamy odpowiedni dodatek.
Wyróżniamy najbardziej aktywnych twórców na pierwszej stronie podręcznika, ale jest wielu innych współpracowników, którzy pomagają w pracach, lub włożyli wiele pracy w przeszłości. Jest wielu bezimiennych pomocników, którzy wnieśli swój udział komentarzami do podręcznika, które cały czas są uwzględniane w odnośnikach, i za które to uwagi także dziękujemy. Wszystkie poniższe listy uporządkowane są alfabetycznie.
Poniżsi współpracownicy powinni zostali wyróżnieni za wpływ jaki mieli (lub ciągle mają) w rozwijanie podręcznika: Jouni Ahto, Alexander Aulbach, Daniel Beckham, Stig Bakken, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall, Simone Cortesi, Markus Fischer, Wez Furlong, Sara Golemon, Rui Hirokawa, Brad House, Moriyoshi Koizumi, Rasmus Lerdorf, Andrew Lindeman, Stanislav Malyshev, Rafael Martinez, Yasuo Ohgaki, Derick Rethans, Sander Roobol, Egon Schmid, Thomas Schoefbeck, Sascha Schumann, Dan Scott, Lars Torben Wilson, Jim Winstead, Jeroen van Wolffelaar i Andrei Zmievski.
Poniżsi współpracownicy włożyli wiele pracy przy edycji podręcznika: Stig Bakken, Gabor Hojtsy, Hartmut Holzgraefe i Egon Schmid.
Aktualnie najbardziej aktywni opiekunowie to: Mehdi Achour, Friedhelm Betz, Vincent Gevers, Aidan Lister, Nuno Lopes i Tom Sommer.
Te osoby także pracowały nad zarządzaniem notatkami: Daniel Beckham, Victor Boivie, Jesus M. Castagnetto, Nicolas Chaillan, Ron Chmara, James Cox, Sara Golemon, Zak Greant, Szabolcs Heilig, Oliver Hinckel, Hartmut Holzgraefe, Rasmus Lerdorf, Andrew Lindeman, Maxim Maletsky, James Moore, Sebastian Picklum, Derick Rethans, Sander Roobol, Damien Seguy, Jason Sheets, Jani Taskinen, Yasuo Ohgaki, Philip Olson, Lars Torben Wilson, Jim Winstead, Jared Wyles i Jeroen van Wolffelaar.
PHP (akronim rekursywny "PHP: Hypertext Preprocessor"), jest szeroko używanym językiem skryptowym ogólnego zastosowania, tworzonym na zasadach Open Source, dopasowanym do potrzeb aplikacji WWW, z możliwością zagnieżdżania w HTML.
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, albo samouczek w przypadku zainteresowania tylko programowaniem dla celów www.
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ć korzystając z przeglądarki poprzez serwer. Wszystko to można uruchomić na swoim domowym komputerze. 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 (systemy Uniksowe) lub menedżer zadań (systemy Windows), lub przetwarzania tekstu. Zobacz rozdział Uruchamianie 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ść 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 4, wiele bibliotek i dużych aplikacji (włączając w to biblioteki PEAR) jest napisanych całkowicie w sposób obiektowy. W PHP 5 naprawiono niedomagania OOP istniejące w PHP 4, implementując pełny model 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 InterBase PostgreSQL dBase FrontBase SQLite Empress mSQL Solid FilePro (tylko do odczytu) Direct MS-SQL Sybase Hyperwave MySQL Velocis IBM DB2 ODBC Unix dbm Informix Oracle (OCI7 i OCI8) Ingres Ovrimos
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 w PHP 4 wykorzystywane są standardy SAX i DOM, można także użyć rozszerzeń XSLT do przetwarzania dokumentów XML. PHP 5 standaryzuje wszystkie rozszerzenia XML na solidnej podstawie libxml2 i poszerza gamę możliwości dodając wsparcie dla SimpleXML i XMLReader.
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 MCVE, przydatne przy płatnościach on-line.
Na koniec warto wspomnieć, że w PHP istnieje wiele innych interesujących rozszerzeń, takich jak funkcje przeszukiwawcze 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.
W tym małym przewodniku chcielibyśmy przybliżyć ci podstawy PHP. Rozdział ten opisuje tylko tworzenie dynamicznych stron internetowych, ale PHP ma także inne zastosowania. Więcej informacji znajdziesz w rozdziale Co potrafi PHP.
Strony zawierające skrypty PHP nie różnią się zbytnio od zwykłych dokumentów HTML, co oznacza, że w ten sam sposób możesz je tworzyć i modyfikować.
Zakładamy, że twój serwer ma włączoną obsługę PHP i wszystkie pliki o rozszerzeniu .php są przetwarzane przez interpreter PHP. Na wielu serwerach jest to domyślne rozszerzenie dla skryptów, ale mimo wszystko warto zasięgnąć informacji u administratora. Jeżeli twój serwer obsługuje PHP, nie musisz wykonywać żadnych dodatkowych czynności. Po prostu twórz swoje pliki .php i umieszczaj je w dowolnych katalogach na serwerze. Nie musisz nic kompilować ani instalować żadnych dodatkowych narzędzi. Pomyśl o skryptach PHP jak o zwyczajnych dokumentach HTML wykorzystujących całą gamę nowych znaczników, które dają ci praktycznie nieograniczone możliwości. Większość komercyjnych i część niekomercyjnych serwerów WWW obsługuje skrypty PHP, jednak jeśli twój serwer do tej grupy nie należy, możesz poszukać odpowiedniej oferty w jednym z kilku katalogów, których adresy znajdziesz w sekcji linki.
Powiedzmy, że chcesz budować i uruchamiać swoje skrypty na własnym komputerze. W tym wypadku, będzisz musiał zainstalować serwer WWW np. Apache i oczywiście PHP. Najprawdopodobniej będziesz chciał także umożliwić skryptom dostęp do bazy danych, takiej jak MySQL. Elementy te możesz zainstalować odzielnie lub w łatwiejszy sposób, korzystając z pakietu, który zarówno zainstaluje jak i skonfiguruje wszystkie składniki. Instalacja serwera WWW z obsługą PHP nie nie jest trudna zarówno w systemach Linux jak i Windows. Jeśli używasz systemu Linux, możesz skorzystać z wyszukiwarki rpmfind w celu odnalezienia wymaganych pakietów RPM.
Utwórz w głównym katalogu serwera (DOCUMENT_ROOT) plik o nazwie hello.php i następującej treści:
Zauważ jak bardzo to się różni od skryptów CGI. Plik nie musi być kompilowany ani poddawany jakimkolwiek innym przetworzeniom.
To chyba najprostszy program, jaki można sobie wyobrazić i chyba naprawdę nigdy nie będziesz musiał używać PHP do tworzenia stron takich jak ta. Całe jego zadanie polega na wyświetleniu zdania: Witaj Świecie ! przy użyciu wbudowanej w PHP instrukcji echo().
Jeżeli po wypróbowaniu tego przykładu w przeglądarce pojawiła się pusta strona, otworzyło się okno z pytaniem o zapisanie pliku lub też wyświetliła się cała zawartość hello.php, bardzo możliwe, że serwer ma wyłączoną obsługę PHP (lub też nie ma jej wcale). W takim wypadku poproś administratora o jej aktywowanie przy pomocy wskazówek z rozdziału Instalacja. Jeśli tworzysz skrypty lokalnie, również powinieneś zapoznać się z treścią tego rozdziału, aby upewnić się czy wszystko jest poprawnie skonfigurowane. Gdy problem mimo wszystko w dalszym ciągu się powtarza, skorzystaj z informacji zawartych na stronie Pomocy technicznej PHP.
Głównym celem tego przykładu było pokazanie specyficznej składni PHP. Najpierw użyliśmy znacznika <?php, aby poinformować interpreter, że w tym miejscu rozpoczyna się kod PHP. Następnie wprowadziliśmy instrukcję wyświetlającą napis Witaj Świecie ! i zakończyliśmy skrypt znacznikiem ?>. W ten właśnie sposób możesz mieszać kod PHP ze znacznikami HTML. Więcej informacji o składni PHP znajdziesz w rozdziale Podstawowa składnia.
Edytory tekstowe: Istnieje wiele tekstowych edytorów i zintegrowanych środowisk programistycznych (IDE), których możesz użyć do tworzenia, modyfikowania i zarządzania skryptami PHP. Obszerna lista takich programów znajduje się na stronie http://www.thelinuxconsultancy.co.uk/phpeditors.php. Jeżeli chciałbyś polecić innym jakiś edytor, zajrzyj na powyższą stronę i poproś jej właściciela o dodanie programu do spisu.
Procesory tekstu: Programy takie jak StarOffice Writer, Microsoft Word i Abiword nie nadają się zbytnio do pracy ze skryptami PHP. Jeżeli mimo to chcesz korzystać z którejś z wymienionych aplikacji, musisz mieć pewność, że kod skrypu zapisywany jest jako zwykły tekst. W przeciwnym wypadku PHP nie będzie w stanie przetworzyć pliku.
Notatnik Windows: Jeśli piszesz skrypty w Windowsowym Notatniku, sprawdzaj czy pliki zapisywane są z rozszerzeniem .php (Notatnik domyślnie zapisuje wszystkie pliki dodając rozszerzenie .txt). Kiedy zapisujesz plik i program wyświetla okno dialogowe z pytaniem o nazwę pliku, umieść tę nazwę w cudzysłowie (np. "hello.php"). Drugim sposobem jest wybranie z rozwijanej listy 'Zapisz jako typ' w tym samym oknie opcji 'Wszystkie pliki' (zamiast ustawionej domyślnie 'Dokumenty tekstowe (*.txt)'). Teraz możesz podać nazwę pliku bez cudzysłowów.
Teraz kiedy napisałeś już pierwszy działający program, czas stworzyć chyba najbardziej znany skrypt PHP! Stwórz nowy plik, umieść w nim znaczniki PHP i wywołaj funkcję phpinfo(). Po uruchomienia skryptu, ujrzysz w swojej przeglądarce długą stronę zawierającą wiele przydatnych informacji o twoim systemie operacyjnym i ustawieniach takich jak zmienne predefiniowane, załadowane moduły PHP, i opcje konfiguracji. Poświęć trochę czasu na przejrzenie tych informacji.
Zabierzmy się teraz za coś, co może się nam do czegoś przydać. Chcemy sprawdzić w jakiej przeglądarce internetowej użytkownik ogląda naszą stronę. W tym celu odczytamy nagłówek User-Agent, który został przesłany w żądaniu HTTP przez przeglądarkę użytkownika. Informacja ta znajduje się w zmiennej. Nazwy zmiennych są w PHP poprzedzone znakiem dolara "$". Zmienna, która nas interesuje, to $_SERVER["HTTP_USER_AGENT"].
Zmienne superglobalne: $_SERVER jest specjalną zmienną PHP, która zawiera informacje związane z serwerem i środowiskiem uruchomieniowym danego skryptu. Zmienna ta jest nazywana superglobalną (bądź autoglobalną). Co to oznacza, dowiesz się na stronie poświęconej zmiennym predefiniowanym. Zmienne superglobalne wprowadzono w PHP w wersji 4.1.0. Przedtem wykorzystywane były tablice $HTTP_*_VARS, takie jak $HTTP_SERVER_VARS. Chociaż używanie ich nie jest zalecane, są one w dalszym ciągu dostępne w PHP (przeczytaj także notatkę dotyczącą używania starej składni).
Możemy w łatwy sposób wyświetlić wartość tej zmiennej:
W PHP istnieje wiele typów zmiennych. W powyższym przykładzie wyświetliliśmy wartość elementu tablicy. Tablice mogą mieć wiele zastosowań.
$_SERVER jest tylko jedną ze zmiennych, które zawsze są dostępne dla skryptów PHP. Lista wszystkich takich zmiennych znajduje się w sekcji Predefiniowane zmienne, możesz także wygenerować ją przy pomocy prostego skryptu:
Po wywołaniu skryptu, ujrzysz w swojej przeglądarce stronę zawierającą wiele informacji o PHP łącznie z kompletną listą zmiennych predefiniowanych.
Pomiędzy znacznikami skryptu PHP możesz umieścić wiele różnych instrukcji, nie tylko echo(). Przykładowo, jeśli chcesz sprawdzić czy przeglądarka użytkownika to Internet Explorer, możesz napisać taki skrypt:
Przykład 2-4. Przykład wykorzystania struktur kontrolnych i funkcji
Jak nietrudno się domyślić, skrypt może wyświetlić:
|
W powyższym przykładzie wprowadziliśmy kilka nowych rozwiązań. Przede wszystkim mamy tutaj instrukcję if. Dla osób znających podstawową składnię języka C powinna ona wyglądać znajomo. Jeśli nie rozumiesz do czego ta instrukcja służy, nie obejdzie się bez lektury rozdziału Opis języka. W początkowej fazie nauki języka pomocne mogą być także książki opisujące PHP od podstaw. Spis publikacji poświęconych PHP znajduje się pod adresem http://www.php.net/books.php.
Następnym nowym rozwiązaniem jest wywołanie funkcji strpos(). strpos() jest funkcją wbudowaną w PHP, służy do wyszukiwania jednego łańcucha znaków w drugim. W naszym przykładzie próbowaliśmy odnaleźć "MSIE" w zmiennej $_SERVER["HTTP_USER_AGENT"]. Jeżeli ciąg ten został odnaleziony, funkcja zwróciła jego pozycję w łańcuchu $_SERVER["HTTP_USER_AGENT"]. Jeśli funkcja nie zwróciła wartości FALSE, wykonywany był kod umieszczony wewnątrz nawiasów klamrowych instrukcji if. W przeciwnym wypadku, gdy strpos() zwróciła wartość FALSE, kod był pomijany. Spróbuj napisać kilka podobnych przykładów z wykorzystaniem instrukcji if, else oraz funkcji takich jak strtoupper() lub strlen(). Każda ze stron opisujących te metody zawiera także przykłady, które pomogą ci zrozumieć ich działanie. Jeżeli nie jesteś pewny jak używać funkcji, zajrzyj na stronę wyjaśniającą jak czytać opisy funkcji i do rozdziału Funkcje.
Przejdźmy teraz krok dalej i zobaczmy w jaki sposób możemy przeplatać kod HTML instrukcjami języka PHP:
Przykład 2-5. Mieszanie HTML z PHP
Wynikiem działania tego skryptu może być:
|
Tym razem zamiast instrukcji echo() skorzystaliśmy z innej możliwości - wymieszaliśmy ze sobą kod HTML i PHP. W tym miejscu warto zaznaczyć, że skrypt mimo dużych zmian w zastosowanej składni, nadal działa tak samo. W zależności od tego, co zwróci funkcja strpos(), wyświetlony zostanie tylko jeden blok kodu HTML. Innymi słowy, wszystko zależy od tego, czy ciąg MSIE zostanie odnaleziony w łańcuchu $_SERVER["HTTP_USER_AGENT"].
Obsługa formularzy HTML to jedno z podstawowych zadań skryptów PHP. Najprościej mówiąc, wartości wszystkich elementów formularza (pól tekstowych, pól checkbox i radio, list rozwijanych itp.) są automatycznie udostępniane skryptom PHP. Przykłady i informacje na ten temat znajdziesz w sekcji Zmienne spoza PHP. Oto przykładowy formularz HTML:
Nie ma tu nic niezwykłego. To po prostu zwyczajny formularz zbudowany ze standardowych znaczników języka HTML. Gdy użytkownik wypełni pola tekstowe i kliknie przycisk, informacje zostaną przesłane do skryptu action.php. W tym pliku mógłbyś umieścić coś takiego:
Chyba nie trzeba tłumaczyć do czego służy powyższy skrypt. Zmienne $_POST['imie'] i $_POST['rok'] są automatycznie ustawiane po przesłaniu formularza przez użytkownika. Wcześniej użyliśmy zmiennej superglobalnej $_SERVER; teraz poznaliśmy zmienną $_POST (również superglobalną), która przechowuje wszystkie dane wysłane w formularzu. Zauważ, że nasz formularz przekazywany jest metodą POST (parametr method). Jeśli wybralibyśmy metodę GET, wszystkie dane znajdowały się w zmiennej superglobalnej $_GET. Ostatecznie możesz również skorzystać ze zmiennej $_REQUEST, jeśli nie interesuje cię to, skąd pochodzą przesłane dane. Zmienna ta zawiera wszystkie informacje niezależnie od tego czy zostały one przekazane metodą GET, POST czy też w ciasteczku (cookie). Przyjrzyj się też funkcji import_request_variables().
Odkąd PHP stało się popularnym językiem skryptowym, istnieją duże archiwa darmowych skryptów, które można często bez żadnych ograniczeń wykorzystywać na swoich stronach WWW. Twórcy PHP postarali się, aby uruchamianie starszych skryptów było możliwe we wszystkich nowszych wersjach środowiska. Czasami jednak, aby uruchomić taki program, trzeba będzie dokonać w nim pewnych zmian.
Dwie najistotniejsze zmiany w stosunku do starszych wersji PHP to:
Zastąpienie zmiennych $HTTP_*_VARS (które wewnątrz funkcji muszą być importowane tak jak zmienne globalne) tablicami superglobalnymi w wersji 4.1.0 środowiska PHP. Oto one: $_GET, $_POST, $_COOKIE, $_SERVER, $_FILES, $_ENV, $_REQUEST i $_SESSION. Wykorzystywane wcześniej tablice $HTTP_*_VARS, takie jak np. $HTTP_POST_VARS, nadal są dostępne dla skryptów. Od PHP w wersji 5.0.0, długie tablice zmiennych predefiniowanych mogą być wyłączone dyrektywą konfiguracji register_long_arrays.
Zmienne pochodzące "z zewnątrz" nie są już domyślnie rejestrowane jako zwyczajne zmienne skryptu. Inaczej mówiąc, od wersji 4.2.0 dyrektywa konfiguracyjna register_globals w pliku php.ini domyślnie przyjmuje wartość off. Zalecana metoda odwoływania się do zmiennych "z zewnątrz" polega na zastosowaniu opisanych wyżej tablic superglobalnych. W starszych skryptach, książkach i kursach możesz się spotkać ze starą składnią, która jest niestety mniej bezpieczna. Korzystając ze zmiennych superglobalnych masz pewność, że dane przesłane metodą GET znajdą się w tablicy $_GET, metodą POST w $_POST itd.
Z już nabytą wiedzą nie powinieneś mieć problemów ze zrozumieniem kolejnych rozdziałów podręcznika i zawartych w nich przykładowych skryptów. Przykłady możesz znaleźć również na innych stronach poświęconych PHP: http://www.php.net/links.php.
Jeśli chcesz obejrzeć rozmaite prezentacje na temat PHP i jego zastosowań, zajrzyj na strony: http://conf.php.net/ i http://talks.php.net/
Before starting the installation, first you need to know what do you want to use PHP for. There are three main fields you can use PHP, as described in the What can PHP do? section:
Websites and web applications (server-side scripting)
Command line scripting
Desktop (GUI) applications
For the first and most common form, you need three things: PHP itself, a web server and a web browser. You probably already have a web browser, and depending on your operating system setup, you may also have a web server (e.g. Apache on Linux and MacOS X; IIS on Windows). You may also rent webspace at a company. This way, you don't need to set up anything on your own, only write your PHP scripts, upload it to the server you rent, and see the results in your browser.
In case of setting up the server and PHP on your own, you have two choices for the method of connecting PHP to the server. For many servers PHP has a direct module interface (also called SAPI). These servers include Apache, Microsoft Internet Information Server, Netscape and iPlanet servers. Many other servers have support for ISAPI, the Microsoft module interface (OmniHTTPd for example). If PHP has no module support for your web server, you can always use it as a CGI or FastCGI processor. This means you set up your server to use the CGI executable of PHP to process all PHP file requests on the server.
If you are also interested to use PHP for command line scripting (e.g. write scripts autogenerating some images for you offline, or processing text files depending on some arguments you pass to them), you always need the command line executable. For more information, read the section about writing command line PHP applications. In this case, you need no server and no browser.
With PHP you can also write desktop GUI applications using the PHP-GTK extension. This is a completely different approach than writing web pages, as you do not output any HTML, but manage windows and objects within them. For more information about PHP-GTK, please visit the site dedicated to this extension. PHP-GTK is not included in the official PHP distribution.
From now on, this section deals with setting up PHP for web servers on Unix and Windows with server module interfaces and CGI executables. You will also find information on the command line executable in the following sections.
PHP source code and binary distributions for Windows can be found at http://www.php.net/downloads.php. We recommend you to choose a mirror nearest to you for downloading the distributions.
This section will guide you through the general configuration and installation of PHP on Unix systems. Be sure to investigate any sections specific to your platform or web server before you begin the process.
As our manual outlines in the General Installation Considerations section, we are mainly dealing with web centric setups of PHP in this section, although we will cover setting up PHP for command line usage as well.
There are several ways to install PHP for the Unix platform, either with a compile and configure process, or through various pre-packaged methods. This documentation is mainly focused around the process of compiling and configuring PHP. Many Unix like systems have some sort of package installation system. This can assist in setting up a standard configuration, but if you need to have a different set of features (such as a secure server, or a different database driver), you may need to build PHP and/or your webserver. If you are unfamiliar with building and compiling your own software, it is worth checking to see whether somebody has already built a packaged version of PHP with the features you need.
Prerequisite knowledge and software for compiling:
Basic Unix skills (being able to operate "make" and a C compiler)
An ANSI C compiler
flex: Version 2.5.4
bison: Version 1.28 (preferred), 1.35, or 1.75
A web server
Any module specific components (such as gd, pdf libs, etc.)
The initial PHP setup and configuration process is controlled by the use of the commandline options of the configure script. You could get a list of all available options along with short explanations running ./configure --help. Our manual documents the different options separately. You will find the core options in the appendix, while the different extension specific options are descibed on the reference pages.
When PHP is configured, you are ready to build the module and/or executables. The command make should take care of this. If it fails and you can't figure out why, see the Problems section.
This section contains notes and hints specific to Apache installs of PHP on Unix platforms. We also have instructions and notes for Apache 2 on a separate page.
You can select arguments to add to the configure on line 10 below from the list of core configure options and from extension specific options described at the respective places in the manual. The version numbers have been omitted here, to ensure the instructions are not incorrect. You will need to replace the 'xxx' here with the correct values from your files.
Przykład 4-1. Installation Instructions (Apache Shared Module Version) for PHP
|
Alternatively, to install PHP as a static object:
Przykład 4-2. Installation Instructions (Static Module Installation for Apache) for PHP
|
Notatka: Replace php-5 by php-4 and php5 by php4 in PHP 4.
Depending on your Apache install and Unix variant, there are many possible ways to stop and restart the server. Below are some typical lines used in restarting the server, for different apache/unix installations. You should replace /path/to/ with the path to these applications on your systems.
Przykład 4-3. Example commands for restarting Apache
|
The locations of the apachectl and http(s)dctl binaries often vary. If your system has locate or whereis or which commands, these can assist you in finding your server control programs.
Different examples of compiling PHP for apache are as follows:
This will create a libphp5.so (or libphp4.so in PHP 4) shared library that is loaded into Apache using a LoadModule line in Apache's httpd.conf file. The PostgreSQL support is embedded into this library.
This will create a libphp4.so shared library for Apache, but it will also create a pgsql.so shared library that is loaded into PHP either by using the extension directive in php.ini file or by loading it explicitly in a script using the dl() function.
This will create a libmodphp5.a library, a mod_php5.c and some accompanying files and copy this into the src/modules/php5 directory in the Apache source tree. Then you compile Apache using --activate-module=src/modules/php5/libphp5.a and the Apache build system will create libphp5.a and link it statically into the httpd binary (replace php5 by php4 in PHP 4). The PostgreSQL support is included directly into this httpd binary, so the final result here is a single httpd binary that includes all of Apache and all of PHP.
Same as before, except instead of including PostgreSQL support directly into the final httpd you will get a pgsql.so shared library that you can load into PHP from either the php.ini file or directly using dl().
When choosing to build PHP in different ways, you should consider the advantages and drawbacks of each method. Building as a shared object will mean that you can compile apache separately, and don't have to recompile everything as you add to, or change, PHP. Building PHP into apache (static method) means that PHP will load and run faster. For more information, see the Apache webpage on DSO support.
Notatka: Apache's default httpd.conf currently ships with a section that looks like this:
Unless you change that to "Group nogroup" or something like that ("Group daemon" is also very common) PHP will not be able to open files.
Notatka: Make sure you specify the installed version of apxs when using --with-apxs=/path/to/apxs. You must NOT use the apxs version that is in the apache sources but the one that is actually installed on your system.
This section contains notes and hints specific to Apache 2.0 installs of PHP on Unix systems.
| Ostrzeżenie |
Nie zalecamy korzystania z wątkowanego MPM na produkcyjnych serwerach Apache2. Zamiast niego wskazane jest używanie preforkowanego MPM, lub używanie Apache1. Wyjaśnienie powodów można znaleźć w odpowiednim punkcie FAQ, dotyczącym używania Apache2 z wątkowanym MPM |
You are highly encouraged to take a look at the Apache Documentation to get a basic understanding of the Apache 2.0 Server.
PHP and Apache 2.0.x compatibility notes: The following versions of PHP are known to work with the most recent version of Apache 2.0.x:
These versions of PHP are compatible to Apache 2.0.40 and later.
- PHP 4.3.0 or later available at http://www.php.net/downloads.php.
- the latest stable development version. Get the source code http://snaps.php.net/php5-latest.tar.gz or download binaries for Windows http://snaps.php.net/win32/php5-win32-latest.zip.
- a prerelease version downloadable from http://qa.php.net/.
- you have always the option to obtain PHP through anonymous CVS.
Apache 2.0 SAPI-support started with PHP 4.2.0. PHP 4.2.3 works with Apache 2.0.39, don't use any other version of Apache with PHP 4.2.3. However, the recommended setup is to use PHP 4.3.0 or later with the most recent version of Apache2.
All mentioned versions of PHP will work still with Apache 1.3.x.
Download the most recent version of Apache 2.0 and a fitting PHP version from the above mentioned places. This quick guide covers only the basics to get started with Apache 2.0 and PHP. For more information read the Apache Documentation. The version numbers have been omitted here, to ensure the instructions are not incorrect. You will need to replace the 'NN' here with the correct values from your files.
Przykład 4-4. Installation Instructions (Apache 2 Shared Module Version)
|
Following the steps above you will have a running Apache 2.0 with support for PHP as SAPI module. Of course there are many more configuration options available for both, Apache and PHP. For more information use ./configure --help in the corresponding source tree. In case you wish to build a multithreaded version of Apache 2.0 you must overwrite the standard MPM-Module prefork either with worker or perchild. To do so append to your configure line in step 6 above either the option --with-mpm=worker or --with-mpm=perchild. Take care about the consequences and understand what you are doing. For more information read the Apache documentation about the MPM-Modules.
Notatka: If you want to use content negotiation, read the Apache MultiViews FAQ.
Notatka: To build a multithreaded version of Apache your system must support threads. This also implies to build PHP with experimental Zend Thread Safety (ZTS). Therefore not all extensions might be available. The recommended setup is to build Apache with the standard prefork MPM-Module.
PHP 4 can be built as a Pike module for the Caudium webserver. Note that this is not supported with PHP 3. Follow the simple instructions below to install PHP 4 for Caudium.
Przykład 4-5. Caudium Installation Instructions
|
You can of course compile your Caudium module with support for the various extensions available in PHP 4. See the reference pages for extension specific configure options.
Notatka: When compiling PHP 4 with MySQL support you must make sure that the normal MySQL client code is used. Otherwise there might be conflicts if your Pike already has MySQL support. You do this by specifying a MySQL install directory the --with-mysql option.
To build PHP as an fhttpd module, answer "yes" to "Build as an fhttpd module?" (the --with-fhttpd=DIR option to configure) and specify the fhttpd source base directory. The default directory is /usr/local/src/fhttpd. If you are running fhttpd, building PHP as a module will give better performance, more control and remote execution capability.
Notatka: Support for fhttpd is no longer available as of PHP 4.3.0.
This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Sun Solaris.
From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to generate custom directory listings and error pages. Additional functions for Apache compatibility are also available. For support in current webservers read the note about subrequests.
You can find more information about setting up PHP for the Netscape Enterprise Server (NES) here: http://benoit.noss.free.fr/php/install-php4.html
To build PHP with Sun JSWS/Sun ONE WS/iPlanet/Netscape webservers, enter the proper install directory for the --with-nsapi=[DIR] option. The default directory is usually /opt/netscape/suitespot/. Please also read /php-xxx-version/sapi/nsapi/nsapi-readme.txt.
Install the following packages from http://www.sunfreeware.com/ or another download site:
| autoconf-2.13 |
| automake-1.4 |
| bison-1_25-sol26-sparc-local |
| flex-2_5_4a-sol26-sparc-local |
| gcc-2_95_2-sol26-sparc-local |
| gzip-1.2.4-sol26-sparc-local |
| m4-1_4-sol26-sparc-local |
| make-3_76_1-sol26-sparc-local |
| mysql-3.23.24-beta (if you want mysql support) |
| perl-5_005_03-sol26-sparc-local |
| tar-1.13 (GNU tar) |
Make sure your path includes the proper directories PATH=.:/usr/local/bin:/usr/sbin:/usr/bin:/usr/ccs/bin and make it available to your system export PATH.
gunzip php-x.x.x.tar.gz (if you have a .gz dist, otherwise go to 4).
tar xvf php-x.x.x.tar
Change to your extracted PHP directory: cd ../php-x.x.x
For the following step, make sure /opt/netscape/suitespot/ is where your netscape server is installed. Otherwise, change to the correct path and run:
./configure --with-mysql=/usr/local/mysql \ --with-nsapi=/opt/netscape/suitespot/ \ --enable-libgcc |
Run make followed by make install.
After performing the base install and reading the appropriate readme file, you may need to perform some additional configuration steps.
Configuration Instructions for Sun/iPlanet/Netscape. Firstly you may need to add some paths to the LD_LIBRARY_PATH environment for the server to find all the shared libs. This can best done in the start script for your webserver. The start script is often located in: /path/to/server/https-servername/start. You may also need to edit the configuration files that are located in: /path/to/server/https-servername/config/.
Add the following line to mime.types (you can do that by the administration server):
type=magnus-internal/x-httpd-php exts=php |
Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following, shlib will vary depending on your system, it will be something like /opt/netscape/suitespot/bin/libphp4.so. You should place the following lines after mime types init.
Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="/opt/netscape/suitespot/bin/libphp4.so" Init fn="php4_init" LateInit="yes" errorString="Failed to initialize PHP!" [php_ini="/path/to/php.ini"] |
Configure the default object in obj.conf (for virtual server classes [version 6.0+] in their vserver.obj.conf):
<Object name="default"> . . . .#NOTE this next line should happen after all 'ObjectType' and before all 'AddLog' lines Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...] . . </Object> |
This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):
<Object name="x-httpd-php"> ObjectType fn="force-type" type="magnus-internal/x-httpd-php" Service fn=php4_execute [inikey=value inikey=value ...] </Object> |
Setup of authentication: PHP authentication cannot be used with any other authentication. ALL AUTHENTICATION IS PASSED TO YOUR PHP SCRIPT. To configure PHP Authentication for the entire server, add the following line to your default object:
<Object name="default"> AuthTrans fn=php4_auth_trans . . . </Object> |
To use PHP Authentication on a single directory, add the following:
<Object ppath="d:\path\to\authenticated\dir\*"> AuthTrans fn=php4_auth_trans </Object> |
Notatka: The stacksize that PHP uses depends on the configuration of the webserver. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").
Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the webserver itself) and this space has only one environment. If you want to get CGI variables like PATH_INFO, HTTP_HOST etc. it is not the correct way to try this in the old PHP 3.x way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running webserver without any valid CGI variables!
Notatka: Why are there (invalid) CGI variables in the environment?
Answer: This is because you started the webserver process from the admin server which runs the startup script of the webserver, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started webserver has some CGI environment variables in it. You can test this by starting the webserver not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.
Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):
variables_order = "GPCS" register_globals = On |
You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:
Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...] |
Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:
Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...] |
The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the webserver and insert the result in the webpage. This function uses some undocumented features from the NSAPI library. On Unix the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.
Notatka: But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!
The default is to build PHP as a CGI program. This creates a commandline interpreter, which can be used for CGI processing, or for non-web-related PHP scripting. If you are running a web server PHP has module support for, you should generally go for that solution for performance reasons. However, the CGI version enables users to run different PHP-enabled pages under different user-ids.
| Ostrzeżenie |
Używając instalacji CGI, serwer jest podatny na wiele potencjalnych ataków. Sposoby obrony przed nimi zostały opisane w rozdziale o bezpieczeństwie instalacji CGI. |
As of PHP 4.3.0, some important additions have happened to PHP. A new SAPI named CLI also exists and it has the same name as the CGI binary. What is installed at {PREFIX}/bin/php depends on your configure line and this is described in detail in the manual section named Using PHP from the command line. For further details please read that section of the manual.
If you have built PHP as a CGI program, you may test your build by typing make test. It is always a good idea to test your build. This way you may catch a problem with PHP on your platform early instead of having to struggle with it later.
If you have built PHP 3 as a CGI program, you may benchmark your build by typing make bench. Note that if tryb bezpieczny is on by default, the benchmark may not be able to finish if it takes longer then the 30 seconds allowed. This is because the set_time_limit() can not be used in tryb bezpieczny. Use the max_execution_time configuration setting to control this time for your own scripts. make bench ignores the configuration file.
Notatka: make bench is only available for PHP 3.
Some server supplied environment variables are not defined in the current CGI/1.1 specification. Only the following variables are defined there: AUTH_TYPE, CONTENT_LENGTH, CONTENT_TYPE, GATEWAY_INTERFACE, PATH_INFO, PATH_TRANSLATED, QUERY_STRING, REMOTE_ADDR, REMOTE_HOST, REMOTE_IDENT, REMOTE_USER, REQUEST_METHOD, SCRIPT_NAME, SERVER_NAME, SERVER_PORT, SERVER_PROTOCOL, and SERVER_SOFTWARE. Everything else should be treated as 'vendor extensions'.
This section contains notes and hints specific to installing PHP on HP-UX systems. (Contributed by paul_mckay at clearwater-it dot co dot uk).
Notatka: These tips were written for PHP 4.0.4 and Apache 1.3.9.
You need gzip, download a binary distribution from http://hpux.connect.org.uk/ftp/hpux/Gnu/gzip-1.2.4a/gzip-1.2.4a-sd-10.20.depot.Z uncompress the file and install using swinstall.
You need gcc, download a binary distribution from http://gatekeep.cs.utah.edu/ftp/hpux/Gnu/gcc-2.95.2/gcc-2.95.2-sd-10.20.depot.gz. uncompress this file and install gcc using swinstall.
You need the GNU binutils, you can download a binary distribution from http://hpux.connect.org.uk/ftp/hpux/Gnu/binutils-2.9.1/binutils-2.9.1-sd-10.20.depot.gz. uncompress this file and install binutils using swinstall.
You now need bison, you can download a binary distribution from http://hpux.connect.org.uk/ftp/hpux/Gnu/bison-1.28/bison-1.28-sd-10.20.depot.gz, install as above.
You now need flex, you need to download the source from one of the http://www.gnu.org mirrors. It is in the non-gnu directory of the ftp site. Download the file, gunzip, then tar -xvf it. Go into the newly created flex directory and run ./configure, followed by make, and then make install.
If you have errors here, it's probably because gcc etc. are not in your PATH so add them to your PATH.
Download the PHP and apache sources.
gunzip and tar -xvf them. We need to hack a couple of files so that they can compile OK.
Firstly the configure file needs to be hacked because it seems to lose track of the fact that you are a hpux machine, there will be a better way of doing this but a cheap and cheerful hack is to put lt_target=hpux10.20 on line 47286 of the configure script.
Next, the Apache GuessOS file needs to be hacked. Under apache_1.3.9/src/helpers change line 89 from echo "hp${HPUXMACH}-hpux${HPUXVER}"; exit 0 to: echo "hp${HPUXMACH}-hp-hpux${HPUXVER}"; exit 0
You cannot install PHP as a shared object under HP-UX so you must compile it as a static, just follow the instructions at the Apache page.
PHP and Apache should have compiled OK, but Apache won't start. you need to create a new user for Apache, e.g. www, or apache. You then change lines 252 and 253 of the conf/httpd.conf in Apache so that instead of
User nobody Group nogroup |
you have something like
User www Group sys |
This is because you can't run Apache as nobody under hp-ux. Apache and PHP should then work.
This section contains notes and hints specific to installing PHP on OpenBSD 3.6.
Using binary packages to install PHP on OpenBSD is the recommended and simplest method. The core package has been separated from the various modules, and each can be installed and removed independently from the others. The files you need can be found on your OpenBSD CD or on the FTP site.
The main package you need to install is php4-core-4.3.8.tgz, which contains the basic engine (plus gettext and iconv). Next, take a look at the module packages, such as php4-mysql-4.3.8.tgz or php4-imap-4.3.8.tgz. You need to use the phpxs command to activate and deactivate these modules in your php.ini.
Przykład 4-6. OpenBSD Package Install Example
|
Read the packages(7) manual page for more information about binary packages on OpenBSD.
You can also compile up PHP from source using the ports tree. However, this is only recommended for users familiar with OpenBSD. The PHP 4 port is split into two sub-directories: core and extensions. The extensions directory generates sub-packages for all of the supported PHP modules. If you find you do not want to create some of these modules, use the no_* FLAVOR. For example, to skip building the imap module, set the FLAVOR to no_imap.
The default install of Apache runs inside a chroot(2) jail, which will restrict PHP scripts to accessing files under /var/www. You will therefore need to create a /var/www/tmp directory for PHP session files to be stored, or use an alternative session backend. In addition, database sockets need to be placed inside the jail or listen on the localhost interface. If you use network functions, some files from /etc such as /etc/resolv.conf and /etc/services will need to be moved into /var/www/etc. The OpenBSD PEAR package automatically installs into the correct chroot directories, so no special modification is needed there. More information on the OpenBSD Apache is available in the OpenBSD FAQ.
The OpenBSD 3.6 package for the gd extension requires XFree86 to be installed. If you do not wish to use some of the font features that require X11, install the php4-gd-4.3.8-no_x11.tgz package instead.
Older releases of OpenBSD used the FLAVORS system to compile up a statically linked PHP. Since it is hard to generate binary packages using this method, it is now deprecated. You can still use the old stable ports trees if you wish, but they are unsupported by the OpenBSD team. If you have any comments about this, the current maintainer for the port is Anil Madhavapeddy (avsm at openbsd dot org).
This section contains notes and hints specific to installing PHP on Solaris systems.
Solaris installs often lack C compilers and their related tools. Read this FAQ for information on why using GNU versions for some of these tools is necessary. The required software is as follows:
gcc (recommended, other C compilers may work)
make
flex
bison
m4
autoconf
automake
perl
gzip
tar
GNU sed
You can simplify the Solaris install process by using pkgadd to install most of your needed components.
This section contains notes and hints specific to installing PHP on Debian GNU/Linux.
While you can just download the PHP source and compile it yourself, using Debian's packaging system is the simplest and cleanest method of installing PHP. If you are not familiar with building software on Linux, this is the way to go.
The first decision you need to make is whether you want to install Apache 1.3.x or Apache 2.x. The corresponding PHP packages are respectively named libapache-mod-php* and libapache2-mod-php*. The steps given below will use Apache 1.3.x. Please note that, as of this writing, there is no official Debian packages of PHP 5. Then the steps given below will install PHP 4.
PHP is available in Debian as CGI or CLI flavour too, named respectively php4-cgi and php4-cli. If you need them, you'll just have to reproduce the following steps with the good package names. Another special package you'd want to install is php4-pear. It contains a minimal PEAR installation and the pear commandline utility.
If you need more recent packages of PHP than the Debian's stable ones or if some PHP modules lacks the Debian official repository, perhaps you should take a look at http://www.apt-get.org/. One of the results found should be Dotdeb. This unofficial repository is maintained by Guillaume Plessis and contains Debian packages of the most recent versions of PHP 4 and PHP 5. To use it, just add the to following two lines to your /etc/apt/sources.lists and run apt-get update :
The last thing to consider is whether your list of packages is up to date. If you have not updated it recently, you need to run apt-get update before anything else. This way, you will be using the most recent stable version of the Apache and PHP packages.
Now that everything is in place, you can use the following example to install Apache and PHP:
APT will automatically install the PHP 4 module for Apache 1.3, and all its dependencies and then activate it. If you're not asked to restart Apache during the install process, you'll have to do it manually :
In the last section, PHP was installed with only core modules. This may not be what you want and you will soon discover that you need more activated modules, like MySQL, cURL, GD, etc.
When you compile PHP from source yourself, you need to activate modules via the configure command. With APT, you just have to install additional packages. They're all named 'php4-*' (or 'php5-*' if you installed PHP 5 from a third party repository).
As you can see from the last output, there's a lot of PHP modules that you can install (excluding the php4-cgi, php4-cli or php4-pear special packages). Look at them closely and choose what you need. If you choose a module and you do not have the proper libraries, APT will automatically install all the dependencies for you.
If you choose to add the MySQL, cURL and GD support to PHP the command will look something like this:
APT will automatically add the appropriate lines to your different php.ini (/etc/php4/apache/php.ini, /etc/php4/cgi/php.ini, etc).
You'll only have to stop/start Apache as previously to activate the modules.
If you see the PHP source instead of the result the script should produce, APT has probably not included /etc/apache/conf.d/php4 in your Apache 1.3 configuration. Please ensure that the following line is present in your /etc/apache/httpd.conf file then stop/start Apache:
If you installed an additional module and if its functions are not available in your scripts, please ensure that the appropriate line is present in your php.ini, as seen before. APT may fail during the installation of the additional module, due to a confusing debconf configuration.
This section contains notes and hints specific to installing PHP on Mac OS X. There are two slightly different versions of Mac OS X, Client and Server, our manual deals with installing PHP on both systems. Note that PHP is not available for MacOS 9 and earlier versions.
There are a few pre-packaged and pre-compiled versions of PHP for Mac OS X. This can help in setting up a standard configuration, but if you need to have a different set of features (such as a secure server, or a different database driver), you may need to build PHP and/or your web server yourself. If you are unfamiliar with building and compiling your own software, it's worth checking whether somebody has already built a packaged version of PHP with the features you need.
Get the latest distributions of Apache and PHP.
Untar them, and run the configure program on Apache like so.
./configure --exec-prefix=/usr \ --localstatedir=/var \ --mandir=/usr/share/man \ --libexecdir=/System/Library/Apache/Modules \ --iconsdir=/System/Library/Apache/Icons \ --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \ --enable-shared=max \ --enable-module=mos |