Prawa autorskie do tego podręcznika © 1997 - 2009 należą do PHP Documentation Group. Materiał ten może być rozprowadzany tylko pod warunkami określonymi w Creative Commons Attribution 3.0 lub nowszych. Kopia Creative Commons Attribution 3.0 license jest dystrybuowana z tym podręcznikiem. Najnowsza wersja jest aktualnie dostępna pod adresem » http://creativecommons.org/licenses/by/3.0/.
W przypadku zainteresowania redystrybucją lub publikowaniem tego dokumentu w całości lub jego części, zmodyfikowanego lub niezmodyfikowanego, wszystkie pytania należy zadawać właścicielom praw autorskich do niego pod adresem » doc-license@lists.php.net. Adres ten jest podłączony do publicznie archiwizowanej listy dyskusyjnej.
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 internetowych, 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 w przeszłości wiele pracy przy tym projekcie. Jest wiele niewymienionych tutaj ludzi, którzy wnieśli wkład w rozwój tego podręcznika licznymi komentarzami. Cały czas te uwagi są one uwzględniane w odnośnikach, i za nie serdecznie dziękujemy. Wszystkie poniższe listy uporządkowane są w kolejności alfabetycznej.
Poniżsi współpracownicy powinni zostać wyróżnieni za wpływ jaki mieli (lub ciągle mają) w rozwój podręcznika: Bill Abt, Jouni Ahto, Alexander Aulbach, Daniel Beckham, Stig Bakken, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall, Simone Cortesi, Markus Fischer, Wez Furlong, Sara Golemon, Rui Hirokawa, Brad House, Pierre-Alain Joye, Etienne Kneuss, Moriyoshi Koizumi, Rasmus Lerdorf, Andrew Lindeman, Stanislav Malyshev, Rafael Martinez, Rick McGuire, Yasuo Ohgaki, Derick Rethans, Rob Richards, Sander Roobol, Egon Schmid, Thomas Schoefbeck, Sascha Schumann, Dan Scott, Masahiro Takagi, Michael Wallner, Lars Torben Wilson, Jim Winstead, Jeroen van Wolffelaar 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: Daniel Brown, Nuno Lopes, Felipe Pena, Thiago Pojda i Maciek Sokolewicz.
Te osoby także pracowały nad zarządzaniem notatkami: Mehdi Achour, Daniel Beckham, Friedhelm Betz, Victor Boivie, Jesus M. Castagnetto, Nicolas Chaillan, Ron Chmara, Sean Coates, James Cox, Vincent Gevers, Sara Golemon, Zak Greant, Szabolcs Heilig, Oliver Hinckel, Hartmut Holzgraefe, Etienne Kneuss, Rasmus Lerdorf, Matthew Li, Andrew Lindeman, Aidan Lister, Hannes Magnusson, Maxim Maletsky, Bobby Matthis, James Moore, Philip Olson, Sebastian Picklum, Derick Rethans, Sander Roobol, Damien Seguy, Jason Sheets, Tom Sommer, Jani Taskinen, Yasuo Ohgaki, Jakub Vrana, Lars Torben Wilson, Jim Winstead, Jared Wyles i Jeroen van Wolffelaar.
PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.
Nice, but what does that mean? An example:
Przykład #1 An introductory example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Example</title>
</head>
<body>
<?php
echo "Hi, I'm a PHP script!";
?>
</body>
</html>
Instead of lots of commands to output HTML (as seen in C or Perl),
PHP pages contain HTML with embedded code that does
"something" (in this case, output "Hi, I'm a PHP script!").
The PHP code is enclosed in special start and end processing
instructions <?php and ?>
that allow you to jump into and out of "PHP mode."
What distinguishes PHP from something like client-side JavaScript is that the code is executed on the server, generating HTML which is then sent to the client. The client would receive the results of running that script, but would not know what the underlying code was. You can even configure your web server to process all your HTML files with PHP, and then there's really no way that users can tell what you have up your sleeve.
The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid reading the long list of PHP's features. You can jump in, in a short time, and start writing simple scripts in a few hours.
Although PHP's development is focused on server-side scripting, you can do much more with it. Read on, and see more in the What can PHP do? section, or go right to the introductory tutorial if you are only interested in web programming.
Anything. PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more.
There are three main areas where PHP scripts are used.
PHP can be used on all major operating systems, including Linux, many Unix variants (including HP-UX, Solaris and OpenBSD), Microsoft Windows, Mac OS X, RISC OS, and probably others. PHP has also support for most of the web servers today. This includes Apache, Microsoft Internet Information Server, Personal Web Server, Netscape and iPlanet servers, Oreilly Website Pro server, Caudium, Xitami, OmniHTTPd, and many others. For the majority of the servers, PHP has a module, for the others supporting the CGI standard, PHP can work as a CGI processor.
So with PHP, you have the freedom of choosing an operating system and a web server. Furthermore, you also have the choice of using procedural programming or object oriented programming, or a mixture of them. Although not every standard OOP feature is implemented in PHP 4, many code libraries and large applications (including the PEAR library) are written only using OOP code. PHP 5 fixes the OOP related weaknesses of PHP 4, and introduces a complete object model.
With PHP you are not limited to output HTML. PHP's abilities includes outputting images, PDF files and even Flash movies (using libswf and Ming) generated on the fly. You can also output easily any text, such as XHTML and any other XML file. PHP can autogenerate these files, and save them in the file system, instead of printing it out, forming a server-side cache for your dynamic content.
One of the strongest and most significant features in PHP is its support for a wide range of databases. Writing a database-enabled web page is incredibly simple. The following databases are currently supported:
We also have a database abstraction extension (named PDO) allowing you to transparently use any database supported by that extension. Additionally PHP supports ODBC, the Open Database Connection standard, so you can connect to any other database supporting this world standard.
- Adabas D
- dBase
- Empress
- FilePro (read-only)
- Hyperwave
- IBM DB2
- Informix
- Ingres
- InterBase
- FrontBase
- mSQL
- Direct MS-SQL
- MySQL
- ODBC
- Oracle (OCI7 and OCI8)
- Ovrimos
- PostgreSQL
- SQLite
- Solid
- Sybase
- Velocis
- Unix dbm
PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (on Windows) and countless others. You can also open raw network sockets and interact using any other protocol. PHP has support for the WDDX complex data exchange between virtually all Web programming languages. Talking about interconnection, PHP has support for instantiation of Java objects and using them transparently as PHP objects. You can also use our CORBA extension to access remote objects.
PHP has extremely useful text processing features, from the POSIX Extended or Perl regular expressions to parsing XML documents. For parsing and accessing XML documents, PHP 4 supports the SAX and DOM standards, and you can also use the XSLT extension to transform XML documents. PHP 5 standardizes all the XML extensions on the solid base of libxml2 and extends the feature set adding SimpleXML and XMLReader support.
At last but not least, we have many other interesting extensions, the mnoGoSearch search engine functions, the IRC Gateway functions, many compression utilities (gzip, bz2, zip), calendar conversion, translation...
As you can see this page is not enough to list all the features and benefits PHP can offer. Read on in the sections about installing PHP, and see the function reference part for explanation of the extensions mentioned here.
Here we would like to show the very basics of PHP in a short, simple tutorial. This text only deals with dynamic web page creation with PHP, though PHP is not only capable of creating web pages. See the section titled What can PHP do for more information.
PHP-enabled web pages are treated just like regular HTML pages and you can create and edit them the same way you normally create regular HTML pages.
In this tutorial we assume that your server has activated support for PHP and that all files ending in .php are handled by PHP. On most servers, this is the default extension for PHP files, but ask your server administrator to be sure. If your server supports PHP, then you do not need to do anything. Just create your .php files, put them in your web directory and the server will automatically parse them for you. There is no need to compile anything nor do you need to install any extra tools. Think of these PHP-enabled files as simple HTML files with a whole new family of magical tags that let you do all sorts of things. Most web hosts offer PHP support, but if your host does not, consider reading the » PHP Links section for resources on finding PHP enabled web hosts.
Let us say you want to save precious bandwidth and develop locally. In this case, you will want to install a web server, such as » Apache, and of course » PHP. You will most likely want to install a database as well, such as » MySQL.
You can either install these individually or choose a simpler way. Our manual has installation instructions for PHP (assuming you already have some web server set up). In case you have problems with installing PHP yourself, we would suggest you ask your questions on our » installation mailing list. If you choose to go on the simpler route, then » locate a pre-configured package for your operating system, which automatically installs all of these with just a few mouse clicks. It is easy to setup a web server with PHP support on any operating system, including MacOSX, Linux and Windows. On Linux, you may find » rpmfind and » PBone helpful for locating RPMs. You may also want to visit » apt-get to find packages for Debian.
Create a file named hello.php and put it in your web server's root directory (DOCUMENT_ROOT) with the following content:
Przykład #1 Our first PHP script: hello.php
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>
Use your browser to access the file with your web server's URL, ending with the /hello.php file reference. When developing locally this URL will be something like http://localhost/hello.php or http://127.0.0.1/hello.php but this depends on the web server's configuration. If everything is configured correctly, this file will be parsed by PHP and the following output will be sent to your browser:
<html> <head> <title>PHP Test</title> </head> <body> <p>Hello World</p> </body> </html>
This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display: Hello World using the PHP echo() statement. Note that the file does not need to be executable or special in any way. The server finds out that this file needs to be interpreted by PHP because you used the ".php" extension, which the server is configured to pass on to PHP. Think of this as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things.
If you tried this example and it did not output anything, it prompted for download, or you see the whole file as text, chances are that the server you are on does not have PHP enabled, or is not configured properly. Ask your administrator to enable it for you using the Installation chapter of the manual. If you are developing locally, also read the installation chapter to make sure everything is configured properly. Make sure that you access the file via http with the server providing you the output. If you just call up the file from your file system, then it will not be parsed by PHP. If the problems persist anyway, do not hesitate to use one of the many » PHP support options.
The point of the example is to show the special PHP tag format. In this example we used <?php to indicate the start of a PHP tag. Then we put the PHP statement and left PHP mode by adding the closing tag, ?>. You may jump in and out of PHP mode in an HTML file like this anywhere you want. For more details, read the manual section on the basic PHP syntax.
Informacja: A Note on Line Feeds
Line feeds have little meaning in HTML, however it is still a good idea to make your HTML look nice and clean by putting line feeds in. A linefeed that follows immediately after a closing ?> will be removed by PHP. This can be extremely useful when you are putting in many blocks of PHP or include files containing PHP that aren't supposed to output anything. At the same time it can be a bit confusing. You can put a space after the closing ?> to force a space and a line feed to be output, or you can put an explicit line feed in the last echo/print from within your PHP block.
Informacja: A Note on Text Editors
There are many text editors and Integrated Development Environments (IDEs) that you can use to create, edit and manage PHP files. A partial list of these tools is maintained at » PHP Editors List. If you wish to recommend an editor, please visit the above page and ask the page maintainer to add the editor to the list. Having an editor with syntax highlighting can be helpful.
Informacja: A Note on Word Processors
Word processors such as StarOffice Writer, Microsoft Word and Abiword are not optimal for editing PHP files. If you wish to use one for this test script, you must ensure that you save the file as plain text or PHP will not be able to read and execute the script.
Informacja: A Note on Windows Notepad
If you are writing your PHP scripts using Windows Notepad, you will need to ensure that your files are saved with the .php extension. (Notepad adds a .txt extension to files automatically unless you take one of the following steps to prevent it.) When you save the file and are prompted to provide a name for the file, place the filename in quotes (i.e. "hello.php"). Alternatively, you can click on the 'Text Documents' drop-down menu in the 'Save' dialog box and change the setting to "All Files". You can then enter your filename without quotes.
Now that you have successfully created a working PHP script, it is time to create the most famous PHP script! Make a call to the phpinfo() function and you will see a lot of useful information about your system and setup such as available predefined variables, loaded PHP modules, and configuration settings. Take some time and review this important information.
Przykład #2 Get system information from PHP
<?php phpinfo(); ?>
Let us do something more useful now. We are going to check what sort of browser the visitor is using. For that, we check the user agent string the browser sends as part of the HTTP request. This information is stored in a variable. Variables always start with a dollar-sign in PHP. The variable we are interested in right now is $_SERVER['HTTP_USER_AGENT'].
Informacja: $_SERVER is a special reserved PHP variable that contains all web server information. It is known as a superglobal. See the related manual page on superglobals for more information. These special variables were introduced in PHP » 4.1.0. Before this time, we used the older $HTTP_*_VARS arrays instead, such as $HTTP_SERVER_VARS. Although deprecated, these older variables still exist. (See also the note on old code.)
To display this variable, you can simply do:
Przykład #1 Printing a variable (Array element)
<?php
echo $_SERVER['HTTP_USER_AGENT'];
?>
A sample output of this script may be:
There are many types of variables available in PHP. In the above example we printed an Array element. Arrays can be very useful.
$_SERVER is just one variable that PHP automatically makes available to you. A list can be seen in the Reserved Variables section of the manual or you can get a complete list of them by looking at the output of the phpinfo() function used in the example in the previous section.
You can put multiple PHP statements inside a PHP tag and create little blocks of code that do more than just a single echo. For example, if you want to check for Internet Explorer you can do this:
Przykład #2 Example using control structures and functions
<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
echo 'You are using Internet Explorer.<br />';
}
?>
A sample output of this script may be:
You are using Internet Explorer.<br />
Here we introduce a couple of new concepts. We have an if statement. If you are familiar with the basic syntax used by the C language, this should look logical to you. Otherwise, you should probably pick up an introductory PHP book and read the first couple of chapters, or read the Language Reference part of the manual.
The second concept we introduced was the strpos() function call. strpos() is a function built into PHP which searches a string for another string. In this case we are looking for 'MSIE' (so-called needle) inside $_SERVER['HTTP_USER_AGENT'] (so-called haystack). If the needle is found inside the haystack, the function returns the position of the needle relative to the start of the haystack. Otherwise, it returns FALSE. If it does not return FALSE, the if expression evaluates to TRUE and the code within its {braces} is executed. Otherwise, the code is not run. Feel free to create similar examples, with if, else, and other functions such as strtoupper() and strlen(). Each related manual page contains examples too. If you are unsure how to use functions, you will want to read both the manual page on how to read a function definition and the section about PHP functions.
We can take this a step further and show how you can jump in and out of PHP mode even in the middle of a PHP block:
Przykład #3 Mixing both HTML and PHP modes
<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
?>
<h3>strpos() must have returned non-false</h3>
<p>You are using Internet Explorer</p>
<?php
} else {
?>
<h3>strpos() must have returned false</h3>
<p>You are not using Internet Explorer</p>
<?php
}
?>
A sample output of this script may be:
<h3>strpos() must have returned non-false</h3> <p>You are using Internet Explorer</p>
Instead of using a PHP echo statement to output something, we jumped out of PHP mode and just sent straight HTML. The important and powerful point to note here is that the logical flow of the script remains intact. Only one of the HTML blocks will end up getting sent to the viewer depending on the result of strpos(). In other words, it depends on whether the string MSIE was found or not.
One of the most powerful features of PHP is the way it handles HTML forms. The basic concept that is important to understand is that any form element will automatically be available to your PHP scripts. Please read the manual section on Variables from external sources for more information and examples on using forms with PHP. Here is an example HTML form:
Przykład #1 A simple HTML form
<form action="action.php" method="post"> <p>Your name: <input type="text" name="name" /></p> <p>Your age: <input type="text" name="age" /></p> <p><input type="submit" /></p> </form>
There is nothing special about this form. It is a straight HTML form with no special tags of any kind. When the user fills in this form and hits the submit button, the action.php page is called. In this file you would write something like this:
Przykład #2 Printing data from our form
Hi <?php echo htmlspecialchars($_POST['name']); ?>.
You are <?php echo (int)$_POST['age']; ?> years old.
A sample output of this script may be:
Hi Joe. You are 22 years old.
Apart from the htmlspecialchars() and (int) parts, it should be obvious what this does. htmlspecialchars() makes sure any characters that are special in html are properly encoded so people can't inject HTML tags or Javascript into your page. For the age field, since we know it is a number, we can just convert it to an integer which will automatically get rid of any stray characters. You can also have PHP do this for you automatically by using the filter extension. The $_POST['name'] and $_POST['age'] variables are automatically set for you by PHP. Earlier we used the $_SERVER superglobal; above we just introduced the $_POST superglobal which contains all POST data. Notice how the method of our form is POST. If we used the method GET then our form information would live in the $_GET superglobal instead. You may also use the $_REQUEST superglobal, if you do not care about the source of your request data. It contains the merged information of GET, POST and COOKIE data. Also see the import_request_variables() function.
You can also deal with XForms input in PHP, although you will find yourself comfortable with the well supported HTML forms for quite some time. While working with XForms is not for beginners, you might be interested in them. We also have a short introduction to handling data received from XForms in our features section.
Now that PHP has grown to be a popular scripting language, there are a lot of public repositories and libraries containing code you can reuse. The PHP developers have largely tried to preserve backwards compatibility, so a script written for an older version will run (ideally) without changes in a newer version of PHP. In practice, some changes will usually be needed.
Two of the most important recent changes that affect old code are:
For more details on these changes, see the section on predefined variables and links therein.
With your new knowledge you should be able to understand most of the manual and also the various example scripts available in the example archives. You can also find other examples on the php.net websites in the links section: » http://www.php.net/links.php.
To view various slide presentations that show more of what PHP can do, see the PHP Conference Material Site: » http://talks.php.net/
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?
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.
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, Netscape i iPlanet. Przez 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 lub FastCGI. 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żywaniem 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. W następnych sekcjach znajdziesz informacje o wywoływaniu PHP z linii poleceń.
Kod źródlowy oraz dystrybucje binarne dla Windows, można znaleźć na stronie » http://www.php.net/downloads.php. Zalecane jest korzystanie z jednego z najbliższego » serweru lustrzanego do pobierania dystrybucji PHP.
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 web server. 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:
The initial PHP setup and configuration process is controlled by the use of the command line 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 #1 Installation Instructions (Apache Shared Module Version) for PHP
1. gunzip apache_xxx.tar.gz
2. tar -xvf apache_xxx.tar
3. gunzip php-xxx.tar.gz
4. tar -xvf php-xxx.tar
5. cd apache_xxx
6. ./configure --prefix=/www --enable-module=so
7. make
8. make install
9. cd ../php-xxx
10. Now, configure your PHP. This is where you customize your PHP
with various options, like which extensions will be enabled. Do a
./configure --help for a list of available options. In our example
we'll do a simple configure with Apache 1 and MySQL support. Your
path to apxs may differ from our example.
./configure --with-mysql --with-apxs=/www/bin/apxs
11. make
12. make install
If you decide to change your configure options after installation,
you only need to repeat the last three steps. You only need to
restart apache for the new module to take effect. A recompile of
Apache is not needed.
Note that unless told otherwise, 'make install' will also install PEAR,
various PHP tools such as phpize, install the PHP CLI, and more.
13. Setup your php.ini file:
cp php.ini-development /usr/local/lib/php.ini
You may edit your .ini file to set PHP options. If you prefer your
php.ini in another location, use --with-config-file-path=/some/path in
step 10.
If you instead choose php.ini-production, be certain to read the list
of changes within, as they affect how PHP behaves.
14. Edit your httpd.conf to load the PHP module. The path on the right hand
side of the LoadModule statement must point to the path of the PHP
module on your system. The make install from above may have already
added this for you, but be sure to check.
For PHP 4:
LoadModule php4_module libexec/libphp4.so
For PHP 5:
LoadModule php5_module libexec/libphp5.so
15. And in the AddModule section of httpd.conf, somewhere under the
ClearModuleList, add this:
For PHP 4:
AddModule mod_php4.c
For PHP 5:
AddModule mod_php5.c
16. Tell Apache to parse certain extensions as PHP. For example,
let's have Apache parse the .php extension as PHP. You could
have any extension(s) parse as PHP by simply adding more, with
each separated by a space. We'll add .phtml to demonstrate.
AddType application/x-httpd-php .php .phtml
It's also common to setup the .phps extension to show highlighted PHP
source, this can be done with:
AddType application/x-httpd-php-source .phps
17. Use your normal procedure for starting the Apache server. (You must
stop and restart the server, not just cause the server to reload by
using a HUP or USR1 signal.)
Alternatively, to install PHP as a static object:
Przykład #2 Installation Instructions (Static Module Installation for Apache) for PHP
1. gunzip -c apache_1.3.x.tar.gz | tar xf -
2. cd apache_1.3.x
3. ./configure
4. cd ..
5. gunzip -c php-5.x.y.tar.gz | tar xf -
6. cd php-5.x.y
7. ./configure --with-mysql --with-apache=../apache_1.3.x
8. make
9. make install
10. cd ../apache_1.3.x
11. ./configure --prefix=/www --activate-module=src/modules/php5/libphp5.a
(The above line is correct! Yes, we know libphp5.a does not exist at this
stage. It isn't supposed to. It will be created.)
12. make
(you should now have an httpd binary which you can copy to your Apache bin dir if
it is your first install then you need to "make install" as well)
13. cd ../php-5.x.y
14. cp php.ini-development /usr/local/lib/php.ini
15. You can edit /usr/local/lib/php.ini file to set PHP options.
Edit your httpd.conf or srm.conf file and add:
AddType application/x-httpd-php .php
Informacja: 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 #3 Example commands for restarting Apache
1. Several Linux and SysV variants: /etc/rc.d/init.d/httpd restart 2. Using apachectl scripts: /path/to/apachectl stop /path/to/apachectl start 3. httpdctl and httpsdctl (Using OpenSSL), similar to apachectl: /path/to/httpsdctl stop /path/to/httpsdctl start 4. Using mod_ssl, or another SSL server, you may want to manually stop and start: /path/to/apachectl stop /path/to/apachectl startssl
The locations of the apachectl and http(s)dctl binaries often vary. If your system has locate or whereis or which commands, these can assist you in finding your server control programs.
Different examples of compiling PHP for apache are as follows:
./configure --with-apxs --with-pgsql
This will create a libphp5.so (or libphp4.so in PHP 4) shared library that is loaded into Apache using a LoadModule line in Apache's httpd.conf file. The PostgreSQL support is embedded into this library.
./configure --with-apxs --with-pgsql=shared
This will create a libphp4.so shared library for Apache, but it will also create a pgsql.so shared library that is loaded into PHP either by using the extension directive in php.ini file or by loading it explicitly in a script using the dl() function.
./configure --with-apache=/path/to/apache_source --with-pgsql
This will create a libmodphp5.a library, a mod_php5.c and some accompanying files and copy this into the src/modules/php5 directory in the Apache source tree. Then you compile Apache using --activate-module=src/modules/php5/libphp5.a and the Apache build system will create libphp5.a and link it statically into the httpd binary (replace php5 by php4 in PHP 4). The PostgreSQL support is included directly into this httpd binary, so the final result here is a single httpd binary that includes all of Apache and all of PHP.
./configure --with-apache=/path/to/apache_source --with-pgsql=shared
Same as before, except instead of including PostgreSQL support directly into the final httpd you will get a pgsql.so shared library that you can load into PHP from either the php.ini file or directly using dl().
When choosing to build PHP in different ways, you should consider the advantages and drawbacks of each method. Building as a shared object will mean that you can compile apache separately, and don't have to recompile everything as you add to, or change, PHP. Building PHP into apache (static method) means that PHP will load and run faster. For more information, see the Apache » web page on DSO support.
Informacja: Apache's default httpd.conf currently ships with a section that looks like this:
User nobody Group "#-1"Unless you change that to "Group nogroup" or something like that ("Group daemon" is also very common) PHP will not be able to open files.
Informacja: 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.x installs of PHP on Unix systems.
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
The » Apache Documentation is the most authoritative source of information on the Apache 2.x server. More information about installation options for Apache may be found there.
Informacja: 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:
- 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 SVN.
These versions of PHP are compatible to Apache 2.0.40 and later.
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.
The most receive version of Apache HTTP Server may be obtained from » Apache download site, and a fitting PHP version from the above mentioned places. This quick guide covers only the basics to get started with Apache 2.x and PHP. For more information read the » Apache Documentation. The version numbers have been omitted here, to ensure the instructions are not incorrect. In the examples below, 'NN' should be replaced with the specific version of Apache being used.
There are currently two versions of Apache 2.x - there's 2.0 and 2.2. While there are various reasons for choosing each, 2.2 is the current latest version, and the one that is recommended, if that option is available to you. However, the instructions here will work for either 2.0 or 2.2.
Przykład #1 Installation Instructions (Apache 2 Shared Module Version)
1. gzip -d httpd-2_x_NN.tar.gz
2. tar xvf httpd-2_x_NN.tar
3. gunzip php-NN.tar.gz
4. tar -xvf php-NN.tar
5. cd httpd-2_x_NN
6. ./configure --enable-so
7. make
8. make install
Now you have Apache 2.x.NN available under /usr/local/apache2,
configured with loadable module support and the standard MPM prefork.
To test the installation use your normal procedure for starting
the Apache server, e.g.:
/usr/local/apache2/bin/apachectl start
and stop the server to go on with the configuration for PHP:
/usr/local/apache2/bin/apachectl stop.
9. cd ../php-NN
10. Now, configure your PHP. This is where you customize your PHP
with various options, like which extensions will be enabled. Do a
./configure --help for a list of available options. In our example
we'll do a simple configure with Apache 2 and MySQL support. Your
path to apxs may differ, in fact, the binary may even be named apxs2 on
your system.
./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql
11. make
12. make install
If you decide to change your configure options after installation,
you only need to repeat the last three steps. You only need to
restart apache for the new module to take effect. A recompile of
Apache is not needed.
Note that unless told otherwise, 'make install' will also install PEAR,
various PHP tools such as phpize, install the PHP CLI, and more.
13. Setup your php.ini
cp php.ini-development /usr/local/lib/php.ini
You may edit your .ini file to set PHP options. If you prefer having
php.ini in another location, use --with-config-file-path=/some/path in
step 10.
If you instead choose php.ini-production, be certain to read the list
of changes within, as they affect how PHP behaves.
14. Edit your httpd.conf to load the PHP module. The path on the right hand
side of the LoadModule statement must point to the path of the PHP
module on your system. The make install from above may have already
added this for you, but be sure to check.
LoadModule php5_module modules/libphp5.so
15. Tell Apache to parse certain extensions as PHP. For example, let's have
Apache parse .php files as PHP. Instead of only using the Apache AddType
directive, we want to avoid potentially dangerous uploads and created
files such as exploit.php.jpg from being executed as PHP. Using this
example, you could have any extension(s) parse as PHP by simply adding
them. We'll add .phtml to demonstrate.
<FilesMatch \.php$>
SetHandler application/x-httpd-php
</FilesMatch>
Or, if we wanted to allow .php, .php2, .php3, .php4, .php5, .php6, and
.phtml files to be executed as PHP, but nothing else, we'd use this:
<FilesMatch "\.ph(p[2-6]?|tml)$">
SetHandler application/x-httpd-php
</FilesMatch>
And to allow .phps files to be handled by the php source filter, and
displayed as syntax-highlighted source code, use this:
<FilesMatch "\.phps$">
SetHandler application/x-httpd-php-source
</FilesMatch>
mod_rewrite may be used To allow any arbitrary .php file to be displayed
as syntax-highlighted source code, without having to rename or copy it
to a .phps file:
RewriteEngine On
RewriteRule (.*\.php)s$ $1 [H=application/x-httpd-php-source]
The php source filter should not be enabled on production systems, where
it may expose confidential or otherwise sensitive information embedded in
source code.
16. Use your normal procedure for starting the Apache server, e.g.:
/usr/local/apache2/bin/apachectl start
- OR -
service httpd restart
Following the steps above you will have a running Apache2 web server with support for PHP as a SAPI module. Of course there are many more configuration options available Apache and PHP. For more information type ./configure --help in the corresponding source tree.
Apache may be built multithreaded by selecting the worker MPM, rather than the standard prefork MPM, when Apache is built. This is done by adding the following option to the argument passed to ./configure, in step 6 above:
This should not be undertaken without being aware of the consequences of this decision, and having at least a fair understanding of the implications. The Apache documentation regarding » MPM-Modules discusses MPMs in a great deal more detail.
Informacja: The Apache MultiViews FAQ discusses using multiviews with PHP.
Informacja: To build a multithreaded version of Apache, the target system must support threads. In this case, PHP should also be built with experimental Zend Thread Safety (ZTS). Under this configuration, not all extensions will be available. The recommended setup is to build Apache with the default prefork MPM-Module.
This section contains notes and hints specific to Lighttpd 1.4 installs of PHP on Unix systems.
Please use the » Lighttpd trac to learn how to install Lighttpd properly before continuing.
Fastcgi is the preferred SAPI to connect PHP and Lighttpd. Fastcgi is automagically enabled in php-cgi in PHP 5.3, but for older versions configure PHP with --enable-fastcgi. To confirm that PHP has fastcgi enabled, php -v should contain PHP 5.2.5 (cgi-fcgi) Before PHP 5.2.3, fastcgi was enabled on the php binary (there was no php-cgi).
To configure Lighttpd to connect to php and spawn fastcgi processes, edit lighttpd.conf. Sockets are preferred to connect to fastcgi processes on the local system.
Przykład #1 Partial lighttpd.conf
server.modules += ( "mod_fastcgi" )
fastcgi.server = ( ".php" =>
((
"socket" => "/tmp/php.socket",
"bin-path" => "/usr/local/bin/php-cgi",
"bin-environment" => (
"PHP_FCGI_CHILDREN" => "16",
"PHP_FCGI_MAX_REQUESTS" => "10000"
),
"min-procs" => 1,
"max-procs" => 1,
"idle-timeout" => 20
))
)
The bin-path directive allows lighttpd to spawn fastcgi processes dynamically. PHP will spawn children according to the PHP_FCGI_CHILDREN environment variable. The "bin-environment" directive sets the environment for the spawned processes. PHP will kill a child process after the number of requests specified by PHP_FCGI_MAX_REQUESTS is reached. The directives "min-procs" and "max-procs" should generally be avoided with PHP. PHP manages its own children and opcode caches like APC will only share among children managed by PHP. If "min-procs" is set to something greater than 1, the total number of php responders will be multiplied PHP_FCGI_CHILDREN (2 min-procs * 16 children gives 32 responders).
Lighttpd provides a program called spawn-fcgi to ease the process of spawning fastcgi processes easier.
It is possible to spawn processes without spawn-fcgi, though a bit of heavy-lifting is required. Setting the PHP_FCGI_CHILDREN environment var controls how many children PHP will spawn to handle incoming requests. Setting PHP_FCGI_MAX_REQUESTS will determine how long (in requests) each child will live. Here's a simple bash script to help spawn php responders.
Przykład #2 Spawning FastCGI Responders
#!/bin/sh
# Location of the php-cgi binary
PHP=/usr/local/bin/php-cgi
# PID File location
PHP_PID=/tmp/php.pid
# Binding to an address
#FCGI_BIND_ADDRESS=10.0.1.1:10000
# Binding to a domain socket
FCGI_BIND_ADDRESS=/tmp/php.sock
PHP_FCGI_CHILDREN=16
PHP_FCGI_MAX_REQUESTS=10000
env -i PHP_FCGI_CHILDREN=$PHP_FCGI_CHILDREN \
PHP_FCGI_MAX_REQUESTS=$PHP_FCGI_MAX_REQUESTS \
$PHP -b $FCGI_BIND_ADDRESS &
echo $! > "$PHP_PID"
Fastcgi instances can be spawned on multiple remote machines in order to scale applications.
Przykład #3 Connecting to remote php-fastcgi instances
fastcgi.server = ( ".php" =>
(( "host" => "10.0.0.2", "port" => 1030 ),
( "host" => "10.0.0.3", "port" => 1030 ))
)
PHP can be built as a Pike module for the » Caudium webserver. Follow the simple instructions below to install PHP for Caudium.
Przykład #1 Caudium Installation Instructions
1. Make sure you have Caudium installed prior to attempting to
install PHP 4. For PHP 4 to work correctly, you will need Pike
7.0.268 or newer. For the sake of this example we assume that
Caudium is installed in /opt/caudium/server/.
2. Change directory to php-x.y.z (where x.y.z is the version number).
3. ./configure --with-caudium=/opt/caudium/server
4. make
5. make install
6. Restart Caudium if it's currently running.
7. Log into the graphical configuration interface and go to the
virtual server where you want to add PHP 4 support.
8. Click Add Module and locate and then add the PHP 4 Script Support module.
9. If the documentation says that the 'PHP 4 interpreter isn't
available', make sure that you restarted the server. If you did
check /opt/caudium/logs/debug/default.1 for any errors related to
PHP4.so. Also make sure that
caudium/server/lib/[pike-version]/PHP4.so
is present.
10. Configure the PHP Script Support module if needed.
You can of course compile your Caudium module with support for the various extensions available in PHP 4. See the reference pages for extension specific configure options.
Informacja: 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.
Informacja: 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 web servers read the note about subrequests.
You can find more information about setting up PHP for the Netscape Enterprise Server (NES) here: » http://benoit.noss.free.fr/php/install-php4.html
To build PHP with Sun JSWS/Sun ONE WS/iPlanet/Netscape web servers, enter the proper install directory for the --with-nsapi=[DIR] option. The default directory is usually /opt/netscape/suitespot/. Please also read /php-xxx-version/sapi/nsapi/nsapi-readme.txt.
Install the following packages from » http://www.sunfreeware.com/ or another download site:
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
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
After performing the base install and reading the appropriate readme file, you may need to perform some additional configuration steps.
Firstly you may need to add some paths to the LD_LIBRARY_PATH environment for the server to find all the shared libs. This can best done in the start script for your web server. The start script is often located in: /path/to/server/https-servername/start. You may also need to edit the configuration files that are located in: /path/to/server/https-servername/config/.
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"]
(PHP >= 4.3.3) The php_ini parameter is optional but with it you can place your php.ini in your web server config directory.
Configure the default object in obj.conf (for virtual server classes [version 6.0+] in their vserver.obj.conf):
<Object name="default"> . . . .#NOTE this next line should happen after all 'ObjectType' and before all 'AddLog' lines Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...] . . </Object>
(PHP >= 4.3.3) As additional parameters you can add some special php.ini-values, for example you can set a docroot="/path/to/docroot" specific to the context php4_execute is called. For boolean ini-keys please use 0/1 as value, not "On","Off",... (this will not work correctly), e.g. zlib.output_compression=1 instead of zlib.output_compression="On"
This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):
<Object name="x-httpd-php"> ObjectType fn="force-type" type="magnus-internal/x-httpd-php" Service fn=php4_execute [inikey=value inikey=value ...] </Object>
After that you can configure a directory in the Administration server and assign it the style x-httpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming files to .html.
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>
Informacja: The stacksize that PHP uses depends on the configuration of the web server. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").
Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the web server itself) and this space has only one environment. If you want to get CGI variables like PATH_INFO, HTTP_HOST etc. it is not the correct way to try this in the old PHP way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running web server without any valid CGI variables!
Informacja: Why are there (invalid) CGI variables in the environment?
Answer: This is because you started the web server process from the admin server which runs the startup script of the web server, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started web server has some CGI environment variables in it. You can test this by starting the web server not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.
Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):
variables_order = "GPCS" register_globals = On
You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:
Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...]
where XXX is the HTTP error code. Please delete any other Error directives which could interfere with yours. If you want to place a page for all errors that could exist, leave the code parameter out. Your script can get the HTTP status code with $_SERVER['ERROR_TYPE'].
Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:
Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...]
For both error and directory listing pages the original URI and translated URI are in the variables $_SERVER['PATH_INFO'] and $_SERVER['PATH_TRANSLATED'].
The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the web server and insert the result in the web page. This function uses some undocumented features from the NSAPI library. On Unix the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.
Informacja: But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!
The default is to build PHP as a CGI program. This creates a command line interpreter, which can be used for CGI processing, or for non-web-related PHP scripting. If you are running a web server PHP has module support for, you should generally go for that solution for performance reasons. However, the CGI version enables users to run different PHP-enabled pages under different user-ids.
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.
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.
There are two main options for installing PHP on HP-UX systems. Either compile it, or install a pre-compiled binary.
Official pre-compiled packages are located here: » http://software.hp.com/
Until this manual section is rewritten, the documentation about compiling PHP (and related extensions) on HP-UX systems has been removed. For now, consider reading the following external resource: » Building Apache and PHP on HP-UX 11.11
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 #1 OpenBSD Package Install Example
# pkg_add php4-core-4.3.8.tgz # /usr/local/sbin/phpxs -s # cp /usr/local/share/doc/php4/php.ini-recommended /var/www/conf/php.ini (add in mysql) # pkg_add php4-mysql-4.3.8.tgz # /usr/local/sbin/phpxs -a mysql (add in imap) # pkg_add php4-imap-4.3.8.tgz # /usr/local/sbin/phpxs -a imap (remove mysql as a test) # pkg_delete php4-mysql-4.3.8 # /usr/local/sbin/phpxs -r mysql (install the PEAR libraries) # pkg_add php4-pear-4.3.8.tgz
Read the » packages(7) manual page for more information about binary packages on OpenBSD.
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.
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:
In addition, you will need to install (and possibly compile) any additional software specific to your configuration, such as Oracle or MySQL.
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 the instructions for building PHP on Unix apply to Debian as well, this manual page contains specific information for other options, such as using either the apt-get or aptitude commands. This manual page uses these two commands interchangeably.
First, note that other related packages may be desired like libapache2-mod-php5 to integrate with Apache 2, and php-pear for PEAR.
Second, before installing a package, it's wise to ensure the package list is up to date. Typically, this is done by running the command apt-get update.
Przykład #1 Debian Install Example with Apache 2
# apt-get install php5-common libapache2-mod-php5 php5-cli
APT will automatically install the PHP 5 module for Apache 2 and all of its dependencies, and then activate it. Apache should be restarted in order for the changes take place. For example:
Przykład #2 Stopping and starting Apache once PHP is installed
# /etc/init.d/apache2 stop # /etc/init.d/apache2 start
In the last section, PHP was installed with only core modules. It's very likely that additional modules will be desired, such as MySQL, cURL, GD, etc. These may also be installed via the apt-get command.
Przykład #3 Methods for listing additional PHP 5 packages
# apt-cache search php5 # aptitude search php5 # aptitude search php5 |grep -i mysql
The examples will show a lot of packages including several PHP specific ones like php5-cgi, php5-cli and php5-dev. Determine which are needed and install them like any other with either apt-get or aptitude. And because Debian performs dependency checks, it'll prompt for those so for example to install MySQL and cURL:
Przykład #4 Install PHP with MySQL, cURL
# apt-get install php5-mysql php5-curl
APT will automatically add the appropriate lines to the different php.ini related files like /etc/php5/apache2/php.ini, /etc/php5/conf.d/pdo.ini, etc. and depending on the extension will add entries similar to extension=foo.so. However, restarting the web server (like Apache) is required before these changes take affect.
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.
The following resources offer easy to install packages and precompiled binaries for PHP on Mac OS:
PHP has come standard with Macs since OS X version 10.0.0. Enabling PHP with the default web server requires uncommenting a few lines in the Apache configuration file httpd.conf whereas the CGI and/or CLI are enabled by default (easily accessible via the Terminal program).
Enabling PHP using the instructions below is meant for quickly setting up a local development environment. It's highly recommended to always upgrade PHP to the newest version. Like most live software, newer versions are created to fix bugs and add features and PHP being is no different. See the appropriate MAC OS X installation documentation for further details. The following instructions are geared towards a beginner with details provided for getting a default setup to work. All users are encouraged to compile, or install a new packaged version.
The standard installation type is using mod_php, and enabling the bundled mod_php on Mac OS X for the Apache web server (the default web server, that is accessible via System Preferences) involves the following steps:
Informacja: One way to open this is by using a Unix based text editor in the Terminal, for example nano, and because the file is owned by root we'll use the sudo command to open it (as root) so for example type the following into the Terminal Application (after, it will prompt for a password): sudo nano /private/etc/apache2/httpd.conf Noteworthy nano commands: ^w (search), ^o (save), and ^x (exit) where ^ represents the Ctrl key.
Informacja: Versions of Mac OS X prior to 10.5 were bundled with older versions of PHP and Apache. As such, the Apache configuration file on legacy machines may be /etc/httpd/httpd.conf.
With a text editor, uncomment the lines (by removing the #) that look similar to the following (these two lines are often not together, locate them both in the file):
# LoadModule php5_module libexec/httpd/libphp5.so # AddModule mod_php5.c
Be sure the desired extensions will parse as PHP (examples: .php .html and .inc)
Due to the following statement already existing in httpd.conf (as of Mac Panther), once PHP is enabled the .php files will automatically parse as PHP.
<IfModule mod_php5.c>
# If php is turned on, we respect .php and .phps files.
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
# Since most users will want index.php to work we
# also automatically enable index.php
<IfModule mod_dir.c>
DirectoryIndex index.html index.php
</IfModule>
</IfModule>
Informacja: Before OS X 10.5 (Leopard), PHP 4 was bundled instead of PHP 5 in which case the above instructions will differ slightly by changing 5's to 4's.
The phpinfo() function will display information about PHP. Consider creating a file in the DocumentRoot with the following PHP code:
<?php phpinfo(); ?>
The CLI (or CGI in older versions) is appropriately named php and likely exists as /usr/bin/php. Open up the terminal, read the command line section of the PHP manual, and execute php -v to check the PHP version of this PHP binary. A call to phpinfo() will also reveal this information.
Untar them, and run the configure program on Apache like so.
./configure --exec-prefix=/usr \ --localstatedir=/var \ --mandir=/usr/share/man \ --libexecdir=/System/Library/Apache/Modules \ --iconsdir=/System/Library/Apache/Icons \ --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \ --enable-shared=max \ --enable-module=most \ --target=apache
If you want the compiler to do some optimization, you may also want to add this line:
setenv OPTIM=-O2
Next, go to the PHP 4 source directory and configure it.
./configure --prefix=/usr \
--sysconfdir=/etc \
--localstatedir=/var \
--mandir=/usr/share/man \
--with-xml \
--with-apache=/src/apache_1.3.12
If you have any other additions (MySQL, GD, etc.), be sure to add them here. For the --with-apache string, put in the path to your apache source directory, for example /src/apache_1.3.12.
Now, reconfigure Apache to build in PHP 4.
./configure --exec-prefix=/usr \ --localstatedir=/var \ --mandir=/usr/share/man \ --libexecdir=/System/Library/Apache/Modules \ --iconsdir=/System/Library/Apache/Icons \ --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \ --enable-shared=max \ --enable-module=most \ --target=apache \ --activate-module=src/modules/php4/libphp4.a
You may get a message telling you that libmodphp4.a is out of date. If so, go to the src/modules/php4 directory inside your Apache source directory and run this command: ranlib libmodphp4.a. Then go back to the root of the Apache source directory and run the above configure command again. That'll bring the link table up to date. Run make and make install again.
cp php.ini-development /usr/local/bin/php.ini
or (if your don't have a local directory)
cp php.ini-development /usr/bin/php.ini
.
The following instructions will help you install a PHP module for the Apache web server included in MacOS X using the MacOS GUI. This version includes MySQL, PostgreSQL, and iODBC database support, cURL, GD, PDFLib, LDAP, and more. These instructions are graciously provided by » Marc Liyanage.
Be sure you know what you're doing before advancing beyond this point! You can cause irreparable harm to your Apache installation otherwise.
Informacja: These instructions will only work with the original Apache web server as shipped by Apple. If you re-built or upgraded your Apache, you will have to build your own PHP module.
To install:
http://www2.entropy.ch/download/entropy-php-5.2.4-1.tar.gz
wget
http://www2.entropy.ch/download/entropy-php-5.2.4-1-apache2.tar.gz
That's all! PHP should now be up and running. You can test it by dropping a file named test.php into your Sites folder in your home directory. Into that file, write this line: <?php phpinfo() ?>.
Now open up 127.0.0.1/~your_username/test.php in your web browser. You should see a status table with information about the PHP module.
This section applies to Windows 98/Me and Windows NT/2000/XP/2003. PHP will not work on 16 bit platforms such as Windows 3.1 and sometimes we refer to the supported Windows platforms as Win32. Windows 95 is no longer supported as of PHP 4.3.0.
Informacja: Windows 98/ME/NT4 is no longer supported as of PHP 5.3.0.
Informacja: Windows 95 is no longer supported as of PHP 4.3.0.
There are two main ways to install PHP for Windows: either manually or by using the installer.
If you have Microsoft Visual Studio, you can also build PHP from the original source code.
Once you have PHP installed on your Windows system, you may also want to load various extensions for added functionality.
There are several all-in-one installers over the Internet, but none of those are endorsed by PHP.net, as we believe that using one of the official windows packages from » http://www.php.net/downloads.php is the best choice to have your system secure and optimized.
The Windows PHP installer is available from the downloads page at » http://www.php.net/downloads.php. This installs the CGI version of PHP and for IIS, PWS, and Xitami, it configures the web server as well. The installer does not include any extra external PHP extensions (php_*.dll) as you'll only find those in the Windows Zip Package and PECL downloads.
Informacja: While the Windows installer is an easy way to make PHP work, it is restricted in many aspects as, for example, the automatic setup of extensions is not supported. Use of the installer isn't the preferred method for installing PHP.
First, install your selected HTTP (web) server on your system, and make sure that it works.
Run the executable installer and follow the instructions provided by the installation wizard. Two types of installation are supported - standard, which provides sensible defaults for all the settings it can, and advanced, which asks questions as it goes along.
The installation wizard gathers enough information to set up the php.ini file, and configure certain web servers to use PHP. One of the web servers the PHP installer does not configure for is Apache, so you'll need to configure it manually.
Once the installation has completed, the installer will inform you if you need to restart your system, restart the server, or just start using PHP.
Be aware, that this setup of PHP is not secure. If you would like to have a secure PHP setup, you'd better go on the manual way, and set every option carefully. This automatically working setup gives you an instantly working PHP installation, but it is not meant to be used on online servers.
The Windows PHP installer for later versions of PHP is built using MSI technology using the Wix Toolkit (» http://wix.sourceforge.net/). It will install and configure PHP and all the built-in and PECL extensions, as well as configure many of the popular web servers such as IIS, Apache, and Xitami.
First, install your selected HTTP (web) server on your system, and make sure that it works. Then proceed with one of the following install types.
Run the MSI installer and follow the instructions provided by the installation wizard. You will be prompted to select the Web Server you wish to configure first, along with any configuration details needed.
You will then be prompted to select which features and extensions you wish to install and enable. By selecting "Will be installed on local hard drive" in the drop-down menu for each item you can trigger whether to install the feature or not. By selecting "Entire feature will be installed on local hard drive", you will be able to install all sub-features of the included feature ( for example by selecting this options for the feature "PDO" you will install all PDO Drivers ).
It is not recommended to install all extensions by default, since many other them require dependencies from outside PHP in order to function properly. Instead, use the Installation Repair Mode that can be triggered thru the 'Add/Remove Programs' control panel to enable or disable extensions and features after installation.
The installer then sets up PHP to be used in Windows and the php.ini file, and configures certain web servers to use PHP. The installer will currently configure IIS, Apache, Xitami, and Sambar Server; if you are using a different web server you'll need to configure it manually.
The installer also supports a silent mode, which is helpful for Systems Administrators to deploy PHP easily. To use silent mode:
msiexec.exe /i php-VERSION-win32-install.msi /q
You can control the install directory by passing it as a parameter to the install. For example, to install to e:\php:
msiexec.exe /i php-VERSION-win32-install.msi /q INSTALLDIR=e:\php
You can also specify what features to install. For example, to install the mysqli extension and the CGI executable:
msiexec.exe /i php-VERSION-win32-install.msi /q ADDLOCAL=cgi,ext_php_mysqli
The current list of Features to install is as follows:
MainExecutable - php.exe executable ( no longer available as of PHP 5.2.10/5.3.0; it is now included by default ) ScriptExecutable - php-win.exe executable ext_php_* - the various extensions ( for example: ext_php_mysql for MySQL ) apache13 - Apache 1.3 module apache20 - Apache 2.0 module apache22 - Apache 2,2 module apacheCGI - Apache CGI executable iis4ISAPI - IIS ISAPI module iis4CGI - IIS CGI executable iis4FastCGI - IIS CGI executable NSAPI - Sun/iPlanet/Netscape server module netserve - NetServe Web Server CGI executable Xitami - Xitami CGI executable Sambar - Sambar Server ISAPI module CGI - php-cgi.exe executable PEAR - PEAR installer Manual - PHP Manual in CHM Format
For more information on installing MSI installers from the command line, visit » http://msdn.microsoft.com/en-us/library/aa367988.aspx
To upgrade, run the installer either graphically or from the command line as normal. The installer will read your current install options, remove your old installation, and reinstall PHP with the same options as before. It is recommended that you use this method of keeping PHP updated instead of manually replacing the files in the installation directory.
This section contains instructions for manually installing and configuring PHP on Microsoft Windows. For the instructions on how to use PHP installer to setup and configure PHP and a web server on Windows refer to Windows Installer (PHP 5.2 and later).
Download the PHP zip binary distribution from » PHP for Windows: Binaries and Sources. There are several different versions of the zip package - chose the version that is suitable for the web server being used:
If PHP is used with IIS then choose PHP 5.3 VC9 Non Thread Safe or PHP 5.2 VC6 Non Thread Safe;
If PHP is used with Apache 1 or Apache 2 then choose PHP 5.3 VC6 or PHP 5.2 VC6.
Informacja: VC9 Versions are compiled with the Visual Studio 2008 compiler and have improvements in performance and stability. The VC9 versions require you to have the » Microsoft 2008 C++ Runtime (x86) or the » Microsoft 2008 C++ Runtime (x64) installed.
Unpack the content of the zip archive into a directory of your choice, for example C:\PHP\. The directory and file structure extracted from the zip will look as below:
Przykład #1 PHP 5 package structure
c:\php | +--dev | | | |-php5ts.lib -- php5.lib in non thread safe version | +--ext -- extension DLLs for PHP | | | |-php_bz2.dll | | | |-php_cpdf.dll | | | |-... | +--extras -- empty | +--pear -- initial copy of PEAR | | |-go-pear.bat -- PEAR setup script | |-... | |-php-cgi.exe -- CGI executable | |-php-win.exe -- executes scripts without an opened command prompt | |-php.exe -- Command line PHP executable (CLI) | |-... | |-php.ini-development -- default php.ini settings | |-php.ini-production -- recommended php.ini settings | |-php5apache2_2.dll -- does not exist in non thread safe version | |-php5apache2_2_filter.dll -- does not exist in non thread safe version | |-... | |-php5ts.dll -- core PHP DLL ( php5.dll in non thread safe version) | |-...
Below is the list of the modules and executables included in the PHP zip distribution:
go-pear.bat - the PEAR setup script. Refer to » Installation (PEAR) for more details.
php-cgi.exe - CGI executable that can be used when running PHP on IIS via CGI or FastCGI.
php-win.exe - the PHP executable for executing PHP scripts without using a command line window (for example PHP applications that use Windows GUI).
php.exe - the PHP executable for executing PHP scripts within a command line interface (CLI).
php5apache2_2.dll - Apache 2.2.X module.
php5apache2_2_filter.dll - Apache 2.2.X filter.
After the php package content has been extracted, copy the php.ini-production into php.ini in the same folder. If necessary, it is also possible to place the php.ini into any other location of your choice but that will require additional configuration steps as described in PHP Configuration.
The php.ini file tells PHP how to configure itself, and how to work with the environment that it runs in. Here are a number of settings for the php.ini file that help PHP work better with Windows. Some of these are optional. There are many other directives that may be relevant to your environment - refer to the list of php.ini directives for more information.
Required directives:
extension_dir = <path to extension directory> - The extension_dir needs to point to the directory where PHP extensions files are stored. The path can be absolute (i.e. "C:\PHP\ext") or relative (i.e. ".\ext"). Extensions that are listed lower in the php.ini file need to be located in the extension_dir.
extension = xxxxx.dll - For each extension you wish to enable, you need a corresponding "extension=" directive that tells PHP which extensions in the extension_dir to load at startup time.
log_errors = On - PHP has an error logging facility that can be used to send errors to a file, or to a service (i.e. syslog) and works in conjunction with the error_log directive below. When running under IIS, the log_errors should be enabled, with a valid error_log.
error_log = <path to the error log file> - The error_log needs to specify the absolute, or relative path to the file where PHP errors should be logged. This file needs to be writable for the web server. The most common places for this file are in various TEMP directories, for example "C:\inetpub\temp\php-errors.log".
cgi.force_redirect = 0 - This directive is required for running under IIS. It is a directory security facility required by many other web servers. However, enabling it under IIS will cause the PHP engine to fail on Windows.
cgi.fix_pathinfo = 1 - This lets PHP access real path info following the CGI Spec. The IIS FastCGI implementation needs this set.
fastcgi.impersonate = 1 - FastCGI under IIS supports the ability to impersonate security tokens of the calling client. This allows IIS to define the security context that the request runs under.
fastcgi.logging = 0 - FastCGI logging should be disabled on IIS. If it is left enabled, then any messages of any class are treated by FastCGI as error conditions which will cause IIS to generate an HTTP 500 exception.
Optional directives
max_execution_time = ## - This directive tells PHP the maximum amount of time that it can spend executing any given script. The default for this is 30 seconds. Increase the value of this directive if PHP application take long time to execute.
memory_limit = ###M - The amount of memory available for the PHP process, in Megabytes. The default is 128, which is fine for most PHP applications. Some of the more complex ones might need more.
display_errors = Off - This directive tells PHP whether to include any error messages in the stream that it returns to the Web server. If this is set to "On", then PHP will send whichever classes of errors that you define with the error_reporting directive back to web server as part of the error stream. For security reasons it is recommended to set it to "Off" on production servers in order not to reveal any security sensitive information that is often included in the error messages.
open_basedir = <paths to directories, separated by semicolon>, e.g. openbasedir="C:\inetpub\wwwroot;C:\inetpub\temp". This directive specified the directory paths where PHP is allowed to perform file system operations. Any file operation outside of the specified paths will result in an error. This directive is especially useful for locking down the PHP installation in shared hosting environments to prevent PHP scripts from accessing any files outside of the web site's root directory.
upload_max_filesize = ###M and post_max_size = ###M - The maximum allowed size of an uploaded file and post data respectively. The values of these directives should be increased if PHP applications need to perform large uploads, such as for example photos or video files.
PHP is now setup on your system. The next step is to choose a web server, and enable it to run PHP. Choose a web server from the table of contents.
In addition to running PHP via a web server, PHP can run from the command line just like a .BAT script. See Command Line PHP on Microsoft Windows for further details.
This section contains notes specific to the ActiveScript installation.
ActiveScript is a Windows only SAPI that enables you to use PHP script in any ActiveScript compliant host, like Windows Script Host, ASP/ASP.NET, Windows Script Components or Microsoft Scriptlet control.
As of PHP 5.0.1, ActiveScript has been moved to the » PECL repository. DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/
Informacja: You should read the manual installation steps first!
After installing PHP, you should download the ActiveScript DLL (php5activescript.dll) and place it in the main PHP folder (e.g. C:\php).
After having all the files needed, you must register the DLL on your system. To achieve this, open a Command Prompt window (located in the Start Menu). Then go to your PHP directory by typing something like cd C:\php. To register the DLL just type regsvr32 php5activescript.dll.
To test if ActiveScript is working, create a new file, named test.wsf (the extension is very important) and type:
<job id="test">
<script language="PHPScript">
$WScript->Echo("Hello World!");
</script>
</job>
Save and double-click on the file. If you receive a little window saying "Hello World!" you're done.
Informacja: In PHP 4, the engine was named 'ActivePHP', so if you are using PHP 4, you should replace 'PHPScript' with 'ActivePHP' in the above example.
Informacja: ActiveScript doesn't use the default php.ini file. Instead, it will look only in the same directory as the .exe that caused it to load. You should create php-activescript.ini and place it in that folder, if you wish to load extensions, etc.
This section contains PHP installation instructions specific to Microsoft Internet Information Services (IIS).
This section contains instructions for manually setting up Internet Information Services (IIS) 5.1 and IIS 6.0 to work with PHP on Microsoft Windows XP and Windows Server 2003. For instructions on setting up IIS 7.0 and later versions on Windows Vista, Windows Server 2008, Windows 7 and Windows Server 2008 R2 refer to Microsoft IIS 7.0 and later.
Download and install PHP in accordance to the instructions described in manual installation steps
Informacja: Non-thread-safe build of PHP is recommended when using IIS. The non-thread-safe builds are available at » PHP for Windows: Binaries and Sources Releases.
Configure the CGI- and FastCGI-specific settings in php.ini file as shown below:
Przykład #1 CGI and FastCGI settings in php.ini
fastcgi.impersonate = 1 fastcgi.logging = 0 cgi.fix_pathinfo=1 cgi.force_redirect = 0
Download and install the » Microsoft FastCGI Extension for IIS 5.1 and 6.0. The extension is available for 32-bit and 64-bit platforms - select the right download package for your platform.
Configure the FastCGI extension to handle PHP-specific requests by running the command shown below. Replace the value of the "-path" parameter with the absolute file path to the php-cgi.exe file.
Przykład #2 Configuring FastCGI extension to handle PHP requests
cscript %windir%\system32\inetsrv\fcgiconfig.js -add -section:"PHP" ^ -extension:php -path:"C:\PHP\php-cgi.exe"
This command will create an IIS script mapping for *.php file extension, which will result in all URLs that end with .php being handled by FastCGI extension. Also, it will configure FastCGI extension to use the executable php-cgi.exe to process the PHP requests.
Informacja: At this point the required installation and configuration steps are completed. The remaining instructions below are optional but highly recommended for achieving optimal functionality and performance of PHP on IIS.
It is recommended to enable FastCGI impersonation in PHP when using IIS. This is controlled by the fastcgi.impersonate directive in php.ini file. When impersonation is enabled, PHP will perform all the file system operations on behalf of the user account that has been determined by IIS authentication. This ensures that even if the same PHP process is shared across different IIS web sites, the PHP scripts in those web sites will not be able to access each others' files as long as different user accounts are used for IIS authentication on each web site.
For example IIS 5.1 and IIS 6.0, in its default configuration, has anonymous authentication enabled with built-in user account IUSR_<MACHINE_NAME> used as a default identity. This means that in order for IIS to execute PHP scripts, it is necessary to grant IUSR_<MACHINE_NAME> account read permission on those scripts. If PHP applications need to perform write operations on certain files or write files into some folders then IUSR_<MACHINE_NAME> account should have write permission to those.
To determine which user account is used by IIS anonymous authentication, follow these steps:
In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";
Expand the list of web sites under the "Web Sites" node in the tree view, right-click on a web site that is being used and select "Properties";
Click the "Directory Security" tab;
Take note of a "User name:" field in the "Authentication Methods" dialog
To modify the permissions settings on files and folders, use the Windows Explorer user interface or icacls command.
Przykład #3 Configuring file access permissions
icacls C:\inetpub\wwwroot\upload /grant IUSR:(OI)(CI)(M)
The IIS default documents are used for HTTP requests that do not specify a document name. With PHP applications, index.php usually acts as a default document. To add index.php to the list of IIS default documents, follow these steps:
In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";
Right-click on the "Web Sites" node in the tree view and select "Properties";
Click the "Documents" tab;
Click the "Add..." button and enter "index.php" for the "Default content page:".
Configure IIS FastCGI extension settings for recycling of PHP processes by using the commands shown below. The FastCGI setting instanceMaxRequests controls how many requests will be processed by a single php-cgi.exe process before FastCGI extension shuts it down. The PHP environment variable PHP_FCGI_MAX_REQUESTS controls how many requests a single php-cgi.exe process will handle before it recycles itself. Make sure that the value specified for FastCGI InstanceMaxRequests setting is less than or equal to the value specified for PHP_FCGI_MAX_REQUESTS.
Przykład #4 Configuring FastCGI and PHP recycling
cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^ -InstanceMaxRequests:10000 cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^ -EnvironmentVars:PHP_FCGI_MAX_REQUESTS:10000
Increase the timeout settings for FastCGI extension if there are applications that have long running PHP scripts. The two settings that control timeouts are ActivityTimeout and RequestTimeout. Refer to » Configuring FastCGI Extension for IIS 6.0 for more information about those settings.
Przykład #5 Configuring FastCGI timeout settings
cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^ -ActivityTimeout:90 cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^ -RequestTimeout:90
PHP searches for php.ini file in several locations and it is possible to change the default locations of php.ini file by using PHPRC environment variable. To instruct PHP to load the configuration file from a custom location run the command shown below. The absolute path to the directory with php.ini file should be specified as a value of PHPRC environment variable.
Przykład #6 Changing the location of php.ini file
cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^ -EnvironmentVars:PHPRC:"C:\Some\Directory\"
This section contains instructions for manually setting up Internet Information Services (IIS) 7.0 and later to work with PHP on Microsoft Windows Vista SP1, Windows 7, Windows Server 2008 and Windows Server 2008 R2. For instructions on setting up IIS 5.1 and IIS 6.0 on Windows XP and Windows Server 2003 refer to Microsoft IIS 5.1 and IIS 6.0.
FastCGI module is disabled in default installation of IIS. The steps to enable it differ based on the version of Windows being used.
To enable FastCGI support on Windows Vista SP1 and Windows 7:
In the Windows Start Menu choose "Run:", type "optionalfeatures.exe" and click "Ok";
In the "Windows Features" dialog expand "Internet Information Services", "World Wide Web Services", "Application Development Features" and then enable the "CGI" checkbox;
Click OK and wait until the installation is complete.
To enable FastCGI support on Windows Server 2008 and Windows Server 2008 R2:
In the Windows Start Menu choose "Run:", type "CompMgmtLauncher" and click "Ok";
If the "Web Server (IIS)" role is not present under the "Roles" node, then add it by clicking "Add Roles";
If the "Web Server (IIS)" role is present, then click "Add Role Services" and then enable the "CGI" checkbox under "Application Development" group;
Click "Next" and then "Install" and wait for the installation to complete.
Download and install PHP in accordance to the instructions described in manual installation steps
Informacja: Non-thread-safe build of PHP is recommended when using IIS. The non-thread-safe builds are available at » PHP for Windows: Binaries and Sources Releases.
Configure the CGI- and FastCGI-specific settings in php.ini file as shown below:
Przykład #1 CGI and FastCGI settings in php.ini
fastcgi.impersonate = 1 fastcgi.logging = 0 cgi.fix_pathinfo=1 cgi.force_redirect = 0
Configure IIS handler mapping for PHP by using either IIS Manager user interface or a command line tool.
Follow these steps to create an IIS handler mapping for PHP in IIS Manager user interface:
In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";
In the IIS Manager user interface select the server node in the "Connections" tree view;
In the "Features View" page open the "Handler Mappings" feature;
In the "Actions" pane click "Add Module Mapping...";
In the "Add Module Mapping" dialog enter the following:
Click "Request Restrictions" button and then configure the mapping to invoke handler only if request is mapped to a file or a folder;
Click OK on all the dialogs to save the configuration.
Use the command shown below to create an IIS FastCGI process pool which will use php-cgi.exe executable for processing PHP requests. Replace the value of the fullPath parameter with the absolute file path to the php-cgi.exe file.
Przykład #2 Creating IIS FastCGI process pool
%windir%\system32\inetsrv\appcmd set config /section:system.webServer/fastCGI ^ /+[fullPath='c:\PHP\php-cgi.exe']
Configure IIS to handle PHP specific requests by running the command shown below. Replace the value of the scriptProcessor parameter with the absolute file path to the php-cgi.exe file.
Przykład #3 Creating handler mapping for PHP requests
%windir%\system32\inetsrv\appcmd set config /section:system.webServer/handlers ^ /+[name='PHP_via_FastCGI', path='*.php',verb='*',modules='FastCgiModule',^ scriptProcessor='c:\PHP\php-cgi.exe',resourceType='Either']
This command creates an IIS handler mapping for *.php file extension, which will result in all URLs that end with .php being handled by FastCGI module.
Informacja: At this point the required installation and configuration steps are completed. The remaining instructions below are optional but highly recommended for achieving optimal functionality and performance of PHP on IIS.
It is recommended to enable FastCGI impersonation in PHP when using IIS. This is controlled by the fastcgi.impersonate directive in php.ini file. When impersonation is enabled, PHP will perform all the file system operations on behalf of the user account that has been determined by IIS authentication. This ensures that even if the same PHP process is shared across different IIS web sites, the PHP scripts in those web sites will not be able to access each other's files as long as different user accounts are used for IIS authentication on each web site.
For example IIS 7, in its default configuration, has anonymous authentication enabled with built-in user account IUSR used as a default identity. This means that in order for IIS to execute PHP scripts, it is necessary to grant IUSR account read permission on those scripts. If PHP applications need to perform write operations on certain files or write files into some folders then IUSR account should have write permission to those.
To determine what user account is used as an anonymous identity in IIS 7 use the following command. Replace the "Default Web Site" with the name of IIS web site that you use. In the output XML configuration element look for the userName attribute.
Przykład #4 Determining the account used as IIS anonymous identity
%windir%\system32\inetsrv\appcmd.exe list config "Default Web Site" ^
/section:anonymousAuthentication
<system.webServer>
<security>
<authentication>
<anonymousAuthentication enabled="true" userName="IUSR" />
</authentication>
</security>
</system.webServer>
Informacja: If userName attribute is not present in the anonymousAuthentication element, or is set to an empty string, then it means that the application pool identity is used as an anonymous identity for that web site.
To modify the permissions settings on files and folders, use the Windows Explorer user interface or icacls command.
Przykład #5 Configuring file access permissions
icacls C:\inetpub\wwwroot\upload /grant IUSR:(OI)(CI)(M)
The IIS default documents are used for HTTP requests that do not specify a document name. With PHP applications, index.php usually acts as a default document. To add index.php to the list of IIS default documents, use this command:
Przykład #6 Set index.php as a default document in IIS
%windir%\system32\inetsrv\appcmd.exe set config ^ -section:system.webServer/defaultDocument /+"files.[value='index.php']" ^ /commit:apphost
Configure IIS FastCGI settings for recycling of PHP processes by using the commands shown below. The FastCGI setting instanceMaxRequests controls how many requests will be processed by a single php-cgi.exe process before IIS shuts it down. The PHP environment variable PHP_FCGI_MAX_REQUESTS controls how many requests a single php-cgi.exe process will handle before it recycles itself. Make sure that the value specified for FastCGI InstanceMaxRequests setting is less than or equal to the value specified for PHP_FCGI_MAX_REQUESTS.
Przykład #7 Configuring FastCGI and PHP recycling
%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/[fullPath='c:\php\php-cgi.exe'].instanceMaxRequests:10000
%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/+"[fullPath='C:\{php_folder}\php-cgi.exe'].environmentVariables.^
[name='PHP_FCGI_MAX_REQUESTS',value='10000']"
Increase the timeout settings for FastCGI if it is expected to have long running PHP scripts. The two settings that control timeouts are activityTimeout and requestTimeout. Use the commands below to change the timeout settings. Make sure to replace the value in the fullPath parameter to contain the absolute path to the php-cgi.exe file.
Przykład #8 Configuring FastCGI and PHP recycling
%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^ /[fullPath='C:\php\php-cgi.exe',arguments=''].activityTimeout:"90" /commit:apphost %windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^ /[fullPath='C:\php\php-cgi.exe',arguments=''].requestTimeout:"90" /commit:apphost
PHP searches for php.ini file in several locations and it is possible to change the default locations of php.ini file by using PHPRC environment variable. To instruct PHP to load the configuration file from a custom location run the command shown below. The absolute path to the directory with php.ini file should be specified as a value of PHPRC environment variable.
Przykład #9 Changing the location of php.ini file
appcmd.exe set config -section:system.webServer/fastCgi ^ /+"[fullPath='C:\php\php.exe',arguments=''].environmentVariables.^ [name='PHPRC',value='C:\Some\Directory\']" /commit:apphost
This section contains notes and hints specific to Apache 1.3.x installs of PHP on Microsoft Windows systems. There are also instructions and notes for Apache 2 on a separate page.
Informacja: Please read the manual installation steps first!
There are two ways to set up PHP to work with Apache 1.3.x on Windows. One is to use the CGI binary (php.exe for PHP 4 and php-cgi.exe for PHP 5), the other is to use the Apache Module DLL. In either case you need to edit your httpd.conf to configure Apache to work with PHP, and then restart the server.
It is worth noting here that now the SAPI module has been made more stable under Windows, we recommend it's use above the CGI binary, since it is more transparent and secure.
Although there can be a few variations of configuring PHP under Apache, these are simple enough to be used by the newcomer. Please consult the Apache Documentation for further configuration directives.
After changing the configuration file, remember to restart the server, for example, NET STOP APACHE followed by NET START APACHE, if you run Apache as a Windows Service, or use your regular shortcuts.
Informacja: Nalezy pamiętać, że podając ścieżki w plikach konfiguracyjnych Apache w systemie Windows, wszystkie znaki backslash takie jak na przykład w ścieżce c:\directory\file.ext muszą być zamienione na znaki slash, na przykład c:/directory/file.ext. Zamykające znaki slash mogą być także niezbędne dla katalogów.
You should add the following lines to your Apache httpd.conf file:
Przykład #1 PHP as an Apache 1.3.x module
This assumes PHP is installed to c:\php. Adjust the path if this is not the case.
For PHP 4:
# Add to the end of the LoadModule section # Don't forget to copy this file from the sapi directory! LoadModule php4_module "C:/php/php4apache.dll" # Add to the end of the AddModule section AddModule mod_php4.c
For PHP 5:
# Add to the end of the LoadModule section LoadModule php5_module "C:/php/php5apache.dll" # Add to the end of the AddModule section AddModule mod_php5.c
For both:
# Add this line inside the <IfModule mod_mime.c> conditional brace AddType application/x-httpd-php .php # For syntax highlighted .phps files, also add AddType application/x-httpd-php-source .phps
If you unzipped the PHP package to C:\php\ as described in the Manual Installation Steps section, you need to insert these lines to your Apache configuration file to set up the CGI binary:
Przykład #2 PHP and Apache 1.3.x as CGI
ScriptAlias /php/ "c:/php/" AddType application/x-httpd-php .php # For PHP 4 Action application/x-httpd-php "/php/php.exe" # For PHP 5 Action application/x-httpd-php "/php/php-cgi.exe" # specify the directory where php.ini is SetEnv PHPRC C:/php
Note that the second line in the list above can be found in the actual versions of httpd.conf, but it is commented out. Remember also to substitute the c:/php/ for your actual path to PHP.
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.
If you would like to present PHP source files syntax highlighted, there is no such convenient option as with the module version of PHP. If you chose to configure Apache to use PHP as a CGI binary, you will need to use the highlight_file() function. To do this simply create a PHP script file and add this code: <?php highlight_file('some_php_script.php'); ?>.
This section contains notes and hints specific to Apache 2.0.x installs of PHP on Microsoft Windows systems. We also have instructions and notes for Apache 1.3.x users on a separate page.
Informacja: You should read the manual installation steps first!
Informacja: Apache 2.2.x Support
Users of Apache 2.2.x may use the documentation below except the appropriate DLL file is named php5apache2_2.dll and it only exists as of PHP 5.2.0. See also » http://snaps.php.net/
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.x Server. Also consider to read the » Windows specific notes for Apache 2.0.x before reading on here.
Informacja: 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:
- 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 SVN.
These versions of PHP are compatible to Apache 2.0.40 and later.
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.
Apache 2.0.x is designed to run on Windows NT 4.0, Windows 2000 or Windows XP. At this time, support for Windows 9x is incomplete. Apache 2.0.x is not expected to work on those platforms at this time.
Download the most recent version of » Apache 2.0.x and a fitting PHP version. Follow the Manual Installation Steps and come back to go on with the integration of PHP and Apache.
There are two ways to set up PHP to work with Apache 2.0.x on Windows. One is to use the CGI binary the other is to use the Apache module DLL. In either case you need to edit your httpd.conf to configure Apache to work with PHP and then restart the server.
Informacja: Nalezy pamiętać, że podając ścieżki w plikach konfiguracyjnych Apache w systemie Windows, wszystkie znaki backslash takie jak na przykład w ścieżce c:\directory\file.ext muszą być zamienione na znaki slash, na przykład c:/directory/file.ext. Zamykające znaki slash mogą być także niezbędne dla katalogów.
You need to insert these three lines to your Apache httpd.conf configuration file to set up the CGI binary:
Przykład #1 PHP and Apache 2.0 as CGI
ScriptAlias /php/ "c:/php/" AddType application/x-httpd-php .php # For PHP 4 Action application/x-httpd-php "/php/php.exe" # For PHP 5 Action application/x-httpd-php "/php/php-cgi.exe"
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.
You need to insert these two lines to your Apache httpd.conf configuration file to set up the PHP module for Apache 2.0:
Przykład #2 PHP and Apache 2.0 as Module
# For PHP 4 do something like this: LoadModule php4_module "c:/php/php4apache2.dll" # Don't forget to copy the php4apache2.dll file from the sapi directory! AddType application/x-httpd-php .php # For PHP 5 do something like this: LoadModule php5_module "c:/php/php5apache2.dll" AddType application/x-httpd-php .php # configure the path to php.ini PHPIniDir "C:/php"
Informacja: Remember to substitute your actual path to PHP for the c:/php/ in the above examples. Take care to use either php4apache2.dll or php5apache2.dll in your LoadModule directive and not php4apache.dll or php5apache.dll as the latter ones are designed to run with Apache 1.3.x.
Informacja: If you want to use content negotiation, read related FAQ.
Don't mix up your installation with DLL files from different PHP versions. You have the only choice to use the DLL's and extensions that ship with your downloaded PHP version.
This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Windows.
From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to generate custom directory listings and error pages. Additional functions for Apache compatibility are also available. For support in current web servers read the note about subrequests.
To install PHP as a CGI handler, do the following:
Make a file association from the command line. Type the following two lines:
assoc .php=PHPScript ftype PHPScript=c:\php\php.exe %1 %*
More details about setting up PHP as a CGI executable can be found here: » http://benoit.noss.free.fr/php/install-php.html
To install PHP with NSAPI, do the following:
Make a file association from the command line. Type the following two lines:
assoc .php=PHPScript ftype PHPScript=c:\php\php.exe %1 %*
Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following: You should place the lines after mime types init.
Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="c:/php/sapi/php4nsapi.dll" Init fn="php4_init" LateInit="yes" errorString="Failed to initialise PHP!" [php_ini="c:/path/to/php.ini"]
(PHP >= 4.3.3) The php_ini parameter is optional but with it you can place your php.ini in your web server configuration directory.
Configure the default object in obj.conf (for virtual server classes [Sun Web Server 6.0+] in their vserver.obj.conf): In the <Object name="default"> section, place this line necessarily after all 'ObjectType' and before all 'AddLog' lines:
Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...]
(PHP >= 4.3.3) As additional parameters you can add some special php.ini-values, for example you can set a docroot="/path/to/docroot" specific to the context php4_execute is called. For boolean ini-keys please use 0/1 as value, not "On","Off",... (this will not work correctly), e.g. zlib.output_compression=1 instead of zlib.output_compression="On"
This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):
<Object name="x-httpd-php"> ObjectType fn="force-type" type="magnus-internal/x-httpd-php" Service fn=php4_execute [inikey=value inikey=value ...] </Object>
After that you can configure a directory in the Administration server and assign it the style x-httpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming files to .html.
Informacja: More details about setting up PHP as an NSAPI filter can be found here: » http://benoit.noss.free.fr/php/install-php4.html
Informacja: The stacksize that PHP uses depends on the configuration of the web server. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").
Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the web server itself) and this space has only one environment. If you want to get CGI variables like PATH_INFO, HTTP_HOST etc. it is not the correct way to try this in the old PHP way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running web server without any valid CGI variables!
Informacja: Why are there (invalid) CGI variables in the environment?
Answer: This is because you started the web server process from the admin server which runs the startup script of the web server, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started web server has some CGI environment variables in it. You can test this by starting the web server not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.
Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):
variables_order = "GPCS" register_globals = On
You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:
Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...]
where XXX is the HTTP error code. Please delete any other Error directives which could interfere with yours. If you want to place a page for all errors that could exist, leave the code parameter out. Your script can get the HTTP status code with $_SERVER['ERROR_TYPE'].
Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:
Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...]
For both error and directory listing pages the original URI and translated URI are in the variables $_SERVER['PATH_INFO'] and $_SERVER['PATH_TRANSLATED'].
The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the web server and insert the result in the web page. The problem is, that this function uses some undocumented features from the NSAPI library.
Under Unix this is not a problem, because the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.
Under Windows limitations in the DLL handling need the use of a automatic detection of the most recent ns-httpdXX.dll file. This is tested for servers till version 6.1. If a newer version of the Sun server is used, the detection fails and nsapi_virtual() is disabled.
If this is the case, try the following: Add the following parameter to php4_init in magnus.conf/obj.conf:
Init fn=php4_init ... server_lib="ns-httpdXX.dll"
where XX is the correct DLL version number. To get it, look in the server-root for the correct DLL name. The DLL with the biggest filesize is the right one.
You can check the status by using the phpinfo() function.
Informacja: But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!
This section contains notes and hints specific to » OmniHTTPd on Windows.
Informacja: You should read the manual installation steps first!
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.
You need to complete the following steps to make PHP work with OmniHTTPd. This is a CGI executable setup. SAPI is supported by OmniHTTPd, but some tests have shown that it is not so stable to use PHP as an ISAPI module.
Informacja: Important for CGI users
Read the faq on cgi.force_redirect for important details. This directive needs to be set to 0.
Install OmniHTTPd server.
Right click on the blue OmniHTTPd icon in the system tray and select Properties
Click on Web Server Global Settings
On the 'External' tab, enter: virtual = .php | actual = c:\php\php.exe (use php-cgi.exe if installing PHP 5), and use the Add button.
On the Mime tab, enter: virtual = wwwserver/stdcgi | actual = .php, and use the Add button.
Click OK
Repeat steps 2 - 6 for each extension you want to associate with PHP.
Informacja: Some OmniHTTPd packages come with built in PHP support. You can choose at setup time to do a custom setup, and uncheck the PHP component. We recommend you to use the latest PHP binaries. Some OmniHTTPd servers come with PHP 4 beta distributions, so you should choose not to set up the built in support, but install your own. If the server is already on your machine, use the Replace button in Step 4 and 5 to set the new, correct information.
This section contains notes and hints specific to the » Sambar Server for Windows.
Informacja: You should read the manual installation steps first!
This list describes how to set up the ISAPI module to work with the Sambar server on Windows.
Find the file called mappings.ini (in the config directory) in the Sambar install directory.
Open mappings.ini and add the following line under [ISAPI]:
Przykład #1 ISAPI configuration of Sambar
#for PHP 4 *.php = c:\php\php4isapi.dll #for PHP 5 *.php = c:\php\php5isapi.dll
(This line assumes that PHP was installed in c:\php.)
Now restart the Sambar server for the changes to take effect.
Informacja: If you intend to use PHP to communicate with resources which are held on a different computer on your network, then you will need to alter the account used by the Sambar Server Service. The default account used for the Sambar Server Service is LocalSystem which will not have access to remote resources. The account can be amended by using the Services option from within the Windows Control Panel Administation Tools.
This section contains notes and hints specific to » Xitami on Windows.
Informacja: You should read the manual installation steps first!
This list describes how to set up the PHP CGI binary to work with Xitami on Windows.
Informacja: Important for CGI users
Read the faq on cgi.force_redirect for important details. This directive needs to be set to 0. If you want to use $_SERVER['PHP_SELF'] you have to enable the cgi.fix_pathinfo directive.
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.
Make sure the web server is running, and point your browser to xitamis admin console (usually http://127.0.0.1/admin), and click on Configuration.
Navigate to the Filters, and put the extension which PHP should parse (i.e. .php) into the field File extensions (.xxx).
In Filter command or script put the path and name of your PHP CGI executable i.e. C:\php\php.exe for PHP 4, or C:\php\php-cgi.exe for PHP 5.
Press the 'Save' icon.
Restart the server to reflect changes.
This chapter teaches how to compile PHP from sources on windows, using Microsoft's tools. To compile PHP with cygwin, please refer to Installation on Unix systems.
This chapter is outdated therefore it's temporarily been removed from the manual. For now, consider the following:
After installing PHP and a web server on Windows, you will probably want to install some extensions for added functionality. You can choose which extensions you would like to load when PHP starts by modifying your php.ini. You can also load a module dynamically in your script using dl().
The DLLs for PHP extensions are prefixed with php_.
Many extensions are built into the Windows version of PHP. This means additional DLL files, and the extension directive, are not used to load these extensions. The Windows PHP Extensions table lists extensions that require, or used to require, additional PHP DLL files. Here's a list of built in extensions:
In PHP 4 (updated PHP 4.3.11): BCMath, Caledar, COM, Ctype, FTP, MySQL, ODBC, Overload, PCRE, Session, Tokenizer, WDDX, XML i Zlib
In PHP 5 (updated PHP 5.0.4), the following changes exist. Built in: DOM, LibXML, Iconv, SimpleXML, SPL i SQLite. And the following are no longer built in: MySQL and Overload.
The default location PHP searches for extensions is C:\php4\extensions in PHP 4 and C:\php5 in PHP 5. To change this setting to reflect your setup of PHP edit your php.ini file:
You will need to change the extension_dir setting to point to the directory where your extensions lives, or where you have placed your php_*.dll files. For example:
extension_dir = C:\php\extensions
Enable the extension(s) in php.ini you want to use by uncommenting the extension=php_*.dll lines in php.ini. This is done by deleting the leading ; from the extension you want to load.
Przykład #1 Enable Bzip2 extension for PHP-Windows
// change the following line from ... ;extension=php_bz2.dll // ... to extension=php_bz2.dll
Some of the extensions need extra DLLs to work. Couple of them can be found in the distribution package, in the C:\php\dlls\ folder in PHP 4 or in the main folder in PHP 5, but some, for example Oracle (php_oci8.dll) require DLLs which are not bundled with the distribution package. If you are installing PHP 4, copy the bundled DLLs from C:\php\dlls folder to the main C:\php folder. Don't forget to include C:\php in the system PATH (this process is explained in a separate FAQ entry).
Some of these DLLs are not bundled with the PHP distribution. See each extensions documentation page for details. Also, read the manual section titled Installation of PECL extensions for details on PECL. An increasingly large number of PHP extensions are found in PECL, and these extensions require a separate download.
Informacja: If you are running a server module version of PHP remember to restart your web server to reflect your changes to php.ini.
The following table describes some of the extensions available and required additional dlls.
| Extension | Description | Notes |
|---|---|---|
| php_bz2.dll | bzip2 compression functions | None |
| php_calendar.dll | Calendar conversion functions | Built in since PHP 4.0.3 |
| php_crack.dll | Crack functions | None |
| php_ctype.dll | ctype family functions | Built in since PHP 4.3.0 |
| php_curl.dll | CURL, Client URL library functions | Requires: libeay32.dll, ssleay32.dll (bundled) |
| php_dba.dll | DBA: DataBase (dbm-style) Abstraction layer functions | None |
| php_dbase.dll | dBase functions | None |
| php_dbx.dll | dbx functions | |
| php_domxml.dll | DOM XML functions | PHP <= 4.2.0 requires: libxml2.dll (bundled) PHP >= 4.3.0 requires: iconv.dll (bundled) |
| php_dotnet.dll | .NET functions | PHP <= 4.1.1 |
| php_exif.dll | EXIF functions | php_mbstring.dll. And, php_exif.dll must be loaded after php_mbstring.dll in php.ini. |
| php_fbsql.dll | FrontBase functions | PHP <= 4.2.0 |
| php_fdf.dll | FDF: Forms Data Format functions. | Requires: fdftk.dll (bundled) |
| php_filepro.dll | filePro functions | Read-only access |
| php_ftp.dll | FTP functions | Built-in since PHP 4.0.3 |
| php_gd.dll | GD library image functions | Removed in PHP 4.3.2. Also note that truecolor functions are not available in GD1, instead, use php_gd2.dll. |
| php_gd2.dll | GD library image functions | GD2 |
| php_gettext.dll | Gettext functions | PHP <= 4.2.0 requires gnu_gettext.dll (bundled), PHP >= 4.2.3 requires libintl-1.dll, iconv.dll (bundled). |
| php_hyperwave.dll | HyperWave functions | None |
| php_iconv.dll | ICONV characterset conversion | Requires: iconv-1.3.dll (bundled), PHP >=4.2.1 iconv.dll |
| php_ifx.dll | Informix functions | Requires: Informix libraries |
| php_iisfunc.dll | IIS management functions | None |
| php_imap.dll | IMAP POP3 and NNTP functions | None |
| php_ingres.dll | Ingres functions | Requires: Ingres libraries |
| php_interbase.dll | InterBase functions | Requires: gds32.dll (bundled) |
| php_java.dll | Java functions | PHP <= 4.0.6 requires: jvm.dll (bundled) |
| php_ldap.dll | LDAP functions | PHP <= 4.2.0 requires libsasl.dll (bundled), PHP >= 4.3.0 requires libeay32.dll, ssleay32.dll (bundled) |
| php_mbstring.dll | Multi-Byte String functions | None |
| php_mcrypt.dll | Mcrypt Encryption functions | Requires: libmcrypt.dll |
| php_mhash.dll | Mhash functions | PHP >= 4.3.0 requires: libmhash.dll (bundled) |
| php_mime_magic.dll | Mimetype functions | Requires: magic.mime (bundled) |
| php_ming.dll | Ming functions for Flash | None |
| php_msql.dll | mSQL functions | Requires: msql.dll (bundled) |
| php_mssql.dll | MSSQL functions | Requires: ntwdblib.dll (bundled) |
| php_mysql.dll | MySQL functions | PHP >= 5.0.0, requires libmysql.dll (bundled) |
| php_mysqli.dll | MySQLi functions | PHP >= 5.0.0, requires libmysql.dll (libmysqli.dll in PHP <= 5.0.2) (bundled) |
| php_oci8.dll | Oracle 8 functions | Requires: Oracle 8.1+ client libraries |
| php_openssl.dll | OpenSSL functions | Requires: libeay32.dll (bundled) |
| php_overload.dll | Object overloading functions | Built in since PHP 4.3.0 |
| php_pdf.dll | PDF functions | None |
| php_pgsql.dll | PostgreSQL functions | None |
| php_printer.dll | Printer functions | None |
| php_shmop.dll | Shared Memory functions | None |
| php_snmp.dll | SNMP get and walk functions | NT only! |
| php_soap.dll | SOAP functions | PHP >= 5.0.0 |
| php_sockets.dll | Socket functions | None |
| php_sybase_ct.dll | Sybase functions | Requires: Sybase client libraries |
| php_tidy.dll | Tidy functions | PHP >= 5.0.0 |
| php_tokenizer.dll | Tokenizer functions | Built in since PHP 4.3.0 |
| php_w32api.dll | W32api functions | None |
| php_xmlrpc.dll | XML-RPC functions | PHP >= 4.2.1 requires: iconv.dll (bundled) |
| php_xslt.dll | XSLT functions | PHP <= 4.2.0 requires sablot.dll, expat.dll (bundled). PHP >= 4.2.1 requires sablot.dll, expat.dll, iconv.dll (bundled). |
| php_yaz.dll | YAZ functions | Requires: yaz.dll (bundled) |
| php_zip.dll | Zip File functions | Read only access |
| php_zlib.dll | ZLib compression functions | Built in since PHP 4.3.0 |
This section contains notes and hints specific to getting PHP running from the command line for Windows.
Informacja: You should read the manual installation steps first!
Getting PHP to run from the command line can be performed without making any changes to Windows.
C:\PHP5\php.exe -f "C:\PHP Scripts\script.php" -- -arg1 -arg2 -arg3
But there are some easy steps that can be followed to make this simpler. Some of these steps should already have been taken, but are repeated here to be able to provide a complete step-by-step sequence.
Add the location of the PHP executable (php.exe, php-win.exe or php-cli.exe depending upon your PHP version and display preferences) to the PATH environment variable. Read more about how to add your PHP directory to PATH in the corresponding FAQ entry.
Add the .PHP extension to the PATHEXT environment variable. This can be done at the same time as amending the PATH environment variable. Follow the same steps as described in the FAQ but amend the PATHEXT environment variable rather than the PATH environment variable.
Informacja: The position in which you place the .PHP will determine which script or program is executed when there are matching filenames. For example, placing .PHP before .BAT will cause your script to run, rather than the batch file, if there is a batch file with the same name.
Associate the .PHP extension with a file type. This is done by running the following command:
assoc .php=phpfile
Associate the phpfile file type with the appropriate PHP executable. This is done by running the following command:
ftype phpfile="C:\PHP5\php.exe" -f "%1" -- %~2
Following these steps will allow PHP scripts to be run from any directory without the need to type the PHP executable or the .PHP extension and all parameters will be supplied to the script for processing.
The example below details some of the registry changes that can be made manually.
Przykład #1 Registry changes
Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.php] @="phpfile" "Content Type"="application/php" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile] @="PHP Script" "EditFlags"=dword:00000000 "BrowserFlags"=dword:00000008 "AlwaysShowExt"="" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\DefaultIcon] @="C:\\PHP5\\php-win.exe0" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell] @="Open" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open] @="&Open" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open\command] @="\"C:\\PHP5\\php.exe\" -f \"%1\" -- %~2"
With these changes the same command can be written as:
"C:\PHP Scripts\script" -arg1 -arg2 -arg3
script -arg1 -arg2 -arg3
Informacja: There is a small problem if you intend to use this technique and use your PHP scripts as commandline filter, like the example below:
ordir | "C:\PHP Scripts\script" -arg1 -arg2 -arg3You may find that the script simply hangs and nothing is output. To get this operational, you need to make another registry change.dir | script -arg1 -arg2 -arg3Further information regarding this issue can be found in this » Microsoft Knowledgebase Article : 321788.Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer] "InheritConsoleHandles"=dword:00000001
» PECL is a repository of PHP extensions that are made available to you via the » PEAR packaging system. This section of the manual is intended to demonstrate how to obtain and install PECL extensions.
These instructions assume /your/phpsrcdir/ is the path to the PHP source distribution, and that extname is the name of the PECL extension. Adjust accordingly. These instructions also assume a familiarity with the » pear command. The information in the PEAR manual for the pear command also applies to the pecl command.
To be useful, a shared extension must be built, installed, and loaded. The methods described below provide you with various instructions on how to build and install the extensions, but they do not automatically load them. Extensions can be loaded by adding an extension directive. To this php.ini file, or through the use of the dl() function.
When building PHP modules, it's important to have known-good versions of the required tools (autoconf, automake, libtool, etc.) See the » Anonymous SVN Instructions for details on the required tools, and required versions.
There are several options for downloading PECL extensions, such as:
On Windows, you have two ways to load a PHP extension: either compile it into PHP, or load the DLL. Loading a pre-compiled extension is the easiest and preferred way.
To load an extension, you need to have it available as a ".dll" file on your system. All the extensions are automatically and periodically compiled by the PHP Group (see next section for the download).
To compile an extension into PHP, please refer to building from source documentation.
To compile a standalone extension (aka a DLL file), please refer to building from source documentation. If the DLL file is available neither with your PHP distribution nor in PECL, you may have to compile it before you can start using the extension.
PHP extensions are usually called "php_*.dll" (where the star represents the name of the extension) and they are located under the "PHP\ext" ("PHP\extensions" in PHP4) folder.
PHP ships with the extensions most useful to the majority of developers. They are called "core" extensions.
However, if you need functionality not provided by any core extension, you may still be able to find one in PECL. The PHP Extension Community Library (PECL) is a repository for PHP Extensions, providing a directory of all known extensions and hosting facilities for downloading and development of PHP extensions.
If you have developed an extension for your own uses, you might want to think about hosting it on PECL so that others with the same needs can benefit from your time. A nice side effect is that you give them a good chance to give you feedback, (hopefully) thanks, bug reports and even fixes/patches. Before you submit your extension for hosting on PECL, please read http://pecl.php.net/package-new.php.
Many times, you will find several versions of each DLL:
You should keep in mind that your extension settings should match all the settings of the PHP executable you are using. The following PHP script will tell you all about your PHP settings:
Przykład #1 phpinfo() call
<?php
phpinfo();
?>
Or from the command line, run:
drive:\\path\to\php\executable\php.exe -i
The most common way to load a PHP extension is to include it in your php.ini configuration file. Please note that many extensions are already present in your php.ini and that you only need to remove the semicolon to activate them.
;extension=php_extname.dll
extension=php_extname.dll
However, some web servers are confusing because they do not use the php.ini located alongside your PHP executable. To find out where your actual php.ini resides, look for its path in phpinfo():
Configuration File (php.ini) Path C:\WINDOWS
Loaded Configuration File C:\Program Files\PHP\5.2\php.ini
After activating an extension, save php.ini, restart the web server and check phpinfo() again. The new extension should now have its own section.
If the extension does not appear in phpinfo(), you should check your logs to learn where the problem comes from.
If you are using PHP from the command line (CLI), the extension loading error can be read directly on screen.
If you are using PHP with a web server, the location and format of the logs vary depending on your software. Please read your web server documentation to locate the logs, as it does not have anything to do with PHP itself.
Common problems are the location of the DLL, the value of the " extension_dir" setting inside php.ini and compile-time setting mismatches.
If the problem lies in a compile-time setting mismatch, you probably didn't download the right DLL. Try downloading again the extension with the right settings. Again, phpinfo() can be of great help.
PECL makes it easy to create shared PHP extensions. Using the » pecl command, do the following:
This will download the source for extname, compile, and install extname.so into your extension_dir. extname.so may then be loaded via php.ini
By default, the pecl command will not install packages that are marked with the alpha or beta state. If no stable packages are available, you may install a beta package using the following command:
You may also install a specific version using this variant:
Informacja: After enabling the extension in php.ini, restarting the web service is required for the changes to be picked up.
Sometimes, using the pecl installer is not an option. This could be because you're behind a firewall, or it could be because the extension you want to install is not available as a PECL compatible package, such as unreleased extensions from SVN. If you need to build such an extension, you can use the lower-level build tools to perform the build manually.
The phpize command is used to prepare the build environment for a PHP extension. In the following sample, the sources for an extension are in a directory named extname:
$ cd extname $ phpize $ ./configure $ make # make install
A successful install will have created extname.so and put it into the PHP extensions directory. You'll need to and adjust php.ini and add an extension=extname.so line before you can use the extension.
If the system is missing the phpize command, and precompiled packages (like RPM's) are used, be sure to also install the appropriate devel version of the PHP package as they often include the phpize command along with the appropriate header files to build PHP and its extensions.
Execute phpize --helpto display additional usage information.
You might find that you need to build a PECL extension statically into your PHP binary. To do this, you'll need to place the extension source under the php-src/ext/ directory and tell the PHP build system to regenerate its configure script.
$ cd /your/phpsrcdir/ext $ pecl download extname $ gzip -d < extname.tgz | tar -xvf - $ mv extname-x.x.x extname
This will result in the following directory:
From here, force PHP to rebuild the configure script, and then build PHP as normal:
Informacja: To run the 'buildconf' script you need autoconf 2.13 and automake 1.4+ (newer versions of autoconf may work, but are not supported).
Whether --enable-extname or --with-extname is used depends on the extension. Typically an extension that does not require external libraries uses --enable. To be sure, run the following after buildconf:
Niektóre problemy występują częściej 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 'Wspracie' na stronie » http://www.php.net/support.php. Aby zapisać się na listę dyskusyjną dotyczącą instalacji PHP, wyślij pusty list na adres » php-install-subscribe@lists.php.net. Adresem listy 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ł, tryb bezpieczny, 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!
The configuration file (php.ini) is read when PHP starts up. For the server module versions of PHP, this happens only once when the web server is started. For the CGI and CLI version, it happens on every invocation.
php.ini is searched in these locations (in order):
SAPI module specific location (PHPIniDir directive in Apache 2, -c command line option in CGI and CLI, php_ini parameter in NSAPI, PHP_INI_PATH environment variable in THTTPD)
The PHPRC environment variable. Before PHP 5.2.0 this was checked after the registry key mentioned below.
As of PHP 5.2.0, the location of the php.ini file can be set for different versions of PHP. The following registry keys are examined in order: [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y.z], [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y] and [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x], where x, y and z mean the PHP major, minor and release versions. If there is a value for IniFilePath in these keys, then the first one found will be used as the location of the php.ini (Windows only).
[HKEY_LOCAL_MACHINE\SOFTWARE\PHP], value of IniFilePath (Windows only).
Current working directory (except CLI)
The web server's directory (for SAPI modules), or directory of PHP (otherwise in Windows)
Windows directory (C:\windows or C:\winnt) (for Windows), or --with-config-file-path compile time option
If php-SAPI.ini exists (where SAPI is used SAPI, so the filename is e.g. php-cli.ini or php-apache.ini), it's used instead of php.ini. SAPI name can be determined by php_sapi_name().
Informacja: The Apache web server changes the directory to root at startup causing PHP to attempt to read php.ini from the root filesystem if it exists.
The php.ini directives handled by extensions are documented respectively on the pages of the extensions themselves. The list of the core directives is available in the appendix. Probably not all PHP directives are documented in the manual though. For a complete list of directives available in your PHP version, please read your well commented php.ini file. Alternatively, you may find the » the latest php.ini from SVN helpful too.
Przykład #1 php.ini example
; any text on a line after an unquoted semicolon (;) is ignored [php] ; section markers (text within square brackets) are also ignored ; Boolean values can be set to either: ; true, on, yes ; or false, off, no, none register_globals = off track_errors = yes ; you can enclose strings in double-quotes include_path = ".:/usr/local/lib/php" ; backslashes are treated the same as any other character include_path = ".;c:\php\lib"
Since PHP 5.1.0, it is possible to refer to existing .ini variables from within .ini files. Example: open_basedir = ${open_basedir} ":/new/dir".
Since PHP 5.3.0, PHP includes support for .htaccess-style INI files on a per-directory basis. These files are processed only by the CGI/FastCGI SAPI. This functionality obsoletes the PECL htscanner extension. If you are using Apache, use .htaccess files for the same effect.
In addition to the main php.ini file, PHP scans for INI files in each directory, starting with the directory of the requested PHP file, and working its way up to the current document root (as set in $_SERVER['DOCUMENT_ROOT']). Only INI settings with the modes PHP_INI_PERDIR and PHP_INI_USER will be recognized in .user.ini-style INI files.
Two new INI directives, user_ini.filename and user_ini.cache_ttl control the use of user INI files.
user_ini.filename sets the name of the file PHP looks for in each directory; if set to an empty string, PHP doesn't scan at all. The default is .user.ini.
user_ini.cache_ttl controls how often user INI files are re-read. The default is 300 seconds (5 minutes).
These modes determine when and where a PHP directive may or may not be set, and each directive within the manual refers to one of these modes. For example, some settings may be set within a PHP script using ini_set(), whereas others may require php.ini or httpd.conf.
For example, the output_buffering setting is PHP_INI_PERDIR therefore it may not be set using ini_set(). However, the display_errors directive is PHP_INI_ALL therefore it may be set anywhere, including with ini_set().
| Mode | Value | Meaning |
|---|---|---|
| PHP_INI_USER | 1 | Entry can be set in user scripts (like with ini_set()) or in the Windows registry |
| PHP_INI_PERDIR | 6 | Entry can be set in php.ini, .htaccess or httpd.conf |
| PHP_INI_SYSTEM | 4 | Entry can be set in php.ini or httpd.conf |
| PHP_INI_ALL | 7 | Entry can be set anywhere |
When using PHP as an Apache module, you can also change the configuration settings using directives in Apache configuration files (e.g. httpd.conf) and .htaccess files. You will need "AllowOverride Options" or "AllowOverride All" privileges to do so.
There are several Apache directives that allow you to change the PHP configuration from within the Apache configuration files. For a listing of which directives are PHP_INI_ALL, PHP_INI_PERDIR, or PHP_INI_SYSTEM, have a look at the List of php.ini directives appendix.
php_value
name
value
Sets the value of the specified directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives. To clear a previously set value use none as the value.
Informacja: Don't use
php_valueto set boolean values.php_flag(see below) should be used instead.
php_flag
name
on|off
Used to set a boolean configuration directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives.
php_admin_value
name
value
Sets the value of the specified directive.
This can not be used in .htaccess files.
Any directive type set with php_admin_value
can not be overridden by .htaccess or ini_set().
To clear a previously set value use none as the value.
php_admin_flag
name
on|off
Used to set a boolean configuration directive.
This can not be used in .htaccess files.
Any directive type set with php_admin_flag
can not be overridden by .htaccess.
Przykład #1 Apache configuration example
<IfModule mod_php5.c> php_value include_path ".:/usr/local/lib/php" php_admin_flag safe_mode on </IfModule> <IfModule mod_php4.c> php_value include_path ".:/usr/local/lib/php" php_admin_flag safe_mode on </IfModule>
PHP constants do not exist outside of PHP. For example, in httpd.conf you can not use PHP constants such as E_ALL or E_NOTICE to set the error_reporting directive as they will have no meaning and will evaluate to 0. Use the associated bitmask values instead. These constants can be used in php.ini
When running PHP on Windows, the configuration values can be modified on a per-directory basis using the Windows registry. The configuration values are stored in the registry key HKLM\SOFTWARE\PHP\Per Directory Values, in the sub-keys corresponding to the path names. For example, configuration values for the directory c:\inetpub\wwwroot would be stored in the key HKLM\SOFTWARE\PHP\Per Directory Values\c\inetpub\wwwroot. The settings for the directory would be active for any script running from this directory or any subdirectory of it. The values under the key should have the name of the PHP configuration directive and the string value. PHP constants in the values are not parsed. However, only configuration values changeable in PHP_INI_USER can be set this way, PHP_INI_PERDIR values can not.
Regardless of how you run PHP, you can change certain values at runtime of your scripts through ini_set(). See the documentation on the ini_set() page for more information.
If you are interested in a complete list of configuration settings on your system with their current values, you can execute the phpinfo() function, and review the resulting page. You can also access the values of individual configuration directives at runtime using ini_get() or get_cfg_var().
Kiedy PHP przetwarza plik, szuka otwierających i zamykających znaczników (tagów), które mówią PHP o rozpoczęciu i zakończeniu interpretowania kodu pomiędzy nimi. Przetwarzanie w taki sposób pozwala zagnieżdzać php w dowolnym rodzaju dokumentów, ponieważ wszystko poza parą znaczników, otwierającym i zamykającym jest ignorowane przez parser PHP. Najczęściej zobaczysz php zagnieżdzone w dokumentach HTML, tak jak w tym przykładzie.
<p>To zostanie zignorowane.</p>
<?php echo 'Kiedy to zostanie przetworzone.'; ?>
<p>To również zostanie zignorowane.</p>
Możesz także użyć bardziej zaawansowanej struktury:
Przykład #1 Zaawansowane wyskakiwanie
<?php
if ($wyrazenie) {
?>
<strong>To jest prawda.</strong>
<?php
} else {
?>
<strong>To jest fałsz.</strong>
<?php
}
?>
To działa jak się spodziewano, ponieważ kiedy PHP natrafi na zamykający znacznik ?>, poprostu zaczyna wyświetlać cokolwiek znajdzie (z wyjątkiem bezpośrednio następującej nowej linii - zobacz oddzielanie instrukcji ) dopóki nie natrafi na kolejny otwierający znacznik. Podany przykład jest oczywiście przekombinowany, ale do wyświetlania dużych bloków tekstu, wychodzenie z trybu przetwarzania PHP jest zasadniczo bardziej efektywne niż wysyłanie całego tekstu przez funkcje echo() lub print().
Mamy cztery różne pary otwierających i zamykających znaczników, które mogą być użyte w php. Dwie z nich, <?php ?> i <script language="php"> </script> są zawsze dostępne. Dwie następne to krótkie znaczniki i znaczniki w stylu ASP, mogą być włączane i wyłączane w pliku konfiguracyjnym php.ini. Część osób postrzega krótkie znaczniki i znaczniki w stylu ASP jako wygodne, jednakże są one mniej przenośne, i zasadniczo nie polecane.
Informacja: Zauważ również, że jeśli zagnieżdzasz PHP w XML lub XHTML musisz stosować znaczniki <?php ?> aby pozostać w zgodzie ze standardami.
Przykład #2 Znaczniki otwierające i zamykające PHP
1. <?php echo 'jeśli chcesz obsługiwać dokumenty XHTML lub XML, zrób to tak'; ?>
2. <script language="php">
echo 'niektóre edytory (jak FrontPage) nie lubią
instrukcji przetwarzania';
</script>
3. <? echo 'to jest najprostsza instrukcja przetwarzania SGML'; ?>
<?= wyrazenie ?> To jest skrót dla "<? echo wyrazenie ?>"
4. <% echo 'Możesz opcjonalnie użyć znaczników w stylu ASP'; %>
<%= $zmienna; # To jest skrót dla "<% echo . . ." %>
Z pokazanych znaczników, pierwszy i drugi przykład są zawsze dostępne, pierwszy przykład jest najbardziej powszechny i rekomendowany.
Krótkie znaczniki (trzeci przykład) są dostepne jedynie, kiedy są włączone za pomocą dyrektywy konfiguracyjnej short_open_tag w php.ini lub jeśli php zostało skonfigurowane z opcją --enable-short-tags.
Znaczniki w stylu ASP (czwarty przykład) są dostępne jedynie gdy zostaną włączone poprzez dyrektywę konfiguracyjną asp_tags w php.ini
Informacja: Powinieneś unikać używania krótkich znaczników, kiedy rozwijasz aplikacje lub biblioteki, które są nastawione na rozpowszechnianie lub pracujesz na serwerach PHP, nad którymi nie masz kontroli, ponieważ krótkie znaczniki mogą nie być obsługiwane na docelowym serwerze. Dla przenośnego, rozpowszechnialnego kodu, miej pewność, aby nie użyć krotkich znaczników.
Podobnie jak C i Perl, PHP wymaga aby instrukcje były zakończone średnikiem, na końcu każdego wyrażenia. Zamykający znacznik bloku kodu PHP automatycznie implikuje średnik; nie musisz mieć średnika zamykającego ostatnią linię z bloku PHP. Zamykający znacznik dla bloku będzie zawierać bezpośrednio następującą nową linie jeśli taka istnieje.
<?php
echo 'To jest test';
?>
<?php echo 'To jest test' ?>
<?php echo 'Pomineliśmy ostatni zamykający znacznik';
Informacja: Zamykający znacznik bloku PHP na końcu pliku jest opcjonalny, i w niektórych przypadkach pominięcie jego jest pomocne kiedy używamy include() lub require(), tak więc niechciane białe znaki nie będą znajdować się na końcu pliku, i ciągle będzie możliwe dodanie nagłówków do odpowiedzi. To jest także poręczne jeśli używasz buferowania wyjścia, i nie chciałbyś zobaczyć dodanych niechcianych białych znaków na końcu cześci generowanej przez includowany plik.
PHP obsługuje komentarze w stylu 'C', 'C++' i powłoki Unix (styl Perl\'a). Na przykład:
<?php
echo 'To jest test'; // To jest jednoliniowy komentarz w stylu c++
/* To jest wieloliniowy komentarz
jeszcze inna linia komentarza */
echo 'To jest jeszcze jeden test';
echo 'Ostatni test'; # To jest jednoliniowy komentarz w stylu powłoki
?>
"Jednolinijkowy" styl komentarzy obowiązuje jedynie do konca linii lub bieżącego bloku kodu PHP, cokolwiek wystąpi pierwsze. Co oznacza, że kod HTML za // ... ?> lub # ... ?> ZOSTANIE wyświetlony: ?> przerywa tryb PHP i wraca do trybu HTML, i // lub # nie może wpłynąć na to. Jeśli, dyrektywa konfiguracyjna asp_tags jest włączona, to działa tak samo z // %> i # %>. Jednakże, znacznik </script> nie przerywa trybu PHP w jednolinijkowym komentarzu.
<h1>To jest <?php # echo 'prosty';?> przykład.</h1>
<p>Nagłowek powyżej będzie mówił 'To jest przykład'.</p>
Komentarze w stylu 'C' kończą się na pierwszym napotkanym */. Upewnij się, że nie zagnieżdzasz komentarzy w stylu 'C'. Łatwo jest popełnić pomyłkę jeśli próbujesz odkomentować duży blok kodu.
<?php
/*
echo 'To jest test'; /* Ten komentarz będzie przyczyną problemów */
*/
?>
PHP supports eight primitive types.
Four scalar types:
Two compound types:
And finally two special types:
This manual also introduces some pseudo-types for readability reasons:
And the pseudo-variable $... .
Some references to the type "double" may remain in the manual. Consider double the same as float; the two names exist only for historic reasons.
The type of a variable is not usually set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used.
Informacja: To check the type and value of an expression, use the var_dump() function. To get a human-readable representation of a type for debugging, use the gettype() function. To check for a certain type, do not use gettype(), but rather the is_type functions. Some examples:
<?php
$a_bool = TRUE; // a boolean
$a_str = "foo"; // a string
$a_str2 = 'foo'; // a string
$an_int = 12; // an integer
echo gettype($a_bool); // prints out: boolean
echo gettype($a_str); // prints out: string
// If this is an integer, increment it by four
if (is_int($an_int)) {
$an_int += 4;
}
// If $bool is a string, print it out
// (does not print out anything)
if (is_string($a_bool)) {
echo "String: $a_bool";
}
?>
To forcibly convert a variable to a certain type, either cast the variable or use the settype() function on it.
Note that a variable may be evaluated with different values in certain situations, depending on what type it is at the time. For more information, see the section on Type Juggling. The type comparison tables may also be useful, as they show examples of various type-related comparisons.
This is the simplest type. A boolean expresses a truth value. It can be either TRUE or FALSE.
Informacja: The boolean type was introduced in PHP 4.
To specify a boolean literal, use the keywords TRUE or FALSE. Both are case-insensitive.
<?php
$foo = True; // assign the value TRUE to $foo
?>
Typically, some kind of operator which returns a boolean value, and the value is passed on to a control structure.
<?php
// == is an operator which test
// equality and returns a boolean
if ($action == "show_version") {
echo "The version is 1.23";
}
// this is not necessary...
if ($show_separators == TRUE) {
echo "<hr>\n";
}
// ...because instead, this can be used:
if ($show_separators) {
echo "<hr>\n";
}
?>
To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unncecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
See also Type Juggling.
When converting to boolean, the following values are considered FALSE:
Every other value is considered TRUE (including any resource).
-1 is considered TRUE, like any other non-zero (whether negative or positive) number!
<?php
var_dump((bool) ""); // bool(false)
var_dump((bool) 1); // bool(true)
var_dump((bool) -2); // bool(true)
var_dump((bool) "foo"); // bool(true)
var_dump((bool) 2.3e5); // bool(true)
var_dump((bool) array(12)); // bool(true)
var_dump((bool) array()); // bool(false)
var_dump((bool) "false"); // bool(true)
?>
An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}.
See also:
Integers can be specified in decimal (base 10), hexadecimal (base 16), or octal (base 8) notation, optionally preceded by a sign (- or +).
To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x.
Przykład #1 Integer literals
<?php
$a = 1234; // decimal number
$a = -123; // a negative number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
?>
Formally, the structure for integer literals is:
decimal : [1-9][0-9]*
| 0
hexadecimal : 0[xX][0-9a-fA-F]+
octal : 0[0-7]+
integer : [+-]?decimal
| [+-]?hexadecimal
| [+-]?octal
The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bits platforms usually have the maximum value of about 9E18. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.
If an invalid digit is given in an octal integer (i.e. 8 or 9), the rest of the number is ignored.
Przykład #2 Octal weirdness
<?php
var_dump(01090); // 010 octal = 8 decimal
?>
If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.
<?php
$large_number = 2147483647;
var_dump($large_number);
// output: int(2147483647)
$large_number = 2147483648;
var_dump($large_number);
// output: float(2147483648)
// it's true also for hexadecimal specified integers between 2^31 and 2^32-1:
var_dump( 0xffffffff );
// output: float(4294967295)
// this doesn't go for hexadecimal specified integers above 2^32-1:
var_dump( 0x100000000 );
// output: int(2147483647)
$million = 1000000;
$large_number = 50000 * $million;
var_dump($large_number);
// output: float(50000000000)
?>
Unfortunately, there was a bug in PHP which caused this to not always work correctly when negative numbers were involved. For example, the result of -50000 * $million is -429496728. However, when both operands were positive, there was no problem.
This was fixed in PHP 4.1.0.
There is no integer division operator in PHP. 1/2 yields the float 0.5. The value can be casted to an integer to round it downwards, or the round() function provides finer control over rounding.
<?php
var_dump(25/7); // float(3.5714285714286)
var_dump((int) (25/7)); // int(3)
var_dump(round(25/7)); // float(4)
?>
To explicitly convert a value to integer, use either the (int) or (integer) casts. However, in most cases the cast is not needed, since a value will be automatically converted if an operator, function or control structure requires an integer argument. A value can also be converted to integer with the intval() function.
See also: type-juggling.
FALSE will yield 0 (zero), and TRUE will yield 1 (one).
When converting from float to integer, the number will be rounded towards zero.
If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31), the result is undefined, since the float doesn't have enough precision to give an exact integer result. No warning, not even a notice will be issued when this happens!
Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results.
<?php
echo (int) ( (0.1+0.7) * 10 ); // echoes 7!
?>
See also the warning about float precision.
The behaviour of converting to integer is undefined for other types. Do not rely on any observed behaviour, as it can change without notice.
Floating point numbers (also known as "floats", "doubles", or "real numbers") can be specified using any of the following syntaxes:
<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?>
Formally:
LNUM [0-9]+
DNUM ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM})
The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64 bit IEEE format).
It is typical that simple decimal fractions like 0.1 or 0.7 cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9.
This is due to the fact that it is impossible to express some fractions in decimal notation with a finite number of digits. For instance, 1/3 in decimal form becomes 0.3.
So never trust floating number results to the last digit, and never compare floating point numbers for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.
For information on converting strings to float, see String conversion to numbers. For values of other types, the conversion is performed by converting the value to integer first and then to float. See Converting to integer for more information. As of PHP 5, a notice is thrown if an object is converted to float.
A string is series of characters. Before PHP 6, a character is the same as a byte. That is, there are exactly 256 different characters possible. This also implies that PHP has no native support of Unicode. See utf8_encode() and utf8_decode() for some basic Unicode functionality.
Informacja: It is no problem for a string to become very large. PHP imposes no boundary on the size of a string; the only limit is the available memory of the computer on which PHP is running.
A string literal can be specified in four different ways:
The simplest way to specify a string is to enclose it in single quotes (the character ').
To specify a literal single quote, escape it with a backslash (\). To specify a literal backslash before a single quote, or at the end of the string, double it (\\). Note that attempting to escape any other character will print the backslash too.
Informacja: Unlike the two other syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
<?php
echo 'this is a simple string';
echo 'You can also have embedded newlines in
strings this way as it is
okay to do';
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';
// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';
// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>
If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:
| Sequence | Meaning |
|---|---|
| \n | linefeed (LF or 0x0A (10) in ASCII) |
| \r | carriage return (CR or 0x0D (13) in ASCII) |
| \t | horizontal tab (HT or 0x09 (9) in ASCII) |
| \v | vertical tab (VT or 0x0B (11) in ASCII) (since PHP 5.2.5) |
| \f | form feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5) |
| \\ | backslash |
| \$ | dollar sign |
| \" | double-quote |
| \[0-7]{1,3} | the sequence of characters matching the regular expression is a character in octal notation |
| \x[0-9A-Fa-f]{1,2} | the sequence of characters matching the regular expression is a character in hexadecimal notation |
As in single quoted strings, escaping any other character will result in the backslash being printed too. Before PHP 5.1.1, the backslash in \{$var} had not been printed.
The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.
A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.
The closing identifier must begin in the first column of the line. Also, the identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.
It is very important to note that the line with the closing identifier must contain no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter (possibly followed by a semicolon) must also be followed by a newline.
If this rule is broken and the closing identifier is not "clean", it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line.
Heredocs can not be used for initializing class properties. Since PHP 5.3, this limitation is valid only for heredocs containing variables.
Przykład #1 Invalid example
<?php
class foo {
public $bar = <<<EOT
bar
EOT;
}
?>
Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.
Przykład #2 Heredoc string quoting example
<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
/* More complex example, with variables. */
class foo
{
var $foo;
var $bar;
function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'MyName';
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>
Powyższy przykład wyświetli:
My name is "MyName". I am printing some Foo. Now, I am printing some Bar2. This should print a capital 'A': A
It is also possible to use the Heredoc syntax to pass data to function arguments:
Przykład #3 Heredoc in arguments example
<?php
var_dump(array(<<<EOD
foobar!
EOD
));
?>
As of PHP 5.3.0, its possible to initialize static variables and class properties/constants using the Heredoc syntax:
Przykład #4 Using Heredoc to initialize static values
<?php
// Static variables
function foo()
{
static $bar = <<<LABEL
Nothing in here...
LABEL;
}
// Class properties/constants
class foo
{
const BAR = <<<FOOBAR
Constant example
FOOBAR;
public $baz = <<<FOOBAR
Property example
FOOBAR;
}
?>
PHP 5.3.0 also introduces the possibility for Heredoc's to use double quotes in declarings:
Przykład #5 Using double quotes in Heredoc
<?php
echo <<<"FOOBAR"
Hello World!
FOOBAR;
?>
Informacja: Heredoc support was added in PHP 4.
Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML <![CDATA[ ]]> construct, in that it declares a block of text which is not for parsing.
A nowdoc is identified with the same <<< seqeuence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.
Przykład #6 Nowdoc string quoting example
<?php
$str = <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;
/* More complex example, with variables. */
class foo
{
public $foo;
public $bar;
function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'MyName';
echo <<<'EOT'
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41
EOT;
?>
Powyższy przykład wyświetli:
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41Informacja: Unlike heredocs, nowdocs can be used in any static data context. The typical example is initializing class properties or constants:
Przykład #7 Static data example
<?php
class foo {
public $bar = <<<'EOT'
bar
EOT;
}
?>
Informacja: Nowdoc support was added in PHP 5.3.0.
When a string is specified in double quotes or with heredoc, variables are parsed within it.
There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort.
The complex syntax was introduced in PHP 4, and can be recognised by the curly braces surrounding the expression.
If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name.
<?php
$beer = 'Heineken';
echo "$beer's taste is great"; // works; "'" is an invalid character for variable names
echo "He drank some $beers"; // won't work; 's' is a valid character for variable names but the variable is "$beer"
echo "He drank some ${beer}s"; // works
echo "He drank some {$beer}s"; // works
?>
Similarly, an array index or an object property can be parsed. With array indices, the closing square bracket (]) marks the end of the index. The same rules apply to object properties as to simple variables.
<?php
// These examples are specific to using arrays inside of strings.
// When outside of a string, always quote array string keys and do not use
// {braces}.
// Show all errors
error_reporting(E_ALL);
$fruits = array('strawberry' => 'red', 'banana' => 'yellow');
// Works, but note that this works differently outside a string
echo "A banana is $fruits[banana].";
// Works
echo "A banana is {$fruits['banana']}.";
// Works, but PHP looks for a constant named banana first, as described below.
echo "A banana is {$fruits[banana]}.";
// Won't work, use braces. This results in a parse error.
echo "A banana is $fruits['banana'].";
// Works
echo "A banana is " . $fruits['banana'] . ".";
// Works
echo "This square is $square->width meters broad.";
// Won't work. For a solution, see the complex syntax.
echo "This square is $square->width00 centimeters broad.";
?>
For anything more complex, you should use the complex syntax.
This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.
In fact, any value in the namespace can be included in a string with this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:
<?php
// Show all errors
error_reporting(E_ALL);
$great = 'fantastic';
// Won't work, outputs: This is { fantastic}
echo "This is { $great}";
// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";
// Works
echo "This square is {$square->width}00 centimeters broad.";
// Works
echo "This works: {$arr[4][3]}";
// This is wrong for the same reason as $foo[bar] is wrong outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}";
// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";
// Works.
echo "This works: " . $arr['foo'][3];
echo "This works too: {$obj->values[3]->name}";
echo "This is the value of the var named $name: {${$name}}";
echo "This is the value of the var named by the return value of getName(): {${getName()}}";
echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";
?>
It is also possible to access class properties using variables within strings using this syntax.
<?php
class foo {
var $bar = 'I am bar.';
}
$foo = new foo();
$bar = 'bar';
$baz = array('foo', 'bar', 'baz', 'quux');
echo "{$foo->$bar}\n";
echo "{$foo->$baz[1]}\n";
?>
Powyższy przykład wyświetli:
Informacja: Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.
<?php
// Show all errors.
error_reporting(E_ALL);
class beers {
const softdrink = 'rootbeer';
public static $ale = 'ipa';
}
$rootbeer = 'A & W';
$ipa = 'Alexander Keith\'s';
// This works; outputs: I'd like an A & W
echo "I'd like an {${beers::softdrink}}\n";
// This works too; outputs: I'd like an Alexander Keith's
echo "I'd like an {${beers::$ale}}\n";
?>
Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose.
Informacja: Strings may also be accessed using braces, as in $str{42}, for the same purpose. However, this syntax is deprecated as of PHP 5.3.0. Use square brackets instead, such as $str[42].
Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer. Illegal offset type emits E_NOTICE. Negative offset emits E_NOTICE in write but reads empty string. Only the first character of an assigned string is used. Assigning empty string assigns NUL byte.
Przykład #8 Some string examples
<?php
// Get the first character of a string
$str = 'This is a test.';
$first = $str[0];
// Get the third character of a string
$third = $str[2];
// Get the last character of a string.
$str = 'This is still a test.';
$last = $str[strlen($str)-1];
// Modify the last character of a string
$str = 'Look at the sea';
$str[strlen($str)-1] = 'e';
?>
Informacja: Accessing variables of other types using [] or {} silently returns NULL.
Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. See String operators for more information.
There are a number of useful functions for string manipulation.
See the string functions section for general functions, and the regular expression functions or the Perl-compatible regular expression functions for advanced find & replace functionality.
There are also functions for URL strings, and functions to encrypt/decrypt strings (mcrypt and mhash).
Finally, see also the character type functions.
A value can be converted to a string using the (string) cast or the strval() function. String conversion is automatically done in the scope of an expression where a string is needed. This happens when using the echo() or print() functions, or when a variable is compared to a string. The sections on Types and Type Juggling will make the following clearer. See also the settype() function.
A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.
An integer or float is converted to a string representing the number textually (including the exponent part for floats). Floating point numbers can be converted using exponential notation (4.1E+6).
Informacja: The decimal point character is defined in the script's locale (category LC_NUMERIC). See the setlocale() function.
Arrays are always converted to the string "Array"; because of this, echo() and print() can not by themselves show the contents of an array. To view a single element, use a construction such as echo $arr['foo']. See below for tips on viewing the entire contents.
Objects in PHP 4 are always converted to the string "Object". To print the values of object properties for debugging reasons, read the paragraphs below. To get an object's class name, use the get_class() function. As of PHP 5, the __toString method is used when applicable.
Resources are always converted to strings with the structure "Resource id #1", where 1 is the unique number assigned to the resource by PHP at runtime. Do not rely upon this structure; it is subject to change. To get a resource's type, use the get_resource_type() function.
NULL is always converted to an empty string.
As stated above, directly converting an array, object, or resource to a string does not provide any useful information about the value beyond its type. See the functions print_r() and var_dump() for more effective means of inspecting the contents of these types.
Most PHP values can also be converted to strings for permanent storage. This method is called serialization, and is performed by the serialize() function. If the PHP engine was built with WDDX support, PHP values can also be serialized as well-formed XML text.
When a string is evaluated in a numeric context, the resulting value and type are determined as follows.
If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.
The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.
<?php
$foo = 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 = 4 + "10.2 Little Piggies"; // $foo is float (14.2)
$foo = "10.0 pigs " + 1; // $foo is float (11)
$foo = "10.0 pigs " + 1.0; // $foo is float (11)
?>
For more information on this conversion, see the Unix manual page for strtod(3).
To test any of the examples in this section, cut and paste the examples and insert the following line to see what's going on:
<?php
echo "\$foo==$foo; type is " . gettype ($foo) . "<br />\n";
?>
Do not expect to get the code of one character by converting it to integer, as is done in C. Use the ord() and chr() functions to convert between ASCII codes and characters.
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
Explanation of those data structures is beyond the scope of this manual, but at least one example is provided for each of them. For more information, look towards the considerable literature that exists about this broad topic.
An array can be created by the array() language construct. It takes as parameters any number of comma-separated key => value pairs.
array( key => value , ... ) // key may only be an integer or string // value may be any value of any type
<?php
$arr = array("foo" => "bar", 12 => true);
echo $arr["foo"]; // bar
echo $arr[12]; // 1
?>
A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.
A value can be any PHP type.
Informacja: Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an E_NOTICE-level error message will be issued, and the result will be NULL.
<?php
$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));
echo $arr["somearray"][6]; // 5
echo $arr["somearray"][13]; // 9
echo $arr["somearray"]["a"]; // 42
?>
If a key is not specified for a value, the maximum of the integer indices is taken and the new key will be that value plus 1. If a key that already has an assigned value is specified, that value will be overwritten.
<?php
// This array is the same as ...
array(5 => 43, 32, 56, "b" => 12);
// ...this array
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
?>
Before PHP 4.3.0, appending to an array in which the current maximum key was negative would create a new key as described above. Since PHP 4.3.0, the new key will be 0.
Using TRUE as key will evaluate to integer 1 as a key. Using FALSE as key will evaluate to integer 0 as a key. Using NULL as a key will evaluate to the empty string. Using the empty string as a key will create (or overwrite) a key with the empty string and its value; it is not the same as using empty brackets.
Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.
An existing array can be modified by explicitly setting values in it.
This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]).
$arr[key] = value; $arr[] = value; // key may be an integer or string // value may be any value of any type
If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the unset() function on it.
<?php
$arr = array(5 => 1, 12 => 2);
$arr[] = 56; // This is the same as $arr[13] = 56;
// at this point of the script
$arr["x"] = 42; // This adds a new element to
// the array with key "x"
unset($arr[5]); // This removes the element from the array
unset($arr); // This deletes the whole array
?>
Informacja: As mentioned above, if no key is specified, the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1. If no integer indices exist yet, the key will be 0 (zero).
Note that the maximum integer key used for this need not currently exist in the array. It need only have existed in the array at some time since the last time the array was re-indexed. The following example illustrates:
<?php
// Create a simple array.
$array = array(1, 2, 3, 4, 5);
print_r($array);
// Now delete every item, but leave the array itself intact:
foreach ($array as $i => $value) {
unset($array[$i]);
}
print_r($array);
// Append an item (note that the new key is 5, instead of 0).
$array[] = 6;
print_r($array);
// Re-index:
$array = array_values($array);
$array[] = 7;
print_r($array);
?>Powyższy przykład wyświetli:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) Array ( ) Array ( [5] => 6 ) Array ( [0] => 6 [1] => 7 )
There are quite a few useful functions for working with arrays. See the array functions section.
Informacja: The unset() function allows removing keys from an array. Be aware that the array will not be reindexed. If a true "remove and shift" behavior is desired, the array can be reindexed using the array_values() function.
<?php
$a = array(1 => 'one', 2 => 'two', 3 => 'three');
unset($a[2]);
/* will produce an array that would have been defined as
$a = array(1 => 'one', 3 => 'three');
and NOT
$a = array(1 => 'one', 2 =>'three');
*/
$b = array_values($a);
// Now $b is array(0 => 'one', 1 =>'three')
?>
The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array.
Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while $foo[bar] is not. But why? It is common to encounter this kind of syntax in old scripts:
<?php
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
?>
This is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in future define constants which, unfortunately for such code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.
Informacja: This does not mean to always quote the key. Do not quote keys which are constants or variables, as this will prevent PHP from interpreting them.
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);
// Simple array:
$array = array(1, 2);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
echo "\nChecking $i: \n";
echo "Bad: " . $array['$i'] . "\n";
echo "Good: " . $array[$i] . "\n";
echo "Bad: {$array['$i']}\n";
echo "Good: {$array[$i]}\n";
}
?>Powyższy przykład wyświetli:
Checking 0: Notice: Undefined index: $i in /path/to/script.html on line 9 Bad: Good: 1 Notice: Undefined index: $i in /path/to/script.html on line 11 Bad: Good: 1 Checking 1: Notice: Undefined index: $i in /path/to/script.html on line 9 Bad: Good: 2 Notice: Undefined index: $i in /path/to/script.html on line 11 Bad: Good: 2
More examples to demonstrate this behaviour:
<?php
// Show all errors
error_reporting(E_ALL);
$arr = array('fruit' => 'apple', 'veggie' => 'carrot');
// Correct
print $arr['fruit']; // apple
print $arr['veggie']; // carrot
// Incorrect. This works but also throws a PHP error of level E_NOTICE because
// of an undefined constant named fruit
//
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit]; // apple
// This defines a constant to demonstrate what's going on. The value 'veggie'
// is assigned to a constant named fruit.
define('fruit', 'veggie');
// Notice the difference now
print $arr['fruit']; // apple
print $arr[fruit]; // carrot
// The following is okay, as it's inside a string. Constants are not looked for
// within strings, so no E_NOTICE occurs here
print "Hello $arr[fruit]"; // Hello apple
// With one exception: braces surrounding arrays within strings allows constants
// to be interpreted
print "Hello {$arr[fruit]}"; // Hello carrot
print "Hello {$arr['fruit']}"; // Hello apple
// This will not work, and will result in a parse error, such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using superglobals in strings as well
print "Hello $arr['fruit']";
print "Hello $_GET['foo']";
// Concatenation is another option
print "Hello " . $arr['fruit']; // Hello apple
?>
When error_reporting is set to show E_NOTICE level errors (by setting it to E_ALL, for example), such uses will become immediately visible. By default, error_reporting is set not to show notices.
As stated in the syntax section, what's inside the square brackets ('[' and ']') must be an expression. This means that code like this works:
<?php
echo $arr[somefunc($bar)];
?>
This is an example of using a function return value as the array index. PHP also knows about constants:
<?php
$error_descriptions[E_ERROR] = "A fatal error has occured";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE] = "This is just an informal notice";
?>
Note that E_ERROR is also a valid identifier, just like bar in the first example. But the last example is in fact the same as writing:
<?php
$error_descriptions[1] = "A fatal error has occured";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";
?>
because E_ERROR equals 1, etc.
At some point in the future, the PHP team might want to add another constant or keyword, or a constant in other code may interfere. For example, it is already wrong to use the words empty and default this way, since they are reserved keywords.
Informacja: To reiterate, inside a double-quoted string, it's valid to not surround array indexes with quotes so "$foo[bar]" is valid. See the above examples for details on why as well as the section on variable parsing in strings.
For any of the types: integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue).
If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behaviour:
<?php
class A {
private $A; // This will become '\0A\0A'
}
class B extends A {
private $A; // This will become '\0B\0A'
public $AA; // This will become 'AA'
}
var_dump((array) new B());
?>
The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'.
It is possible to compare arrays with the array_diff() function and with array operators.
The array type in PHP is very versatile. Here are some examples:
<?php
// This:
$a = array( 'color' => 'red',
'taste' => 'sweet',
'shape' => 'round',
'name' => 'apple',
4 // key will be 0
);
$b = array('a', 'b', 'c');
// . . .is completely equivalent with this:
$a = array();
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name'] = 'apple';
$a[] = 4; // key will be 0
$b = array();
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// After the above code is executed, $a will be the array
// array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round',
// 'name' => 'apple', 0 => 4), and $b will be the array
// array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c').
?>
Przykład #1 Using array()
<?php
// Array as (property-)map
$map = array( 'version' => 4,
'OS' => 'Linux',
'lang' => 'english',
'short_tags' => true
);
// strictly numerical keys
$array = array( 7,
8,
0,
156,
-10
);
// this is the same as array(0 => 7, 1 => 8, ...)
$switching = array( 10, // key = 0
5 => 6,
3 => 7,
'a' => 4,
11, // key = 6 (maximum of integer-indices was 5)
'8' => 2, // key = 8 (integer!)
'02' => 77, // key = '02'
0 => 12 // the value 10 will be overwritten by 12
);
// empty array
$empty = array();
?>
Przykład #2 Collection
<?php
$colors = array('red', 'blue', 'green', 'yellow');
foreach ($colors as $color) {
echo "Do you like $color?\n";
}
?>
Powyższy przykład wyświetli:
Do you like red? Do you like blue? Do you like green? Do you like yellow?
Changing the values of the array directly is possible since PHP 5 by passing them by reference. Before that, a workaround is necessary:
Przykład #3 Collection
<?php
// PHP 5
foreach ($colors as &$color) {
$color = strtoupper($color);
}
unset($color); /* ensure that following writes to
$color will not modify the last array element */
// Workaround for older versions
foreach ($colors as $key => $color) {
$colors[$key] = strtoupper($color);
}
print_r($colors);
?>
Powyższy przykład wyświetli:
Array
(
[0] => RED
[1] => BLUE
[2] => GREEN
[3] => YELLOW
)
This example creates a one-based array.
Przykład #4 One-based index
<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>
Powyższy przykład wyświetli:
Array
(
[1] => 'January'
[2] => 'February'
[3] => 'March'
)
Przykład #5 Filling an array
<?php
// fill an array with all items from a directory
$handle = opendir('.');
while (false !== ($file = readdir($handle))) {
$files[] = $file;
}
closedir($handle);
?>
Arrays are ordered. The order can be changed using various sorting functions. See the array functions section for more information. The count() function can be used to count the number of items in an array.
Przykład #6 Sorting an array
<?php
sort($files);
print_r($files);
?>
Because the value of an array can be anything, it can also be another array. This enables the creation of recursive and multi-dimensional arrays.
Przykład #7 Recursive and multi-dimensional arrays
<?php
$fruits = array ( "fruits" => array ( "a" => "orange",
"b" => "banana",
"c" => "apple"
),
"numbers" => array ( 1,
2,
3,
4,
5,
6
),
"holes" => array ( "first",
5 => "second",
"third"
)
);
// Some examples to address values in the array above
echo $fruits["holes"][5]; // prints "second"
echo $fruits["fruits"]["a"]; // prints "orange"
unset($fruits["holes"][0]); // remove "first"
// Create a new multi-dimensional array
$juices["apple"]["green"] = "good";
?>
Array assignment always involves value copying. Use the reference operator to copy an array by reference.
<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
// $arr1 is still array(2, 3)
$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>
To create a new object, use the new statement to instantiate a class:
<?php
class foo
{
function do_foo()
{
echo "Doing foo.";
}
}
$bar = new foo;
$bar->do_foo();
?>
For a full discussion, see the Classes and Objects chapter.
If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. If the value was NULL, the new instance will be empty. Arrays convert to an object with properties named by keys, and corresponding values. For any other value, a member variable named scalar will contain the value.
<?php
$obj = (object) 'ciao';
echo $obj->scalar; // outputs 'ciao'
?>
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.
Informacja: The resource type was introduced in PHP 4
See also the get_resource_type() function.
As resource variables hold special handlers to opened files, database connections, image canvas areas and the like, converting to a resource makes no sense.
Thanks to the reference-counting system introduced with PHP 4's Zend Engine, a resource with no more references to it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the memory manually.
Informacja: Persistent database links are an exception to this rule. They are not destroyed by the garbage collector. See the persistent connections section for more information.
The special NULL value represents a variable with no value. NULL is the only possible value of type NULL.
Informacja: The null type was introduced in PHP 4.
A variable is considered to be null if:
it has been assigned the constant NULL.
it has not been set to any value yet.
it has been unset().
There is only one value of type null, and that is the case-insensitive keyword NULL.
<?php
$var = NULL;
?>
Casting a variable to null will remove the variable and unset its value.
mixed indicates that a parameter may accept multiple (but not necessarily all) types.
gettype() for example will accept all PHP types, while str_replace() will accept strings and arrays.
Some functions like call_user_func() or usort() accept user-defined callback functions as a parameter. Callback functions can not only be simple functions, but also object methods, including static class methods.
A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs such as: array(), echo(), empty(), eval(), exit(), isset(), list(), print() or unset().
A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.
Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object at index 0.
Apart from common user-defined function, create_function() can also be used to create an anonymous callback function. As of PHP 5.3.0 it is possible to also pass a closure to a callback parameter.
Przykład #1 Callback function examples
<?php
// An example callback function
function my_callback_function() {
echo 'hello world!';
}
// An example callback method
class MyClass {
static function myCallbackMethod() {
echo 'Hello World!';
}
}
// Type 1: Simple callback
call_user_func('my_callback_function');
// Type 2: Static class method call
call_user_func(array('MyClass', 'myCallbackMethod'));
// Type 3: Object method call
$obj = new MyClass();
call_user_func(array($obj, 'myCallbackMethod'));
// Type 4: Static class method call (As of PHP 5.2.3)
call_user_func('MyClass::myCallbackMethod');
// Type 5: Relative static class method call (As of PHP 5.3.0)
class A {
public static function who() {
echo "A\n";
}
}
class B extends A {
public static function who() {
echo "B\n";
}
}
call_user_func(array('B', 'parent::who')); // A
?>
Przykład #2 Callback example using a Closure
<?php
// Our closure
$double = function($a) {
return $a * 2;
};
// This is our range of numbers
$numbers = range(1, 5);
// Use the closure as a callback here to
// double the size of each element in our
// range
$new_numbers = array_map($double, $numbers);
print implode(' ', $new_numbers);
?>
Powyższy przykład wyświetli:
2 4 6 8 10
Informacja: In PHP4, it was necessary to use a reference to create a callback that points to the actual object, and not a copy of it. For more details, see References Explained.
void as a return type means that the return value is useless. void in a parameter list means that the function doesn't accept any parameters.
$... in function prototypes means and so on. This variable name is used when a function can take an endless number of arguments.
PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.
An example of PHP's automatic type conversion is the addition operator '+'. If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does not change the types of the operands themselves; the only change is in how the operands are evaluated and what the type of the expression itself is.
<?php
$foo = "0"; // $foo is string (ASCII 48)
$foo += 2; // $foo is now an integer (2)
$foo = $foo + 1.3; // $foo is now a float (3.3)
$foo = 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 to numbers.
To force a variable to be evaluated as a certain type, see the section on Type casting. To change the type of a variable, see the settype() function.
To test any of the examples in this section, use the var_dump() function.
Informacja: The behaviour of an automatic conversion to array is currently undefined.
Also, because PHP supports indexing into strings via offsets using the same syntax as array indexing, the following example holds true for all PHP versions:
<?php
$a = 'car'; // $a is a string
$a[0] = 'b'; // $a is still a string
echo $a; // bar
?>See the section titled String access by character for more information.
Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.
<?php
$foo = 10; // $foo is an integer
$bar = (boolean) $foo; // $bar is a boolean
?>
The casts allowed are:
(binary) casting and b prefix forward support was added in PHP 5.2.1
Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent:
<?php
$foo = (int) $bar;
$foo = ( int ) $bar;
?>
Casting literal strings and variables to binary strings:
<?php
$binary = (binary) $string;
$binary = b"binary string";
?>
Informacja: Instead of casting a variable to a string, it is also possible to enclose the variable in double quotes.
<?php
$foo = 10; // $foo is an integer
$str = "$foo"; // $str is a string
$fst = (string) $foo; // $fst is also a string
// This prints out that "they are the same"
if ($fst === $str) {
echo "they are the same";
}
?>
It may not be obvious exactly what will happen when casting between certain types. For more information, see these sections:
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]*'
Informacja: W naszym rozumieniu, litery to znaki a-z, A-Z i bajty od 127 do 255 (0x7f-0xff).
Informacja: $this to specialna zmienna, której nie można definiować.
Zobacz także Userland Naming Guide.
Aby uzyskać więcej informacji na temat funkcji powiązanych ze zmiennymi, zobacz Funkcje Obsługi Zmiennych.
<?php
$zmienna = 'Pan';
$Zmienna = 'Jan';
echo "$zmienna, $Zmienna"; // wyświetla "Pan, Jan"
$7dni = 'tydzień'; // niepoprawna nazwa - zaczyna się od cyfry
$_7dni = 'tydzień'; // poprawna nazwa - zaczyna się znakiem podkreślenia
$jaźń = 'osobowość'; // poprawna nazwa - "ń" i "ź" należą do ASCII 127-255
?>
Domyślnie, zmienne zawsze są zawsze przypisywane 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 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.
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 $bar;
echo $foo; // $foo też się zmieniło.
?>
Należy pamiętać, że tylko wyrażenia posiadające nazwę mogą być przypisane przez referencję.
<?php
$foo = 25;
$bar = &$foo; // Przypisanie poprawne.
$bar = &(24 * 7); // Przypisanie niepoprawne - do nienazwanego wyrażenia.
function test()
{
return 25;
}
$bar = &test(); // Niepoprawne.
?>
W PHP nie jest konieczne inicjowanie zmiennych, jednak jest to bardzo dobry nawyk. Niezainicjowane zmienne mają domyślne wartości dla ich typu, zależnie od kontekstu, w jaki zmienne te zostały użyte - zmienne logiczne typu boolean domyślnie przyjmują wartość FALSE, zmiennym całkowitym typu integer domyślnie nadawane jest zero, łańcuchom tekstowym (np. użytym wewnątrz echo()) nadany jest łańcuch pusty, natomiast tablice zostają pustymi tablicami.
Przykład #1 Domyślne wartości niezainicjowanych zmiennych
<?php
// Zmienna bez nadanej wartości ORAZ bez odwołań do niej (brak kontekstu, w jakim została użyta); zwróci NULL
var_dump($zmienna_bez_kontekstu_uzycia);
// Używanie zmiennej logicznej typu boolean; zwróci 'false' (Zobacz informacje o operatorach trójparametrowych, by poznać tę składnię)
echo($nieinicjowana_zmiena_bool ? "true\n" : "false\n");
// Używanie łańcuchów; zwróci 'string(3) "abc"'
$nieinicjowany_lancuch .= 'abc';
var_dump($nieinicjowany_lancuch);
// Używanie zmiennych całkowitych; zwróci 'int(25)'
$nieinicjowana_zmienna_int += 25; // 0 + 25 => 25
var_dump($nieinicjowana_zmienna_int);
// Używanie zmiennych typu float/double; zwróci 'float(1.25)'
$nieinicjowana_zmienna_float += 1.25;
var_dump($nieinicjowana_zmienna_float);
// Używanie tablicy; zwróci array(1) { [3]=> string(3) "def" }
$nieinicjowana_tablica[3] = "def"; // array() + array(3 => "def") => array(3 => "def")
var_dump($nieinicjowana_tablica);
// Używanie obiektu; stworzy nowy obiekt stdClass (zobacz http://www.php.net/manual/pl/reserved.classes.php)
// Zwróci: object(stdClass)#1 (1) { ["foo"]=> string(3) "bar" }
$nieinicjowany_obiekt->foo = 'bar';
var_dump($nieinicjowany_obiekt);
?>
Poleganie na domyślnej wartości niezainicjowanej zmiennej jest problematyczne, w razie zawarcia jednego pliku wewnątrz innego, posiadającego tak samo nazwane zmienne. Jest to również poważne zagrożenie dla bezpieczeństwa przy włączonej opcji register_globals. Ostrzeżenie klasy E_NOTICE pojawi się podczas pracy z niezainicjowanymi zmiennymi, jednak w przypadku przypisywania elentów do niezainicjowanych tablic - już nie. Funkcja isset() może zostać użyta w celu wykrycia, czy zmienna została już zainicjowana.
PHP udostępnia dla każdego pracującego skryptu dużą ilość predefiniowanych zmiennych. 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, ustawień i innych czynników. Niektóre z tych zmiennych nie będą dostępne dla skryptów PHP uruchomionych z Linii Poleceń. Lista tych zmiennych znajduje się w rozdziale Predefiniowane Zmienne.
W PHP 4.2.0 i późniejszych, domyślne ustawienie dla instrukcji PHP register_globals jest wyłączone. Jest to bardzo istotna zmiana w PHP. Mając opcję register_globals wyłączoną wpływamy na ustawienie zmiennych predefiniowanych, dostępnych globalnie. Na przykład, aby poznać wartość DOCUMENT_ROOT użyjesz $_SERVER['DOCUMENT_ROOT'] zamiast $DOCUMENT_ROOT, lub $_GET['id'] z adresu URL http://www.example.com/test.php?id=3 zamiast $id, albo $_ENV['HOME'] a nie $HOME.
Aby uzyskać informacje powiązane z tą zmianą, przeczytaj część o konfiguracji register_globals, rozdziału o bezpieczeństwie Używanie Register Globals , oraz w informacjach o wydaniu (ang. Release Announcements) PHP » 4.1.0 jak i » 4.2.0
Używanie dostępnych zmiennych predefiniowanych, jak tablice superglobalne, jest zalecane.
Począwszy od wersji 4.1.0, PHP udostępnia dodatkowo zestaw predefiniowanych tablic, które zawierają zmienne serwera, zmienne środowiskowe oraz zmienne użytkownika. Tablice te są dość specyficzne, gdyż są one automatycznie globalne, tzn. automatycznie dostępne w każdym miejscu. Dlatego nazywa się je "superglobalami". (W PHP nie ma mechanizmu pozwalającego użytkownikowi na definiowanie własnych superglobali.) Superglobale PHP wymienione są poniżej; jednakże wykaz ich zawartości i głębsze omówienie prefiniowanych zmiennych PHP oraz ich natury znajduje się w rozdziale predefiniowane zmienne. Zauważ także, że starsze zmienne predefiniowane ($HTTP_*_VARS) wciąż funkcjonują. Od PHP 5.0.0, długie tablice zmiennych predefiniowanych mogą być wyłączone dyrektywą konfiguracji register_long_arrays.
Informacja: Zmienne zmienne
Zmienne superglobale nie mogą być użyte jako zmienne zmienne wewnątrz funkcji, ani jako metody klasy.
Informacja: Nawet pomimo tego, że zmienne superglobalne i HTTP_*_VARS mogą istnieć w tym samym czasie; nie są one tożsame, czyli zmiana jednej nie zmieni drugiej.
Jeśli pewne zmienne w variables_order nie są ustawione, to ich odpowiedniki zmiennych predefiniowanych PHP również są puste.
Zasięg zmiennej zależy od miejsca, w jakim ją zdefiniowano. Najczęściej zmienne PHP widoczne są tylko w jednym zasięgu. Taki zasięg obejmuje również pliki dołączone funkcjami include i require. Na przykład:
<?php
$a = 1;
include 'b.inc';
?>
Tutaj zmienna $a będzie dostępna także wewnątrz dołączonego funkcją include pliku b.inc w skrypcie. Jednakże wewnątrz funkcji zdefiniowanych samodzielnie zmienne mają zasięg lokalny. Każda zmienna użyta wewnątrz funkcji jest domyślnie ograniczona do zasięgu lokalnego funkcji. Na przykład:
<?php
$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ć 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.
Najpierw, przykład użycia global:
Przykład #1 Używanie polecenia global
<?php
$a = 1;
$b = 2;
function Suma()
{
global $a, $b;
$b = $a + $b;
}
Suma();
echo $b;
?>
Powyższy skrypt wyświetli wynik "3". Przez zadeklarowanie wewnątrz funkcji globalności zmiennych $a i $b, wszystkie odwołania do tych zmiennych będą odnosiły się do ich globalnych wersji. Nie ma żadnych ograniczeń w ilości zmiennych globalnych, na których chcemy operować wewnątrz funkcji.
Drugim sposobem uzyskania dostępu do zmiennych globalnych wewnątrz funkcji jest użycie specjalnej, zdefiniowanej przez PHP tablicy $GLOBALS. Powyższy przykład można zatem przepisać tak:
Przykład #2 Używanie $GLOBALS zamiast polecenia global
<?php
$a = 1;
$b = 2;
function Suma()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
Suma();
echo $b;
?>
Tablica $GLOBALS jest asocjacyjną tablicą, w której nazwa zmiennej jest kluczem, a zawartość zmiennej wartością komórki tablicy. Zauważ, że $GLOBALS jest dostępna z każdego miejsca, ponieważ $GLOBALS jest tablicą superglobalną. Poniżej przykład demonstrujący moc superglobali:
Przykład #3 Przykład demonstrujący superglobale i zasięg zmiennych
<?php
function test_global()
{
// Większość predefiniowanych zmiennych nie jest "super i wymaga
// 'global', by być dostępnymi w zasięgu lokalnym funkcji.
global $HTTP_POST_VARS;
echo $HTTP_POST_VARS['name'];
// Superglobale są dostępne z każdego miejsca
// i nie wymagają 'global'. Superglobale udostępniono
// wraz z PHP 4.1.0, a HTTP_POST_VARS jest
// uważane za przestarzałe.
echo $_POST['name'];
}
?>
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. Rozważmy poniższy przykład:
Przykład #4 Przykład ukazujący przydatność zmiennych statycznych
<?php
function test()
{
$a = 0;
echo $a;
$a++;
}
?>
Ta funkcja jest bezużyteczna, gdyż przy każdym jej wywołaniu zmienna $a otrzymuje wartość 0, w związku z czym funkcja stale wyświetla "0". Występująca potem inkrementacja $a++ nie ma żadnego znaczenia, gdyż funkcja się kończy i zmienna $a znika. Aby powyższa funkcja miała jakiś sens, należy zapobiec gubieniu wartości $a, do czego używamy słowa kluczowego static:
Przykład #5 Przykład użycia zmiennych statycznych
<?php
function Test()
{
static $a = 0;
echo $a;
$a++;
}
?>
Teraz, $a jest inicjowana tylko pry pierwszym wywołaniu funkcji a, przy każdym wywołaniu 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 jakimś momencie. Poniższa, prosta funkcja rekurencyjnie liczy do 10, używając zmiennej statycznej $licznik, aby wiedzieć, kiedy się zatrzymać:
Przykład #6 Zmienne statyczne w funkcjach rekurencyjnych
<?php
function test()
{
static $licznik = 0;
$licznik++;
echo $licznik;
if ($licznik < 10) {
test();
}
$licznik--;
}
?>
Informacja: Zmienne statyczne mogą być deklarowane, tak jak w powyższym przykładzie. Próba przypisania wartości do tego typu zmiennych, poprzez wynik jakiegoś wyrażenia, spowoduje błąd składni (ang. Parse error).
Przykład #7 Deklaracja zmiennych statycznych
<?php
function foo(){
static $int = 0; // prawidłowo
static $int = 1+2; // błąd (w rzeczywistości to jest wyrażenie)
static $int = sqrt(121); // błąd (to również jest wyrażenie)
$int++;
echo $int;
}
?>
Silnik Zend 1 (ang. Zend Engine 1) napędzający PHP4, implementuje modyfikatory statyczny oraz globalny dla zmiennych, pod względem referencji. Na przykład, w rzeczywistości globalna zmienna wprowadzona wewnątrz zasięgu funkcji z wyrażeniem global na dziś dzień tworzy referencję do zmiennej globalnej. Takie zachowanie może prowadzić do nieoczekiwanych sytuacji, czego dowodzi poniższy przykład:
<?php
function test_global_ref() {
global $obj;
$obj = &new stdclass;
}
function test_global_noref() {
global $obj;
$obj = new stdclass;
}
test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>
Wykonanie tego przykładu da następujące wyniki:
Podobna sytuacja dotyczy deklaracji static. Referencje nie są magazynowane statycznie:
<?php
function &get_instance_ref() {
static $obj;
echo 'Obiekt statyczny: ';
var_dump($obj);
if (!isset($obj)) {
// Przypisanie referencji do zmiennej statycznej.
$obj = &new stdclass;
}
$obj->property++;
return $obj;
}
function &get_instance_noref() {
static $obj;
echo 'Obiekt statyczny: ';
var_dump($obj);
if (!isset($obj)) {
// Przypisanie do obiektu zmiennej statycznej
$obj = new stdclass;
}
$obj->property++;
return $obj;
}
$obj1 = get_instance_ref();
$still_obj1 = get_instance_ref();
echo "\n";
$obj2 = get_instance_noref();
$still_obj2 = get_instance_noref();
?>
Wykonanie tego przykładu da następujące wyniki:
Ten przykład pokazuje, że podczas przypisywania referencji do zmiennej statycznej, nie następuje zapamiętanie, gdy wywołasz funkcję &get_instance_ref() po raz drugi.
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:
<?php
$a = "witaj";
?>
Zmienna zmienna pobiera wartość jednej zmiennej i traktuje ją jako nazwę innej. W powyższym przykładzie, witaj, może stać się nazwą zmiennej, dzięki użyciu dwóch znaków dolara, tzn.
<?php
$$a = "świecie";
?>
W tym momencie dwie zmienne zostały zdefiniowane i umieszczone w drzewie symbolicznym PHP: $a zawierająca "witaj" i $witaj zawierająca "świecie". Zatem poniższy zapis:
<?php
echo "$a ${$a}";
?>
znaczy to samo, co:
<?php
echo "$a $witaj";
?>
tzn. obydwa wyświetlą: witaj świecie.
Aby używać zmiennych zmiennych jako tablic, trzeba wyjaśnić 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.
Zauważ, że zmienne zmienne nie mogą być używane z Tablicami superglobalnymi PHP, wewnątrz funkcji, czy metod klas. Zmienna $this jest także specjalną zmienną, dla której referencje dynamiczne nie są dozwolone.
Kiedy do skryptu PHP zostanie wysłany formularz, informacja z niego jest automatycznie dostępna w skrypcie. Istnieje wiele sposobów na uzyskanie tych informacji, dla przykładu:
Przykład #1 Prosty formularz HTML
<form action="foo.php" method="post">
Imie: <input type="text" name="imie" /><br />
Email: <input type="text" name="email" /><br />
<input type="submit" name="submit" value="Wyslij!" />
</form>
W zależności od twoich szczególnych ustawień i osobistych upodobań, istnieje wiele sposobów dostępu do danych z twoich formularzy HTML. Oto kilka przykładów:
Przykład #2 Dostęp do informacji z prostego formularza HTML (wysłanego metodą POST)
<?php
// Możliwe od PHP 4.1.0
echo $_POST['imie'];
echo $_REQUEST['imie'];
import_request_variables('p', 'p_');
echo $p_imie;
// Niedostępne od PHP 6. Od PHP 5.0.0, te długie predefiniowane
// zmienne mogą być niedostępne z włączoną opcją register_long_arrays.
echo $HTTP_POST_VARS['imie'];
// Dostępne, jeśli opcja register_globals jest włączona - "on". Począwszy od
// PHP 4.2.0 domyślna wartość opcji register_globals to off.
// Nie jest zalecane poleganie na tej metodzie.
echo $imie;
?>
Przesyłanie danych z formularza metodą GET jest podobne, z takim wyjątkiem, że użyjesz zmienną predefiniowaną odpowiednią dla tej metody, zamiast poprzedniej. GET także odnosi się do tzw. QUERY_STRING (informacje w adresie URL, po znaku '?'). Tak więc, dla przykładu, http://www.example.com/test.php?id=3 zawiera dane dla metody GET, dostępne poprzez $_GET['id']. Zobacz także $_REQUEST oraz import_request_variables().
Informacja: Tablice superglobalne, takie jak $_POST i $_GET, zostały udostępnione w PHP 4.1.0
Jak widać, przed PHP 4.2.0 domyślną wartością opcji register_globals było on. Społeczność PHP jest całkowiie przekonana, by nie polegać na tej opcji; i rzeczywiście najlepiej jest nadać jej wartość off, oraz przystosować do tego kod.
Informacja: Dyrektywa konfiguracyjna magic_quotes_gpc oddziałuje na zmienne z Get, Post i Cookie. Jeśli jest włączona, tekst (It's "PHP!") automagicznie zmieni się w (It\'s \"PHP!\"). Jest to potrzebne przy wpisywaniu danych do baz danych. Zobacz także 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). Na przykład, wyślijmy formularz z pliku metodą POST do samego siebie i wyświetlmy te dane:
Przykład #3 Bardziej złożone zmienne w formularzach
<?php
if ($_POST) {
echo '<pre>';
echo htmlspecialchars(print_r($_POST, true));
echo '</pre>';
}
?>
<form action="" method="post">
Nazwisko: <input type="text" name="personal[nazwisko]"><br />
Email: <input type="text" name="personal[email]"><br />
Piwo: <br />
<select multiple name="piwo[]">
<option value="zywiec">Żywiec</option>
<option value="tyskie">Tyskie</option>
<option value="lech">Lech</option>
</select><br />
<input type="submit" value="Wyślij mnie!" />
</form>
Przy tworzeniu formularza, można użyć obrazka, zamiast standardowego przycisku Wyślij, za pomocą takiego znacznika:
<input type="image" src="obrazek.gif" name="sub" />
Kiedy użytkownik kliknie gdzieś na obrazku, formularz, którego to dotyczy, zostanie wysłany do serwera z dwiema dodatkowymi zmiennymi, sub_x i sub_y. Zawierają one współrzędne miejsca kliknięcia na obrazek. Można przy tym zauważyć, że na razie w nazwach zmiennych znajduje się kropka zamiast podkreślnika, ale PHP konwertuje kropkę na podkreślnik automatycznie.
PHP normalnie nie zmienia nazw zmiennych podczas przekazywania ich do skryptu. Jednakże należy pamiętać, że kropka "." nie jest poprawnym znakiem w nazwie zmiennej PHP. Dlaczego? Proszę spojrzeć na to:
<?php
$varname.ext; /* niepoprawna nazwa zmiennej */
?>
To co widzi parser, to zmienna o nazwie $varname, po której pojawia się operator konkatenacji, a następnie pusty łańcuch (czyli taki, który nie jest żadnym słowem kluczowym, ani zarezerwowanym) "ext". Oczywiście, nie daje to żadnego sensownego wyniku.
Warto zatem wiedzieć, że PHP automatycznie zastąpi podkreślnikiem "_" każdą kropkę w nazwie każdej odebranej 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, takich jak: gettype(), is_array(), is_float(), is_int(), is_object() i is_string(). Zobacz także rozdział o Typach.
Stałe są to nazwy, identyfikujące proste wartości. Jak sama nazwa wskazuje, nie mogą się one zmieniać w trakcie wykonywania skryptu (wyjątkiem są magiczne stałe, które własciwie nie sa stałymi). W nazwach stałych domyślnie rozróżniana jest wielkość liter. Zgodnie z ogólnie przyjętą konwencją, nazwy stałych zawsze pisane sa wielkimi literami.
Nazwy stałych obowiązują identyczne zasady, jak w przypadku wszystkich innych etykiet. Poprawna nazwa stałej zaczyna się od litery lub podkreślnika, po których następuje dowolna ilość liter, cyfr i podkreślników. Jako wyrażenie regularne, określone zostałoby to następująco: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
Zobacz także Userland Naming Guide.
Przykład #1 Poprawne i niepoprawne nazwy stałych
<?php
// Poprawne nazwy stałych
define("FOO", "something");
define("FOO2", "something else");
define("FOO_BAR", "something more");
// Niepoprawne nazwy stałych
define("2FOO", "something");
// Pomimo tego, że poniższy zapis jest poprawny, powinno się go unikać:
// PHP może kiedyś zawierać magiczną stałą,
// która zepsuje Twój skrypt
define("__FOO__", "something");
?>
Informacja: Dla naszych celów, literami są a-z, A-Z, oraz znaki ASCII z przedziału od 127 do 255 (0x7f-0xff).
Podobnie jak superglobals, zasięg stałych jest globalny. Można sie odwoływać do nich w każdym miejscu pliku, nie przejmując sie zasięgiem. Więcej informacji na ten temat znajdziesz w rozdziale pt. zasięg zmiennych.
Możesz zdefiniować stałą, używając funkcji define(). Raz zdefiniowana stała nie może byc zmieniona ani usunięta.
Stałe mogą zawierać jedynie dane skalarne (boolean, integer, float oraz string) Stałe nie mogą być typu resource.
Wartość stałej otrzymujemy, używając jej nazwy. W przeciwieństwie do zmiennych, nazw stałych nie poprzedzamy znakiem $. Możesz także użyć funkcji constant() do odczytania wartości stałej, jeśli chcesz wygenerować jej nazwę dynamicznie. Aby uzyskać listę wszystkich zdefiniowanych stałych, użyj get_defined_constants().
Informacja: Stałe i zmienne globalne operują w różnych przestrzeniach nazw. Oznacza to, że na przykład TRUE i $TRUE oznaczają co innego.
Jeśli używasz niezdefiniowanej stałej, PHP traktuje to, jak gdybyś chciał użyć nazwy stałej jako wartości typu string (STAŁA a "STAŁA"). Błąd typu E_NOTICE zostanie wywołany, kiedy to się stanie. Przeczytaj także, dlaczego $foo[bar] jest niepoprawne (jeśli nie zdefiniujesz bar jako stałej). Chcąc sprawdzić, czy dana stała istnieje, użyj funkcji defined().
Oto różnice pomiędzy stałymi i zmiennymi:
Przykład #1 Definiowanie stałych
<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // wypisuje "Hello world."
echo Constant; // wypisuje "Constant" i wywoułuje ostrzeżenie.
?>
Zobacz także Stałe Klas.
PHP zapewnia szeroki zakres predefiniowanych stałych każdemu skryptowi, który jest uruchamiany. Wiele z tych stałych jest jednak dostępnych dzieki różnym rozszerzeniom i można z nich korzystać jedynie, kiedy te rozszerzenia sa dostępne przez dynamiczne załadowanie, badź też zostały wkompilowane.
Istnieje siedem magicznych stałych, które zmieniają sie w zależności od tego, gdzie są użyte. Na przykład, wartość __LINE__ zależy od linii, w której ta stała została użyta. Nazwy tych magicznych stałych są niezależne od wielkości liter:
| Nazwa | Opis |
|---|---|
| __LINE__ | Aktualna linia pliku. |
| __FILE__ | Pełna scieżka i nazwa pliku. Jeśli użyta wewnątrz dołączonego pliku, jego nazwa jest zwracana. Od PHP 4.0.2, __FILE__zawsze zawiera bezwzględną scieżkę z rozwiązanymi dowiązaniami symbolicznymi, podczas kiedy w starszych wersjach czasem zawierała scieżkę względną. |
| __DIR__ | Nazwa katalogu pliku. Jeśli użyta wewnątrz dołączonego pliku, zwraca nazwę jego katalogu. Odpowiada dirname(__FILE__). Zwracana nazwa nie zawiera końcowego ukośnika, chyba że jest to katalog root. (Dodano w PHP 5.3.0.) |
| __FUNCTION__ | Nazwa funkcji. (Dodano w PHP 4.3.0) W PHP 5 ta stała zwraca nazwę funkcji tak jak ją zadeklarowano (z uwzględnieniem wielkości liter), podczas kiedy w PHP 4 zwracana wartość zawiera jedynie małe litery. |
| __CLASS__ | Nazwa klasy. (Dodano w PHP 4.3.0) W PHP 5 ta stała zwraca nazwę klasy tak jak ją zadeklarowano (z uwzględnieniem wielkości liter), podczas kiedy w PHP 4 zwracana wartość zawiera jedynie małe litery. |
| __METHOD__ | Nazwa metody. (Dodano w PHP 5.0.0) Nazwa metody zwracana jest tak jak ją zadeklarowano (z uwzględnieniem wielkości liter). |
| __NAMESPACE__ | Nazwa aktualnej przestrzeni nazw (z uwzględnieniem wielkości liter). Ta stała definiowana jest w czasie kompilacji (Dodano w PHP 5.3.0). |
Zobacz także get_class(), get_object_vars(), file_exists() i function_exists().
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, wszystko będzie się dziać tak jak napisano wyżej.
Trochę bardziej złożonymi przykładami wyrażeń są funkcje. Przyjrzyj się poniższej funkcji:
<?php
function foo ()
{
return 5;
}
?>
Zakładając, że zapoznał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 (integer), wartości rzeczywiste (float 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ę.
PHP rozwija wyrażenia prawdopodobnie znacznie bardziej, niż wiele innych języków programowania. PHP jest językiem wyrażeń, co oznacza że prawie wszystko w nim 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 korzystania z wyrażeń jest pre- i postinkrementacja, a także dekrementacja. Użytkownicy PHP 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ą porównania. Wyrażenia te zwracają wartość FALSE lub TRUE. PHP obsługuje > (większy), >= (większy lub równy), == (równy), != (nie równy), < (mniejszy) i <= (mniejszy lub równy). Język obsługuje także zbiór operatorów ścisłego porównania: === (równy i tego samego typu) i !== (nie równy lub różnego typu). 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 z powrotem 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ą z powrotem 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:
<?php
$pierwsze ? $drugie : $trzecie
?>
Jeśli wartością pierwszego podwyrażenia jest TRUE (rózna od zera), to zwracany jest drugie podwyrażanie, i jest to wynik wyrażenia warunkowego. W przeciwnym wypadku, zwracana jest wartość trzeciego podwyrażenia.
Poniższy przykład powinien pomóc w lepszym zrozumieniu pre- i postinkrementacji i ogólnie koncepcji wyrażeń:
<?php
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 przed
inkrementacji, 2*6 = 12 do $f */
$g = double(++$e); /* przypisz podwojoną wartość $e po
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ą. Niektóre wyrażenia mogą być instrukcjami. Ten przypadek 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.
An operator is something that you feed with one or more values (or expressions, in programming jargon) which yields another value (so that the construction itself becomes an expression). So you can think of functions or constructions that return a value (like print) as operators and those that return nothing (like echo) as any other thing.
There are three types of operators. Firstly there is the unary operator which operates on only one value, for example ! (the negation operator) or ++ (the increment operator). The second group are termed binary operators; this group contains most of the operators that PHP supports, and a list follows below in the section Operator Precedence.
The third group is the ternary operator: ?:. It should be used to select between two expressions depending on a third one, rather than to select two sentences or paths of execution. Surrounding ternary expressions with parentheses is a very good idea.
The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18. If operator precedence is equal, left to right associativity is used.
The following table lists the precedence of operators with the highest-precedence operators listed at the top of the table. Operators on the same line have equal precedence, in which case their associativity decides which order to evaluate them in.
| Associativity | Operators | Additional Information |
|---|---|---|
| non-associative | clone new | clone and new |
| left | [ | array() |
| non-associative | ++ -- | increment/decrement |
| right | ~ - (int) (float) (string) (array) (object) (bool) @ | types |
| non-associative | instanceof | types |
| right | ! | logical |
| left | * / % | arithmetic |
| left | + - . | arithmetic i string |
| left | << >> | bitwise |
| non-associative | < <= > >= <> | comparison |
| non-associative | == != === !== | comparison |
| left | & | bitwise i references |
| left | ^ | bitwise |
| left | | | bitwise |
| left | && | logical |
| left | || | logical |
| left | ? : | ternary |
| right | = += -= *= /= .= %= &= |= ^= <<= >>= | assignment |
| left | and | logical |
| left | xor | logical |
| left | or | logical |
| left | , | many uses |
Left associativity means that the expression is evaluated from left to right, right associativity means the opposite.
Przykład #1 Associativity
<?php
$a = 3 * 3 % 5; // (3 * 3) % 5 = 4
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2
$a = 1;
$b = 2;
$a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5
?>
Use parentheses to increase readability of the code.
Informacja: Although = has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is put into $a.
Remember basic arithmetic from school? These work just like those.
| Example | Name | Result |
|---|---|---|
| -$a | Negation | Opposite of $a. |
| $a + $b | Addition | Sum of $a and $b. |
| $a - $b | Subtraction | Difference of $a and $b. |
| $a * $b | Multiplication | Product of $a and $b. |
| $a / $b | Division | Quotient of $a and $b. |
| $a % $b | Modulus | Remainder of $a divided by $b. |
The division operator ("/") returns a float value unless the two operands are integers (or strings that get converted to integers) and the numbers are evenly divisible, in which case an integer value will be returned.
Operands of modulus are converted to integers (by stripping the decimal part) before processing.
Informacja: Remainder $a % $b is negative for negative $a.
See also the manual page on Math functions.
The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the rights (that is, "gets set to").
The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3. This allows you to do some tricky things:
<?php
$a = ($b = 4) + 5; // $a is equal to 9 now, and $b has been set to 4.
?>
In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic, array union and string operators that allow you to use a value in an expression and then set its value to the result of that expression. For example:
<?php
$a = 3;
$a += 5; // sets $a to 8, as if we had said: $a = $a + 5;
$b = "Hello ";
$b .= "There!"; // sets $b to "Hello There!", just like $b = $b . "There!";
?>
Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. This may also have relevance if you need to copy something like a large array inside a tight loop. Assignment by reference is also supported, using the $var = &$othervar; syntax. 'Assignment by reference' means that both variables end up pointing at the same data, and nothing is copied anywhere. To learn more about references, please read References explained. As of PHP 5, objects are assigned by reference unless explicitly told otherwise with the new clone keyword.
Bitwise operators allow evaluation and manipulation of specific bits within an integer.
| Example | Name | Result |
|---|---|---|
$a & $b
|
And | Bits that are set in both $a and $b are set. |
$a | $b
|
Or (inclusive or) | Bits that are set in either $a or $b are set. |
$a ^ $b
|
Xor (exclusive or) | Bits that are set in $a or $b but not both are set. |
~ $a
|
Not | Bits that are set in $a are not set, and vice versa. |
$a << $b
|
Shift left | Shift the bits of $a $b steps to the left (each step means "multiply by two") |
$a >> $b
|
Shift right | Shift the bits of $a $b steps to the right (each step means "divide by two") |
Bit shifting in PHP is arithmetic. Bits shifted off either end are discarded. Left shifts have zeros shifted in on the right while the sign bit is shifted out on the left, meaning the sign of an operand is not preserved. Right shifts have copies of the sign bit shifted in on the left, meaning the sign of an operand is preserved.
Use parentheses to ensure the desired precedence. For example, $a & $b == true evaluates the equivalency then the bitwise and; while ($a & $b) == true evaluates the bitwise and then the equivalency.
Be aware of data type conversions. If both the left-hand and right-hand parameters are strings, the bitwise operator will operate on the characters' ASCII values.
PHP's error_reporting ini setting uses bitwise values,
providing a real-world demonstration of turning
bits off. To show all errors, except for notices,
the php.ini file instructions say to use:
E_ALL & ~E_NOTICE
This works by starting with E_ALL: 00000000000000000111011111111111 Then taking the value of E_NOTICE... 00000000000000000000000000001000 ... and inverting it via ~: 11111111111111111111111111110111 Finally, it uses AND (&) to find the bits turned on in both values: 00000000000000000111011111110111
Another way to accomplish that is using XOR (^)
to find bits that are on in only one value or the other:
E_ALL ^ E_NOTICE
error_reporting can also be used to demonstrate turning bits on.
The way to show just errors and recoverable errors is:
E_ERROR | E_RECOVERABLE_ERROR
This process combines E_ERROR 00000000000000000000000000000001 and 00000000000000000001000000000000 using the OR (|) operator to get the bits turned on in either value: 00000000000000000001000000000001
Przykład #1 Bitwise AND, OR and XOR operations on integers
<?php
/*
* Ignore the top section,
* it is just formatting to make output clearer.
*/
$format = '(%1$2d = %1$04b) = (%2$2d = %2$04b)'
. ' %3$s (%4$2d = %4$04b)' . "\n";
echo <<<EOH
--------- --------- -- ---------
result value op test
--------- --------- -- ---------
EOH;
/*
* Here are the examples.
*/
$values = array(0, 1, 2, 4, 8);
$test = 1 + 4;
echo "\n Bitwise AND \n";
foreach ($values as $value) {
$result = $value & $test;
printf($format, $result, $value, '&', $test);
}
echo "\n Bitwise Inclusive OR \n";
foreach ($values as $value) {
$result = $value | $test;
printf($format, $result, $value, '|', $test);
}
echo "\n Bitwise Exclusive OR (XOR) \n";
foreach ($values as $value) {
$result = $value ^ $test;
printf($format, $result, $value, '^', $test);
}
?>
Powyższy przykład wyświetli:
--------- --------- -- --------- result value op test --------- --------- -- --------- Bitwise AND ( 0 = 0000) = ( 0 = 0000) & ( 5 = 0101) ( 1 = 0001) = ( 1 = 0001) & ( 5 = 0101) ( 0 = 0000) = ( 2 = 0010) & ( 5 = 0101) ( 4 = 0100) = ( 4 = 0100) & ( 5 = 0101) ( 0 = 0000) = ( 8 = 1000) & ( 5 = 0101) Bitwise Inclusive OR ( 5 = 0101) = ( 0 = 0000) | ( 5 = 0101) ( 5 = 0101) = ( 1 = 0001) | ( 5 = 0101) ( 7 = 0111) = ( 2 = 0010) | ( 5 = 0101) ( 5 = 0101) = ( 4 = 0100) | ( 5 = 0101) (13 = 1101) = ( 8 = 1000) | ( 5 = 0101) Bitwise Exclusive OR (XOR) ( 5 = 0101) = ( 0 = 0000) ^ ( 5 = 0101) ( 4 = 0100) = ( 1 = 0001) ^ ( 5 = 0101) ( 7 = 0111) = ( 2 = 0010) ^ ( 5 = 0101) ( 1 = 0001) = ( 4 = 0100) ^ ( 5 = 0101) (13 = 1101) = ( 8 = 1000) ^ ( 5 = 0101)
Przykład #2 Bitwise XOR operations on strings
<?php
echo 12 ^ 9; // Outputs '5'
echo "12" ^ "9"; // Outputs the Backspace character (ascii 8)
// ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8
echo "hallo" ^ "hello"; // Outputs the ascii values #0 #4 #0 #0 #0
// 'a' ^ 'e' = #4
echo 2 ^ "3"; // Outputs 1
// 2 ^ ((int)"3") == 1
echo "2" ^ 3; // Outputs 1
// ((int)"2") ^ 3 == 1
?>
Przykład #3 Bit shifting on integers
<?php
/*
* Here are the examples.
*/
echo "\n--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---\n";
$val = 4;
$places = 1;
$res = $val >> $places;
p($res, $val, '>>', $places, 'copy of sign bit shifted into left side');
$val = 4;
$places = 2;
$res = $val >> $places;
p($res, $val, '>>', $places);
$val = 4;
$places = 3;
$res = $val >> $places;
p($res, $val, '>>', $places, 'bits shift out right side');
$val = 4;
$places = 4;
$res = $val >> $places;
p($res, $val, '>>', $places, 'same result as above; can not shift beyond 0');
echo "\n--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---\n";
$val = -4;
$places = 1;
$res = $val >> $places;
p($res, $val, '>>', $places, 'copy of sign bit shifted into left side');
$val = -4;
$places = 2;
$res = $val >> $places;
p($res, $val, '>>', $places, 'bits shift out right side');
$val = -4;
$places = 3;
$res = $val >> $places;
p($res, $val, '>>', $places, 'same result as above; can not shift beyond -1');
echo "\n--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---\n";
$val = 4;
$places = 1;
$res = $val << $places;
p($res, $val, '<<', $places, 'zeros fill in right side');
$val = 4;
$places = (PHP_INT_SIZE * 8) - 4;
$res = $val << $places;
p($res, $val, '<<', $places);
$val = 4;
$places = (PHP_INT_SIZE * 8) - 3;
$res = $val << $places;
p($res, $val, '<<', $places, 'sign bits get shifted out');
$val = 4;
$places = (PHP_INT_SIZE * 8) - 2;
$res = $val << $places;
p($res, $val, '<<', $places, 'bits shift out left side');
echo "\n--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---\n";
$val = -4;
$places = 1;
$res = $val << $places;
p($res, $val, '<<', $places, 'zeros fill in right side');
$val = -4;
$places = (PHP_INT_SIZE * 8) - 3;
$res = $val << $places;
p($res, $val, '<<', $places);
$val = -4;
$places = (PHP_INT_SIZE * 8) - 2;
$res = $val << $places;
p($res, $val, '<<', $places, 'bits shift out left side, including sign bit');
/*
* Ignore this bottom section,
* it is just formatting to make output clearer.
*/
function p($res, $val, $op, $places, $note = '') {
$format = '%0' . (PHP_INT_SIZE * 8) . "b\n";
printf("Expression: %d = %d %s %d\n", $res, $val, $op, $places);
echo " Decimal:\n";
printf(" val=%d\n", $val);
printf(" res=%d\n", $res);
echo " Binary:\n";
printf(' val=' . $format, $val);
printf(' res=' . $format, $res);
if ($note) {
echo " NOTE: $note\n";
}
echo "\n";
}
?>
Wyświetla następujący przykład na systemach 32 bitowych:
--- BIT SHIFT RIGHT ON POSITIVE INTEGERS --- Expression: 2 = 4 >> 1 Decimal: val=4 res=2 Binary: val=00000000000000000000000000000100 res=00000000000000000000000000000010 NOTE: copy of sign bit shifted into left side Expression: 1 = 4 >> 2 Decimal: val=4 res=1 Binary: val=00000000000000000000000000000100 res=00000000000000000000000000000001 Expression: 0 = 4 >> 3 Decimal: val=4 res=0 Binary: val=00000000000000000000000000000100 res=00000000000000000000000000000000 NOTE: bits shift out right side Expression: 0 = 4 >> 4 Decimal: val=4 res=0 Binary: val=00000000000000000000000000000100 res=00000000000000000000000000000000 NOTE: same result as above; can not shift beyond 0 --- BIT SHIFT RIGHT ON NEGATIVE INTEGERS --- Expression: -2 = -4 >> 1 Decimal: val=-4 res=-2 Binary: val=11111111111111111111111111111100 res=11111111111111111111111111111110 NOTE: copy of sign bit shifted into left side Expression: -1 = -4 >> 2 Decimal: val=-4 res=-1 Binary: val=11111111111111111111111111111100 res=11111111111111111111111111111111 NOTE: bits shift out right side Expression: -1 = -4 >> 3 Decimal: val=-4 res=-1 Binary: val=11111111111111111111111111111100 res=11111111111111111111111111111111 NOTE: same result as above; can not shift beyond -1 --- BIT SHIFT LEFT ON POSITIVE INTEGERS --- Expression: 8 = 4 << 1 Decimal: val=4 res=8 Binary: val=00000000000000000000000000000100 res=00000000000000000000000000001000 NOTE: zeros fill in right side Expression: 1073741824 = 4 << 28 Decimal: val=4 res=1073741824 Binary: val=00000000000000000000000000000100 res=01000000000000000000000000000000 Expression: -2147483648 = 4 << 29 Decimal: val=4 res=-2147483648 Binary: val=00000000000000000000000000000100 res=10000000000000000000000000000000 NOTE: sign bits get shifted out Expression: 0 = 4 << 30 Decimal: val=4 res=0 Binary: val=00000000000000000000000000000100 res=00000000000000000000000000000000 NOTE: bits shift out left side --- BIT SHIFT LEFT ON NEGATIVE INTEGERS --- Expression: -8 = -4 << 1 Decimal: val=-4 res=-8 Binary: val=11111111111111111111111111111100 res=11111111111111111111111111111000 NOTE: zeros fill in right side Expression: -2147483648 = -4 << 29 Decimal: val=-4 res=-2147483648 Binary: val=11111111111111111111111111111100 res=10000000000000000000000000000000 Expression: 0 = -4 << 30 Decimal: val=-4 res=0 Binary: val=11111111111111111111111111111100 res=00000000000000000000000000000000 NOTE: bits shift out left side, including sign bit
Wyświetla następujący przykład na systemach 64 bitowych:
--- BIT SHIFT RIGHT ON POSITIVE INTEGERS --- Expression: 2 = 4 >> 1 Decimal: val=4 res=2 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000000010 NOTE: copy of sign bit shifted into left side Expression: 1 = 4 >> 2 Decimal: val=4 res=1 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000000001 Expression: 0 = 4 >> 3 Decimal: val=4 res=0 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000000000 NOTE: bits shift out right side Expression: 0 = 4 >> 4 Decimal: val=4 res=0 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000000000 NOTE: same result as above; can not shift beyond 0 --- BIT SHIFT RIGHT ON NEGATIVE INTEGERS --- Expression: -2 = -4 >> 1 Decimal: val=-4 res=-2 Binary: val=1111111111111111111111111111111111111111111111111111111111111100 res=1111111111111111111111111111111111111111111111111111111111111110 NOTE: copy of sign bit shifted into left side Expression: -1 = -4 >> 2 Decimal: val=-4 res=-1 Binary: val=1111111111111111111111111111111111111111111111111111111111111100 res=1111111111111111111111111111111111111111111111111111111111111111 NOTE: bits shift out right side Expression: -1 = -4 >> 3 Decimal: val=-4 res=-1 Binary: val=1111111111111111111111111111111111111111111111111111111111111100 res=1111111111111111111111111111111111111111111111111111111111111111 NOTE: same result as above; can not shift beyond -1 --- BIT SHIFT LEFT ON POSITIVE INTEGERS --- Expression: 8 = 4 << 1 Decimal: val=4 res=8 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000001000 NOTE: zeros fill in right side Expression: 4611686018427387904 = 4 << 60 Decimal: val=4 res=4611686018427387904 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=0100000000000000000000000000000000000000000000000000000000000000 Expression: -9223372036854775808 = 4 << 61 Decimal: val=4 res=-9223372036854775808 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=1000000000000000000000000000000000000000000000000000000000000000 NOTE: sign bits get shifted out Expression: 0 = 4 << 62 Decimal: val=4 res=0 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000000000 NOTE: bits shift out left side --- BIT SHIFT LEFT ON NEGATIVE INTEGERS --- Expression: -8 = -4 << 1 Decimal: val=-4 res=-8 Binary: val=1111111111111111111111111111111111111111111111111111111111111100 res=1111111111111111111111111111111111111111111111111111111111111000 NOTE: zeros fill in right side Expression: -9223372036854775808 = -4 << 61 Decimal: val=-4 res=-9223372036854775808 Binary: val=1111111111111111111111111111111111111111111111111111111111111100 res=1000000000000000000000000000000000000000000000000000000000000000 Expression: 0 = -4 << 62 Decimal: val=-4 res=0 Binary: val=1111111111111111111111111111111111111111111111111111111111111100 res=0000000000000000000000000000000000000000000000000000000000000000 NOTE: bits shift out left side, including sign bit
Don't right shift for more than 32 bits on 32 bits systems. Don't left shift in case it results to number longer than 32 bits. Use functions from the gmp extension for bitwise manipulation on numbers beyond PHP_INT_MAX.
See also pack(), unpack(), gmp_and(), gmp_or(), gmp_xor(), gmp_testbit(), gmp_clrbit()
Comparison operators, as their name implies, allow you to compare two values. You may also be interested in viewing the type comparison tables, as they show examples of various type related comparisons.
| Example | Name | Result |
|---|---|---|
| $a == $b | Equal | TRUE if $a is equal to $b. |
| $a === $b | Identical | TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4) |
| $a != $b | Not equal | TRUE if $a is not equal to $b. |
| $a <> $b | Not equal | TRUE if $a is not equal to $b. |
| $a !== $b | Not identical | TRUE if $a is not equal to $b, or they are not of the same type. (introduced in PHP 4) |
| $a < $b | Less than | TRUE if $a is strictly less than $b. |
| $a > $b | Greater than | TRUE if $a is strictly greater than $b. |
| $a <= $b | Less than or equal to | TRUE if $a is less than or equal to $b. |
| $a >= $b | Greater than or equal to | TRUE if $a is greater than or equal to $b. |
If you compare an integer with a string, the string is converted to a number. If you compare two numerical strings, they are compared as integers. These rules also apply to the switch statement.
<?php
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("1" == "1e0"); // 1 == 1 -> true
switch ("a") {
case 0:
echo "0";
break;
case "a": // never reached because "a" is already matched with 0
echo "a";
break;
}
?>
For various types, comparison is done according to the following table (in order).
| Type of Operand 1 | Type of Operand 2 | Result |
|---|---|---|
| null or string | string | Convert NULL to "", numerical or lexical comparison |
| bool or null | anything | Convert to bool, FALSE < TRUE |
| object | object | Built-in classes can define its own comparison, different classes are uncomparable, same class - compare properties the same way as arrays (PHP 4), PHP 5 has its own explanation |
| string, resource or number | string, resource or number | Translate strings and resources to numbers, usual math |
| array | array | Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are uncomparable, otherwise - compare value by value (see following example) |
| array | anything | array is always greater |
| object | anything | object is always greater |
Przykład #1 Transcription of standard array comparison
<?php
// Arrays are compared like this with standard comparison operators
function standard_array_compare($op1, $op2)
{
if (count($op1) < count($op2)) {
return -1; // $op1 < $op2
} elseif (count($op1) > count($op2)) {
return 1; // $op1 > $op2
}
foreach ($op1 as $key => $val) {
if (!array_key_exists($key, $op2)) {
return null; // uncomparable
} elseif ($val < $op2[$key]) {
return -1;
} elseif ($val > $op2[$key]) {
return 1;
}
}
return 0; // $op1 == $op2
}
?>
See also strcasecmp(), strcmp(), Array operators, and the manual section on Types.
Another conditional operator is the "?:" (or ternary) operator.
Przykład #2 Assigning a default value
<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
// The above is identical to this if/else statement
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}
?>
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
Informacja: Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.
Informacja: It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious:
Przykład #3 Non-obvious Ternary Behaviour
<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');
// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right
// the following is a more obvious version of the same code as above
echo ((true ? 'true' : 'false') ? 't' : 'f');
// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>
PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.
If the track_errors feature is enabled, any error message generated by the expression will be saved in the variable $php_errormsg. This variable will be overwritten on each error, so check early if you want to use it.
<?php
/* Intentional file error */
$my_file = @file ('non_existent_file') or
die ("Failed opening file: error was '$php_errormsg'");
// this works for any expression, not just functions:
$value = @$cache[$key];
// will not issue a notice if the index $key doesn't exist.
?>
Informacja: The @-operator works only on expressions. A simple rule of thumb is: if you can take the value of something, you can prepend the @ operator to it. For instance, you can prepend it to variables, function and include() calls, constants, and so forth. You cannot prepend it to function or class definitions, or conditional structures such as if and foreach, and so forth.
See also error_reporting() and the manual section for Error Handling and Logging functions.
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.
PHP supports one execution operator: backticks (``). Note that these are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned (i.e., it won't simply be dumped to output; it can be assigned to a variable). Use of the backtick operator is identical to shell_exec().
<?php
$output = `ls -al`;
echo "<pre>$output</pre>";
?>
Informacja: The backtick operator is disabled when tryb bezpieczny is enabled or shell_exec() is disabled.
See also the manual section on Program Execution functions, popen() proc_open(), and Using PHP from the commandline.
PHP supports C-style pre- and post-increment and decrement operators.
Informacja: The increment/decrement operators do not affect boolean values. Decrementing NULL values has no effect too, but incrementing them results in 1.
| Example | Name | Effect |
|---|---|---|
| ++$a | Pre-increment | Increments $a by one, then returns $a. |
| $a++ | Post-increment | Returns $a, then increments $a by one. |
| --$a | Pre-decrement | Decrements $a by one, then returns $a. |
| $a-- | Post-decrement | Returns $a, then decrements $a by one. |
Here's a simple example script:
<?php
echo "<h3>Postincrement</h3>";
$a = 5;
echo "Should be 5: " . $a++ . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";
echo "<h3>Preincrement</h3>";
$a = 5;
echo "Should be 6: " . ++$a . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";
echo "<h3>Postdecrement</h3>";
$a = 5;
echo "Should be 5: " . $a-- . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
echo "<h3>Predecrement</h3>";
$a = 5;
echo "Should be 4: " . --$a . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
?>
PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in Perl 'Z'+1 turns into 'AA', while in C 'Z'+1 turns into '[' ( ord('Z') == 90, ord('[') == 91 ). Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.
Przykład #1 Arithmetic Operations on Character Variables
<?php
$i = 'W';
for ($n=0; $n<6; $n++) {
echo ++$i . "\n";
}
?>
Powyższy przykład wyświetli:
X Y Z AA AB AC
Incrementing or decrementing booleans has no effect.
| Example | Name | Result |
|---|---|---|
| $a and $b | And | TRUE if both $a and $b are TRUE. |
| $a or $b | Or | TRUE if either $a or $b is TRUE. |
| $a xor $b | Xor | TRUE if either $a or $b is TRUE, but not both. |
| ! $a | Not | TRUE if $a is not TRUE. |
| $a && $b | And | TRUE if both $a and $b are TRUE. |
| $a || $b | Or | TRUE if either $a or $b is TRUE. |
The reason for the two different variations of "and" and "or" operators is that they operate at different precedences. (See Operator Precedence.)
Przykład #1 Logical operators illustrated
<?php
// --------------------
// foo() will never get called as those operators are short-circuit
$a = (false && foo());
$b = (true || foo());
$c = (false and foo());
$d = (true or foo());
// --------------------
// "||" has a greater precedence than "or"
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f and then true is ignored
// Acts like: (($e = false) or true)
$f = false or true;
var_dump($e, $f);
// --------------------
// "&&" has a greater precedence than "and"
// The result of the expression (true && false) is assigned to $g
// Acts like: ($g = (true && false))
$g = true && false;
// The constant true is assigned to $h and then false is ignored
// Acts like: (($h = true) and false)
$h = true and false;
var_dump($g, $h);
?>
Powyższy przykład wyświetli coś podobnego do:
bool(true) bool(false) bool(false) bool(true)
There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends the argument on the right side to the argument on the left side. Please read Assignment Operators for more information.
<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
$a = "Hello ";
$a .= "World!"; // now $a contains "Hello World!"
?>
See also the manual sections on the String type and String functions.
| Example | Name | Result |
|---|---|---|
| $a + $b | Union | Union of $a and $b. |
| $a == $b | Equality | TRUE if $a and $b have the same key/value pairs. |
| $a === $b | Identity | TRUE if $a and $b have the same key/value pairs in the same order and of the same types. |
| $a != $b | Inequality | TRUE if $a is not equal to $b. |
| $a <> $b | Inequality | TRUE if $a is not equal to $b. |
| $a !== $b | Non-identity | TRUE if $a is not identical to $b. |
The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.
<?php
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
var_dump($c);
$c = $b + $a; // Union of $b and $a
echo "Union of \$b and \$a: \n";
var_dump($c);
?>
When executed, this script will print the following:
Union of $a and $b:
array(3) {
["a"]=>
string(5) "apple"
["b"]=>
string(6) "banana"
["c"]=>
string(6) "cherry"
}
Union of $b and $a:
array(3) {
["a"]=>
string(4) "pear"
["b"]=>
string(10) "strawberry"
["c"]=>
string(6) "cherry"
}
Elements of arrays are equal for the comparison if they have the same key and value.
Przykład #1 Comparing arrays
<?php
$a = array("apple", "banana");
$b = array(1 => "banana", "0" => "apple");
var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>
See also the manual sections on the Array type and Array functions.
instanceof is used to determine whether a PHP variable is an instantiated object of a certain class:
Przykład #1 Using instanceof with classes
<?php
class MyClass
{
}
class NotMyClass
{
}
$a = new MyClass;
var_dump($a instanceof MyClass);
var_dump($a instanceof NotMyClass);
?>
Powyższy przykład wyświetli:
bool(true) bool(false)
instanceof can also be used to determine whether a variable is an instantiated object of a class that inherits from a parent class:
Przykład #2 Using instanceof with inherited classes
<?php
class ParentClass
{
}
class MyClass extends ParentClass
{
}
$a = new MyClass;
var_dump($a instanceof MyClass);
var_dump($a instanceof ParentClass);
?>
Powyższy przykład wyświetli:
bool(true) bool(true)
To check if an object is not an instanceof a class, the logical not operator can be used.
Przykład #3 Using instanceof to check if object is not an instanceof a class
<?php
class MyClass
{
}
$a = new MyClass;
var_dump(!($a instanceof stdClass));
?>
Powyższy przykład wyświetli:
bool(true)
Lastly, instanceof can also be used to determine whether a variable is an instantiated object of a class that implements an interface:
Przykład #4 Using instanceof for class
<?php
interface MyInterface
{
}
class MyClass implements MyInterface
{
}
$a = new MyClass;
var_dump($a instanceof MyClass);
var_dump($a instanceof MyInterface);
?>
Powyższy przykład wyświetli:
bool(true) bool(true)
Although instanceof is usually used with a literal classname, it can also be used with another object or a string variable:
Przykład #5 Using instanceof with other variables
<?php
interface MyInterface
{
}
class MyClass implements MyInterface
{
}
$a = new MyClass;
$b = new MyClass;
$c = 'MyClass';
$d = 'NotMyClass';
var_dump($a instanceof $b); // $b is an object of class MyClass
var_dump($a instanceof $c); // $c is a string 'MyClass'
var_dump($a instanceof $d); // $d is a string 'NotMyClass'
?>
Powyższy przykład wyświetli:
bool(true) bool(true) bool(false)
There are a few pitfalls to be aware of. Before PHP version 5.1.0, instanceof would call __autoload() if the class name did not exist. In addition, if the class was not loaded, a fatal error would occur. This can be worked around by using a dynamic class reference, or a string variable containing the class name:
Przykład #6 Avoiding classname lookups and fatal errors with instanceof in PHP 5.0
<?php
$d = 'NotMyClass';
var_dump($a instanceof $d); // no fatal error here
?>
Powyższy przykład wyświetli:
bool(false)
The instanceof operator was introduced in PHP 5. Before this time is_a() was used but is_a() has since been deprecated in favor of instanceof. Note that as of PHP 5.3.0, is_a() is no longer deprecated.
See also get_class() and is_a().
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 or 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:
if (expr) statement
As described in the section about expressions, expression is evaluated to its Boolean value. If expression 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:
<?php
if ($a > $b)
echo "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:
<?php
if ($a > $b) {
echo "a is bigger than b";
$b = $a;
}
?>
If statements can be nested infinitely 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 greater than b if $a is greater than $b, and a is NOT greater than b otherwise:
<?php
if ($a > $b) {
echo "a is greater than b";
} else {
echo "a is NOT greater than b";
}
?>
The else statement is only executed if the if expression evaluated to FALSE, and if there were any elseif expressions - only if they evaluated to FALSE as well (see elseif).
elseif, 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:
<?php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "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.
Informacja: Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define your if/elseif conditions, you must not separate else if into two words, or PHP will fail with a parse error.
<?php
/* Incorrect Method: */
if($a > $b):
echo $a." is greater than ".$b;
else if($a == $b): // Will not compile.
echo "The above line causes a parse error.";
endif;
/* Correct Method: */
if($a > $b):
echo $a." is greater than ".$b;
elseif($a == $b): // Note the combination of the words.
echo $a." equals ".$b;
else:
echo $a." is neither greater than or equal to ".$b;
endif;
?>
PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.
<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>
In the above example, the HTML block "A is equal to 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:
<?php
if ($a == 5):
echo "a equals 5";
echo "...";
elseif ($a == 6):
echo "a equals 6";
echo "!!!";
else:
echo "a is neither 5 nor 6";
endif;
?>
while loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is:
while (expr)
statement
The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once.
Like with the if statement, you can group multiple statements within the same while loop by surrounding a group of statements with curly braces, or by using the alternate syntax:
while (expr):
statement
...
endwhile;
The following examples are identical, and both print the numbers 1 through 10:
<?php
/* example 1 */
$i = 1;
while ($i <= 10) {
echo $i++; /* the printed value would be
$i before the increment
(post-increment) */
}
/* example 2 */
$i = 1;
while ($i <= 10):
echo $i;
$i++;
endwhile;
?>
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 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:
<?php
$i = 0;
do {
echo $i;
} while ($i > 0);
?>
The above loop would run one time exactly, since after the first iteration, when truth expression is checked, it evaluates to FALSE ($i is not bigger than 0) and the loop execution ends.
Advanced C users may be familiar with a different usage of the do-while loop, to allow stopping execution in the middle of code blocks, by encapsulating them with do-while (0), and using the break statement. The following code fragment demonstrates this:
<?php
do {
if ($i < 5) {
echo "i is not big enough";
break;
}
$i *= $factor;
if ($i < $minimum_limit) {
break;
}
echo "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'. Since PHP 5.3.0, it is possible to use goto operator instead of this hack.
for loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is:
for (expr1; expr2; expr3)
statement
The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.
In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.
At the end of each iteration, expr3 is evaluated (executed).
Each of the expressions can be empty or contain multiple expressions separated by commas. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part. 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 the numbers 1 through 10:
<?php
/* example 1 */
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
/* example 2 */
for ($i = 1; ; $i++) {
if ($i > 10) {
break;
}
echo $i;
}
/* example 3 */
$i = 1;
for (; ; ) {
if ($i > 10) {
break;
}
echo $i;
$i++;
}
/* example 4 */
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
?>
Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in for loops comes in handy in many occasions.
PHP also supports the alternate "colon syntax" for for loops.
for (expr1; expr2; expr3):
statement
...
endfor;
Its a common thing to many users to iterate though arrays like in the example below.
<?php
/*
* This is an array with some data we want to modify
* when running through the for loop.
*/
$people = Array(
Array('name' => 'Kalle', 'salt' => 856412),
Array('name' => 'Pierre', 'salt' => 215863)
);
for($i = 0; $i < sizeof($people); ++$i)
{
$people[$i]['salt'] = rand(000000, 999999);
}
?>
The problem lies in the second for expression. This code can be slow because it has to calculate the size of the array on each iteration. Since the size never change, it can be optimized easily using an intermediate variable to store the size and use in the loop instead of sizeof. The example below illustrates this:
<?php
$people = Array(
Array('name' => 'Kalle', 'salt' => 856412),
Array('name' => 'Pierre', 'salt' => 215863)
);
for($i = 0, $size = sizeof($people); $i < $size; ++$i)
{
$people[$i]['salt'] = rand(000000, 999999);
}
?>
PHP 4 introduced a foreach construct, much like Perl and some other languages. This simply gives an easy way to iterate over arrays. foreach works only on arrays, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes; the second is a minor but useful extension of the first:
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement
The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element).
The second form does the same thing, except that the current element's key will be assigned to the variable $key on each loop.
As of PHP 5, it is possible to iterate objects too.
Informacja: 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.
Informacja: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.
As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>
This is possible only if iterated array can be referenced (i.e. is variable), that means the following code won't work:
<?php
foreach (array(1, 2, 3, 4) as &$value) {
$value = $value * 2;
}
?>
Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().
Informacja: foreach does not support the ability to suppress error messages using '@'.
You may have noticed that the following are functionally identical:
<?php
$arr = array("one", "two", "three");
reset($arr);
while (list(, $value) = each($arr)) {
echo "Value: $value<br />\n";
}
foreach ($arr as $value) {
echo "Value: $value<br />\n";
}
?>
The following are also functionally identical:
<?php
$arr = array("one", "two", "three");
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:
<?php
/* foreach example 1: value only */
$a = array(1, 2, 3, 17);
foreach ($a as $v) {
echo "Current value of \$a: $v.\n";
}
/* foreach example 2: value (with its manual access notation printed for illustration) */
$a = array(1, 2, 3, 17);
$i = 0; /* for illustrative purposes only */
foreach ($a as $v) {
echo "\$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) {
echo "\$a[$k] => $v.\n";
}
/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";
foreach ($a as $v1) {
foreach ($v1 as $v2) {
echo "$v2\n";
}
}
/* foreach example 5: dynamic arrays */
foreach (array(1, 2, 3, 4, 5) as $v) {
echo "$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.
<?php
$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 condition evaluation and then the beginning of the next iteration.
Informacja: Note that in PHP the switch statement is considered a looping structure for the purposes of continue.
continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.
<?php
while (list($key, $value) = each($arr)) {
if (!($key % 2)) { // skip odd members
continue;
}
do_something_odd($value);
}
$i = 0;
while ($i++ < 5) {
echo "Outer<br />\n";
while (1) {
echo " Middle<br />\n";
while (1) {
echo " Inner<br />\n";
continue 3;
}
echo "This never gets output.<br />\n";
}
echo "Neither does this.<br />\n";
}
?>
Omitting the semicolon after continue can lead to confusion. Here's an example of what you shouldn't do.
<?php
for ($i = 0; $i < 5; ++$i) {
if ($i == 2)
continue
print "$i\n";
}
?>
One can expect the result to be :
0 1 3 4
but this script will output :
2
because the return value of the print() call is int(1), and it will look like the optional numeric argument mentioned above.
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.
Informacja: Note that unlike some other languages, the continue statement applies to switch and acts similar to break. If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2.
Informacja: Note that switch/case does loose comparision.
The following two examples are two different ways to write the same thing, one using a series of if and elseif statements, and the other using the switch statement:
Przykład #1 switch structure
<?php
if ($i == 0) {
echo "i equals 0";
} elseif ($i == 1) {
echo "i equals 1";
} elseif ($i == 2) {
echo "i equals 2";
}
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
?>
Przykład #2 switch structure allows usage of strings
<?php
switch ($i) {
case "apple":
echo "i is apple";
break;
case "bar":
echo "i is bar";
break;
case "cake":
echo "i is cake";
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:
<?php
switch ($i) {
case 0:
echo "i equals 0";
case 1:
echo "i equals 1";
case 2:
echo "i equals 2";
}
?>
Here, if $i is equal to 0, PHP would execute all of the echo statements! If $i is equal to 1, PHP would execute the last two echo statements. You would get the expected behavior ('i equals 2' would be displayed) only if $i is equal to 2. Thus, it is 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.
<?php
switch ($i) {
case 0:
case 1:
case 2:
echo "i is less than 3 but not negative";
break;
case 3:
echo "i is 3";
}
?>
A special case is the default case. This case matches anything that wasn't matched by the other cases. For example:
<?php
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
}
?>
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.
<?php
switch ($i):
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
endswitch;
?>
Its possible to use a semicolon instead of a colon after a case like:
<?php
switch($beer)
{
case 'tuborg';
case 'carlsberg';
case 'heineken';
echo 'Good choice';
break;
default;
echo 'Please make a new selection...';
break;
}
?>
The declare construct is used to set execution directives for a block of code. The syntax of declare is similar to the syntax of other flow control constructs:
declare (directive)
statement
The directive section allows the behavior of the declare block to be set. Currently only two directives are recognized: the ticks directive (See below for more information on the ticks directive) and the encoding directive (See below for more information on the encoding directive).
Informacja: The encoding directive was added in PHP 5.3.0
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.
The declare construct can also be used in the global scope, affecting all code following it (however if the file with declare was included then it does not affect the parent file).
<?php
// these are the same:
// you can use this:
declare(ticks=1) {
// entire script here
}
// or you can use this:
declare(ticks=1);
// entire script here
?>
A tick is an event that occurs for every
N low-level tickable 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.
Not all statements are tickable. Typically, condition expressions and argument expressions are not tickable.
The event(s) that occur on each tick are 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 #1 Tick usage example
<?php
declare(ticks=1);
// A function called on each tick event
function tick_handler()
{
echo "tick_handler() called\n";
}
register_tick_function('tick_handler');
$a = 1;
if ($a > 0) {
$a += 2;
print($a);
}
?>
Przykład #2 Ticks usage example
<?php
function tick_handler()
{
echo "tick_handler() called\n";
}
$a = 1;
tick_handler();
if ($a > 0) {
$a += 2;
tick_handler();
print($a);
tick_handler();
}
tick_handler();
?>
See also register_tick_function() and unregister_tick_function().
A script's encoding can be specified per-script using the encoding directive.
Przykład #3 Declaring an encoding for the script.
<?php
declare(encoding='ISO-8859-1');
// code here
?>
When combined with namespaces, the only legal syntax for declare is declare(encoding='...'); where ... is the encoding value. declare(encoding='...') {} will result in a parse error when combined with namespaces.
The encoding declare value is ignored in PHP 5.3 unless php is compiled with --enable-zend-multibyte. In PHP 6.0, the encoding directive will be used to inform the scanner what encoding the file is created in. Legal values are encoding names such as UTF-8.
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 php.ini, then that script file's execution is ended.
For more information, see Returning values.
Informacja: Note that since return() is a language construct and not a function, the parentheses surrounding its arguments are not required. It is common to leave them out, and you actually should do so as PHP has less work to do in this case.
Informacja: If no parameter is supplied, then the parentheses must be omitted and NULL will be returned. Calling return() with parentheses but with no arguments will result in a parse error.
Informacja: You should never use parentheses around your return variable when returning by reference, as this will not work. You can only return variables by reference, not the result of a statement. If you use return ($a); then you're not returning a variable, but the result of the expression ($a) (which is, of course, the value of $a).
require() is identical to include() except upon failure it will also produce a fatal E_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.
See the include() documentation for how this works.
The include() statement includes and evaluates the specified file.
The documentation below also applies to require().
Files are included based on the file path given or, if none is given, the include_path specified. The include() construct will emit a warning if it cannot find a file; this is different behavior from require(), which will emit a fatal error.
If a path is defined (full or relative), the include_path will be ignored altogether. For example, if a filename begins with ../, the parser will look in the parent directory to find the requested file.
For more information on how PHP handles including files and the include path, see the documentation for include_path.
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. However, all functions and classes defined in the included file have the global scope.
Przykład #1 Basic include() example
vars.php
<?php
$color = 'green';
$fruit = 'apple';
?>
test.php
<?php
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A green apple
?>
If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function. An exception to this rule are magic constants which are evaluated by the parser before the include occurs.
Przykład #2 Including within functions
<?php
function foo()
{
global $color;
include 'vars.php';
echo "A $color $fruit";
}
/* vars.php is in the scope of foo() so *
* $fruit is NOT available outside of this *
* scope. $color is because we declared it *
* as global. */
foo(); // A green apple
echo "A $color $fruit"; // A green
?>
When a file is included, parsing drops out of PHP mode and into HTML mode at the beginning of the target file, and resumes again at the end. For this reason, any code inside the target file which should be executed as PHP code must be enclosed within valid PHP start and end tags.
If "URL fopen wrappers" are enabled in PHP (which they are in the default configuration), you can specify the file to be included using a URL (via HTTP or other supported wrapper - see List of Supported Protocols/Wrappers for a list of protocols) 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 a 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.
PHP w wersji starszej niż 4.3.0, pracujące pod kontrolą systemów Windows, nie obsługują dostępu do zdalnych plików w tej funkcji, nawet jeśli opcja allow_url_fopen jest włączona.
Przykład #3 include() through HTTP
<?php
/* This example assumes that www.example.com is configured to parse .php
* files and not .txt files. Also, 'Works' here means that the variables
* $foo and $bar are available within the included file. */
// Won't work; file.txt wasn't handled by www.example.com as PHP
include 'http://www.example.com/file.txt?foo=1&bar=2';
// Won't work; looks for a file named 'file.php?foo=1&bar=2' on the
// local filesystem.
include 'file.php?foo=1&bar=2';
// Works.
include 'http://www.example.com/file.php?foo=1&bar=2';
$foo = 1;
$bar = 2;
include 'file.txt'; // Works.
include 'file.php'; // Works.
?>
Remote file may be processed at the remote server (depending on the file extension and the fact if the remote server runs PHP or not) but it still has to produce a valid PHP script because it will be processed at the local server. If the file from the remote server should be processed there and outputted only, readfile() is much better function to use. Otherwise, special care should be taken to secure the remote script to produce a valid and desired code.
See also Remote files, fopen() and file() for related information.
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. This is not, however, possible when including remote files unless the output of the remote file has valid PHP start and end tags (as with any local file). You can declare the needed variables within those tags and they will be introduced at whichever point the file was included.
Because include() is a special language construct, parentheses are not needed around its argument. Take care when comparing return value.
Przykład #4 Comparing return value of include
<?php
// won't work, evaluated as include(('vars.php') == 'OK'), i.e. include('')
if (include('vars.php') == 'OK') {
echo 'OK';
}
// works
if ((include 'vars.php') == 'OK') {
echo 'OK';
}
?>
Przykład #5 include() and the return() statement
return.php
<?php
$var = 'PHP';
return $var;
?>
noreturn.php
<?php
$var = 'PHP';
?>
testreturns.php
<?php
$foo = include 'return.php';
echo $foo; // prints 'PHP'
$bar = include 'noreturn.php';
echo $bar; // prints 1
?>
$bar is the value 1 because the include was successful. Notice the difference between the above examples. The first uses return() within the included file while the other does not. If the file can't be included, FALSE is returned and E_WARNING is issued.
If there are functions defined in the included file, they can be used in the main file independent if they are before return() or after. If the file is included twice, PHP 5 issues fatal error because functions were already declared, while PHP 4 doesn't complain about functions defined after return(). It is recommended to use include_once() instead of checking if the file was already included and conditionally return inside the included file.
Another way to "include" a PHP file into a variable is to capture the output by using the Output Control Functions with include(). For example:
Przykład #6 Using output buffering to include a PHP file into a string
<?php
$string = get_include_contents('somefile.php');
function get_include_contents($filename) {
if (is_file($filename)) {
ob_start();
include $filename;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
return false;
}
?>
In order to automatically include files within scripts, see also the auto_prepend_file and auto_append_file configuration options in php.ini.
Informacja: Ponieważ jest to element składni języka a nie funkcja, nie może być on wywoływany używając zmiennych funkcji
See also require(), require_once(), include_once(), get_included_files(), readfile(), virtual(), and include_path.
The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.
See the include_once() documentation for information about the _once behaviour, and how it differs from its non _once siblings.
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() may be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, so in this case it may help avoid problems such as function redefinitions, variable value reassignments, etc.
See the include() documentation for information about how this function works.
Informacja: With PHP 4, _once functionality differs with case-insensitive operating systems (like Windows) so for example:
Przykład #1 include_once() with a case insensitive OS in PHP 4
<?php
include_once "a.php"; // this will include a.php
include_once "A.php"; // this will include a.php again! (PHP 4 only)
?>
This behaviour changed in PHP 5, so for example with Windows the path is normalized first so that C:\PROGRA~1\A.php is realized the same as C:\Program Files\a.php and the file is included just once.
The goto operator can be used to jump to another section in the program. The target point is specified by a label followed by a colon, and the instruction is given as goto followed by the desired target label. This is not a full unrestricted goto. The target label must be within the same file and context, meaning that you cannot jump out of a function or method, nor can you jump into one. You also cannot jump into any sort of loop or switch structure. You may jump out of these, and a common use is to use a goto in place of a multi-level break.
Przykład #1 goto example
<?php
goto a;
echo 'Foo';
a:
echo 'Bar';
?>
Powyższy przykład wyświetli:
Bar
Przykład #2 goto loop example
<?php
for($i=0,$j=50; $i<100; $i++) {
while($j--) {
if($j==17) goto end;
}
}
echo "i = $i";
end:
echo 'j hit 17';
?>
Powyższy przykład wyświetli:
j hit 17
Przykład #3 This will not work
<?php
goto loop;
for($i=0,$j=50; $i<100; $i++) {
while($j--) {
loop:
}
}
echo "$i = $i";
?>
Powyższy przykład wyświetli:
Fatal error: 'goto' into loop or switch statement is disallowed in script on line 2
Informacja: The goto operator is available as of PHP 5.3.
Funkcja może być definiowana przy użyciu następującej składni:
Przykład #1 Pseudokod demonstrujący użycie funkcji
<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
echo "Przykładowa funkcja.\n";
return $retval;
}
?>
Każdy poprawny kod może być użyty wewnątrz funkcji, łącznie z definicjami innych funkcji i klas.
Nazwy funkcji obowiązują identyczne zasady, jak w przypadku wszystkich innych etykiet w PHP. Poprawna nazwa funkcji zaczyna się od litery lub podkreślnika, po których następuje dowolna ilość liter, cyfr i podkreślników. Jako wyrażenie regularne, określone zostałoby to następująco: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.
Zobacz także Userland Naming Guide.
Funkcje nie muszą być zdefiniowane przed odniesieniem się do nich, oprócz sytuacji, w których funkcja jest zdefiniowana warunkowo jak w dwóch poniższych przykładach.
Kiedy funkcja jest zdefiniowana warunkowo, jak w dwóch poniższych przykładach, jej definicja musi być przetworzona przed jej wywołaniem.
Przykład #2 Funkcje zdefiniowane warunkowo
<?php
$makefoo = true;
/* Nie możemy tu wywołać foo()
ponieważ jeszcze nie istnieje,
ale możemy wywołać bar() */
bar();
if ($makefoo) {
function foo()
{
echo "Nie istnieję, dopóki nie zostanę wykonana.\n";
}
}
/* Teraz możemy bezpiecznie wywołać foo()
ponieważ $makefoo ma wartość logiczną 1 */
if ($makefoo) foo();
function bar()
{
echo "Istnieję od początku działania skryptu.\n";
}
?>
Przykład #3 Funkcje wewnątrz funkcji
<?php
function foo()
{
function bar()
{
echo "Nie istnieję, dopóki foo() nie jest wywołana.\n";
}
}
/* Nie możemy tu wywołać bar()
ponieważ jeszcze nie istnieje. */
foo();
/* Teraz możemy wywołać bar(),
wykonanie foo() spodowało
że jest to już możliwe. */
bar();
?>
Wszystkie funkcje i klasy w PHP mają globalny zasięg - mogą być wykonane poza funkcją, nawet jeśli były zdefiniowane wewnątrz niej, i odwrotnie.
PHP nie umożliwia przeładowywania funkcji, nie jest też możliwe usunięcie jej definicji lub redefiniowanie poprzednio określonych funkcji.
Informacja: Nazwy funkcji nie rozróżniają wielkości liter, ale dobrym zwyczajem jest wywoływanie ich w formie, w której zostały zdefiniowane.
Zarówno przyjmowanie różnej ilości argumentów jak i wartości domyślne argumentów są obsługiwane w funkcjach. Zobacz także opisy funkcji func_num_args(), func_get_arg(), i func_get_args() aby uzyskać więcej informacji.
W PHP jest możliwe wykonywanie rekurencyjnych funkcji. Unikaj jednak wywoływania rekurencyjnych funkcji/metod które osiągają poziom rekurencji większy niż 100-200, ponieważ może to spowodować przepełnienie stosu i zakończenie wykonywania skryptu.
Przykład #4 Funkcje rekurencyjne
<?php
function recursion($a)
{
if ($a < 20) {
echo "$a\n";
recursion($a + 1);
}
}
?>
Dane mogą być przekazywane do funkcji przez listę argumentów, która jest listą oddzielonych przecinkami wyrażeń.
PHP obsługuje podawanie argumentów jako wartości (domyślnie), przez referencję, oraz domyślne wartości argumentów. Różna ilość argumentów także jest obsługiwana, zobacz opisy funkcji func_num_args(), func_get_arg(), i func_get_args() aby dowiedzieć się więcej.
Przykład #1 Tablica jako argument funkcji
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>
Domyślnie, argumenty funkcji podawane są jako wartości (kiedy wartość argumentu wewnątrz funkcji się zmienia, nie wpływa to na wartość zmiennej poza funkcją). Aby pozwolić funkcji na modyfikację jej jej argumentów, muszą one być podane przez referencję.
Aby argument zawsze był podawany przez referencję, poprzedź nazwę argumentu znakiem (&) w definicji funkcji:
Przykład #2 Podawanie parametrów funkcji przez referencję
<?php
function add_some_extra(&$string)
{
$string .= 'i coś ekstra.';
}
$str = 'To jest ciąg znaków, ';
add_some_extra($str);
echo $str; // wypisuje 'To jest ciąg znaków, i coś ekstra.'
?>
Można zdefiniować domyślne wartości skalarne argumentów w stylu C++ następująco:
Przykład #3 Użycie domyślnych wartości argumentów w funkcji
<?php
function makecoffee($type = "cappuccino")
{
return "Robię kubek $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>
Wynikiem powyższego kodu jest:
PHP pozwala również na użycie tablic(array) i specjalnego typu NULL jako domyślnych wartości, na przykład:
Przykład #4 Użycie nie-skalarnych typów jako domyślnych wartości
<?php
function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
{
$device = is_null($coffeeMaker) ? "rąk" : $coffeeMaker;
return "Robię kubek ".join(", ", $types)." za pomocą $device.\n";
}
echo makecoffee();
echo makecoffee(array("cappuccino", "lavazza"), "teapot");
?>
Domyślna wartość musi być stałym wyrażeniem, a nie na przykład zmienną, członkiem klasy czy wywołaniem funkcji.
Zauważ, że przy użyciu domyślnych wartości, powinne one być zdefiniowane po prawej stronie nie-domyślnych argumentów; W przeciwnym wypadku, nie zadziała to jak powinno. Na przykład:
Przykład #5 Niepoprawne użycie domyślnych wartości argumentów
<?php
function makeyogurt($type = "acidophilus", $flavour)
{
return "Making a bowl of $type $flavour.\n";
}
echo makeyogurt("raspberry"); // nie zadziała tak, jak oczekujemy
?>
Wynik powyższego skryptu to:
Porównaj go teraz z:
Przykład #6 Poprawne użycie domyślnych wartości argumentów
<?php
function makeyogurt($flavour, $type = "jogurtu")
{
return "Robię miskę $type $flavour.\n";
}
echo makeyogurt("malinowego"); // działa zgodnie z naszymi oczekiwaniami
?>
Wynikiem działania powyższego przykładu jest:
Informacja: Od PHP 5 domyślne wartości argumentów mogą być podawane przez referencję.
Od PHP 4 możliwe jest użycie różnej ilości argumentów dla funkcji definiowanych przez użytkownika. Jest to dosyć proste przy użyciu funkcji func_num_args(), func_get_arg() i func_get_args().
Nie wymaga to żadnej specjalnej składni, listy argumentów w dalszym ciągu podawane są przy definiowaniu funkcji i zachowują się normalnie.
Wartości zwracane są przy użyciu opcjonalnego wyrażenia return. Wszystkie typy mogą być zwracane, łącznie z tablicami i obiektami. Powoduje to natychmiastowe zakończenie wykonywania funkcji i wznowienie wykonywania skryptu od linijki w której funkcja została wywołana. Zobacz return() aby uzyskać więcej informacji.
Przykład #1 Użycie return()
<?php
function square($num)
{
return $num * $num;
}
echo square(4); // wypisuje '16'.
?>
Funkcjia nie może zwracać wielu wartości, ale podobny efekt może zostać osiągnięty poprzez zwracanie tablicy.
Przykład #2 Zwracanie tablicy
<?php
function small_numbers()
{
return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
?>
Aby zwrócić referencję, użyj operatora & zarówno w deklaracji funkcji jak i podczas przypisywania zwracanej wartości zmiennej:
Przykład #3 Zwracanie referencji
<?php
function &returns_reference()
{
return $someref;
}
$newref =& returns_reference();
?>
Aby uzyskać więcej informacji o referencjach, przejdź do Wyjaśnienie Referencji.
PHP obsługuje opcję funkcji zmiennych. Oznacza to, że jeśli do nazwy zmiennej dodane są nawiasy, PHP postara się znaleźć funkcję o nazwie takiej jak wartość zmiennej i spróbuje ją wykonać. Między innymi, może to służyć do zaimplementowania tzw. callbacks, tablic funkcji, a także wielu innych rzeczy.
Funkcje zmiennych nie zadziałają z takimi elementami języka jak echo(), print(), unset(), isset(), empty(), include(), require() i podobnymi. Używaj okrężnych funkcji aby skorzystać z któregoś z powyższych elementów języka jako funkcji zmiennych.
Przykład #1 Przykład funkcji zmiennych
<?php
function foo() {
echo "W foo()<br />\n";
}
function bar($arg = '')
{
echo "W bar(); argumentem było '$arg'.<br />\n";
}
// To jest funkcja okrężna dla "echo"
function echoit($string)
{
echo $string;
}
$func = 'foo';
$func(); // Wywołuje foo()
$func = 'bar';
$func('test'); // Wywołuje bar()
$func = 'echoit';
$func('test'); // Wywołuje echoit()
?>
Jako funkcje zmiennych mogą być także wywoływane metody obiektów.
Przykład #2 Przykład metod zmiennych
<?php
class Foo
{
function Zmienna()
{
$name = 'Bar';
$this->$name(); // Wywołuje metodę Bar()
}
function Bar()
{
echo "To jest Bar";
}
}
$foo = new Foo();
$funcname = "Zmienna";
$foo->$funcname(); // Wywołuje $foo->Zmienna()
?>
Zobacz także call_user_func(), zmienne zmienne oraz function_exists().
PHP zapewnia wiele wbudowanych funkcji i konstrukcji. Istnieją także funkcje wymagające wkompilowania specyficznych rozszerzeń PHP, w przeciwnym wypadku wywołanie ich skutkuje błędami "undefined function". Na przykładd, aby użyć funkcji obrazków takich jak imagecreatetruecolor(), PHP musi być skompilowane z obsługą GD. Aby użyć mysql_connect(), PHP musi być skompilowane z obsługą MySQL. Jest wiele funkcji wbudowanych w rdzeń każdej wersji PHP, takich jak funkcje typu string oraz zmiennych. Wywołanie to phpinfo() lub get_loaded_extensions() pokaże, które rozszerzenia PHP są załadowane. Zauważ, że wiele rozszerzeń jest domyślnie załadowanych i podręcznik PHP jest podzielony według rozszerzeń. Zobacz rozdziały o konfiguracji, instalacji, a także te dotyczące poszczególnych rozszerzeń, aby dowiedzieć się jak uruchomić PHP.
Czytanie i rozumienie prototypów funkcji wyjaśnione jest w rozdziale podręcznika zatytułowanym jak czytać definicje funkcji. Ważne jest zrozumienie, czy funkcja zwraca konkretną wartość czy operuje bezpośrednio na podanej zmiennej. Na przykład, str_replace() zwróci zmodyfikowany obiekt typu string, podczas gdy usort() pracuje bezpośrednio na podanej zmiennej. Każda funkcja posiada swoją stronę w podręczniku PHP, która podaje informacje takie jak parametry funkcji, jej zachowanie, wartości zwracane po poprawnym wykonaniu i w przypadku błędu, a także dane dotyczące jej dostępności. Znanie tych ważnych (chociaż często drobnych) różnic jest kluczowe podczas pisania kodu w PHP.
Informacja: Jeśli parametry podane funkcji nie są takie, jak spodziewane, na przykład tablica(array) podawana jest w miejscu, gdzie oczekiwana jest zmienna typu string, wartość zwracana przez funkcję nie jest zdefiniowana. W takim wypadku funkcja prawdopodobnie zwróci NULL ale jest to jedynie konwencja a nie zasada, na której można się opierać.
Zobacz także function_exists(), the function reference, get_extension_funcs() i dl().
Starting with PHP 5, the object model was rewritten to allow for better performance and more features. This was a major change from PHP 4. PHP 5 has a full object model.
Among the features in PHP 5 are the inclusions of visibility, abstract and final classes and methods, additional magic methods, interfaces, cloning and typehinting.
PHP treats objects in the same way as references or handles, meaning that each variable contains an object reference rather than a copy of the entire object. See Objects and References
Zobacz także Userland Naming Guide.
Every class definition begins with the keyword class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the class's properties and methods.
The class name can be any valid label which is a not a PHP reserved word. A valid class name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.
A class may contain its own constants, variables (called "properties"), and functions (called "methods").
Przykład #1 Simple Class definition
<?php
class SimpleClass
{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo $this->var;
}
}
?>
The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).
Przykład #2 Some examples of the $this pseudo-variable
<?php
class A
{
function foo()
{
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")\n";
} else {
echo "\$this is not defined.\n";
}
}
}
class B
{
function bar()
{
// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
}
}
$a = new A();
$a->foo();
// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
$b = new B();
$b->bar();
// Note: the next line will issue a warning if E_STRICT is enabled.
B::bar();
?>
Powyższy przykład wyświetli:
$this is defined (A) $this is not defined. $this is defined (B) $this is not defined.
To create an instance of a class, a new object must be created and assigned to a variable. An object will always be assigned when creating a new object unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).
Przykład #3 Creating an instance
<?php
$instance = new SimpleClass();
// This can also be done with a variable:
$className = 'Foo';
$instance = new $className(); // Foo()
?>
In the class context, it is possible to create a new object by new self and new parent.
When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A copy of an already created object can be made by cloning it.
Przykład #4 Object Assignment
<?php
$assigned = $instance;
$reference =& $instance;
$instance->var = '$assigned will have this value';
$instance = null; // $instance and $reference become null
var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>
Powyższy przykład wyświetli:
NULL
NULL
object(SimpleClass)#1 (1) {
["var"]=>
string(30) "$assigned will have this value"
}
A class can inherit the methods and properties of another class by using the keyword extends in the class declaration. It is not possible to extend multiple classes; a class can only inherit from one base class.
The inherited methods and properties can be overridden by redeclaring them with the same name defined in the parent class. However, if the parent class has defined a method as final, that method may not be overridden. It is possible to access the overridden methods or static properties by referencing them with parent::.
Przykład #5 Simple Class Inheritance
<?php
class ExtendClass extends SimpleClass
{
// Redefine the parent method
function displayVar()
{
echo "Extending class\n";
parent::displayVar();
}
}
$extended = new ExtendClass();
$extended->displayVar();
?>
Powyższy przykład wyświetli:
Extending class a default value
Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
See Visibility for more information on the meanings of public, protected, and private.
Informacja: In order to maintain backward compatibility with PHP 4, PHP 5 will still accept the use of the keyword var in property declarations instead of (or in addition to) public, protected, or private. However, var is no longer required. In versions of PHP from 5.0 to 5.1.3, the use of var was considered deprecated and would issue an E_STRICT warning, but since PHP 5.1.3 it is no longer deprecated and does not issue the warning.
If you declare a property using var instead of one of public, protected, or private, then PHP 5 will treat the property as if it had been declared as public.
Within class methods the properties, constants, and methods may be accessed by using the form $this->property (where property is the name of the property) unless the access is to a static property within the context of a static class method, in which case it is accessed using the form self::$property. See Static Keyword for more information.
The pseudo-variable $this is available inside any class method when that method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).
Przykład #1 property declarations
<?php
class SimpleClass
{
// invalid property declarations:
public $var1 = 'hello ' . 'world';
public $var2 = <<<EOD
hello world
EOD;
public $var3 = 1+2;
public $var4 = self::myStaticMethod();
public $var5 = $myVar;
// valid property declarations:
public $var6 = myConstant;
public $var7 = array(true, false);
// This is allowed only in PHP 5.3.0 and later.
public $var8 = <<<'EOD'
hello world
EOD;
}
?>
Informacja: There are some nice functions to handle classes and objects. You might want to take a look at the Class/Object Functions.
Unlike heredocs, nowdocs can be used in any static data context, including property declarations.
Przykład #2 Example of using a nowdoc to initialize a property
<?php
class foo {
// As of PHP 5.3.0
public $bar = <<<'EOT'
bar
EOT;
}
?>
Informacja: Nowdoc support was added in PHP 5.3.0.
It is possible to define constant values on a per-class basis remaining the same and unchangeable. Constants differ from normal variables in that you don't use the $ symbol to declare or use them.
The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.
Its also possible for interfaces to have constants. Look at the interface documentation for examples.
As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).
Przykład #1 Defining and using a constant
<?php
class MyClass
{
const constant = 'constant value';
function showConstant() {
echo self::constant . "\n";
}
}
echo MyClass::constant . "\n";
$classname = "MyClass";
echo $classname::constant . "\n"; // As of PHP 5.3.0
$class = new MyClass();
$class->showConstant();
echo $class::constant."\n"; // As of PHP 5.3.0
?>
Przykład #2 Static data example
<?php
class foo {
// As of PHP 5.3.0
const bar = <<<'EOT'
bar
EOT;
}
?>
Unlike heredocs, nowdocs can be used in any static data context.
Informacja: Nowdoc support was added in PHP 5.3.0.
Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).
In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class/interface which hasn't been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.
Informacja: Exceptions thrown in __autoload function cannot be caught in the catch block and results in a fatal error.
Informacja: Autoloading is not available if using PHP in CLI interactive mode.
Informacja: If the class name is used e.g. in call_user_func() then it can contain some dangerous characters such as ../. It is recommended to not use the user-input in such functions or at least verify the input in __autoload().
Przykład #1 Autoload example
This example attempts to load the classes MyClass1 and MyClass2 from the files MyClass1.php and MyClass2.php respectively.
<?php
function __autoload($class_name) {
require_once $class_name . '.php';
}
$obj = new MyClass1();
$obj2 = new MyClass2();
?>
Przykład #2 Autoload other example
This example attempts to load the interface ITest.
<?php
function __autoload($name) {
var_dump($name);
}
class Foo implements ITest {
}
/*
string(5) "ITest"
Fatal error: Interface 'ITest' not found in ...
*/
?>
PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.
Informacja: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.
Przykład #1 using new unified constructors
<?php
class BaseClass {
function __construct() {
print "In BaseClass constructor\n";
}
}
class SubClass extends BaseClass {
function __construct() {
parent::__construct();
print "In SubClass constructor\n";
}
}
$obj = new BaseClass();
$obj = new SubClass();
?>
For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.
PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence.
Przykład #2 Destructor Example
<?php
class MyDestructableClass {
function __construct() {
print "In constructor\n";
$this->name = "MyDestructableClass";
}
function __destruct() {
print "Destroying " . $this->name . "\n";
}
}
$obj = new MyDestructableClass();
?>
Like constructors, parent destructors will not be called implicitly by the engine. In order to run a parent destructor, one would have to explicitly call parent::__destruct() in the destructor body.
Informacja: Destructors called during the script shutdown have HTTP headers already sent. The working directory in the script shutdown phase can be different with some SAPIs (e.g. Apache).
Informacja: Attempting to throw an exception from a destructor (called in the time of script termination) causes a fatal error.
The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.
Class properties must be defined as public, private, or protected. If declared using var without an explicit visibility keyword, the property will be defined as public.
Przykład #1 Property declaration
<?php
/**
* Define MyClass
*/
class MyClass
{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private
/**
* Define MyClass2
*/
class MyClass2 extends MyClass
{
// We can redeclare the public and protected method, but not private
protected $protected = 'Protected2';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj2 = new MyClass2();
echo $obj2->public; // Works
echo $obj2->private; // Undefined
echo $obj2->protected; // Fatal Error
$obj2->printHello(); // Shows Public, Protected2, Undefined
?>
Informacja: The PHP 4 method of declaring a variable with the var keyword is still supported for compatibility reasons (as a synonym for the public keyword). In PHP 5 before 5.1.3, its usage would generate an E_STRICT warning.
Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public.
Przykład #2 Method Declaration
<?php
/**
* Define MyClass
*/
class MyClass
{
// Declare a public constructor
public function __construct() { }
// Declare a public method
public function MyPublic() { }
// Declare a protected method
protected function MyProtected() { }
// Declare a private method
private function MyPrivate() { }
// This is public
function Foo()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate();
}
}
$myclass = new MyClass;
$myclass->MyPublic(); // Works
$myclass->MyProtected(); // Fatal Error
$myclass->MyPrivate(); // Fatal Error
$myclass->Foo(); // Public, Protected and Private work
/**
* Define MyClass2
*/
class MyClass2 extends MyClass
{
// This is public
function Foo2()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate(); // Fatal Error
}
}
$myclass2 = new MyClass2;
$myclass2->MyPublic(); // Works
$myclass2->Foo2(); // Public and Protected work, not Private
class Bar
{
public function test() {
$this->testPrivate();
$this->testPublic();
}
public function testPublic() {
echo "Bar::testPublic\n";
}
private function testPrivate() {
echo "Bar::testPrivate\n";
}
}
class Foo extends Bar
{
public function testPublic() {
echo "Foo::testPublic\n";
}
private function testPrivate() {
echo "Foo::testPrivate\n";
}
}
$myFoo = new foo();
$myFoo->test(); // Bar::testPrivate
// Foo::testPublic
?>
Inheritance is a well-esablished programming principle, and PHP makes use of this principle in its object model. This principle will affect the way many classes and objects relate to one another.
For example, when you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.
This is useful for defining and abstracting functionality, and permits the implementation of additional functionality in similar objects without the need to reimplement all of the shared functionality.
Przykład #1 Inheritance Example
<?php
class foo
{
public function printItem($string)
{
echo 'Foo: ' . $string . PHP_EOL;
}
public function printPHP()
{
echo 'PHP is great.' . PHP_EOL;
}
}
class bar extends foo
{
public function printItem($string)
{
echo 'Bar: ' . $string . PHP_EOL;
}
}
$foo = new foo();
$bar = new bar();
$foo->printItem('baz'); // Output: 'Foo: baz'
$foo->printPHP(); // Output: 'PHP is great'
$bar->printItem('baz'); // Output: 'Bar: baz'
$bar->printPHP(); // Output: 'PHP is great'
?>
The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.
When referencing these items from outside the class definition, use the name of the class.
As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).
Paamayim Nekudotayim would, at first, seem like a strange choice for naming a double-colon. However, while writing the Zend Engine 0.5 (which powers PHP 3), that's what the Zend team decided to call it. It actually does mean double-colon - in Hebrew!
Przykład #1 :: from outside the class definition
<?php
class MyClass {
const CONST_VALUE = 'A constant value';
}
$classname = 'MyClass';
echo $classname::CONST_VALUE; // As of PHP 5.3.0
echo MyClass::CONST_VALUE;
?>
Two special keywords self and parent are used to access properties or methods from inside the class definition.
Przykład #2 :: from inside the class definition
<?php
class OtherClass extends MyClass
{
public static $my_static = 'static var';
public static function doubleColon() {
echo parent::CONST_VALUE . "\n";
echo self::$my_static . "\n";
}
}
$classname = 'OtherClass';
echo $classname::doubleColon(); // As of PHP 5.3.0
OtherClass::doubleColon();
?>
When an extending class overrides the parents definition of a method, PHP will not call the parent's method. It's up to the extended class on whether or not the parent's method is called. This also applies to Constructors and Destructors, Overloading, and Magic method definitions.
Przykład #3 Calling a parent's method
<?php
class MyClass
{
protected function myFunc() {
echo "MyClass::myFunc()\n";
}
}
class OtherClass extends MyClass
{
// Override parent's definition
public function myFunc()
{
// But still call the parent function
parent::myFunc();
echo "OtherClass::myFunc()\n";
}
}
$class = new OtherClass();
$class->myFunc();
?>
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can).
For compatibility with PHP 4, if no visibility declaration is used, then the property or method will be treated as if it was declared as public.
Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.
Static properties cannot be accessed through the object using the arrow operator ->.
Calling non-static methods statically generates an E_STRICT level warning.
Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.
As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).
Przykład #1 Static property example
<?php
class Foo
{
public static $my_static = 'foo';
public function staticValue() {
return self::$my_static;
}
}
class Bar extends Foo
{
public function fooStatic() {
return parent::$my_static;
}
}
print Foo::$my_static . "\n";
$foo = new Foo();
print $foo->staticValue() . "\n";
print $foo->my_static . "\n"; // Undefined "Property" my_static
print $foo::$my_static . "\n";
$classname = 'Foo';
print $classname::$my_static . "\n"; // As of PHP 5.3.0
print Bar::$my_static . "\n";
$bar = new Bar();
print $bar->fooStatic() . "\n";
?>
Przykład #2 Static method example
<?php
class Foo {
public static function aStaticMethod() {
// ...
}
}
Foo::aStaticMethod();
$classname = 'Foo';
$classname::aStaticMethod(); // As of PHP 5.3.0
?>
PHP 5 introduces abstract classes and methods. It is not allowed to create an instance of a class that has been defined as abstract. Any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature they cannot define the implementation.
When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.
Przykład #1 Abstract class example
<?php
abstract class AbstractClass
{
// Force Extending class to define this method
abstract protected function getValue();
abstract protected function prefixValue($prefix);
// Common method
public function printOut() {
print $this->getValue() . "\n";
}
}
class ConcreteClass1 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass1";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass1";
}
}
class ConcreteClass2 extends AbstractClass
{
public function getValue() {
return "ConcreteClass2";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass2";
}
}
$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."\n";
$class2 = new ConcreteClass2;
$class2->printOut();
echo $class2->prefixValue('FOO_') ."\n";
?>
Powyższy przykład wyświetli:
ConcreteClass1 FOO_ConcreteClass1 ConcreteClass2 FOO_ConcreteClass2
Old code that has no user-defined classes or functions named 'abstract' should run without modifications.
Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.
Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.
All methods declared in an interface must be public, this is the nature of an interface.
To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.
Informacja: A class cannot implement two interfaces that share function names, since it would cause ambiguity.
Informacja: Interfaces can be extended like classes using the extends operator.
Informacja: The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error.
Its possible for interfaces to have constants. Interface constants works exactly like class constants. They cannot be overridden by a class/interface that inherits it.
Przykład #1 Interface example
<?php
// Declare the interface 'iTemplate'
interface iTemplate
{
public function setVariable($name, $var);
public function getHtml($template);
}
// Implement the interface
// This will work
class Template implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
public function getHtml($template)
{
foreach($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}
return $template;
}
}
// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
}
?>
Przykład #2 Extendable Interfaces
<?php
interface a
{
public function foo();
}
interface b extends a
{
public function baz(Baz $baz);
}
// This will work
class c implements b
{
public function foo()
{
}
public function baz(Baz $baz)
{
}
}
// This will not work and result in a fatal error
class d implements b
{
public function foo()
{
}
public function baz(Foo $foo)
{
}
}
?>
Przykład #3 Multiple interface inheritance
<?php
interface a
{
public function foo();
}
interface b
{
public function bar();
}
interface c extends a, b
{
public function baz();
}
class d implements c
{
public function foo()
{
}
public function bar()
{
}
public function baz()
{
}
}
?>
Przykład #4 Interfaces with constants
<?php
interface a
{
const b = 'Interface constant';
}
// Prints: Interface constant
echo a::b;
// This will however not work because its not allowed to
// override constants. This is the same concept as with
// class constants
class b implements a
{
const b = 'Class constant';
}
?>
An interface, together with type-hinting, provides a good way to make sure that a particular object contains particular methods. See instanceof operator and type hinting.
Overloading in PHP provides means to dynamically "create" properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types.
The overloading methods are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope. The rest of this section will use the terms "inaccessible properties" and "inaccessible methods" to refer to this combination of declaration and visibility.
All overloading methods must be defined as public.
Informacja: None of the arguments of these magic methods can be passed by reference.
Informacja: PHP's interpretation of "overloading" is different than most object oriented languages. Overloading traditionally provides the ability to have multiple methods with the same name but different quantities and types of arguments.
| Wersja | Opis |
|---|---|
| 5.3.0 | Added __callStatic(). Added warning to enforce public visibility and non-static declaration. |
| 5.1.0 | Added __isset() and __unset(). |
__set() is run when writing data to inaccessible properties.
__get() is utilized for reading data from inaccessible properties.
__isset() is triggered by calling isset() or empty() on inaccessible properties.
__unset() is invoked when unset() is used on inaccessible properties.
The $name argument is the name of the property being interacted with. The __set() method's $value argument specifies the value the $name'ed property should be set to.
Property overloading only works in object context. These magic methods will not be triggered in static context. Therefore these methods can not be declared static.
Informacja: The return value of __set() is ignored because of the way PHP processes the assignment operator. Similarly, __get() is never called when chaining assignemnts together like this:
$a = $obj->b = 8;
Przykład #1 Overloading properties via the __get(), __set(), __isset() and __unset() methods
<?php
class PropertyTest {
/** Location for overloaded data. */
private $data = array();
/** Overloading not used on declared properties. */
public $declared = 1;
/** Overloading only used on this when accessed outside the class. */
private $hidden = 2;
public function __set($name, $value) {
echo "Setting '$name' to '$value'\n";
$this->data[$name] = $value;
}
public function __get($name) {
echo "Getting '$name'\n";
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
$trace = debug_backtrace();
trigger_error(
'Undefined property via __get(): ' . $name .
' in ' . $trace[0]['file'] .
' on line ' . $trace[0]['line'],
E_USER_NOTICE);
return null;
}
/** As of PHP 5.1.0 */
public function __isset($name) {
echo "Is '$name' set?\n";
return isset($this->data[$name]);
}
/** As of PHP 5.1.0 */
public function __unset($name) {
echo "Unsetting '$name'\n";
unset($this->data[$name]);
}
/** Not a magic method, just here for example. */
public function getHidden() {
return $this->hidden;
}
}
echo "<pre>\n";
$obj = new PropertyTest;
$obj->a = 1;
echo $obj->a . "\n\n";
var_dump(isset($obj->a));
unset($obj->a);
var_dump(isset($obj->a));
echo "\n";
echo $obj->declared . "\n\n";
echo "Let's experiment with the private property named 'hidden':\n";
echo "Privates are visible inside the class, so __get() not used...\n";
echo $obj->getHidden() . "\n";
echo "Privates not visible outside of class, so __get() is used...\n";
echo $obj->hidden . "\n";
?>
Powyższy przykład wyświetli:
Setting 'a' to '1' Getting 'a' 1 Is 'a' set? bool(true) Unsetting 'a' Is 'a' set? bool(false) 1 Let's experiment with the private property named 'hidden': Privates are visible inside the class, so __get() not used... 2 Privates not visible outside of class, so __get() is used... Getting 'hidden' Notice: Undefined property via __get(): hidden in <file> on line 70 in <file> on line 29
__call() is triggered when invoking inaccessible methods in an object context.
__callStatic() is triggered when invoking inaccessible methods in a static context.
The $name argument is the name of the method being called. The $arguments argument is an enumerated array containing the parameters passed to the $name'ed method.
Przykład #2 Overloading methods via the __call() and __callStatic() methods
<?php
class MethodTest {
public function __call($name, $arguments) {
// Note: value of $name is case sensitive.
echo "Calling object method '$name' "
. implode(', ', $arguments). "\n";
}
/** As of PHP 5.3.0 */
public static function __callStatic($name, $arguments) {
// Note: value of $name is case sensitive.
echo "Calling static method '$name' "
. implode(', ', $arguments). "\n";
}
}
$obj = new MethodTest;
$obj->runTest('in object context');
MethodTest::runTest('in static context'); // As of PHP 5.3.0
?>
Powyższy przykład wyświetli:
Calling object method 'runTest' in object context Calling static method 'runTest' in static context
PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example a foreach statement. By default, all visible properties will be used for the iteration.
Przykład #1 Simple Object Iteration
<?php
class MyClass
{
public $var1 = 'value 1';
public $var2 = 'value 2';
public $var3 = 'value 3';
protected $protected = 'protected var';
private $private = 'private var';
function iterateVisible() {
echo "MyClass::iterateVisible:\n";
foreach($this as $key => $value) {
print "$key => $value\n";
}
}
}
$class = new MyClass();
foreach($class as $key => $value) {
print "$key => $value\n";
}
echo "\n";
$class->iterateVisible();
?>
Powyższy przykład wyświetli:
var1 => value 1 var2 => value 2 var3 => value 3 MyClass::iterateVisible: var1 => value 1 var2 => value 2 var3 => value 3 protected => protected var private => private var
As the output shows, the foreach iterated through all visible variables that can be accessed. To take it a step further you can implement one of PHP 5's internal interface named Iterator. This allows the object to decide what and how the object will be iterated.
Przykład #2 Object Iteration implementing Iterator
<?php
class MyIterator implements Iterator
{
private $var = array();
public function __construct($array)
{
if (is_array($array)) {
$this->var = $array;
}
}
public function rewind() {
echo "rewinding\n";
reset($this->var);
}
public function current() {
$var = current($this->var);
echo "current: $var\n";
return $var;
}
public function key() {
$var = key($this->var);
echo "key: $var\n";
return $var;
}
public function next() {
$var = next($this->var);
echo "next: $var\n";
return $var;
}
public function valid() {
$var = $this->current() !== false;
echo "valid: {$var}\n";
return $var;
}
}
$values = array(1,2,3);
$it = new MyIterator($values);
foreach ($it as $a => $b) {
print "$a: $b\n";
}
?>
Powyższy przykład wyświetli:
rewinding current: 1 valid: 1 current: 1 key: 0 0: 1 next: 2 current: 2 valid: 1 current: 2 key: 1 1: 2 next: 3 current: 3 valid: 1 current: 3 key: 2 2: 3 next: current: valid:
You can also define your class so that it doesn't have to define all the Iterator functions by simply implementing the PHP 5 IteratorAggregate interface.
Przykład #3 Object Iteration implementing IteratorAggregate
<?php
class MyCollection implements IteratorAggregate
{
private $items = array();
private $count = 0;
// Required definition of interface IteratorAggregate
public function getIterator() {
return new MyIterator($this->items);
}
public function add($value) {
$this->items[$this->count++] = $value;
}
}
$coll = new MyCollection();
$coll->add('value 1');
$coll->add('value 2');
$coll->add('value 3');
foreach ($coll as $key => $val) {
echo "key/value: [$key -> $val]\n\n";
}
?>
Powyższy przykład wyświetli:
rewinding current: value 1 valid: 1 current: value 1 key: 0 key/value: [0 -> value 1] next: value 2 current: value 2 valid: 1 current: value 2 key: 1 key/value: [1 -> value 2] next: value 3 current: value 3 valid: 1 current: value 3 key: 2 key/value: [2 -> value 3] next: current: valid:
Informacja: For more examples of iterators, see the SPL Extension.
Patterns are ways to describe best practices and good designs. They show a flexible solution to common programming problems.
The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for "manufacturing" an object. A Parameterized Factory receives the name of the class to instantiate as argument.
Przykład #1 Parameterized Factory Method
<?php
class Example
{
// The parameterized factory method
public static function factory($type)
{
if (include_once 'Drivers/' . $type . '.php') {
$classname = 'Driver_' . $type;
return new $classname;
} else {
throw new Exception ('Driver not found');
}
}
}
?>
Defining this method in a class allows drivers to be loaded on the fly. If the Example class was a database abstraction class, loading a MySQL and SQLite driver could be done as follows:
<?php
// Load a MySQL Driver
$mysql = Example::factory('MySQL');
// Load a SQLite Driver
$sqlite = Example::factory('SQLite');
?>
The Singleton pattern applies to situations in which there needs to be a single instance of a class. The most common example of this is a database connection. Implementing this pattern allows a programmer to make this single instance easily accessible by many other objects.
Przykład #2 Singleton Function
<?php
class Example
{
// Hold an instance of the class
private static $instance;
// A private constructor; prevents direct creation of object
private function __construct()
{
echo 'I am constructed';
}
// The singleton method
public static function singleton()
{
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
// Example method
public function bark()
{
echo 'Woof!';
}
// Prevent users to clone the instance
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
}
?>
This allows a single instance of the Example class to be retrieved.
<?php
// This would fail because the constructor is private
$test = new Example;
// This will always retrieve a single instance of the class
$test = Example::singleton();
$test->bark();
// This will issue an E_USER_ERROR.
$test_clone = clone $test;
?>
The function names __construct, __destruct, __call, __callStatic, __get, __set, __isset, __unset, __sleep, __wakeup, __toString, __invoke, __set_state and __clone are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.
PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality.
serialize() checks if your class has a function with the magic name __sleep. If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.
The intended use of __sleep is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which do not need to be saved completely.
Conversely, unserialize() checks for the presence of a function with the magic name __wakeup. If present, this function can reconstruct any resources that the object may have.
The intended use of __wakeup is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.
Przykład #1 Sleep and wakeup
<?php
class Connection {
protected $link;
private $server, $username, $password, $db;
public function __construct($server, $username, $password, $db)
{
$this->server = $server;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$this->connect();
}
private function connect()
{
$this->link = mysql_connect($this->server, $this->username, $this->password);
mysql_select_db($this->db, $this->link);
}
public function __sleep()
{
return array('server', 'username', 'password', 'db');
}
public function __wakeup()
{
$this->connect();
}
}
?>
The __toString method allows a class to decide how it will react when it is converted to a string.
Przykład #2 Simple example
<?php
// Declare a simple class
class TestClass
{
public $foo;
public function __construct($foo) {
$this->foo = $foo;
}
public function __toString() {
return $this->foo;
}
}
$class = new TestClass('Hello');
echo $class;
?>
Powyższy przykład wyświetli:
Hello
It is worth noting that before PHP 5.2.0 the __toString method was only called when it was directly combined with echo() or print(). Since PHP 5.2.0, it is called in any string context (e.g. in printf() with %s modifier) but not in other types contexts