html/ 0040755 0001012 0001012 00000000000 11254656333 013026 5 ustar docbuilder docbuilder html/copyright.html 0100644 0001012 0001012 00000005031 11254655606 015722 0 ustar docbuilder docbuilder
Авторските права © 1997 - 2009 принадлежат на PHP Documentation Group. Този материал може да бъде разпространяван единствено според реда и условията определени по-нататък в Creative Commons Attribution 3.0 License или по-късен. Копие на лиценза Creative Commons Attribution 3.0 се разпространява с това ръководство, като последната версия се намира на » http://creativecommons.org/licenses/by/3.0/.
Ако се интересувате от разпространението или преиздаването на този документ - в цялост или на части от него, бил той променен или непроменен, или имате някакви въпроси, моля свържете се с притежателя на авторските права на » doc-license@lists.php.net. Забележете, че адресът е свързан с пощенски списък, който се съхранява публично.
PHP, което е съкращение от "PHP: Hypertext Preprocessor", е широко разпространен скриптов език с отворен код (Open Source), пригоден за различни цели, който е специално създаден за уеб разработване (Web development) и може да бъде вмъкван в HTML. Синтаксисът му се базира на C, Java и Perl, и е лесен за изучаване. Главната цел на езика е да позволи на уеб разработчиците да пишат динамични уеб страници бързо, но с PHP можете и много повече.
Това ръководство се състои предимно от справочник на функциите, но съдържа също и справочник на езика, обяснения на някои от основните възможности на PHP, както и друга допълнителна информация
Можете да свалите това ръководство в няколко формата от » http://www.php.net/download-docs.php. Повече информация относно начина, по който е разработено това ръководство може да бъде намерена в приложение 'Относно ръководството'. Ако се интересувате от историята на PHP, посетете съответното приложение.
На началната страница на ръководството, сме изтъкнали най-активните хора в момента, но има много хора, допринесли за ръководството, които помагат в работата ни, или в миналото са помогнали изключително много на проекта. Има много незнайни хора, които са помогнали с потребителски бележки, които постоянно се добавят на страниците на ръководството, и за чиято помощ ние сме много благодарни. Всички списъци по-долу са по азбучен ред.
Следните хора, са допринесли значително много за създаването и/или продължават да допринасят, като добавят съдържание към ръководството: 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 и Andrei Zmievski.
Следните хора са допринесли, значително при редакцията на ръководството: Stig Bakken, Gabor Hojtsy, Hartmut Holzgraefe и Egon Schmid.
В момента най-активните отговорници са: Daniel Brown, Nuno Lopes, Felipe Pena, Thiago Pojda и Maciek Sokolewicz.
Тези хора също са положили доста усилия за поддръжката на потребителските бележки: 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 и Jeroen van Wolffelaar.
PHP (рекурсивно съкращение от PHP: Hypertext Preprocessor) е широко използван скриптов език с отворен код, предназначен за обща употреба, който е изключително удобен за уеб разработки и може да се вгражда в HTML.
Добре, но какво означава това? Пример:
Example #1 Въвеждащ пример
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Пример</title>
</head>
<body>
<?php
echo "Здрасти, аз съм PHP-скрипт!";
?>
</body>
</html>
Вместо множество команди, които извеждат HTML (като при C и Perl),
PHP-страниците съдържат HTML с вграден код, който прави "нещо"
(в нашия случай извежда "Здрасти, аз съм PHP-скрипт!").
PHP-кодът се огражда със специални инструкции за начало и край
на обработката <?php и ?>,
които ви позволяват да преминавате и излизате от "PHP режима".
Това, което отличава PHP от примерно клиентски JavaScript, е че кодът се изпълнява на сървъра, генерира HTML, който се изпраща към клиента. Клиентът ще получи резултата от изпълнението на този скрипт, но няма да знае какъв код е генерирал този резултат. Дори можете да конфигурирате уеб сървъра си да обработва всички HTML-файлове с PHP и тогава няма как потребителите да знаят какво правите зад гърба им.
Най-хубавото нещо при използването на PHP е, че е изключително лесно за новаци, а разполага с много разширени възможности за професионалния програмист. Не се притеснявайте от четенето на дълги списъци с възможности. Много бързо можете да влезете в крачка и до няколко часа да започнете да пишете прости скриптове.
Въпреки че, програмирането на PHP е насочено основно към писането на скриптове от страна на сървъра, с него могат да се правят много други неща. Повече за това може да прочетете по-долу, в секцията Какво може да прави PHP?, или да прескочите направо към уводния урок, ако се интересувате само от уеб програмиране.
Всичко. PHP е насочено основно към писането на скриптове от страна на сървъра, така че, можете да правите всички, което може да се направи с която и да е CGI програма, като например приемане на данни от формуляр, генериране на динамично съдържание за страници или изпращане и получаване на бисквитки. А PHP може да върши и много други неща.
Има три основни области, в които се използват PHP-скриптове.
PHP може да се използва на всички по-известни операционни системи, в това число Линукс, много Юникс варианти (включително HP-UX, Solaris и OpenBSD), Microsoft Windows, Mac OS X, RISC OS, а вероятно и други. Също така PHP поддържа по-голяма част от съвременните уеб сървъри. Това включва Apache, Microsoft Internet Information Server, Personal Web Server, сървърите Netscape и iPlanet, Oreilly Website Pro server, Caudium, Xitami, OmniHTTPd, и много други. За по-голяма част от сървърите PHP разполага с модули, а за другите поддържайки CGI стандарта, PHP може да работи като CGI процесор.
Така с PHP имате свободата да изберете операционна система и уеб сървър. Освен това, ви е предоставена възможността да изберете да работите с процедурно програмиране, обектно-ориентирано програмиране, или смесица от двете. Въпреки че, не всяка стандартна възможност на ООП е реализирана в PHP 4, много библиотеки и големи приложения (включително и PEAR библиотеката) са написани единствено и само обектно-ориентиран код. С PHP 5 са коригирани някои слабости свързани с обектно-ориентираните възможности на PHP 4 и е въведен един завършен обектен модел.
С PHP вие не сте ограничени само в генерирането на HTML. Възможностите на PHP включват генериране на изображения, PDF файлове и дори Flash анимации (посредством libswf и Ming), които се генерират в реално време. Също така може да генерирате всякакъв текст, като например XHTML и всякакъв друг XML файл. PHP може автоматично да генерира тези файлове и да ги съхрани във файловата система, вместо да ги извежда на екрана, създавайки по този начин кеш от страна на сървъра за динамичното ви съдържание.
Една от най-сериозните и значителни възможности на PHP е поддръжката на широк набор от бази от данни. Създаването на уеб страници използващи бази от данни е изключително лесно. По настоящем се поддържат следните бази от данни:
Също така, разполагате и си разширение за абстракция на бази от данни (нарича се PDO), което ви предоставя прозрачно използване на всички бази от данни поддържани от това разширение. Освен това, PHP поддържа ODBC, Open Database Connection стандарта, така че, може да осъществявате връзки с други бази от данни, които поддържат този световен стандарт.
- Adabas D
- dBase
- Empress
- FilePro (само четене)
- Hyperwave
- IBM DB2
- Informix
- Ingres
- InterBase
- FrontBase
- mSQL
- Direct MS-SQL
- MySQL
- ODBC
- Oracle (OCI7 и OCI8)
- Ovrimos
- PostgreSQL
- SQLite
- Solid
- Sybase
- Velocis
- Unix dbm
PHP също така поддържа комуникация с други услуги посредством съответните протоколи, като LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (при Windows) и още много други. Също така може директно да отваряте мрежови сокети и да осъществявате достъп посредством някой друг протокол. PHP също така има поддръжка на WDDX обмяна на данни, виртуално между всички езици за уеб програмиране. Говорейки за взаимосвързаност, трябва да се спомене, че PHP поддържа инстанцииране а Java обекти и възможността за прозрачното им използване като PHP обекти. Също така можете да използвате CORBA разширението, за осъществяване на достъп до отдалечени обекти.
PHP разполага с изключително удобни възможности за текстообработка, от разширени POSIX или Perl регулярни изрази, до разбор на XML документи. За осъществяване на достъп и извършване на разбор на XML документи, PHP 4 поддържа SAX и DOM стандартите, като също така може да използвате и XSLT разширението за преобразуване на на XML документи. При PHP 5 всички XML разширения са стандартизирани, на базата на libxml2, а с добавянето на SimpleXML и XMLReader поддръжката, значително е разширен набора от възможности.
Накрая, но не на последно място, разполагаме с други интересни разширения, като mnoGoSearch функциите за търсещата машина, функциите за ICQ Gateway, много помощни инструменти за компресия (gzip, bz2, zip), календарни преобразувания, преводи...
Както забелязвате, тази страница не е достатъчна, за да се опишат всички възможности и предимства на PHP. Прегледайте информацията за инсталиране на PHP и частта Справочник на функциите за повече информация относно споменатите по-горе разширения на PHP.
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:
Example #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.
Забележка: 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.
Забележка: 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.
Забележка: 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.
Забележка: 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.
Example #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'].
Забележка: $_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:
Example #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:
Example #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:
Example #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:
Example #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:
Example #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/
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.
Before starting the installation, first you need to know what do you want to use PHP for. There are three main fields you can use PHP, as described in the What can PHP do? section:
For the first and most common form, you need three things: PHP itself, a web server and a web browser. You probably already have a web browser, and depending on your operating system setup, you may also have a web server (e.g. Apache on Linux and MacOS X; IIS on Windows). You may also rent webspace at a company. This way, you don't need to set up anything on your own, only write your PHP scripts, upload it to the server you rent, and see the results in your browser.
In case of setting up the server and PHP on your own, you have two choices for the method of connecting PHP to the server. For many servers PHP has a direct module interface (also called SAPI). These servers include Apache, Microsoft Internet Information Server, Netscape and iPlanet servers. Many other servers have support for ISAPI, the Microsoft module interface (OmniHTTPd for example). If PHP has no module support for your web server, you can always use it as a CGI or FastCGI processor. This means you set up your server to use the CGI executable of PHP to process all PHP file requests on the server.
If you are also interested to use PHP for command line scripting (e.g. write scripts autogenerating some images for you offline, or processing text files depending on some arguments you pass to them), you always need the command line executable. For more information, read the section about writing command line PHP applications. In this case, you need no server and no browser.
With PHP you can also write desktop GUI applications using the PHP-GTK extension. This is a completely different approach than writing web pages, as you do not output any HTML, but manage windows and objects within them. For more information about PHP-GTK, please » visit the site dedicated to this extension. PHP-GTK is not included in the official PHP distribution.
From now on, this section deals with setting up PHP for web servers on Unix and Windows with server module interfaces and CGI executables. You will also find information on the command line executable in the following sections.
PHP source code and binary distributions for Windows can be found at » http://www.php.net/downloads.php. We recommend you to choose a » mirror nearest to you for downloading the distributions.
This section 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.
Example #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-dist /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-recommended, 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:
Example #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-dist /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
Забележка: 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.
Example #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.
Забележка: 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.
Забележка: Make sure you specify the installed version of apxs when using --with-apxs=/path/to/apxs. You must NOT use the apxs version that is in the apache sources but the one that is actually installed on your system.
This section contains notes and hints specific to Apache 2.0 installs of PHP on Unix systems.
Не препоръчваме използването на нишков MPM с Apache2 за масова употреба. Вместо това, използвайте MPM или Apache1. За разяснение относно този проблем, вижте FAQ информацията по въпроса за Apache2 с нишков MPM
You are highly encouraged to take a look at the » Apache Documentation to get a basic understanding of the Apache 2.0 Server.
Забележка: PHP and Apache 2.0.x compatibility notes
The following versions of PHP are known to work with the most recent version of Apache 2.0.x:
- 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.
Download the most recent version of » Apache 2.0 and a fitting PHP version from the above mentioned places. This quick guide covers only the basics to get started with Apache 2.0 and PHP. For more information read the » Apache Documentation. The version numbers have been omitted here, to ensure the instructions are not incorrect. You will need to replace the 'NN' here with the correct values from your files.
Example #1 Installation Instructions (Apache 2 Shared Module Version)
1. gzip -d httpd-2_0_NN.tar.gz
2. tar xvf httpd-2_0_NN.tar
3. gunzip php-NN.tar.gz
4. tar -xvf php-NN.tar
5. cd httpd-2_0_NN
6. ./configure --enable-so
7. make
8. make install
Now you have Apache 2.0.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-dist /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-recommended, 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 modules/libphp4.so
For PHP 5:
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 executed as PHP source files, add this:
<FilesMatch "\.phps$">
SetHandler application/x-httpd-php-source
</FilesMatch>
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. If you wish to build a multithreaded version of Apache2, you must overwrite the standard MPM-Module prefork either with worker or perchild. To do so append to your configure line in step 6 above either the option --with-mpm=worker or --with-mpm=perchild. Before doing so, please beware the consequences and have at least a fair understand of what the implications. For more information, read the Apache documentation regarding » MPM-Modules.
Забележка: If you want to use content negotiation, read the Apache MultiViews FAQ.
Забележка: To build a multithreaded version of Apache your system must support threads. This also implies to build PHP with experimental Zend Thread Safety (ZTS). Therefore not all extensions might be available. The recommended setup is to build Apache with the standard prefork MPM-Module.
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.
Example #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.
Example #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.
Example #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.
Example #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.
Забележка: 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.
Забележка: 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>
Забележка: 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!
Забележка: 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.
Забележка: 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.
Сървър, инсталиран в режим CGI, е открит за множество възможни уязвимости. Моля, прочетете раздела за сигурност на 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.
Example #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.
Example #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:
Example #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.
Example #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:
Example #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 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.
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:
Забележка: 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.
Забележка: 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>
Забележка: 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-dist /usr/local/bin/php.ini
or (if your don't have a local directory)
cp php.ini-dist /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.
Забележка: 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 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.
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.
Забележка: 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 install guide will help you manually install and configure PHP with a web server on Microsoft Windows. To get started you'll need to download the zip binary distribution from the downloads page at » http://www.php.net/downloads.php.
Although there are many all-in-one installation kits, and we also distribute a PHP installer for Microsoft Windows, we recommend you take the time to setup PHP yourself as this will provide you with a better understanding of the system, and enables you to install PHP extensions easily when needed.
Забележка: Upgrading from a previous PHP version
Previous editions of the manual suggest moving various ini and DLL files into your SYSTEM (i.e. C:\WINDOWS) folder and while this simplifies the installation procedure it makes upgrading difficult. We advise you remove all of these files (like php.ini and PHP related DLLs from the Windows SYSTEM folder) before moving on with a new PHP installation. Be sure to backup these files as you might break the entire system. The old php.ini might be useful in setting up the new PHP as well. And as you'll soon learn, the preferred method for installing PHP is to keep all PHP related files in one directory and have this directory available to your systems PATH.
Забележка: MDAC requirements
If you use Microsoft Windows 98/NT4 download the latest version of the Microsoft Data Access Components (MDAC) for your platform. MDAC is available at » http://msdn.microsoft.com/data/. This requirement exists because ODBC is built into the distributed Windows binaries.
The following steps should be completed on all installations before any server specific instructions are performed:
Extract the distribution file into a directory of your choice. If you are installing PHP 4, extract to C:\, as the zip file expands to a foldername like php-4.3.7-Win32. If you are installing PHP 5, extract to C:\php as the zip file doesn't expand as in PHP 4. You may choose a different location but do not have spaces in the path (like C:\Program Files\PHP) as some web servers will crash if you do.
The directory structure extracted from the zip is different for PHP versions 4 and 5 and look like as follows:
Example #1 PHP 4 package structure
c:\php | +--cli | | | |-php.exe -- CLI executable - ONLY for command line scripting | +--dlls -- support DLLs required by some extensions | | | |-expat.dll | | | |-fdftk.dll | | | |-... | +--extensions -- extension DLLs for PHP | | | |-php_bz2.dll | | | |-php_cpdf.dll | | | |-... | +--mibs -- support files for SNMP | +--openssl -- support files for Openssl | +--pdf-related -- support files for PDF | +--sapi -- SAPI (server module support) DLLs | | | |-php4apache.dll | | | |-php4apache2.dll | | | |-... | +--PEAR -- initial copy of PEAR | | |-go-pear.bat -- PEAR setup script | |-... | |-php.exe -- CGI executable | |-... | |-php.ini-dist -- default php.ini settings | |-php.ini-recommended -- recommended php.ini settings | |-php4ts.dll -- core PHP DLL | |-...
Or:
Example #2 PHP 5 package structure
c:\php | +--dev | | | |-php5ts.lib | +--ext -- extension DLLs for PHP | | | |-php_bz2.dll | | | |-php_cpdf.dll | | | |-... | +--extras | | | +--mibs -- support files for SNMP | | | +--openssl -- support files for Openssl | | | +--pdf-related -- support files for PDF | | | |-mime.magic | +--pear -- initial copy of PEAR | | |-go-pear.bat -- PEAR setup script | |-fdftk.dll | |-... | |-php-cgi.exe -- CGI executable | |-php-win.exe -- executes scripts without an opened command prompt | |-php.exe -- CLI executable - ONLY for command line scripting | |-... | |-php.ini-dist -- default php.ini settings | |-php.ini-recommended -- recommended php.ini settings | |-php5activescript.dll | |-php5apache.dll | |-php5apache2.dll | |-... | |-php5ts.dll -- core PHP DLL | |-...
Notice the differences and similarities. Both PHP 4 and PHP 5 have a CGI executable, a CLI executable, and server modules, but they are located in different folders and/or have different names. While PHP 4 packages have the server modules in the sapi folder, PHP 5 distributions have no such directory and instead they're in the PHP folder root. The supporting DLLs for the PHP 5 extensions are also not in a seperate directory.
Забележка: In PHP 4, you should move all files located in the dll and sapi folders to the main folder (e.g. C:\php).
Here is a list of server modules shipped with PHP 4 and PHP 5:
sapi/php4activescript.dll (php5activescript.dll) - ActiveScript engine, allowing you to embed PHP in your Windows applications.
sapi/php4apache.dll (php5apache.dll) - Apache 1.3.x module.
sapi/php4apache2.dll (php5apache2.dll) - Apache 2.0.x module.
sapi/php5apache2_2.dll - Apache 2.2.x module.
sapi/php4isapi.dll (php5isapi.dll) - ISAPI Module for ISAPI compliant web servers like IIS 4.0/PWS 4.0 or newer.
sapi/php4nsapi.dll (php5nsapi.dll) - Sun/iPlanet/Netscape server module.
sapi/php4pi3web.dll (no equivalent in PHP 5) - Pi3Web server module.
Server modules provide significantly better performance and additional functionality compared to the CGI binary. The CLI version is designed to let you use PHP for command line scripting. More information about CLI is available in the chapter about using PHP from the command line.
The SAPI modules have been significantly improved as of the 4.1 release, however, in older systems you may encounter server errors or other server modules failing, such as ASP.
The CGI and CLI binaries, and the web server modules all require the php4ts.dll (php5ts.dll) file to be available to them. You have to make sure that this file can be found by your PHP installation. The search order for this DLL is as follows:
The same directory from where php.exe is called, or in case you use a SAPI module, the web server's directory (e.g. C:\Program Files\Apache Group\Apache2\bin).
Any directory in your Windows PATH environment variable.
To make php4ts.dll / php5ts.dll available you have three options: copy the file to the Windows system directory, copy the file to the web server's directory, or add your PHP directory, C:\php to the PATH. For better maintenance, we advise you to follow the last option, add C:\php to the PATH, because it will be simpler to upgrade PHP in the future. Read more about how to add your PHP directory to PATH in the corresponding FAQ entry (and then don't forget to restart the computer - logoff isn't enough).
The next step is to set up a valid configuration file for PHP, php.ini. There are two ini files distributed in the zip file, php.ini-dist and php.ini-recommended. We advise you to use php.ini-recommended, because we optimized the default settings in this file for performance, and security. Read this well documented file carefully because it has changes from php.ini-dist that will drastically affect your setup. Some examples are display_errors being off and magic_quotes_gpc being off. In addition to reading these, study the ini settings and set every element manually yourself. If you would like to achieve the best security, then this is the way for you, although PHP works fine with these default ini files. Copy your chosen ini-file to a directory that PHP is able to find and rename it to php.ini. PHP searches for php.ini in the locations described in The configuration file section.
If you are running Apache 2, the simpler option is to use the PHPIniDir directive (read the installation on Apache 2 page), otherwise your best option is to set the PHPRC environment variable. This process is explained in the following FAQ entry.
Забележка: If you're using NTFS on Windows NT, 2000, XP or 2003, make sure that the user running the web server has read permissions to your php.ini (e.g. make it readable by Everyone).
The following steps are optional:
Edit your new php.ini file. If you plan to use OmniHTTPd, do not follow the next step. Set the doc_root to point to your web servers document_root. For example:
doc_root = c:\inetpub\wwwroot // for IIS/PWS doc_root = c:\apache\htdocs // for Apache
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 файла на това разширение може да бъде изтеглен или от страницата за » изтегляне на PHP или от » http://pecl4win.php.net/
Забележка: 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.
Забележка: 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.
Забележка: 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 notes and hints specific to IIS (Microsoft Internet Information Server).
Сървър, инсталиран в режим CGI, е открит за множество възможни уязвимости. Моля, прочетете раздела за сигурност на CGI, за да научите как да се защитавате от подобни атаки.
PHP may be installed as a CGI binary, or with the ISAPI module. In either case, you need to start the Microsoft Management Console (may appear as 'Internet Services Manager', either in your Windows NT 4.0 Option Pack branch or the Control Panel=>Administrative Tools under Windows 2000/XP). Then right click on your Web server node (this will most probably appear as 'Default Web Server'), and select 'Properties'.
If you want to use the CGI binary, do the following:
To use the ISAPI module, do the following:
With IIS 6 (2003 Server), open up the IIS Manager, go to Web Service Extensions, choose "Add a new Web service extension", enter in a name such as PHP, choose the Add button and for the value browse to either the ISAPI file (php4isapi.dll or php5isapi.dll) or CGI (php.exe or php-cgi.exe) then check "Set extension status to Allowed" and click OK.
In order to use index.php as a default content page, do the following: From within the Documents tab, choose Add. Type in index.php and click OK. Adjust the order by choosing Move Up or Move Down. This is similar to setting DirectoryIndex with Apache.
The steps above must be repeated for each extension that is to be associated with PHP scripts. .php is the most common although .php3 may be required for legacy applications.
If you experience 100% CPU usage after some time, turn off the IIS setting Cache ISAPI Application.
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.
Забележка: 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.
Забележка: Запомнете, че при добавяне на стойности за пътя в конфигурацията на Apache при Windows, всички обратно наклонени черти, като c:\directory\file.ext, трява да бъдат преобразувани до наклонени черти: c:/directory/file.ext. Наклонена черта в края също може да бъде необходима за директории.
You should add the following lines to your Apache httpd.conf file:
Example #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:
Example #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.
Сървър, инсталиран в режим CGI, е открит за множество възможни уязвимости. Моля, прочетете раздела за сигурност на 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.
Забележка: You should read the manual installation steps first!
Забележка: 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/
Не препоръчваме използването на нишков MPM с Apache2 за масова употреба. Вместо това, използвайте MPM или Apache1. За разяснение относно този проблем, вижте FAQ информацията по въпроса за Apache2 с нишков 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.
Забележка: 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.
Забележка: Запомнете, че при добавяне на стойности за пътя в конфигурацията на Apache при Windows, всички обратно наклонени черти, като c:\directory\file.ext, трява да бъдат преобразувани до наклонени черти: c:/directory/file.ext. Наклонена черта в края също може да бъде необходима за директории.
You need to insert these three lines to your Apache httpd.conf configuration file to set up the CGI binary:
Example #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"
Сървър, инсталиран в режим CGI, е открит за множество възможни уязвимости. Моля, прочетете раздела за сигурност на 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:
Example #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"
Забележка: 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.
Забележка: 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.
Забележка: More details about setting up PHP as an NSAPI filter can be found here: » http://benoit.noss.free.fr/php/install-php4.html
Забележка: 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!
Забележка: 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.
Забележка: But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!
This section contains notes and hints specific to » OmniHTTPd on Windows.
Забележка: You should read the manual installation steps first!
Сървър, инсталиран в режим CGI, е открит за множество възможни уязвимости. Моля, прочетете раздела за сигурност на 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.
Забележка: 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.
Забележка: 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.
Забележка: 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]:
Example #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.
Забележка: 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.
Забележка: 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.
Забележка: 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.
Сървър, инсталиран в режим CGI, е открит за множество възможни уязвимости. Моля, прочетете раздела за сигурност на 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 и Zlib
In PHP 5 (updated PHP 5.0.4), the following changes exist. Built in: DOM, LibXML, Iconv, SimpleXML, SPL и 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.
Example #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.
Забележка: 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.
Забележка: 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 "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.
Забележка: 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 typing the running the following command:
assoc .php=phpfile
Associate the phpfile file type with the appropriate PHP executable. This is done by typing the running the following command:
ftype phpfile=php.exe "%1" -- %*
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.
Example #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.exe,0" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell] @="Run" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open] @="&Open" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open\command] @="\"C:\\PHP5\\PHP.EXE\" \"%1\" -- %*"
With these changes the same command can be written as:
"C:\PHP Scripts\script" -arg1 -arg2 -arg3
script -arg1 -arg2 -arg3
Забележка: There is a small problem if you intend to use this techique and use your PHP scripts as commandline filters, 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
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.
Забележка: Windows 98/ME/NT4 is no longer supported as of PHP 5.3.0.
Забележка: 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.
» 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:
Example #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:
Забележка: 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:
Забележка: 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:
Some problems are more common than others. The most common ones are listed in the PHP FAQ, part of this manual.
If you are still stuck, someone on the PHP installation mailing list may be able to help you. You should check out the archive first, in case someone already answered someone else who had the same problem as you. The archives are available from the support page on » http://www.php.net/support.php. To subscribe to the PHP installation mailing list, send an empty mail to » php-install-subscribe@lists.php.net. The mailing list address is » php-install@lists.php.net.
If you want to get help on the mailing list, please try to be precise and give the necessary details about your environment (which operating system, what PHP version, what web server, if you are running PHP as CGI or a server module, защитен режим, etc.), and preferably enough code to make others able to reproduce and test your problem.
If you think you have found a bug in PHP, please report it. The PHP developers probably don't know about it, and unless you report it, chances are it won't be fixed. You can report bugs using the bug-tracking system at » http://bugs.php.net/. Please do not send bug reports in mailing list or personal letters. The bug system is also suitable to submit feature requests.
Read the » How to report a bug document before submitting any bug reports!
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().
Забележка: 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.
Example #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 | Meaning |
|---|---|
| PHP_INI_USER | Entry can be set in user scripts (like with ini_set()) or in the Windows registry |
| PHP_INI_PERDIR | Entry can be set in php.ini, .htaccess or httpd.conf |
| PHP_INI_SYSTEM | Entry can be set in php.ini or httpd.conf |
| PHP_INI_ALL | 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.
Забележка: 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.
Example #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().
Когато PHP прави разбор на файл, той гледа за отварящи и затварящи тагове, които да укажат започването и спирането на интерпретацията на кода между тях. Този вид разбор позволява php да бъде поставян в най-различни документи като всичко извън двойката отварящи и затварящи тагове се игнорира от синтактичния анализатор на PHP. В повечето случаи ще видите php, поставен в документи от тип HTML, както в следния пример.
<p>Това ще бъде игнорирано.</p>
<?php echo 'Докато това ще бъде анализирано.'; ?>
<p>Това също ще бъде игнорирано.</p>
Можете да използвате и по-сложни структури:
Example #1 Излизане за напреднали
<?php
if ($expression) {
?>
<strong>Това е истина.</strong>
<?php
} else {
?>
<strong>Това е неистина.</strong>
<?php
}
?>
Това работи както се очаква, защото когато PHP се натъкне на затварящия таг ?>, той просто започва да извежда всичко, което намери (с изключение на първия знак за нов ред - вж. разделяне на инструкции ), докато не намери друг отварящ таг. Даденият пример е скалъпен, разбира се, но за извеждането на големи блокове от текст излизането от синтактичния режим на PHP като цяло е по-ефикасно, отколкото изпращането на целия текст през echo() или print().
Има четири различни двойки отварящи и затварящи тагове, които могат да бъдат използвани в PHP. Две от тях (<?php. . .?> и <script language="php">. . .</script>) са налични винаги. Другите две са късите тагове и тези в стил ASP и могат да бъдат включвани или изключвани в конфигурационния файл php.ini. Като такива, въпреки че някои хора считат късите тагове и тези в стил ASP за удобни, те не са толкова преносими и като цяло не са препоръчителни.
Забележка: Също така, ако възнамерявате да вмъквате PHP код в XML или XHTML, ще трябва да използвате <?php. . .?> формата, за дa бъде съобразен със стандартите.
Example #2 Отварящи и затварящи тагове в PHP
1. <?php echo 'правете така, ако искате да работите с документи от тип XHTML или XML'; ?>
2. <script language="php">
echo 'някои редактори (като FrontPage) не
харесват ходовите инструкции';
</script>
3. <? echo 'това е най-простата, SGML-ходова инструкция'; ?>
<?= expression ?> Това е съкращение на "<? echo expression ?>"
4. <% echo 'По избор, можете да използвате тагове в стил ASP'; %>
<%= $variable; # Това е съкращение на "<% echo . . ." %>
Въпреки че таговете в примери едно и две са налични винаги, първият пример е най-използван и е препоръчителен.
Късите тагове (пример три) са налични единствено ако са били позволени посредством конфигурационната директива short_open_tag в php.ini или ако php е конфигуриран с --enable-short-tags.
Таговете в стил ASP (пример четири) са налични единствено ако са били позволени посредством конфигурационната директива asp_tags в php.ini.
Забележка: Употребата на къси тагове трябва да бъде избягвана при разработването на приложения или библиотеки, предназначени за повторно разпространение или инсталиране на сървъри с PHP, които не са под ваш контрол, тъй като е възможно късите тагове да не се поддържат на сървъра. За преносим, разпространим код, се осигурете, че не използвате къси тагове.
Също както в C и Perl, PHP изисква инструкциите да бъдат завършвани с точка и запетая на края на всеки израз. Затварящият таг на блок от PHP код автоматично заключва в себе си и точка и запетая; не е необходимо да завършвате с точка и запетая последния ред от PHP блок. Затварящият таг на блока ще включи и непосредствено последващия знак за нов ред, ако има такъв.
<?php
echo 'Това е проба';
?>
<?php echo 'Това е проба' ?>
<?php echo 'Пропуснахме последния затварящ таг';
Забележка: Затварящият таг на PHP блок в края на файл е незадължителен и в някои случаи пропускането му е полезно, в случай че се използва include() или require(), така че да не се появят нежелани празнини в краищата на файловете и да можете да добавяте заглавки към отговора по-късно. Това е удобно и когато използвате буфериране на изхода и не искате да се появява нежелана празнина в края на частите, генерирани от включваните файлове.
PHP поддържа коментари в 'C', 'C++' или Unix shell стил. Например:
<?php
echo 'Това е проба'; // Това е едноредов коментар в стил c++
/* Това е многоредов коментар
още един ред коментар */
echo 'Това е друга проба';
echo 'Последна проба'; # Това е едноредов коментар в стил обвивка (shell)
?>
Едноредовият коментар коментира до края на реда или до края на текущия блок PHP код, което от двете дойде първо. Това означава, че кодът HTML след // ... ?> или # ... ?> ЩЕ БЪДЕ отпечатан: ?> излиза от режим PHP и се връща в режим HTML и // или # не могат да повлияят на това. Поведението е същото с // %> и # %> ако конфигурационната директива asp_tags е включена. Все пак, тагът </script> не излиза от режим PHP при едноредов коментар.
<h1>Това е <?php # echo 'прост';?> пример.</h1>
<p>Заглавието горе ще бъде 'Това е пример'.
Коментарите в стил 'C' завършват при първото срещане на */. Осигурете се, че не влагате коментари в стил 'C' един в друг. Това е лесно допустима грешка при коментиране на голям блок от код.
<?php
/*
echo 'Това е проба'; /* Този коментар ще създаде проблем */
*/
?>
PHP поддържа осем примитивни типа.
Четири скаларни типа:
Два съставни типа:
И накрая, два специални типа:
Това ръководство въвежда също и някои псевдо-типове с цел - по-добра четимост:
И псевдо-променливата $... .
Възможно е да се натъкнете също и на препратки към типа "double" (двоен). Разглеждайте го като число с плаваща запетая (float), двете имена съществуват единствено по исторически причини.
Типът на променливата обикновено не се указва от програмиста; по-често, той се решава по време на изпълнение от PHP в зависимост от контекста, в който е използвана тази променлива.
Забележка: Ако искате да разберете типа и стойността на даден израз, използвайте var_dump(). Ако желаете човешко представяне на типа, с цел откриване на грешки, използвайте gettype(). За да проверите даден тип, не използвайте gettype(), а функциите is_type. Няколко примера:
<?php
$a_bool = TRUE; // булев
$a_str = "foo"; // низ
$an_int = 12; // цяло число
echo gettype($a_bool); // отпечатва "boolean"
echo gettype($a_str); // отпечатва "string"
// Ако това е цяло число, увеличи го с четири
if (is_int($an_int)) {
$int += 4;
}
// Ако $a_bool е низ го отпечатай на екрана
// (does not print out anything)
if (is_string($a_bool)) {
echo "Низ: $a_bool";
}
?>
Ако искате изрично да превърнете променлива в даден тип, можете или да я преобразувате, или да използвате функцията settype() върху нея.
Забележете, че в някои случаи променливата може да бъде изчислена по различен начин, в зависимост от това какъв е типът й в момента. За повече информация, вижте раздела за Манипулации с типове. Също, би представлявало интерес за вас да разгледате таблицата за сравнение на типовете, тъй като там има примери за най-различни сравнения, свързани с типовете.
Това е най-лесния тип. Булевият тип изразява стойност за истинност. Той може да бъде или TRUE (истина), или FALSE (неистина).
Забележка: Булевият тип беше въведен в PHP 4.
За да укажете булев литерал, използвайте една от двете ключови думи: TRUE или FALSE. И двете са нечувствителни към регистъра.
<?php
$foo = True; // присвояване на стойността TRUE на $foo
?>
В повечето случаи се използва някакъв вид оператор, който връща булева стойност, която след това се предава на контролна структура.
<?php
// == е оператор, който проверява
// равенство и връща булев
if ($action == "show_version") {
echo "The version is 1.23";
}
// това не е необходимо...
if ($show_separators == TRUE) {
echo "<hr>\n";
}
// ...защото може просто да напишете
if ($show_separators) {
echo "<hr>\n";
}
?>
За да превърнете изрично стойност в булев тип, използвайте преобразуването (bool) или (boolean). В повечето случаи обаче няма нужда да се използва преобразуване, понеже стойността ще бъде преобразувана автоматично, когато даден оператор, функция или контролна структура изискват булев аргумент.
Вж. също Манипулации с типове.
При преобразуване в булев тип, следните стойности се считат за FALSE:
Всяка друга стойност се смята за TRUE (включително който и да е ресурс).
-1 се смята за TRUE, като всяко друго не-нулево (отрицателно или положително) число!
<?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)
?>
Целочислено е всяко число от множеството Z = {..., -2, -1, 0, 1, 2, ...}.
Вж. също: Цели числа с произволна дължина / GMP, Числа с плаваща запетая и Произволна точност / BCMath
Целите числа могат да бъдат дефинирани в десетична (с основа 10), шестнайсетична (с основа 16) или осмична (с основа 8) бройна система, незадължително предшествани от знак (- или +).
Ако използвате осмична бройна система, трябва да предшествате числото с 0 (нула), а за да използвате шестнайсетична система, трябва да го предшествате с 0x.
Example #1 Целочислени литерали
<?php
$a = 1234; // десетично число
$a = -123; // отрицателно число
$a = 0123; // осмично число (еквивалентно на десетично 83)
$a = 0x1A; // шестнайсетично число (еквивалентно на десетично 26)
?>
Възможните шаблони за цели числа са:
десетично : [1-9][0-9]*
| 0
шестнадесетично : 0[xX][0-9a-fA-F]+
осмично : 0[0-7]+
цяло число : [+-]?decimal
| [+-]?hexadecimal
| [+-]?octal
Размерът на целите числа е платформено-зависим, макар че обикновено максималната стойност е около два милиарда (т.е. 32 бита със знак). PHP не поддържа беззнакови цели числа. Текущият размер на целите числа може да бъде установен посредством PHP_INT_SIZE, а максималната стойност - от PHP_INT_MAX, след PHP 4.4.0 и PHP 5.0.5.
Ако на осмично число бъде подадена невалидна цифра (т.е. 8 или 9), остатъкът от числото ще бъде пренебрегнат.
Example #2 Осмична особеност
<?php
var_dump(01090); // осмично 010 = десетично 8
?>
Ако укажете число извън обхвата на целочисления тип, то ще бъде интерпретирано като число с плаваща запетая. Също така, ако извършите операция, чийто резултат е число извън обхвата на целочисления тип, то също ще бъде върнато в плаващ тип.
<?php
$large_number = 2147483647;
var_dump($large_number);
// изход: int(2147483647)
$large_number = 2147483648;
var_dump($large_number);
// изход: float(2147483648)
// работи също за цели числа, указани в шестнадесетична система, в интервала от 2^31 до 2^32-1:
var_dump( 0xffffffff );
// output: float(4294967295)
// не работи за цели числа, указани в шестнадесетична система, за стойности над 2^32-1:
var_dump( 0x100000000 );
// изход: int(2147483647)
$million = 1000000;
$large_number = 50000 * $million;
var_dump($large_number);
// изход: float(50000000000)
?>
За нещастие, в PHP съществуваше грешка, така че това не работи винаги както трябва, когато са намесени отрицателни числа. Например: когато правите -50000 * $million, резултатът ще бъде -429496728. Все пак, когато и двата операнда са положителни, няма проблем.
Грешката е поправена в PHP 4.1.0.
В PHP няма оператор за целочислено деление. 1/2 дава плаващо 0.5. Можете да преобразувате стойността до цяло число, така че тя винаги да се закръгля надолу, или пък да използвате функцията round().
<?php
var_dump(25/7); // float(3.5714285714286)
var_dump((int) (25/7)); // int(3)
var_dump(round(25/7)); // float(4)
?>
За да превърнете изрично стойност в цяло число, използвайте преобразуването (int) или (integer). В повечето случаи обаче няма нужда да се използва преобразуване, понеже стойността ще бъде преобразувана автоматично, когато даден оператор, функция или контролна структура изискват целочислен аргумент. Можете също да превърнете стойност в цяло число посредством функцията intval().
Вж. също Манипулации с типове.
FALSE ще даде 0 (нула), а TRUE ще даде 1 (едно).
При превръщане от плаващо в цяло, числото ще бъде закръглено към нулата (надолу).
Ако плаващото е извън обхвата на цяло число (обикновено +/- 2.15e+9 = 2^31), резултатът е недефиниран, тъй като плаващото не е имало достатъчно точност, за да даде правилен целочислен резултат. В този случай няма да бъде изведено нито предупреждение, нито дори и съобщение!
Никога не преобразувайте неизвестна дроб в цяло число, защото понякога това може да доведе до неочаквани резултати.
<?php
echo (int) ( (0.1+0.7) * 10 ); // извежда 7!
?>
За повече информация, вижте предупреждението за плаваща точност.
Поведението при превръщане от други типове в цяло число е недефинирано. В момента, поведението е същото, както ако стойността първо е била превърната в булев. Все пак, не разчитайте на това поведение, тъй като в бъдеще то може да се промени без предупреждение.
Числата с плаваща запетая (също познати като "плаващи", "двойни" или "реални числа") могат да бъдат дефинирани посредством кой да е от следните синтаксиси:
<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?>
Формално:
LNUM [0-9]+
DNUM ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM ( ({LNUM} | {DNUM}) [eE][+-]? {LNUM})
Размерът на плаващите числа е платформено-зависим, макар че обикновено максималната стойност е около ~1.8e308, с 14-цифрена точност (64-битов IEEE формат).
В много случаи, прости десетични дроби като 0.1 или 0.7 не могат да бъдат превърнати във вътрешните им двоични еквиваленти без да претърпят малка загуба в точността. Това може да доведе до объркващи резултати: например floor((0.1+0.7)*10) в повечето случаи ще върне 7, вместо очакваното 8, тъй като вътрешното представяне в действителност е нещо подобно на 7.9999999999....
Това е свързано с факта, че някои дроби не могат да бъдат представени в десетичен вид с краен брой цифри. Например 1/3 в десетичен вид става 0.3333333. . ..
Така че, никога не се доверявайте на последните цифри в резултати от плаващи числа и никога не сравнявайте числа с плаваща запетая за равенство. Ако наистина се нуждаете от по-висока точност, трябва да използвате математическите функции за произволна точност или пък функциите gmp.
За информация кога и как низовете биват преобразувани в плаващи, вижте раздела, озаглавен Превръщане на низ в число. За стойности от други типове, преобразуването е същото, както ако стойността първо е била превърната в цяло число и после в плаващо. Вижте раздел Преобразуване в цяло число за повече информация. След PHP 5, ще бъде хвърлено съобщение (notice) ако опитате да превърнете обект в плаващо число.
Низът представлява поредица от знаци. В PHP, знакът е същото като байт, т.е., съществуват точно 256 възможни знака. Това също означава, че PHP няма естествена поддръжка за Unicode. Вж. utf8_encode() и utf8_decode() за Unicode поддръжка.
Забележка: За даден низ не е проблем да стане много дълъг. Няма практическо ограничение в размера на низовете, наложено от PHP, така че не трябва да се безпокоите за дългите низове.
Низов литерал може да бъде дефиниран по три различни начина.
Най-лесният начин да се дефинира обикновен низ е да се загради с апострофи (знакът ').
За да укажете знака апостроф, трябва да го екранирате с обратно-наклонена черта (\), както това се прави и в редица други езици. Ако все пак се налага преди апострофа да се появи обратно-наклонена черта, ще трябва да я дублирате. Отбележете, че ако се опитате да екранирате който и да е друг знак, обратно-наклонената черта също ще бъде отпечатана! Така че обикновено тя няма нужда да бъде екранирана.
Забележка: В PHP 3 ще бъде изведено предупреждение от ниво E_NOTICE, когато това се случи.
Забележка: За разлика от другите два синтаксиса, тук променливите и екраниращите последователности за специални знаци няма да бъдат обработени.
<?php
echo 'това е обикновен низ';
echo 'Можете също да поставяте и
нови редове по този
начин';
// Извежда: Арнолд веднъж каза: "I'll be back"
echo 'Арнолд веднъж каза: "I\'ll be back"';
// Извежда: Вие изтрихте C:\*.*?
echo 'Вие изтрихте C:\\*.*?';
// Извежда: Вие изтрихте C:\*.*?
echo 'Вие изтрихте C:\*.*?';
// Извежда: Това няма да се изведе: \n - нов ред
echo 'Това няма да се изведе: \n - нов ред';
// Извежда: Променливите също: $alpha $beta
echo 'Променливите също: $alpha $beta';
?>
Ако низът е заграден в кавички ("), PHP разбира повече екраниращи последователности за специални знаци:
| последователност | значение |
|---|---|
| \n | нов ред (LF или 0x0A (10) в ASCII) |
| \r | връщане на каретката (CR или 0x0D (13) в ASCII) |
| \t | табулация (HT или 0x09 (9) в ASCII) |
| \v | вертикална табулация (VT или 0x0B (11) в ASCII) (от PHP 5.2.5) |
| \f | form feed (FF или 0x0C (12) в ASCII) (от PHP 5.2.5) |
| \\ | обратно-наклонена черта |
| \$ | знак за долар |
| \" | кавичка |
| \[0-7]{1,3} | последователността от знаци, съвпадаща с регулярния израз, е знак в осмична бройна система |
| \x[0-9A-Fa-f]{1,2} | последователността от знаци, съвпадаща с регулярния израз, е знак в шестнайсетична бройна система |
И тук ако се опитате да екранирате който и да е друг знак, обратно-наклонената черта също ще бъде отпечатана! Преди PHP 5.1.1, обратно-наклонената черта в \{$var} не се отпечатваше.
Най-важната особеност на кавичките, обаче, е че променливите ще бъдат обработени. За повече информация вижте разбор на низ.
Друг начин да се дефинира низ е да се използва синтаксис от тип heredoc ("<<<"). След <<< трябва да се укаже идентификатор (последван от нов ред), след това низа и накрая самия идентификатор, който да затвори цитата.
Затварящият идентификатор трябва да започне в първата колона на реда. Освен това, използваният идентификатор трябва да следва същите правила за именуване като всеки друг етикет в PHP: трябва да се състои единствено от буквено-цифрови знаци или подчертавки и трябва да започва със знак, който не е цифра.
Много важно е да се отбележи, че на реда със затварящия идентификатор няма никакви други знаци, освен по възможност точка и запетая (;). Това преди всичко означава, че идентификаторът не може да бъде отместван като абзац и не може да има никакви интервали или табулации преди или след точката и запетаята. Важно е също да се разбере, че първият знак преди затварящия идентификатор трябва да бъде знака за нов ред, както е дефиниран от съответната операционна система. Например на Macintosh това е \r. Освен това, затварящият идентификатор (по желание последван от точка и запетая) трябва да бъде последван и от знак за нов ред.
Ако това правило не се спази и затварящият идентификатор не е "чист", тогава той няма да бъде възприет като такъв и PHP ще продължи да го търси. Ако в този случай не бъде намерен правилен затварящ идентификатор, това ще доведе до синтактична грешка с номер на реда в края на скрипта.
Не е разрешена употребата на синтаксис от тип heredoc в инициализиране на членове на клас. В този случай използвайте другите низови синтаксиси.
Example #1 Невалиден пример
<?php
class foo {
public $bar = <<<EOT
bar
EOT;
}
?>
Heredoc текстът работи по същия начин както и низът в кавички, само че без кавичките. Това означава, че няма нужда да екранирате кавичките, но че можете да използвате екраниращите кодове изброени по-горе. Променливите биват обработени, но трябва да се внимава при изразяване на сложни променливи вътре в heredoc, какъвто е и случаят с низовете.
Example #2 Пример за цитат от тип heredoc
<?php
$str = <<<EOD
Пример за низ,
който преминава на няколко
реда със синтаксис heredoc.
EOD;
/* По-сложен пример, с променливи. */
class foo
{
var $foo;
var $bar;
function foo()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
$name = 'MyName';
echo <<<EOT
Казвам се "$name". Отпечатвам някое $foo->foo.
Сега, отпечатвам някое {$foo->bar[1]}.
Това трябва да отпечата главно 'A': \x41
EOT;
?>
Забележка: Поддръжката на heredoc беше добавена в 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.
Example #3 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;
?>
Примерът по-горе ще изведе:
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Забележка: Unlike heredocs, nowdocs can be used in any static data context. The typical example is initializing class members or constants:
Example #4 Static data example
<?php
class foo {
public $bar = <<<'EOT'
bar
EOT;
}
?>
Забележка: Nowdoc support was added in PHP 5.3.0.
Когато даден низ се дефинира в кавички или с heredoc, променливите в него биват анализирани.
Съществуват два типа синтаксис: прост и сложен. Простият синтаксис е най-разпространен и удобен. Той предлага начин да се анализира променлива, стойност от масив, или свойство на обект.
Сложният синтаксис беше въведен в PHP 4 и може да бъде разпознат по фигурните скоби, заграждащи израза.
Ако срещне знака за долар ($), синтактичният анализатор ще се опита да поеме лакомо колкото се може повече знаци, за да образува валидно име на променлива. Заградете името на променливата във фигурни скоби, ако искате изрично да укажете края на името.
<?php
$beer = 'Kamenitza';
echo "$beer's taste is great"; // работи, "'" е невалиден знак за име на променлива
echo "He drank some $beers"; // няма да работи, 's' е валиден знак за име на променлива
echo "He drank some ${beer}s"; // работи
echo "He drank some {$beer}s"; // работи
?>
По същия начин се прави разбор и на елемент от масив или свойство на обект. При индексите на масиви, затварящата квадратна скоба (]) обозначава края на индекса. За свойствата на обекти важат същите правила както за обикновените променливи, макар че при обектните свойства не съществува трик като този при променливите.
<?php
// Тези примери са специфични за употребата на масиви в низове.
// Извън низ, винаги заграждайте с апострофи низовите ключове на масиви
// и съответно - не използвайте {фигурни скоби}.
// Нека се показват всички грешки
error_reporting(E_ALL);
$fruits = array('strawberry' => 'red', 'banana' => 'yellow');
// Работи, но отбележете, че това работи по друг начин извън низовите кавички
echo "A banana is $fruits[banana].";
// Работи
echo "A banana is {$fruits['banana']}.";
// Работи, но PHP първо търси константа с името "banana",
// както е обяснено по-долу.
echo "A banana is {$fruits[banana]}.";
// Няма да работи, използвайте фигурни скоби. Това ще предизвика синтактична грешка.
echo "A banana is $fruits['banana'].";
// Работи
echo "A banana is " . $fruits['banana'] . ".";
// Работи
echo "This square is $square->width meters broad.";
// Няма да работи. За решение, вижте сложния синтаксис.
echo "This square is $square->width00 centimeters broad.";
?>
За всичко по-сложно трябва да използвате сложния синтаксис.
Името "сложен" не е защото синтаксисът е сложен, а защото чрез него можете да включвате сложни изрази.
На практика, с този синтаксис можете да включите в низ коя да е стойност, която е налична в пространството от имена. Просто пишете израза по същия начин както бихте го направили извън низа, след което го поставете между { и }. Тъй като не можете да екранирате '{', този синтаксис ще бъде разпознат единствено, когато $ следва непосредствено {. (Използвайте "{\$", за да получите литерала "{$"). Няколко разяснителни примера:
<?php
// Нека се показват всички грешки
error_reporting(E_ALL);
$great = 'fantastic';
// Няма да работи, извежда: This is { fantastic}
echo "This is { $great}";
// Работи, извежда: This is fantastic
echo "This is {$great}";
echo "This is ${great}";
// Работи
echo "This square is {$square->width}00 centimeters broad.";
// Работи
echo "This works: {$arr[4][3]}";
// Това е грешно по същата причина, поради която и $foo[bar] е грешно
// извън низ. С други думи, ще работи, но понеже PHP първо
// ще потърси константата foo, ще хвърли грешка от ниво
// E_NOTICE (недефинирана константа).
echo "This is wrong: {$arr[foo][3]}";
// Работи. При многомерни масиви, винаги поставяйте
// фигурни скоби около масивите, когато са в низове.
echo "This works: {$arr['foo'][3]}";
// Работи.
echo "This works: " . $arr['foo'][3];
echo "You can even write {$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()}}";
?>
Забележка: Извикването на функции и методи в рамките на {$ } работи от PHP 5.
Забележка: Разборът на променливи в рамките на низове използва повече памет отколкото свързването на низове. Когато пишете PHP скрипт, в който паметта е фактор, обмислете възможността да използвате оператора за свързване (.), а не разбор на променливи.
Знаците в даден низ могат да бъдат достъпвани и изменяни чрез указване на отместване от нулата за желания знак след низа посредством квадратни скоби, например $str[42], така че бихте могли да мислите за даден низ като за масив от знаци.
Забележка: Те също могат да бъдат достъпвани и с фигурни скоби - $str{42}, със същата цел. Все пак, употребата на квадратни скоби е за предпочитане, тъй като {фигурният} стил става непрепоръчителен от PHP 6.
Example #5 Някои низови примери
<?php
// Вземане на първия знак от низ.
$str = 'Това е тест.';
$first = $str[0];
// Вземане на третия знак от низ.
$third = $str[2];
// Вземане на последния знак от низ.
$str = 'Това продължава да бъде тест.';
$last = $str[strlen($str)-1];
// Промяна на последния знак от низ.
$str = 'На масата има ябълка';
$str[strlen($str)-1] = 'и';
// Алтернативният метод с {} е непрепоръчителен от PHP 6
$third = $str{2};
?>
Забележка: Достъпването до променливи от друг тип с [] или {} мълчаливо връща NULL.
Низовете могат да бъдат съединявани посредством оператора '.' (точка). Забележете, че операторът '+' (събиране) няма да направи това. За повече информация вижте Низови оператори.
Съществуват доста на брой полезни функции за изменение на низове.
За основните функции вижте раздел низови функции, а за по-сложно търсене и заместване - функциите за регулярни изрази (в две разновидности: Perl и POSIX разширения).
Има също функции за URL низове и функции за криптиране и декриптиране на низове (mcrypt и mhash).
Накрая, ако все още не сте намерили това, което търсите, вижте също и функциите за типове знаци.
Можете да превърнете стойност в низ посредством преобразуването (string) или функцията strval(). Низовото преобразуване се извършва автоматично в обхвата на израз, който се нуждае от низ. Това се случва, когато използвате функциите echo() и print(), или когато сравнявате стойността на променлива с низ. Прочитането на разделите за Типове и Манипулации с типове ще направи нещата още по-ясни. Вж. също settype().
Булевата стойност TRUE се преобразува в низа "1", а стойността FALSE се представя като "" (празен низ). По този начин можете да преобразувате двупосочно между булеви и низови стойности.
Цяло число (integer) или число с плаваща запетая (float) се преобразува в низ, който се състои от цифрите на числото (включително и експонентата - за числата с плаваща запетая). Числата с плаваща запетая може да бъдат преобразувани посредством експоненциалната система за означаване (4.1E+6).
Забележка: Знакът за десетична запетая се дефинира в локалните настройки на скрипта (категория LC_NUMERIC). Вж. setlocale().
Масивите винаги се преобразуват в низа "Array", така че не можете да покажете съдържанието на даден масив с echo() или print(). За да видите един елемент, трябва да направите нещо от рода на echo $arr['foo']. Погледнете по-долу за начини за показване на цялото съдържание.
Обектите в PHP 4 винаги се преобразуват в низа "Object". Ако искате да покажете стойностите на член-променливите на даден обект, с цел отстраняване на програмни грешки, прочетете следващите абзаци. За да видите името на класа, на който е инстанция обектът, използвайте get_class(). От PHP 5 се използва метода __toString(), ако е приложим.
Ресурсите винаги се преобразуват в низове със структура "Resource id #1", където 1 е уникалното число на ресурса, присвоено от PHP по време на изпълнение. Ако искате да вземете типа на ресурса, използвайте get_resource_type().
NULL винаги се преобразува в празен низ.
Както можете да видите по-горе, отпечатването на масиви, обекти или ресурси не ви предоставя никаква полезна информация за самите стойности. Разгледайте функциите print_r() и var_dump() за по-добри начини за показване на стойностите, в процеса на отстраняване на грешки.
Можете също да превърнете стойности от PHP в низове за постоянно съхранение. Този метод се нарича сериализация и може да се осъществи посредством функцията serialize(). Можете също да сериализирате стойности от PHP в XML структури, стига във вашата инсталация на PHP да имате поддръжка за WDDX.
Когато даден низ бъде разпознат като число, резултантната стойност и типът се определят както следва.
Низът ще се изчисли като плаващо ако съдържа който и да е от знаците '.', 'e' или 'E'. В противен случай, ще се изчисли като цяло число.
Стойността се взима от първата част на низа. Ако низът започва с валидни числови данни, това ще бъде и използваната стойност. В противен случай стойността ще бъде 0 (нула). Валидните числови данни са незадължителен знак, последван от една или повече цифри (по желание съдържащи и плаваща запетая), последвани от незадължителна експонента. Експонентата се изразява с латинската буква 'e' или 'E', последвана от една или повече цифри.
<?php
$foo = 1 + "10.5"; // $foo е плаващо (11.5)
$foo = 1 + "-1.3e3"; // $foo е плаващо (-1299)
$foo = 1 + "bob-1.3e3"; // $foo е цяло число (1)
$foo = 1 + "bob3"; // $foo е цяло число (1)
$foo = 1 + "10 малки прасета"; // $foo е цяло число (11)
$foo = 4 + "10.2 малки прасенца"; // $foo е плаващо (14.2)
$foo = "10.0 прасета " + 1; // $foo е плаващо (11)
$foo = "10.0 прасета " + 1.0; // $foo е плаващо (11)
?>
За повече информация относно това преобразуване вижте страницата от ръководството на Unix за strtod(3).
В случай, че искате да проверите някой от примерите в този раздел, можете да ги препишете и да сложите следния ред, за да се уверите сами какво се случва:
<?php
echo "\$foo==$foo; типът е " . gettype ($foo) . "<br />\n";
?>
Не разчитайте да получите кода на даден низ като го преобразувате в цяло число (както бихте направили в C например). Използвайте функциите ord() и chr(), за да правите преобразувания между знаци и съответните им кодове.
Масивът в PHP всъщност представлява подредена асоциация (ordered map). Асоциацията е тип, който асоциира стойности към ключове. Този тип е оптимизиран по няколко направления, така че можете да го използвате като реален масив, като списък (вектор), хеш-таблица (което е реализация на асоциация), речник, колекция, стек, опашка и др. Тъй като за стойност може да имате друг масив, много лесно можете да симулирате и дървета.
Описанието на тези структури от данни е извън обхвата на това ръководство, но ще намерите поне един пример за всяка от тях. За повече информация по тази обширна тема ви препоръчваме да се насочите към външна литература.
Масив може да бъде създаден посредством езиковата конструкция array(). Тя приема определено количество двойки ключ => стойност , разделени със запетаи.
array( ключ => стойност , ... ) // ключът може да бъде цяло число или низ // стойността може да бъде всякаква
<?php
$arr = array("foo" => "bar", 12 => true);
echo $arr["foo"]; // bar
echo $arr[12]; // 1
?>
Ключът може да бъде или цяло число, или низ. Ако ключът е представен като обикновено цяло число, той ще бъде интерпретиран като такова (т.е. "8" ще се интерпретира като 8, докато "08" - като "08"). Плаващите числа в ключовете се съкращават до цели. В PHP не съществуват различни типове за индексирани и асоциативни масиви; има само един тип масив, който може да съдържа едновременно целочислени и низови индекси.
Стойността може да бъде от всякакъв тип.
<?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
?>
Ако не укажете изрично ключ за дадена стойност, то ще се вземе най-голямата стойност от целочислените индекси и новият ключ ще бъде тази стойност + 1. Ако укажете ключ, който вече има присвоена стойност, то тази стойност ще бъде презаписана.
<?php
// Този масив е същият като ...
array(5 => 43, 32, 56, "b" => 12);
// ...този.
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
?>
От PHP 4.3.0 насам поведението за генериране на индекси се промени. Сега ако добавяте към масив, в който текущият максимален ключ е отрицателен, следващият създаден ключ ще бъде нула (0). А преди, новият индекс щеше да бъде установен в най-големия съществуващ ключ + 1, както е случая с положителните индекси.
Използването на TRUE като ключ ще се изчисли като целочислено 1. Употребата на FALSE като ключ ще се изчисли като целочислено 0. Използването на NULL като ключ ще се изчисли като празнен низ. Употребата на празен низ като ключ ще създаде (или презапише) ключ с празен низ и съответната му стойност; това не е същото като използването на празни квадратни скоби.
Не можете да използвате масиви или обекти като ключове. Ако се опитате да го направите ще предизвикате предупреждение: Illegal offset type (невалиден тип отместване).
Можете също да променяте съществуващ масив чрез изрично установяване на стойностите в него.
Това се осъществява чрез присвояване на стойностите в масива, като ключовете се указват в квадратни скоби. Можете също да пропуснете ключа като добавите празна двойка квадратни скоби ("[]") към името на променливата.
$arr[key] = value; $arr[] = value; // key може да бъде цяло число или низ // value може да бъде каква да е стойностАко масивът $arr все още не съществува, той ще бъде създаден. Така че това също е и алтернативен начин за указване на масив. За да промените дадена стойност, просто присвоете нова стойност на елемента, указан чрез ключа му. Ако искате да премахнете някоя двойка ключ/стойност, трябва да я унищожите посредством unset().
<?php
$arr = array(5 => 1, 12 => 2);
$arr[] = 56; // Това е същото като $arr[13] = 56;
// в този момент на скрипта
$arr["x"] = 42; // Това добавя нов елемент към
// масива с ключ "x"
unset($arr[5]); // Това премахва елемент от масива
unset($arr); // Това изтрива целия масив
?>
Забележка: Както беше споменато по-горе, ако предоставите квадратните скоби без указан ключ, тогава ще бъде взет максималния съществуващ целочислен индекс и новият ключ ще бъде тази стойност + 1 . Ако все още няма целочислени индекси, ключът ще бъде 0 (нула). Ако укажете ключ, който вече има присвоена стойност, то тази стойност ще бъде презаписана.
ПредупреждениеОт PHP 4.3.0 насам поведението за генериране на индекси, описано по-горе, се промени. Сега ако добавяте към масив, в който текущият максимален ключ е отрицателен, следващият създаден ключ ще бъде нула (0). А преди, новият индекс щеше да бъде установен в най-големия съществуващ ключ + 1, както е случая с положителните индекси.
Забележете, че максималната целочислена стойност, използвана за целта, не е задължително да същестува в масива в момента. Тя просто трябва да е съществувала някога в масива от последния път, когато масивът е бил повторно индексиран. Следният пример пояснява:
<?php
// Създаване на обикновен масив.
$array = array(1, 2, 3, 4, 5);
print_r($array);
// Сега изтриваме всеки елемент, но оставяме самия масив непокътнат:
foreach ($array as $i => $value) {
unset($array[$i]);
}
print_r($array);
// Добавяне на елемент (забележете, че новият ключ е 5, а не 0, както
// вероятно бихте очаквали).
$array[] = 6;
print_r($array);
// Повторно индексиране:
$array = array_values($array);
$array[] = 7;
print_r($array);
?>Примерът по-горе ще изведе:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) Array ( ) Array ( [5] => 6 ) Array ( [0] => 6 [1] => 7 )
Има няколко полезни функции за работа с масиви. Вж. раздел функции за масиви.
Забележка: Функцията unset() позволява унищожаването на ключове от масив, при което масивът НЯМА да бъде повторно индексиран. Ако използвате единствено "обичайните целочислени индекси" (започващи от нула, увеличаващи се с едно), можете да постигнете ефекта на повторно индексиране като използвате array_values().
<?php
$a = array(1 => 'one', 2 => 'two', 3 => 'three');
unset($a[2]);
/* ще доведе до масив, който би бил дефиниран като
$a = array(1 => 'one', 3 => 'three');
а НЕ като
$a = array(1 => 'one', 2 =>'three');
*/
$b = array_values($a);
// Сега $b е array(0 => 'one', 1 =>'three')
?>
Контролната структура foreach е създадена специално за масиви. Тя предоставя лесен начин за обхождане на масив.
Винаги трябва да заграждате низовите индекси на масиви с апострофи. Например използвайте $foo['bar'], а не $foo[bar]. Но защо все пак $foo[bar] е неправилно? Може би сте виждали следния синтаксис в по-стари скриптове:
<?php
$foo[bar] = 'враг';
echo $foo[bar];
// etc
?>
Това е погрешно, но работи. Защо тогава все пак е погрешно? Причината е, че този код използва недефинирана константа (bar), а не низ ('bar' - забележете апострофите) и в бъдеще е възможно PHP да дефинира константи, които за нещастие на кода ви, да имат същото име. Това работи, защото PHP автоматично преобразува голия низ (не-апострофиран низ, който не отговаря на нито един известен символ) в низ, съдържащ голия низ. Например ако няма дефинирана константа bar, PHP ще сложи на нейно място низа 'bar' и ще използва него.
Забележка: Това не означава, че трябва винаги да апострофирате ключа. Не трябва да апострофирате ключове, които са константи или променливи, тъй като това ще попречи на PHP да ги интерпретира.
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);
// Прост масив:
$array = array(1, 2);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
echo "\nПроверка $i: \n";
echo "Неправилно: " . $array['$i'] . "\n";
echo "Правилно: " . $array[$i] . "\n";
echo "Неправилно: {$array['$i']}\n";
echo "Правилно: {$array[$i]}\n";
}
?>Примерът по-горе ще изведе:
Проверка 0: Notice: Undefined index: $i in /path/to/script.html on line 9 Неправилно: Правилно: 1 Notice: Undefined index: $i in /path/to/script.html on line 11 Неправилно: Правилно: 1 Проверка 1: Notice: Undefined index: $i in /path/to/script.html on line 9 Неправилно: Правилно: 2 Notice: Undefined index: $i in /path/to/script.html on line 11 Неправилно: Правилно: 2
Още илюстриращи примери:
<?php
// Let's show all errors
error_reporting(E_ALL);
$arr = array('fruit' => 'apple', 'veggie' => 'carrot');
// Правилно
print $arr['fruit']; // apple
print $arr['veggie']; // carrot
// Неправилно. Това работи, но също така хвърля грешка в PHP от ниво
// E_NOTICE, заради недефинирана константа fruit
//
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit]; // apple
// Нека дефинираме константа, за да демонстрираме какво става. Ще
// присвоим стойност 'veggie' на константа fruit.
define('fruit', 'veggie');
// Забележете разликата сега
print $arr['fruit']; // apple
print $arr[fruit]; // carrot
// Следното е наред, защото е вътре в низ. В низовете не се търсят константи,
// така че няма да има грешка от ниво E_NOTICE.
print "Hello $arr[fruit]"; // Hello apple
// С едно изключение. Фигурните скоби заобикалящи масиви в низове, позволяват
// намирането на константи.
print "Hello {$arr[fruit]}"; // Hello carrot
print "Hello {$arr['fruit']}"; // Hello apple
// Това няма да работи, ще предизвика синтактична грешка подобна на:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// Разбира се, това се отнася също и за употребата на свръхглобални в низове.
print "Hello $arr['fruit']";
print "Hello $_GET['foo']";
// Същото може да бъде постигнато и чрез съединяване
print "Hello " . $arr['fruit']; // Hello apple
?>
В случай, че повишите нивото на error_reporting() до E_NOTICE (например, задавайки го на ниво E_ALL), ще можете да видите тези грешки. По подразбиране нивото на error_reporting е такова, че да не ги показва.
Както беше споменато и в раздел синтаксис, между квадратните скоби ('[' и ']') трябва да има израз. Това означава, че бихте могли да пишете неща подобни на това:
<?php
echo $arr[somefunc($bar)];
?>
Това е пример за използване на стойност, върната от функция, като индекс на масив. PHP също разбира и от константи, както може би сте забелязали в случая с тези от вида E_*.
<?php
$error_descriptions[E_ERROR] = "Настъпи фатална грешка";
$error_descriptions[E_WARNING] = "PHP изведе предупреждение";
$error_descriptions[E_NOTICE] = "Това е просто информиращо съобщение";
?>
Забележете, че E_ERROR също е валиден индентификатор, също както bar в първия пример. Последният пример всъщност е идентичен на следното:
<?php
$error_descriptions[1] = "Настъпи фатална грешка";
$error_descriptions[2] = "PHP изведе предупреждение";
$error_descriptions[8] = "Това е просто информиращо съобщение";
?>
понеже E_ERROR е равно на 1, и т.н.
Както вече обяснихме по-горе, $foo[bar] работи, но е погрешно. Работи, понеже се очаква bar, заради синтаксиса си, да бъде константен израз. В този случай, обаче, не съществува константа с името bar. Тогава PHP приема, че сте имали предвид литерала bar, като низа "bar", но че сте забравили да напишете кавичките.
В даден момент от бъдещето е възможно екипът на PHP да реши да добави нова константа или ключова дума, или пък вие да решите да добавите константа в собственото си приложение и в този случай се оказвате в беда. Например, вече не можете да използвате думите empty и default по този начин, защото те са специални запазени ключови думи.
Забележка: Да повторим, в рамките на низ, ограден от кавички, е валидно да не заграждате индексите на масивите с апострофи - така "$foo[bar]" е валидно. Вижте горните примери за причините, както и разделът за синтактичен разбор на променливи в низ.
За всеки от типовете: integer (цяло число), float (плаващ), string (низ), boolean (булев) или resource (ресурс), ако преобразувате стойност в масив ще получите масив с единствен елемент (с индекс 0), който е скаларната стойност, която сте подали.
Ако преобразувате обект в масив ще получите свойствата (член-променливите) на обекта като елементи на масива. Ключовете са имената на член-променливите, с някои изключния: частните (private) променливи ще имат добавено името на класа пред името на променливата; защитените (protected) променливи ще имат добавено "*" пред името на променливата. Тези допълнителни стойности имат null байт от двете страни. Това би могло да доведе до неочаквани резултати.
<?php
class A {
private $A; // Това ще стане '\0A\0A'
}
class B extends A {
private $A; // Това ще стане '\0B\0A'
public $AA; // Това ще стане 'AA'
}
var_dump((array) new B());
?>
В горния пример ще изглежда, че има два ключа 'AA', въпреки че единият от тях всъщност е '\0A\0A'.
Ако преобразувате стойността NULL в масив ще получите празен масив.
Можете да сравнявате масиви посредством array_diff() или чрез някой от операторите за масиви.
Типът масив в PHP е много гъвкав, така че ето няколко примера, които да демонстрират пълната мощ на масивите.
<?php
// това
$a = array( 'color' => 'red',
'taste' => 'sweet',
'shape' => 'round',
'name' => 'apple',
4 // ключът ще бъде 0
);
// е абсолютно еквивалентно на
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name'] = 'apple';
$a[] = 4; // ключът ще бъде 0
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// ще създаде масив array(0 => 'a' , 1 => 'b' , 2 => 'c'),
// или просто array('a', 'b', 'c')
?>
Example #1 Употреба на array()
<?php
// асоциативен масив
$map = array( 'version' => 4,
'OS' => 'Linux',
'lang' => 'english',
'short_tags' => true
);
// цифрови ключове
$array = array( 7,
8,
0,
156,
-10
);
// това е същото като array(0 => 7, 1 => 8, ...)
$switching = array( 10, // ключ = 0
5 => 6,
3 => 7,
'a' => 4,
11, // ключ = 6 (най-големият целочислен индекс беше 5)
'8' => 2, // ключ = 8 (целочислен!)
'02' => 77, // ключ = '02'
0 => 12 // стойността 10 ще бъде заменена от 12
);
// празен масив
$empty = array();
?>
Example #2 Колекция
<?php
$colors = array('red', 'blue', 'green', 'yellow');
foreach ($colors as $color) {
echo "Do you like $color?\n";
}
?>
Примерът по-горе ще изведе:
Do you like red? Do you like blue? Do you like green? Do you like yellow?
Прякото променяне на стойности в масив е възможно след PHP 5 чрез подаването им по референция. Предишните версии се нуждаят от заобиколно решение:
Example #3 Колекция
<?php
// PHP 5
foreach ($colors as &$color) {
$color = strtoupper($color);
}
unset($color); /* осигуряване, че последващо писане в
$color няма да промени последния елемент на масива */
// заобикаляне за по-стари версии
foreach ($colors as $key => $color) {
$colors[$key] = strtoupper($color);
}
print_r($colors);
?>
Примерът по-горе ще изведе:
Array
(
[0] => RED
[1] => BLUE
[2] => GREEN
[3] => YELLOW
)
Този пример създава масив, започвайки с ключ едно.
Example #4 Едно-базиран индекс
<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>
Примерът по-горе ще изведе:
Array
(
[1] => 'January'
[2] => 'February'
[3] => 'March'
)
Example #5 Попълване на масив
<?php
// пълнене на масив с всички неща от дадена директория
$handle = opendir('.');
while (false !== ($file = readdir($handle))) {
$files[] = $file;
}
closedir($handle);
?>
Масивите са подредени. Можете също да променяте реда с помощта на някоя подреждаща функции. Вижте раздел функции за масиви за повече информация. Можете да получите броя на елементите в масив с функцията count().
Example #6 Подреждане на масив
<?php
sort($files);
print_r($files);
?>
Тъй като стойността на масив може да бъде всякаква, то съответно тя може да бъде и друг масив. По този начин можете да правите рекурсивни и многомерни масиви.
Example #7 Рекурсивни и многомерни масиви
<?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"
)
);
// някои примери за достъп до масива по-горе
echo $fruits["holes"][5]; // отпечатва "second"
echo $fruits["fruits"]["a"]; // отпечатва "orange"
unset($fruits["holes"][0]); // премахва "first"
// създаване на нов много-измерен масив
$juices["apple"]["green"] = "good";
?>
Трябва да сте наясно, че присвояването в масиви винаги става с копиране по стойност. Това също означава, че вътрешният масивен указател, използван от current() и подобните й функции, се изчиства. За да копирате масив по референция, трябва да използвате референтния оператор.
<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 е променен,
// $arr1 е все още array(2, 3)
$arr3 = &$arr1;
$arr3[] = 4; // сега $arr1 и $arr3 са едно и също
?>
За да създадете нов обект, използвайте инструкцията new, така че да инициализирате клас.
<?php
class foo
{
function do_foo()
{
echo "Doing foo.";
}
}
$bar = new foo;
$bar->do_foo();
?>
За пълно описание, моля прочетете раздел Класове и обекти.
Ако обект бъде преобразуван в обект, то той няма да бъде променен. Ако стойност от кой да е друг тип бъде преобразувана в обект, то се създава нова инстанция на вградения клас stdClass. Ако стойността е била NULL, новата инстанция ще бъде празна. Масив ще се преобразува в обект със свойства, именувани според ключовете на масива и със съответните им стойности. Всяка друга стойност ще бъде налична в член-променливата с име scalar.
<?php
$obj = (object) 'ciao';
echo $obj->scalar; // извежда 'ciao'
?>
Ресурсът е специална променлива, която държи референция към външен източник. Ресурсите се създават и биват използвани посредством специални функции. Вижте приложението за списък с всички тези функции и съответните ресурсни типове.
Забележка: Типът ресурс беше въведен в PHP 4
Вж. също get_resource_type().
Тъй като ресурсите държат специални манипулатори към отворени файлове, връзки към бази от данни, изображения и т.н., преобразуването на каквато и да е стойност в ресурс не е възможно.
Благодарение на системата за броене на референции, въведена в Zend Engine на PHP 4, случаи, в които няма останали референции към даден ресурс, се откриват автоматично (също като в Java). В този случай всички източници, които са били използвани от този ресурс, се освобождават от боклукчията (garbage collector). Затова, рядко се налага паметта да бъде освобождавана ръчно, посредством някоя функция от рода free_result.
Забележка: Постоянните връзки към бази от данни са специални - те не се унищожават от боклукчията. Вижте и раздела относно постоянни връзки.
Специалната стойност NULL обозначава, че променливата няма стойност. NULL е единствената възможна стойност от тип NULL.
Забележка: Типът null беше въведен в PHP 4.
Променливата се счита за NULL ако
й е била присвоена константата NULL.
все още не е установена в никаква стойност.
е била изчистена с unset().
mixed обозначава, че даден параметър може да приема множество (но не непременно всички) типове.
gettype() например приема всички типове в PHP, докато str_replace() приема само низове и масиви.
number обозначава, че параметърът може да бъде или цяло (integer) или плаващо (float) число.
Някои функции като call_user_func() или usort() приемат като параметър потребителски-дефинирани функции за обратно извикване. Последните могат да бъдат не само прости функции, но също и методи на обекти, включително и статични такива.
Функцията в PHP просто се предава с името си под формата на низ. Можете да предавате коя да е вградена или потребителски-дефинирана функция. Забележете, че езикови конструкции като array(), echo(), empty(), eval(), exit(), isset(), list(), print() и unset() не могат да бъдат извикани с обратно извикване.
Метод на инстанцииран обект се предава като масив, съдържащ обекта като елемент с индекс 0 и името на метода като елемент с индекс 1.
Статичните методи на клас също могат да бъдат предавани, без да е необходимо да се инстанциира обект от този клас, чрез предаването на името на класа, вместо обекта, за елемента с индекс 0.
Освен обикновените потребителски-дефинирани функции, create_function() може да бъде изполозвана, за да се създаде анонимна функция за обратно извикване.
Example #1 Примери за функции с обратно извикване
<?php
// Примерна функция за обратно извикване
function my_callback_function() {
echo 'hello world!';
}
// Примерен метод за обратно извикване
class MyClass {
static function myCallbackMethod() {
echo 'Hello World!';
}
}
// Тип 1: Просто извикване
call_user_func('my_callback_function');
// Тип 2: Извикване на статичен метод от клас
call_user_func(array('MyClass', 'myCallbackMethod'));
// Тип 3: Извикване на метод от обект
$obj = new MyClass();
call_user_func(array($obj, 'myCallbackMethod'));
// Тип 4: Извикване на статичен метод от обект (От PHP 5.2.3)
call_user_func('MyClass::myCallbackMethod');
// Тип 5: Относително извикване на статичен метод (От 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
?>
Забележка: В PHP4, ще трябва да използвате референция, за да създадете обратно извикване, което да сочи към самия обект, а не към копие от него. За повече информация вижте Референции.
void във връщания тип означава, че връщаната стойност е безполезна. void в списъка с параметри означава, че функцията не приема никакви параметри.
$... в прототипа на функция означава и така нататък. Това име на променлива се използва, когато функцията може да приеме неограничен брой аргументи.
PHP не изисква (и не поддържа) изрично дефиниране на тип при декларирането на променлива; типът на променливата зависи от контекста, в който се използва. С други думи, ако присвоите низова стойност на променливата $var , $var става низ. Ако в последствие присвоите целочислена стойност на $var , то тя става цяло число.
Пример за автоматичното преобразуване на типове в PHP е операторът за събиране '+'. Ако кой да е от операндите е плаващо число, то всички операнди се изчисляват като плаващи и резултатът ще бъде отново плаващо число. В противен случай операндите ще бъдат интерпретирани като цели числа и резултатът също ще бъде цяло число. Забележете, че това НЕ променя типа на самите операнди; единствената промяна е в начина, по който те се изчисляват.
<?php
$foo = "0"; // $foo е низ (ASCII 48)
$foo += 2; // сега $foo е цяло число (2)
$foo = $foo + 1.3; // сега $foo е плаващо (3.3)
$foo = 5 + "10 Little Piggies"; // $foo е цяло число (15)
$foo = 5 + "10 Small Pigs"; // $foo е цяло число (15)
?>
Ако предните два примера изглеждат неясни, разгледайте Превръщане на низ в число.
Ако желаете изрично да накарате променлива да се изчисли като даден тип, вижте раздела за Преобразуване на типове. Ако желаете да промените типа на променлива, вижте settype().
Ако искате да изпробвате някой от примерите в този раздел, можете да използвате функцията var_dump().
Забележка: Поведението при автоматично преобразуване в масив за момента не е дефинирано.
Също, понеже PHP поддържа индексирането в низове чрез отместване посредством същия синтаксис като индексирането в масиви, следното е в сила за всички версии на PHP:<?php
$a = 'car'; // $a е низ
$a[0] = 'b'; // $a продължава да бъде низ
echo $a; // bar
?>
Вижте раздел Достъп до знаците в низ за повече информация.
Преобразуването на типове в PHP работи доста подобно на това в C: името на желания тип се поставя в скоби преди променливата, която трябва да бъде преобразувана.
<?php
$foo = 10; // $foo е цяло число
$bar = (boolean) $foo; // $bar е от булев тип
?>
Разрешените преобразувания са:
(binary) преобразуването и бъдещата поддръжка на представката b бяха добавени в PHP 5.2.1
Забележете, че табулациите и интервалите са разрешени вътре в скобите, така че следните са функционално еквивалентни:
<?php
$foo = (int) $bar;
$foo = ( int ) $bar;
?>
Преобразуване на буквени низове и променливи в двоични низове:
<?php
$binary = (binary)$string;
$binary = b"binary string";
?>
Забележка: Вместо да преобразувате променлива в низ, можете да я заградите с кавички.
<?php
$foo = 10; // $foo е целочислена
$str = "$foo"; // $str е низ
$fst = (string) $foo; // $fst също е низ
// Това отпечатва, че "те са едни и същи"
if ($fst === $str) {
echo "те са едни и същи";
}
?>
Възможно е резултатът от преобразуването между някои типове да не е съвсем очевиден. За повече информация, вижте тези раздели:
Променливите в PHP се представят чрез знака за долар, последван от името на променливата. Името на променливата е чувствително към регистъра.
Имената на променливите следват същите правила като другите етикети в PHP. Валидното име на променлива започва с буква или подчертавка, последвана от произволен брой букви, цифри или подчертавки. Като регулярен израз, това би могло да бъде представено така: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
Забележка: В случая, под буква се разбират a-z, A-Z и байтовете от 127 до 255 (0x7f-0xff).
Забележка: $this е специална променлива, която не може да бъде присвоявана.
Вж. също Userland Naming Guide.
За информация относно функциите, свързани с променливи, вижте Справочник на функциите за променливи.
<?php
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var"; // извежда "Bob, Joe"
$4site = 'not yet'; // невалидно; започва с цифра
$_4site = 'not yet'; // валидно; започва с подчертавка
$tдyte = 'mansikka'; // валидно; 'д' е (Разширен) ASCII 228.
?>
По подразбиране променливите винаги се присвояват по стойност. С други думи, когато присвоявате израз на променлива, цялата стойност на оригиналния израз се копира в променливата. Това означава, например, че след присвояване стойността на една променлива на друга, променянето на една от тези променливи няма да се отрази на другата. За повече информация относно този тип присвояване, вижте главата за Изрази.
PHP също предлага и още един начин за присвояване на стойности на променливи: присвояване по референция. Това означава, че новата променлива просто указва (с други думи, "става псевдоним на" или "сочи към") оригиналната променлива. Промени в новата променлива влияят на оригиналната и обратно.
За да присвоите променлива по референция, просто сложете амперсанд (&) в началото на променливата, която се присвоява (променливата - източник). Например, следващото парче код извежда 'My name is Bob' два пъти:
<?php
$foo = 'Bob'; // Присвояване на стойността 'Bob' на $foo
$bar = &$foo; // Указване на $foo чрез $bar. (Присвояване по референция)
$bar = "My name is $bar"; // Променяне на $bar...
echo $bar;
echo $foo; // $foo е променена също.
?>
Важно нещо за отбелязване е, че само именувани променливи могат да бъдат присвоявани по референция.
<?php
$foo = 25;
$bar = &$foo; // Това е валидно присвояване.
$bar = &(24 * 7); // Невалидно; указва безименен израз.
function test()
{
return 25;
}
$bar = &test(); // Невалидно.
?>
Инициализирането на променливите в PHP не е необходимо, но все пак е добра практика то да се прави. Неинициализираните променливи имат стойност по подразбиране според типа им в зависимост от контекста, в който се използват - булевите имат стойност по подразбиране FALSE, целочислените и плаващите - нула, низовете (напр. използваните в echo()) се установяват в празен низ, а масивите - в празен масив.
Example #1 Стойности по подразбиране на неинициализирани променливи
<?php
// Неинициализирана И нереферирана (без контекст) променлива; извежда NULL
var_dump($unset_var);
// Употреба на булеви; извежда 'false' (Вж. третичния оператор за повече относно синтаксиса)
echo($unset_bool ? "true\n" : "false\n");
// Употреба на низове; извежда 'string(3) "abc"'
$unset_str .= 'abc';
var_dump($unset_str);
// Употреба на целочислени; извежда 'int(25)'
$unset_int += 25; // 0 + 25 => 25
var_dump($unset_int);
// Употреба на плаващи/двойна точност; извежда 'float(1.25)'
$unset_float += 1.25;
var_dump($unset_float);
// Употреба на масиви; извежда array(1) { [3]=> string(3) "def" }
$unset_arr[3] = "def"; // array() + array(3 => "def") => array(3 => "def")
var_dump($unset_arr);
// Употреба на обекти; създава нов обект от stdClass (вж. http://www.php.net/manual/en/reserved.classes.php)
// Извежда: object(stdClass)#1 (1) { ["foo"]=> string(3) "bar" }
$unset_obj->foo = 'bar';
var_dump($unset_obj);
?>
Да се разчита на стойностите по подразбиране на неинициализирана променлива е проблемно в случай на включване (include) на един файл в друг, който използва същото име на променлива. Това също представлява и значителен риск за сигурността с включена директива register_globals. В случай на работа с неинициализирани променливи се извежда грешка от ниво E_NOTICE, освен в случаите на добавяне на елементи към неициализиран масив. За установяване дали дадена променлива е била инициализирана може да се използва езиковата конструкция isset().
PHP предоставя голям брой предварително-дефинирани променливи във всеки скрипт, който пуска. Много от тези променливи, обаче, не могат да бъдат напълно документирани, тъй като те са зависими от това кой сървър работи, версията и устройството на сървъра, както и от други фактори. Някои от тези променливи няма да бъдат налични, когато PHP се пусне на командния ред. За списък с тези променливи, моля вижте раздела в Запазени предварително-дефинирани променливи.
От PHP 4.2.0 стойността по подразбиране на директивата register_globals в PHP е off (изключено). Това е значителна промяна в PHP. register_globals бидейки off влияе на набора от предварително-дефинирани порменливи, налични в глобалната област на действие. Например, за да вземете DOCUMENT_ROOT ще използвате $_SERVER['DOCUMENT_ROOT'] вместо $DOCUMENT_ROOT, или $_GET['id'] от URL-а http://www.example.com/test.php?id=3 вместо $id, или $_ENV['HOME'] вместо $HOME.
За информация, свързана с тази промяна, прочетете конфигурационната точка за register_globals, главата по сигурността в Използване на регистриране на глобални , също както и PHP съобщенията към изданията на » 4.1.0 и » 4.2.0.
Използването на наличните запазени предварително-дефинирани променливи в PHP, като свръхглобалните масиви, е за предпочитане.
От версия 4.1.0 нататък PHP предоставя допълнителен набор от предварително-дефинирани масиви, съдържащи променливи от уеб сървъра (ако е приложимо), от обкръжението, и от потребителския вход. Тези нови масиви са по-специални с това, че са автоматично глобални, т.е. автоматично налични във всеки обхват. Поради тази причина, те често биват познавани като "свръхглобални" (superglobals). (Няма механизъм в PHP за потребителски дефинирани свръхглобални променливи.) Свръхглобалните променливи са изброени по-долу; все пак, за списък с тяхното съдържание и по-нататъшна дискусия за предварително-дефинираните променливи в PHP и тяхната същност, моля вижте раздела Запазени предварително-дефинирани променливи. Също, ще забележите, че старите предварително-дефинирани променливи ($HTTP_*_VARS) все още съществуват. От PHP 5.0.0, дългите PHP предварително-дефинираните променливи могат да бъдат изключени посредством register_long_arrays директивата.
Забележка: Променливи променливи
Свръхглобалните не могат да бъдат използвани като променливи променливи във функции или методи на клас.
Забележка: Макар че и двете - свръхглобалните и HTTP_*_VARS, могат да съществуват едновременно, те не са идентични, така че модифицирането на едното няма да промени другото.
Ако някои променливи в variables_order не са зададени, съответните им PHP предварително-дефинирани масиви също остават празни.
Област на действие или обхват (scope) на променлива е контекстът, в който тя е дефинирана. На повечето места променливите в PHP имат само една област на действие. Тази единствена област на действие се разпростира също и във включените и в изискваните файлове. Например:
<?php
$a = 1;
include 'b.inc';
?>
Тук променливата $a ще бъде налична във включения скрипт b.inc. В рамките на потребителски-дефинирани функции, обаче, се въвежда локална област на действие. Всяка променлива, използвана вътре във функция, по подразбиране е ограничена в локалната област на действие на функцията. Например:
<?php
$a = 1; /* глобална област на действие */
function test()
{
echo $a; /* референция към променлива от локалната област на действие */
}
test();
?>
Този скрипт няма да изведе нищо, защото изразът echo се отнася за локална версия на променливата $a, а тя няма присвоена стойност в тази област на действие. Вероятно забелязвате, че това е малко по-различно от езика C с това, че в C променливите са налични автоматично във функциите, освен ако не са отменени от локална дефиниция. Това може да създаде проблеми, тъй като човек може по невнимание да промени глобална променлива. В PHP глобалните променливи трябва да бъдат декларирани като глобални вътре в дадена функция, ако ще бъдат използвани в тази функция.
Първо, примерна употреба на global:
Example #1 Употреба на global
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>
Горният скрипт ще изведе "3". Декларирайки $a и $b като глобални за функцията, всички референции към променливите ще сочат към глобалната версия. Няма ограничение в броя на глобалните променливи, които могат да бъдат манипулирани от функция.
Вторият начин за достъп до променливи от глобалния обхват е да се използва специалния масив $GLOBALS в PHP. Предният пример може да бъде пренаписан така:
Example #2 Използване на $GLOBALS вместо global
<?php
$a = 1;
$b = 2;
function Sum()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
Sum();
echo $b;
?>
$GLOBALS е асоциативен масив, в който името на глобалната променлива е ключът, а съдържанието на тази променлива е стойността на елемента от масива. Забележете, че $GLOBALS е наличен във всяка област на действие, a това е така, тъй като $GLOBALS е свръхглобален. Ето пример, демонстриращ възможностите на свръхглобалните:
Example #3 Пример, показващ свръхглобални и обхват
<?php
function test_global()
{
// Повечето предварително-дефинирани променливи не са "super" и изискват
// 'global', за да бъдат налични в локалния обхват на функция.
global $HTTP_POST_VARS;
echo $HTTP_POST_VARS['name'];
// Свръхглобалните са налични във всеки обхват и
// не изискват 'global'. Свръхглобалните са налични
// от PHP 4.1.0, и сега HTTP_POST_VARS се
// смята за непрепоръчителен.
echo $_POST['name'];
}
?>
Друга важна особеност на обхвата на променливите е статичната променлива. Статичната променлива съществува единствено в локалната област на действие на функцията, но не губи стойността си, когато изпълнението на програмата напусне тази област. Разгледайте следния пример:
Example #4 Пример, показващ нуждата от статични променливи
<?php
function test()
{
$a = 0;
echo $a;
$a++;
}
?>
Тази функция е напълно безполезна, тъй като всеки път, когато бива извикана, тя установява $a в 0 и отпечатва "0". Изразът $a++ , който инкрементира променливата, е безсмислен, понеже в момента, в който функцията излезе, променливата $a изчезва. За да направим полезна брояща функция, която да не губи представа за текущата сума, променливата $a се дефинира като статична:
Example #5 Примерна употреба на статични променливи
<?php
function test()
{
static $a = 0;
echo $a;
$a++;
}
?>
Тук $a се инициализира само при първото извикване на функцията и при всяко следващо извикване на test(), тя ще отпечатва стойността на $a и ще я инкрементира.
Статичните променливи предоставят също и начин за работа с рекурсивни функции. Рекурсивна функция е такава, която извиква сама себе си. Трябва да се внимава при писане на рекурсивна функция, защото е възможно тя да бъде принудена да се самоизвиква до безкрайност. Трябва да се уверите, че имате подходящ начин за спиране на рекурсията. Следната проста функция брои рекурсивно до 10, използвайки статичната променлива $count, за да разбере кога да спре:
Example #6 Статични променливи с рекурсивни функции
<?php
function test()
{
static $count = 0;
$count++;
echo $count;
if ($count < 10) {
test();
}
$count--;
}
?>
Забележка: Статичните променливи могат да бъдат декларирани, както в примерите по-горе. Опитът да се присвоят стойности на тези променливи, които са резултат от изрази, ще причини грешка в разбора (parse error).
Example #7 Деклариране на статични променливи
<?php
function foo(){
static $int = 0; // правилно
static $int = 1+2; // грешно (тъй като е израз)
static $int = sqrt(121); // грешно (тъй като също е израз)
$int++;
echo $int;
}
?>
Zend Engine 1, управляваща PHP 4, реализира static и global модификаторите за променливи от гледна точка на референции. Например, истинска глобална променлива, внесена в обхвата на функция посредством израза global, в действителност създава референция към глобалната променлива. Това може да доведе до неочаквано поведение, за което става дума и в следващия пример:
<?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);
?>
Изпълнението на този пример ще изведе следното:
Подобно поведение е в сила и за израза static. Референциите не се пазят статично:
<?php
function &get_instance_ref() {
static $obj;
echo 'Static object: ';
var_dump($obj);
if (!isset($obj)) {
// Присвояване на референция на статичната променлива
$obj = &new stdclass;
}
$obj->property++;
return $obj;
}
function &get_instance_noref() {
static $obj;
echo 'Static object: ';
var_dump($obj);
if (!isset($obj)) {
// Присвояване на обект на статичната променлива
$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();
?>
Изпълнението на този пример ще изведе следното:
Този пример показва, че когато присвоявате референция на статична променлива, при извикването на функцията &get_instance_ref() за втори път, тя не е запомнена.
Понякога е удобно да можем да имаме променливи имена на променливи. Това означава - име на променлива, което може да бъде установявано и използвано динамично. Обикновената променлива се установява посредством израз като:
<?php
$a = 'hello';
?>
Променливата променлива взима стойността на променлива и разглежда тази стойност като име на променлива. В горния пример hello може да бъде използвано за име на променлива с помощта на два доларови знака. Т.е.
<?php
$$a = 'world';
?>
В този момент са дефинирани и съхранени две променливи в символното дърво на PHP: $a със съдържание "hello" и $hello със съдържание "world". Следователно, следният израз:
<?php
echo "$a ${$a}";
?>
ще изведе абсолютно същото като:
<?php
echo "$a $hello";
?>
т.е. и двата извеждат: hello world.
За да използвате променливи променливи с масиви, трябва да разрешите една двусмисленост. А именно, когато напишете $$a[1], синтактичният анализатор трябва да знае дали сте искали да използвате $a[1] като променлива, или сте искали $$a като променлива и [1] като индекс от тази променлива. Синтаксисът за разрешаване на тази двусмисленост е: ${$a[1]} за първия случай и ${$a}[1] за втория.
Моля забележете, че променливите променливи не могат да бъдат използвани със Свръхглобалните масиви на PHP вътре във функции или методи на клас. Освен това променливата $this е специална променлива, която не може да бъде достъпвана динамично.
Когато се предаде формуляр към PHP скрипт, автоматично информацията от този формуляр става достъпна в скрипта. Има много начини за осъществяване на достъп до тази информация, например:
Example #1 Прост HTML формуляр
<form action="foo.php" method="post">
Name: <input type="text" name="username" /><br />
Email: <input type="text" name="email" /><br />
<input type="submit" name="submit" value="Submit me!" />
</form>
В зависимост от вашата дистрибуция, настройки и лични предпочитания, има много начини да осъществявате достъп до данните от вашите HTML формуляри. Ето някои примери:
Example #2 Достъпване на данни от прост POST HTML формуляр
<?php
// Налично от PHP 4.1.0
echo $_POST['username'];
echo $_REQUEST['username'];
import_request_variables('p', 'p_');
echo $p_username;
// След PHP 6 не са налични. От PHP 5.0.0, тези дълги предварително-дефинирани
// променливи могат да бъдат изключвани посредством директивата register_long_arrays.
echo $HTTP_POST_VARS['username'];
// Налично, ако PHP директивата register_globals = on. От
// PHP 4.2.0 стойността по подразбиране на register_globals = off.
// Използването/уповаването на този метод е непрепоръчително.
echo $username;
?>
Изполването на GET формуляр е подобно, с изключение на това, че ще използвате подходящата GET предварително-дефинирана променлива. GET също се отразява и в QUERY_STRING (информацията след '?' в URL). Така че, например http://www.example.com/test.php?id=3 съдържа GET данни, които са достъпни посредством$_GET['id']. Вж. също $_REQUEST и import_request_variables().
Забележка: Свръхглобални масиви, като $_POST и $_GET, станаха налични в PHP 4.1.0
Както показахме, преди PHP 4.2.0 стойността по подразбиране на register_globals беше on. Общността на PHP насърчава всички да не разчитат на тази директива, тъй като е за предпочитане да се приеме, че тя е off и да кодират по съответния начин.
Забележка: Конфигурационната директива magic_quotes_gpc влияе върху Get, Post и Cookie стойностите. Ако е включена, стойността (It's "PHP!") автоматично ще се преобразува в (It\'s \"PHP!\"). Необходимо е избягване при вкарване в база данни. Вж. също addslashes(), stripslashes() и magic_quotes_sybase.
PHP също приема и масиви в контекста на променливи от формуляр. (вж. faq в тази връзка). Например, можете да групирате свързаните променливи заедно, или да използвате това свойство, за да получите стойности, въведени чрез множествен (multiple) select. Нека, например, да изпратим формуляр към него си и при предаването му да извеждаме данните:
Example #3 По-сложни формулярни променливи
<?php
if ($_POST) {
echo '<pre>';
echo htmlspecialchars(print_r($_POST, true));
echo '</pre>';
}
?>
<form action="" method="post">
Име: <input type="text" name="personal[name]" /><br />
E-mail: <input type="text" name="personal[email]" /><br />
Бира: <br />
<select multiple name="beer[]">
<option value="shumensko">Шуменско</option>
<option value="kamenitza">Каменица</option>
<option value="zagorka">Загорка</option>
</select><br />
<input type="submit" value="Изпрати ме!" />
</form>
Когато предавате формуляр, можете да използвате изображение вместо предаващ бутон, посредством таг от типа:
<input type="image" src="image.gif" name="sub" />
Когато потребителят щракне някъде по изображението, придружаващият формуляр ще бъде предаден на сървъра с две допълнителни променливи, sub_x и sub_y. Те съдържат координатите на потребителското щракване върху изображението. По-опитните от вас може би са забелязали, че действителните имена на променливите, изпратени от браузъра, съдържат точки, а не подчертавки, но PHP автоматично превръща точката в подчертавка.
В повечето случаи, PHP не променя имената на променливите, когато биват предадени на скрипт. Трябва да бъде отбелязано обаче, че точката не е валиден знак за име на променлива в PHP. Поради тази причина, прегледайте:
<?php
$varname.ext; /* невалидно име на променлива */
?>
Сега, това което синтактичният анализатор вижда е променлива с име $varname, последвана от оператора за съединяване на низове, последван от голия низ (низ извън кавички, който не съвпада с никой известен ключ или запазена дума) 'ext'. Очевидно, това няма да даде желания резултат.
Поради тази причина е важно да се отбележи, че PHP автоматично ще замести всички точки в постъпващите променливи с подчертавки.
Тъй като PHP установява типовете на променливите и ги преобразува (обикновено) ако е необходимо, не винаги е очевидно от какъв тип е дадена променлива във всеки един момент. PHP включва няколко функции, които откриват от какъв тип е променливата, като: gettype(), is_array(), is_float(), is_int(), is_object() и is_string(). Вж. също глава Типове.
Можете да дефинирате константа посредством функциятаdefine() или чрез ключовата дума const извън дефиницията на клас, от PHP 5.3.0. Веднъж дефинирана, константата никога повече не може да бъде променяна или отменяна.
В константи могат да се съхраняват единствено скаларни данни (boolean, integer, float и string). По принцип е възможно да дефинирате и данни от тип resource, но това трябва да бъде избягвано, тъй като може да доведе до неочаквани резултати.
Можете да вземете стойността на константа като просто укажете името й. За разлика от променливите, пред константа не трябва да слагате $. Можете също да използвате функцията constant(), за да получите стойността на константа, в случай, че желаете да получите името на константата динамично. За списък с всички дефинирани константи, използвайте get_defined_constants().
Забележка: Константите и (глобалните) променливи са в различни пространства от имена (namespaces). Това означава, че TRUE и $TRUE обикновено са различни.
Ако използвате недефинирана константа, PHP приема, че имате предвид името на самата константа, също както ако сте я извикали като string (CONSTANT и "CONSTANT"). Когато това се случи, ще бъде изведена грешка от ниво E_NOTICE. Вижте също раздела, в който се повдига въпросът защо $foo[bar] е погрешно (освен ако преди това не сте дефинирали с define() bar като константа). Ако просто искате да проверите дали дадена константа е дефинирана, използвайте функцията defined().
Това са разликите между константи и променливи:
Example #1 Дефиниране на константи
<?php
define("CONSTANT", "Здравей свят.");
echo CONSTANT; // извежда "Здравей свят."
echo Constant; // извежда "Constant" и пуска съобщение (notice).
?>
Example #2 Дефиниране на константи посредством ключовата дума const
<?php
// Работи от PHP 5.3.0
const CONSTANT = 'Здравей свят';
echo CONSTANT;
?>
Вж. също Класови константи.
PHP предоставя голям брой предварително-дефинирани константи във всеки скрипт, който изпълнява. Много от тези константи, все пак, са създадени от различни разширения и ще бъдат налични единствено, в случай че тези разширения са налични, било то чрез динамично зареждане или защото са били компилирани.
Има седем вълшебни константи, които се променят според мястото, на което се използват. Например, стойността на __LINE__ зависи от реда, на който се използва в скрипта ви. Тези специални константи не са чувствителни към регистъра и са както следва:
| Име | Описание |
|---|---|
| __LINE__ | Текущия номер на реда във файла. |
| __FILE__ | Пълния път и име на файла. Ако се използва вътре във включен (include) файл, ще бъде върнато името на включвания файл. След PHP 4.0.2, __FILE__ винаги съдържа абсолютен път с разпънати символни връзки, докато в по-стари версии, при определени обстоятелства, съдържаше относителен път. |
| __DIR__ | Директорията на файла. Ако се използва вътре във включен (include) файл, ще бъде върната директорията на включвания файл. Това е равносилно на dirname(__FILE__). Това име на директория няма последваща наклонена черта, освен ако не е коренната директория. (Добавена в PHP 5.3.0.) |
| __FUNCTION__ | Името на функцията. (Това беше добавено в PHP 4.3.0) След PHP 5 тази константа връща името на функцията така, както е била дефинирана (чувствително към регистъра). В PHP 4 стойността й винаги е с малки букви. |
| __CLASS__ | Името на класа. (Това беше добавено в PHP 4.3.0) След PHP 5 тази константа връща името на класа така, както е бил дефиниран (чувствително към регистъра). В PHP 4 стойността му винаги е с малки букви. |
| __METHOD__ | Името на метода. (Това беше добавено в PHP 5.0.0) Връща името на метода така, както е бил дефиниран (чувствително към регистъра). |
| __NAMESPACE__ | Името на текущото пространство от имена (чувствително към регистъра). Тази константа се дефинира по време на компилация (Добавена в PHP 5.3.0). |
Вж. също get_class(), get_object_vars(), file_exists() и function_exists().
Константата е индентификатор (име) за проста стойност. Както подсказва и името, тази стойност не може да се променя по време на изпълнение на скрипта (с изключение на вълшебните константи, които всъщност не са константи). Константата е чувствителна към регистъра (case-sensitive) по подразбиране. Неписано правило е константните индентификатори да се пишат винаги с главни букви.
Имената на константите следват същите правила като другите етикети в PHP. Валидното име на константа започва с буква или подчертавка, последвана от произволен брой букви, цифри или подчертавки. Като регулярен израз, това би могло да бъде представено така: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
Вж. също Userland Naming Guide.
Example #1 Валидни и невалидни имена на константи
<?php
// Валидни имена на константи
define("FOO", "нещо");
define("FOO2", "нещо друго");
define("FOO_BAR", "нещо в повече");
// Невалидни имена на константи
define("2FOO", "нещо");
// Това е валидно, но трябва да се избягва:
// Възможно е някой ден PHP да предостави вълшебна константа,
// която ще счупи скрипта ви
define("__FOO__", "нещо");
?>
Забележка: В случая, под буква се разбират a-z, A-Z, и ASCII знаците от 127 до 255 (0x7f-0xff).
Както и за superglobals, константата има глобална област на действие. Можете да достъпвате константи където и да е във вашия скрипт без оглед на контекста. За повече информация относно обхват и контекст, прочетете раздел Област на действие на променливи.
Изразите са най-важните градивни елементи на PHP. Почти всичко, което пишете в PHP, е израз. Най-простият и точен начин да се дефинират изразите е "всичко, което има стойност".
Най-простите форми на изрази са константите и променливите. Когато напишете "$a = 5", вие присвоявате '5' на $a. '5', очевидно има стойност 5, или с други думи, '5' е израз със стойността 5 (в този случай '5' е целочислена константа).
След това присвояване, бихте очаквали стойността на $a да бъде също 5, така че би трябвало $b = $a да работи по същия начин като $b = 5. С други думи, $a също става израз със стойност 5. Ако всичко работи правилно, ще се случи точно това.
Малко по-сложен пример за изрази са функциите. Например, да вземем следната функция:
<?php
function foo ()
{
return 5;
}
?>
Ако приемем, че сте наясно с концепцията за функциите (ако не сте, вижте главата за функции), би трябвало да предположите, че $c = foo() е по същество същото като $c = 5, и ще сте прави. Функциите са изрази със стойност - стойността която връщат. Тъй като foo() връща 5, стойността на израза 'foo()' е 5. Обикновено, функциите не просто връщат статична стойност, а изчисляват нещо.
Разбира се, не е задължително стойностите в PHP да са целочислени и в много случаи те не са. PHP поддържа четири скаларни типа стойности: целочислени стойности, стойности с плаваща запетая (плаващи), низови стойности и булеви стойности (скаларни стойности са такива стойности, които не могат да бъдат 'счупени' на по-малки парчета, както масивите, например). PHP също поддържа два съставни (не-скаларни) типа: масиви и обекти. Всеки един от тези типове стойности може да бъде присвояван на променливи или връщан от функции.
PHP навлиза много по-дълбоко в изразите, както правят и много други езици. PHP е изразно-ориентиран език, в смисъл, че почти всичко е израз. Да вземем примера, който вече разгледахме - '$a = 5'. Лесно е да се види, че в случая има две замесени стойности - стойността на целочислената константа '5' и стойността на $a, която се променя на 5. Но истината е, че тук има замесена още една допълнителна стойност и това е стойността на самото присвояване. Самото присвояване се изчислява на присвоената стойност, която в случая е 5. На практика, това означава, че '$a = 5', независимо от това, което прави, е израз със стойност 5. Така че, писането на нещо като '$b = ($a = 5)' е същото като да напишеш '$a = 5; $b = 5;' (точката и запетаята обозначават край на инструкция). Понеже присвояванията се предават от дясно на ляво, можете също да напишете '$b = $a = 5'.
Друг добър пример за изразна ориентираност са предварителното и последващото инкрементиране и декрементиране. Потребителите на PHP и на много други езици вероятно са запознати с нотацията променлива++ и променлива--. Това са операторите за инкрементиране и декрементиране. В PHP/FI 2, инструкцията '$a++' няма стойност (не е израз), и затова не можете да я присвоите или използвате по никакъв начин. PHP увеличава възможностите на инкрементирането и декрементирането като ги прави също изрази, като в C. В PHP, както в C, има два типа инкрементиране - предварително и последващо. И двете всъщност увеличават стойността на променливата с единица и ефектът върху променливата е един и същ. Разликата е в стойността на инкременталния израз. Предварителното инкрементиране, което се пише '++$променлива', се изчислява на увеличената стойност (PHP инкрементира променливата преди да е прочел стойността й, от там и името 'предварително инкрементиране'). Последващото инкрементиране, което се пише '$променлива++' се изчислява на първоначалната стойност на $променлива, преди да бъде инкрементирана (PHP инкрементира променливата след като е прочел стойността й, от там и името 'последващо инкрементиране').
Широко разпространен тип изрази са изразите за сравнение. Тези изрази се изчисляват или на FALSE или на TRUE. PHP поддържа > (по-голямо), >= (по-голямо или равно), == (равно), != (различно), < (по-малко) и <= (по-малко или равно). Езикът също поддържа набор от стриктни оператори за еквивалентност: === (равно и от същия тип) и !== (различно или не от същия тип). Тези изрази най-често се използват при условно изпълнение, като инструкцията if.
Последният пример за изрази, с който ще се занимаваме, е изразът за операторно присвояване. Вече знаете, че за да увеличите $a с 1, можете просто да напишете '$a++' или '++$a'. Но какво ако искате да добавите повече от единица, например 3? Бихте могли да напишете '$a++' няколко пъти, но това очевидно не е много ефикасен и удобен начин. Много по-разпространена практика е да се напише '$a = $a + 3'. '$a + 3' се изчислява на стойността на $a плюс 3, и се присвоява обратно на $a, което увеличава $a с 3. В PHP, както и в много други езици като C, можете да напишете това по-съкратено, което с времето би трябвало да стане също и по-изчистено и по-разбираемо. Добавянето на 3 към текущата стойност на $a може да се напише така: '$a += 3'. Това буквално означава "вземи стойността на $a, добави 3 към нея и я присвои обратно на $a". Освен че е по-късо и по-изчистено, това също е и по-бързо за изпълнение. Стойността на '$a += 3', също като стойността на обикновено присвояване, е присвояваната стойност. Отбележете, че тя НЕ е 3, а комбинираната стойност от $a плюс 3 (това е стойността, която се присвоява на $a). Всички двуместни оператори могат да бъдат използвани в този операторно-присвоителен режим, например '$a -= 5' (изваждане на 5 от стойността на $a), '$b *= 7' (умножаване стойността на $b със 7) и т.н.
Има още един израз, който може би изглежда странно, ако не сте го виждали досега в други езици - третичния оператор:
<?php
$first ? $second : $third
?>
Ако стойността на първия под-израз е TRUE (не-нула), тогава се изчислява вторият под-израз и това е резултатът на условния израз. В противен случай се изчислява третият под-израз и това е стойността.
Следващият пример би трябвало да ви помогне да разберете по-добре предварителното и последващото инкрементиране и изразите като цяло:
<?php
function double($i)
{
return $i*2;
}
$b = $a = 5; /* присвояване на стойността пет на променливите $a и $b */
$c = $a++; /* последващо инкрементиране, присвояване на първоначалната стойност на $a
(5) на $c */
$e = $d = ++$b; /* предваричелно инкрементиране, присвояване на инкрементираната стойност на
$b (6) на $d и $e */
/* в този момент, и $d и $e са равни на 6 */
$f = double($d++); /* присвояване на удвоената стойност на $d преди инкрементирането
2*6 = 12 на $f */
$g = double(++$e); /* присвояване на удвоената стойност на $e след инкрементирането
2*7 = 14 на $g */
$h = $g += 10; /* първо, $g се увеличава с 10 като се получава стойността 24.
след това, стойността на присвояването (24) се
присвоява на $h, и така $h получава също стойност 24. */
?>
Някои изрази могат да бъдат използвани като инструкции. В този случаи, инструкцията е във формат 'израз' ';', т.е. израз последван от точка и запетая. В '$b=$a=5;', $a=5 е валиден израз, но сам по себе си не е инструкция. '$b=$a=5;', обаче, е валидна инструкция.
Едно последно нещо за споменаване е истинната стойност на изразите. При много събития, главно при условно изпълнение и при цикли, не се интересувате от специфичната стойност на израза, а само дали означава TRUE или FALSE. Константите TRUE (истина) и FALSE (неистина) (нечувствителни към регистъра) са двете възможни булеви стойности. Когато е необходимо, изразът автоматично се преобразува в булев тип. Вж. разделът за преобразуване на типове за подробности как става това.
PHP предлага пълна и мощна реализация на изразите и пълното им документиране излиза извън обхвата на това ръководство. Горните примери би трябвало да са ви дали добра представа за това какво са изразите и как да създавате полезни изрази. В останалата част на това ръководство ще пишем expr, за да обозначим валиден израз в PHP.
Приоритетът на операторите описва колко "плътно" даден оператор свързва два израза. Например, в израза 1 + 5 * 3 отговорът е 16, а не 18, защото операторът за умножение ("*") има по-висок приоритет от оператора за събиране ("+"). Ако е необходимо, могат да бъдат използвани скоби, за да се укаже изрично приоритет. Например: (1 + 5) * 3 се изчислява на 18. Ако два оператора имат еднакъв приоритет се използва асоциативност отляво надясно.
Следната таблица описва приоритета на операторите, като операторите с най-висок приоритет са най-отгоре. Операторите на един и същи ред имат еднакъв приоритет, в който случай редът им на изчисление зависи от съответната им асоциативност.
| Асоциативност | Оператори | Допълнителна информация |
|---|---|---|
| без асоциативност | clone new | clone и new |
| лява | [ | array() |
| без асоциативност | ++ -- | инкрементиране/декрементиране |
| без асоциативност | ~ - (int) (float) (string) (array) (object) (bool) @ | типове |
| без асоциативност | instanceof | типове |
| дясна | ! | логически |
| лява | * / % | аритметични |
| лява | + - . | аритметични и низови |
| лява | << >> | побитови |
| без асоциативност | < <= > >= <> | сравнителни |
| без асоциативност | == != === !== | сравнителни |
| лява | & | побитови и референции |
| лява | ^ | побитови |
| лява | | | побитови |
| лява | && | логически |
| лява | || | логически |
| лява | ? : | третични |
| дясна | = += -= *= /= .= %= &= |= ^= <<= >>= | присвоителни |
| лява | and | логически |
| лява | xor | логически |
| лява | or | логически |
| лява | , | множество употреби |
Лява асоциативност означава, че изразът се изчислява отляво надясно, дясна асоциативност - обратното.
Example #1 Асоциативност
<?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
?>
Използвайте скоби, за да увеличите прегледността на кода.
Забележка: Въпреки че = има по-нисък приоритет от повечето останали оператори, PHP позволява изрази като този: if (!$a = foo()), в който случай изходът на foo() се присвоява на $a.
Спомняте ли си началната аритметика от училище? Тези работят точно по същия начин.
| Пример | Наименование | Резултат |
|---|---|---|
| -$a | Отрицание | Противоположното на $a. |
| $a + $b | Събиране | Сумата на $a и $b. |
| $a - $b | Изваждане | Разликата между $a и $b. |
| $a * $b | Умножение | Произведението на $a и $b. |
| $a / $b | Деление | Частното на $a и $b. |
| $a % $b | Остатък от деление | Остатъкът от $a делено на $b. |
Операторът за деление ("/") връща стойност с плаваща запетая, освен ако двата операнда са цели числа (или низове, които са били превърнати в цели числа) и числата се делят без остатък, в който случай ще бъде върната целочислена стойност.
Операндите на остатък от деление (%) се преобразуват в цели числа (чрез изрязване на десетичната част) преди операцията.
Забележка: Остатъкът от $a % $b е отрицателен за отрицателни $a.
Разгледайте също страницата от ръководството за Математически функции.
Основният оператор за присвояване е "=". Първото ви предположение за него би могло да бъде "равно на". Не трябва. Той всъщност означава, че на левия операнд се присвоява стойността от израза на десния.
Стойността на присвоителния израз е и стойността, която бива присвоявана. Така че стойността на "$a = 3" е 3. Това ви позволява да правите някои хитри неща:
<?php
$a = ($b = 4) + 5; // $a е равно на 9, а на $b е присвоена стойност 4.
?>
Освен основния присвоителен оператор, съществуват и "комбинирани оператори" за всички оператори за двоична аритметика, обединение на масиви и низове, които ви позволяват да използвате стойности в изрази и след това да присвоявате резултата от тези изрази. Например:
<?php
$a = 3;
$a += 5; // присвоява 8 на $a, както ако бяхме казали: $a = $a + 5;
$b = "Ей, ти ";
$b .= "там!"; // присвоява на $b "Ей, ти там!", също както $b = $b . "там!";
?>
Забележете, че присвояването копира оригиналната стойност на новата стойност (присвояване по стойност), така че промените върху едната няма да се отразят на другата. Това би могло да бъде от значение, в случаите когато трябва да копирате неща като големи масиви в тежък цикъл. Присвояването по референция също се поддържа, посредством синтаксиса $var = &$othervar;. 'Присвояването по референция' означава, че и двете променливи сочат към едни и същи данни и нищо не се копира никъде. За да научите повече за референциите, прочетете Обяснение на референциите. След PHP 5, обектите се присвояват по референция, освен ако изрично е указано друго с новата ключова дума clone.
Побитовите оператори ви позволяват да променяте определени битове в целите числа. Ако и левият и десният параметър са низове, побитовият оператор ще оперира с ASCII стойностите на съответния символ.
<?php
echo 12 ^ 9; // Извежда '5'
echo "12" ^ "9"; // Извежда символа за изтриване (Backspace) (ascii 8)
// ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8
echo "hallo" ^ "hello"; // Извежда ASCII стойностите #0 #4 #0 #0 #0
// 'a' ^ 'e' = #4
echo 2 ^ "3"; // Извежда 1
// 2 ^ ((int)"3") == 1
echo "2" ^ 3; // Извежда 1
// ((int)"2") ^ 3 == 1
?>
| Пример | Наименование | Резултат |
|---|---|---|
| $a & $b | И (And) | Вдигат се битовете, които са установени и в $a и в $b. |
| $a | $b | Или (Or) | Вдигат се битовете, които са установени или в $a или в $b. |
| $a ^ $b | Изключващо или (Xor) | Вдигат се битовете, които са установени само в $a или само в $b, но не и в двете едновременно. |
| ~ $a | Не (Not) | Вдигат се битовете, които не са установени в $a, и обратното - тези, които са установени, се свалят. |
| $a << $b | Преместване наляво (Shift left) | Преместване битовете на $a с $b позиции наляво (всяка позиция означава "умножение по две") |
| $a >> $b | Преместване надясно (Shift right) | Преместване битовете на $a с $b позиции наляво (всяка позиция означава "деление на две") |
Не премествайте надясно повече от 32 бита на 32-битови системи. Също, не премествайте наляво в случай, че резултатът ще бъде число по-дълго от 32 бита.
Сравнителните оператори, както подсказва и името им, ви позволяват да сравнявате две стойности. Вероятно бихте били заинтересувани да видите и таблицата със сравнение на типовете, тъй като там има примери със сравнения, свързани с типовете.
| Пример | Наименование | Резултат |
|---|---|---|
| $a == $b | Равно | TRUE ако $a е равна на $b. |
| $a === $b | Идентично | TRUE ако $a е равна на $b и ако са от един и също тип. (въведено в PHP 4) |
| $a != $b | Не-равно | TRUE ако $a не е равна на $b. |
| $a <> $b | Не-равно | TRUE ако $a не е равна на $b. |
| $a !== $b | Не-идентично | TRUE ако $a не е равна на $b или ако не са от един и същи тип. (въведено в PHP 4) |
| $a < $b | По-малко | TRUE ако $a е строго по-малка от $b. |
| $a > $b | По-голямо | TRUE ако $a е строго по-голяма от $b. |
| $a <= $b | По-малко или равно | TRUE ако $a е по-малка или равна на $b. |
| $a >= $b | По-голямо или равно | TRUE ако $a е по-голяма или равна на $b. |
В случай, че сравнявате цяло число с низ, низът бива преобразуван в число. Ако пък сравнявате два цифрови низа, те биват сравнявани като цели числа. Тези правила са в сила също и за инструкцията switch.
<?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": // никога не се достига, тъй като "a" вече е съвпаднала с 0
echo "a";
break;
}
?>
За различните типове сравнението се извършва съгласно следната таблица (по ред).
| Тип на Операнд 1 | Тип на Операнд 2 | Резултат |
|---|---|---|
| null или string | string | Преобразува NULL в "", цифрово или лексикално сравнение |
| bool или null | всякакъв | Преобразува до bool, FALSE < TRUE |
| object | object | Вградените класове могат да дефинират техни собствени сравнения, различните класове са несравними, еднаквите класове - сравняват свойствата по същия начин както масивите (PHP 4), PHP 5 има свое собствено обяснение |
| string, resource или number | string, resource или number | Преобразува низовете и ресурсите до числа, обикновена математика |
| array | array | Масив с по-малко елементи е по-малък, ако даден ключ от първия операнд не бъде намерен във втория, тогава масивите са несравними, иначе - сравнява стойност по стойност (по-долния пример) |
| array | всякакъв | Масивът винаги е по-голям |
| object | всякакъв | Обектът винаги е по-голям |
Example #1 Транскрипция на стандартното сравнение на масиви
<?php
// Масивите биват сравнявани посредством стандартни оператори за сравнение, по следния начин
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; // несравняемо
} elseif ($val < $op2[$key]) {
return -1;
} elseif ($val > $op2[$key]) {
return 1;
}
}
return 0; // $op1 == $op2
}
?>
Вж. също strcasecmp(), strcmp(), Оператори за масиви и разделът от ръководството за Типове.
Друг условен оператор е "?:" (или третичния) оператор.
Example #2 Присвояване на стойност по подразбиране
<?php
// Примерна употреба на: Третичен Оператор
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
// Горното е идентично на тази if/else конструкция
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}
?>
Изразът (expr1) ? (expr2) : (expr3) се изчислява на expr2 ако expr1 се изчисли на TRUE, и на expr3 в случай, че expr1 се изчисли на FALSE.
От PHP 5.3 нататък е възможно да пропуснете средната част на третичния оператор. Изразът expr1 ?: expr3 връща expr1 ако expr1 се изчисли на TRUE, и expr3 - иначе.
Забележка: Забележете, че третичният оператор е израз, и че той не се изчислява до променлива, а до резултата на израза. Това е важно да се знае, когато искате да върнете променлива по референция. Затова изразът return $var == 42 ? $a : $b; във функция, която връща по референция няма да работи и в по-късни версии на PHP ще бъде изведено предупреждение.
Забележка: Препоръчително е да избягвате "натрупването" на третични изрази. Поведението на PHP при използване на повече от един третичен оператор в рамките на един израз не е очевиден:
Example #3 Неясно третично поведение
<?php
// на пръв поглед, следното изглежда, че извежда 'true'
echo (true?'true':false?'t':'f');
// действителният изход, обаче, е 't'
// това е така, понеже третичните изрази се изчисляват от ляво на дясно
// следното е по-ясен вариант на същия код
echo ((true ? 'true' : 'false') ? 't' : 'f');
// в този случай може да видите, че първият израз се изчислява на 'true', което
// от своя страна се изчислява на (bool)true и така се връща истинното разклонение на
// втория третичен израз.
?>
PHP поддържа един оператор за контрол на грешки: символът at (@). Когато бъде поставен пред израз в PHP, всички съобщения за грешка, които биха били генерирани от този израз, ще бъдат пренебрегнати.
Ако свойството track_errors е включено, всички съобщения за грешка, генерирани от израза, ще бъдат запазени в променливата $php_errormsg. Тази променлива ще бъде презаписвана при всяка грешка, така че ако искате да я използвате трябва да я проверявате възможно най-рано.
<?php
/* Intentional file error */
$my_file = @file ('non_existent_file') or
die ("Несполучливо отваряне на файл: грешката беше '$php_errormsg'");
// това работи за всякакви изрази, не само за функции:
$value = @$cache[$key];
// няма да изведе съобщение (notice) ако ключът $key не съществува.
?>
Забележка: Операторът @ работи единствено върху изрази. Правилото е: ако можете да вземете стойността на нещо, то можете да поставите и оператора @ пред него. Например, можете да го слагате пред променливи, извиквания на функции и включвания посредством include(), пред константи, и т.н. Не можете да го поставяте пред дефиниции на функции или класове, или пред условни структури като if и foreach, и т.н.
Вж. също error_reporting() и раздела от ръководството Функции за обработка на грешки и дневници.
Понастоящем употребата на оператора за контрол на грешки "@" ще изключи отчитането на грешки дори и за критични грешки, които прекъсват изпълнението на скрипта. Това също означава, че ако използвате "@", за да подтиснете грешките от дадена функция, и ако последната не е налична или пък е написана погрешно, скриптът ще умре точно на това място без никаква индикация за причината.
PHP поддържа един оператор за изпълнение: обратни апострофи (``). Забележете, че това не са единични кавички! PHP ще опита да изпълни съдържанието на обратните апострофи като команда от обвивката; изходът ще бъде върнат (т.е. няма просто да бъде изкаран на изхода, а може да бъде присвоен на променлива). Употребата на този оператор е идентична на shell_exec().
<?php
$output = `ls -al`;
echo "<pre>$output</pre>";
?>
Забележка: Операторът обратни апострофи е изключен, когато е включен защитен режим или когато функцията shell_exec() е изключена.
Вж. също Функции за изпълнение на програми, popen() proc_open() и Употреба на PHP от командния ред.
PHP поддържа предварително и последващо-инкрементиращи и декрементиращи оператори в стил C.
Забележка: Операторите за инкрементиране (нарастване) и декрементиране (намаляване) не влияят на булеви стойности. Декрементирането на NULL стойности също няма ефект, но инкрементирането им дава резултат 1.
| Пример | Наименование | Ефект |
|---|---|---|
| ++$a | Предварително инкрементиране | Увеличава $a с едно, след което връща $a. |
| $a++ | Последващо инкрементиране | Връща $a, след което увеличава $a с едно. |
| --$a | Предварително декрементиране | Намалява $a с едно, след което връща $a. |
| $a-- | Последващо декрементиране | Връща $a, след което намалява $a с едно. |
Ето прост примерен скрипт:
<?php
echo "<h3>Последващо инкрементиране</h3>";
$a = 5;
echo "Би трябвало да бъде 5: " . $a++ . "<br />\n";
echo "Би трябвало да бъде 6: " . $a . "<br />\n";
echo "<h3>Предварително инкрементиране</h3>";
$a = 5;
echo "Би трябвало да бъде 6: " . ++$a . "<br />\n";
echo "Би трябвало да бъде 6: " . $a . "<br />\n";
echo "<h3>Последващо декрементиране</h3>";
$a = 5;
echo "Би трябвало да бъде 5: " . $a-- . "<br />\n";
echo "Би трябвало да бъде 4: " . $a . "<br />\n";
echo "<h3>Предварително декрементиране</h3>";
$a = 5;
echo "Би трябвало да бъде 4: " . --$a . "<br />\n";
echo "Би трябвало да бъде 4: " . $a . "<br />\n";
?>
PHP следва конвенцията на Perl, когато работи с аритметически операции върху символни променливи, а не тази на C. Например, в Perl 'Z'+1 се превръща в 'AA', докато в C 'Z'+1 се превръща в '[' ( ord('Z') == 90, ord('[') == 91 ). Забележете, че символните променливи могат да бъдат инкрементирани, но не и декрементирани и дори тогава се поддържат единствено знаци в чист ASCII (a-z и A-Z).
Example #1 Аритетмически операции върху символни променливи
<?php
$i = 'W';
for ($n=0; $n<6; $n++) {
echo ++$i . "\n";
}
?>
Примерът по-горе ще изведе:
X Y Z AA AB AC
Инкрементирането или декрементирането на булеви стойности няма ефект.
| Пример | Наименование | Резултат |
|---|---|---|
| $a and $b | И | TRUE ако и $a и $b са TRUE. |
| $a or $b | Или | TRUE ако $a или $b е TRUE. |
| $a xor $b | Изключващо или | TRUE ако или $a или $b е TRUE, но не и двете. |
| ! $a | Не | TRUE ако $a не е TRUE. |
| $a && $b | И | TRUE ако и $a и $b са TRUE. |
| $a || $b | Или | TRUE ако $a или $b е TRUE. |
Причината за съществуването на две разновидности на операторите "и" и "или" е, че те оперират с различен приоритет. (Вж. Приоритет на операторите.)
Example #1 Нагледно пояснение на логическите оператори
<?php
// foo() никога няма да бъде извикана, тъй като операторите водят до късо съединение
$a = (false && foo());
$b = (true || foo());
$c = (false and foo());
$d = (true or foo());
// "||" has има по-висок приоритет от "or"
$e = false || true; // на $e ще бъде присвоена стойността от израза (false || true), която е true
$f = false or true; // на $f ще бъде пристоена стойност false
var_dump($e, $f);
// "&&" има по-висок приоритет от "and"
$g = true && false; // на $g ще бъде присвоена стойността от израза (true && false), която е false
$h = true and false; // на $h ще бъде пристоена стойност true
var_dump($g, $h);
?>
Примерът по-горе ще изведе нещо подобно на:
bool(true) bool(false) bool(false) bool(true)
Съществуват два оператора за низове. Първият е операторът за съединяване ('.'), който връща свързването на левия и десния му аргумент. Вторият е съединително-присвоителният оператор ('.='), който прибавя аргумента от дясната страна на аргумента от лявата страна. Моля прочетете Оператори за присвояване за повече информация.
<?php
$a = "Здравей ";
$b = $a . "свят"; // сега $b съдържа "Здравей свят!"
$a = "Здравей ";
$a .= "свят!"; // сега $a съдържа "Здравей свят!"
?>
Вж. също разделите в ръководството за Тип низ и Низови функции.
| Пример | Наименование | Резултат |
|---|---|---|
| $a + $b | Обединение | Обединението на $a и $b. |
| $a == $b | Равенство | TRUE ако $a и $b имат едни и същи двойки ключ/стойност. |
| $a === $b | Идентичност | TRUE ако $a и $b имат едни и същи двойки ключ/стойност в един и същи ред и са от един и същи тип. |
| $a != $b | Неравенство | TRUE ако $a не е равно на $b. |
| $a <> $b | Неравенство | TRUE ако $a не е равно на $b. |
| $a !== $b | Неидентичност | TRUE ако $a не е идентично на $b. |
Операторът + добавя елементи от оставащите ключове на масива от дясната страна на този от лявата страна, при което дублиращите се ключове НЕ се презаписват.
<?php
$a = array("a" => "ябълка", "b" => "банан");
$b = array("a" => "круша", "b" => "ягода", "c" => "череша");
$c = $a + $b; // Обединенито на $a и $b
echo "Обединението на \$a и \$b: \n";
var_dump($c);
$c = $b + $a; // Обединението на $b и $a
echo "Обединението на \$b и \$a: \n";
var_dump($c);
?>
Когато бъде изпълнен, този скрипт ще отпечата следното:
Обединението на $a и $b:
array(3) {
["a"]=>
string(6) "ябълка"
["b"]=>
string(5) "банан"
["c"]=>
string(6) "череша"
}
Обединението на $b и $a:
array(3) {
["a"]=>
string(5) "круша"
["b"]=>
string(5) "ягода"
["c"]=>
string(6) "череша"
}
За целите на сравнението елементите на масивите се считат за равни ако имат едни и същи ключ и стойност.
Example #1 Сравняване на масиви
<?php
$a = array("ябълка", "банан");
$b = array(1 => "банан", "0" => "ябълка");
var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>
Вж. също разделите от ръководството за Тип масив и Функции за масиви.
instanceof се използва, за да се установи дали дадена променлива в PHP представлява инстанцииран обект от определен клас:
Example #1 Употреба на instanceof с класове
<?php
class MyClass
{
}
class NotMyClass
{
}
$a = new MyClass;
var_dump($a instanceof MyClass);
var_dump($a instanceof NotMyClass);
?>
Примерът по-горе ще изведе:
bool(true) bool(false)
instanceof може също да се използва и за определяне дали променливата е инстанцииран обект от клас, който наследява родителския клас:
Example #2 Употреба на instanceof с наследени класове
<?php
class ParentClass
{
}
class MyClass extends ParentClass
{
}
$a = new MyClass;
var_dump($a instanceof MyClass);
var_dump($a instanceof ParentClass);
?>
Примерът по-горе ще изведе:
bool(true) bool(true)
За проверка дали даден обект не е инстанция на клас, може да се използва логическия оператор not.
Example #3 Употреба на instanceof за проверка дали даден обект не е инстанция на клас
<?php
class MyClass
{
}
$a = new MyClass;
var_dump(!($a instanceof stdClass));
?>
Примерът по-горе ще изведе:
bool(true)
Накрая, instanceof може също да се използва и за да се установи дали дадена променлива представлява инстанция на обект от клас, който осъществява интерфейс:
Example #4 Употреба на instanceof за клас
<?php
interface MyInterface
{
}
class MyClass implements MyInterface
{
}
$a = new MyClass;
var_dump($a instanceof MyClass);
var_dump($a instanceof MyInterface);
?>
Примерът по-горе ще изведе:
bool(true) bool(true)
Въпреки че instanceof обикновено се използва с буквеното име на класа, той също може да бъде използван и с друг обект или низова променлива:
Example #5 Употреба на instanceof с други променливи
<?php
interface MyInterface
{
}
class MyClass implements MyInterface
{
}
$a = new MyClass;
$b = new MyClass;
$c = 'MyClass';
$d = 'NotMyClass';
var_dump($a instanceof $b); // $b е обект от клас MyClass
var_dump($a instanceof $c); // $c е низа 'MyClass'
var_dump($a instanceof $d); // $d е низа 'NotMyClass'
?>
Примерът по-горе ще изведе:
bool(true) bool(true) bool(false)
Има няколко клопки, за които трябва да се внимава. Преди версия 5.1.0 на PHP instanceof ще извика __autoload() ако класът не съществува. Освен това, ако класът не е бил зареден, това ще доведе до фатална грешка. Това може да бъде заобиколено като се използва динамична референция към клас или низова променлива, съдържаща името на класа:
Example #6 Избягване търсенето на клас и фатални грешки с instanceof в PHP 5.0
<?php
$d = 'NotMyClass';
var_dump($a instanceof $d); // в случая фатална грешка няма
?>
Примерът по-горе ще изведе:
bool(false)
Операторът instanceof беше въведен в PHP 5. Преди това се използваше is_a(), но от тогава се препоръчва вместо него да се използва instanceof. От PHP 5.3.0 нататък is_a() вече не е непрепоръчителна.
Вж. също get_class() и is_a().
Операторът е нещо, на което се подават една или повече стойности (или изрази, казано на програмистки език), и който дава като резултат друга стойност (така че конструкцията сама по себе си да стане израз). С други думи, можете да считате функциите или конструкциите, които връщат стойност (като print), за оператори, а тези, които не връщат нищо (като echo) - за всичко останало.
Съществуват три типа оператори. Първият тип са унарните оператори, които оперират върху една единствена стойност, например ! (оператора за отрицание) или ++ (оператора за инкрементация). Втората група са двоичните оператори; тази група съдържа повечето оператори, които поддържа PHP, и списък с тях следва по-долу в раздела Приоритет на операторите.
Третата група е третичния оператор: ?:. Той трябва да бъде използван при избор между два израза, зависещи от трети израз, а не при избор между две изречения или два пътя на изпълнение. Заграждането на третичните изрази със скоби е много добра идея.
Всеки PHP скрипт се състои от поредици от инструкции. Инструкция може да бъде задаване на стойност, извикване на функция, цикъл, условен израз или дори инструкция, която не прави нищо (празен израз). Инструкциите обикновено завършват с точка и запетая. В допълнение, инструкциите могат и да бъдат групирани като групата от инструкции се загради във фигурни скоби. Групата от инструкции сама по себе си също представлява инструкция. В тази глава са описани различните видове инструкции.
Конструкцията if (ако) е едно от най-важните свойства на много езици, включително и на PHP. Тя позволява условно изпълнение на части от кода. PHP предоставя структура if, подобна на тази в C:
if (expr)
statement
Както е описано и в раздела за изразите, expression се изчислява до булевата си стойност. Ако expression се изчисли на TRUE, PHP ще изпълни statement, а ако се изчисли на FALSE - ще го пренебрегне. Повече информация относно това кои стойности се изчисляват на FALSE може да бъде намерена в раздела 'Превръщане в булев тип'.
Следващият пример ще изведе a е по-голямо от b ако $a е по-голяма от $b:
<?php
if ($a > $b)
echo "a е по-голямо от b";
?>
В много случаи ще искате условното изпълнение на повече от една инструкция. Разбира се, няма нужда да обвивате всеки израз с клауза if. Вместо това, можете да групирате няколко инструкции в група от инструкции. Например, този код ще изведе a е по-голямо от b ако $a е по-голяма от $b и след това ще присвои стойността на $a в $b:
<?php
if ($a > $b) {
echo "a е по-голямо от b";
$b = $a;
}
?>
Kонструкциите if могат да бъдат вмествани безкраен брой пъти в други конструкции if, което ви дава пълна гъвкавост за условното изпълнение на различни части от вашата програма.
В много случаи ще искате да изпълните една инструкция ако дадено условие е изпълнено и друга инструкция, ако условието не е изпълнено. Точно за това служи else (иначе). else разширява конструкцията if, като изпълнява инструкция в случай, че изразът в конструкцията if се изчисли на FALSE. Например, следният код ще изведе a е по-голямо от b ако $a е по-голяма от $b, или a НЕ е по-голямо от b - в противен случай:
<?php
if ($a > $b) {
echo "a е по-голямо от b";
} else {
echo "a НЕ е по-голямо от b";
}
?>
Конструкцията else се изпълнява само ако изразът if се е изчислил на FALSE и всички налични изрази elseif (ако има такива) са се изчислили също на FALSE (вж. elseif).
elseif, както подсказва и името й, е комбинация от if и else. Също както else, тя разширява конструкцията if така, че да изпълни различна инструкция, в случай че първоначалният израз if се е изчислил на FALSE. За разлика от else обаче тя ще изпълни този алтернативен израз само ако условният израз elseif се изчислява на TRUE. Например, следният код ще изведе a е по-голямо от b, a е равно на b или a е по-малко от b:
<?php
if ($a > $b) {
echo "a е по-голямо от b";
} elseif ($a == $b) {
echo "a е равно на b";
} else {
echo "a е по-малко от b";
}
?>
В рамките на една конструкция if може да има много изрази elseif. Първият израз elseif (ако има такъв), който се изчисли на TRUE ще бъде изпълнен. В PHP можете също да напишете и 'else if' (с две думи) и поведението му ще бъде идентично на 'elseif' (с една дума). Синтактичното значение е малко по-различно (ако сте запознати със C, тук е налице същото поведение), но последният ред е този, който и в двата случая ще има абсолютно същото поведение.
Конструкцията elseif се изпълнява само ако предшестващият израз if и всички предшестващи изрази elseif се изчислят на FALSE и текущият израз elseif се е изчислил на TRUE.
Забележка: Забележете, че elseif и else if ще бъдат разгледани като напълно еднакви, единствено когато се използват къдрави скоби, както в горния пример. Когато използвате двоеточие, за да дефинирате вашите условия if/elseif, не трябва да разделяте else if на две думи, в противен случай PHP ще се провали със синтактична грешка.
<?php
/* Неправилен метод: */
if($a > $b):
echo $a." е по-голямо от ".$b;
else if($a == $b): // Няма да се компилира.
echo "Горният ред предизвиква синтактична грешка.";
endif;
/* Правилен метод: */
if($a > $b):
echo $a." е по-голямо от ".$b;
elseif($a == $b): // Забележете комбинацията от думи.
echo $a." е равно на ".$b;
else:
echo $a." не е по-голямо или равно на ".$b;
endif;
?>
PHP предоставя алтернативен синтаксис за някои от контролните структури, а именно: if, while, for, foreach и switch. Във всички случаи, основната форма на алтернативния синтаксис се получава като се смени отварящата фигурна скоба на двоеточие и затварящата къдрава скоба съответно на endif;, endwhile;, endfor;, endforeach; или endswitch;.
<?php if ($a == 5): ?>
A е равно на 5
<?php endif; ?>
В горния пример, HTML блокът "A е равно на 5" е вложен в конструкция if, написана с алтернативния синтаксис. HTML блокът ще бъде изведен само ако $a е равна на 5.
Алтернативният синтаксис важи също и за else и elseif. Следващият пример представлява структурата if с elseif и else в алтернативен формат:
<?php
if ($a == 5):
echo "a е равно на 5";
echo "...";
elseif ($a == 6):
echo "a е равно на 6";
echo "!!!";
else:
echo "a не е нито 5, нито 6";
endif;
?>
Циклите while (докато) са най-простия тип цикъл в PHP. Те работят по същия начин както техния еквивалент в C. Основната форма на конструкцията while е:
while (expr)
statement
Смисълът на конструкцията while е прост. Тя казва на PHP да повтаря изпълнението на вложените конструкции, докато изразът while се изчислява на TRUE. Стойността на израза се проверява всеки път в началото на цикъла, така че дори и тази стойност да се промени докато се изпълняват вложените конструкции, изпълнението няма да спре докато не се достигне края на итерацията (всеки път, когато PHP пуска конструкциите в цикъла, е една итерация). В случай че изразът while се изчисли на FALSE от самото начало, вложените конструкции няма да бъдат пуснати нито веднъж.
Също както и с конструкцията if, можете да групирате множество конструкции в един и същи цикъл while като оградите групата от конструкции с фигурни скоби, или като използвате алтернативен синтаксис:
while (expr):
statement
...
endwhile;
Следните примери са идентични като и двата отпечатват числата от 1 до 10:
<?php
/* пример 1 */
$i = 1;
while ($i <= 10) {
echo $i++; /* отпечатаната стойност ще бъде
$i преди инкрементацията
(пост-инкрементация) */
}
/* пример 2 */
$i = 1;
while ($i <= 10):
echo $i;
$i++;
endwhile;
?>
Циклите do-while (прави-докато) са подобни на циклите while, с тази разлика, че вместо в началото, изразът за истинност се проверява в края на всяка итерация. Основната разлика от обикновените цикли while е, че първата итерация на цикъл do-while със сигурност ще се изпълни (условието се проверява единствено в края на итерацията), докато при циклите while не е задължително да се изпълни (условието се проверява в началото на всяка итерация, така че ако се изчисли на FALSE от самото начало, цикълът ще завърши незабавно).
Съществува само един синтаксис за цикли do-while:
<?php
$i = 0;
do {
echo $i;
} while ($i > 0);
?>
Горният цикъл ще се изпълни точно един път, тъй като след първата итерация, когато се провери условието, то ще се изчисли на FALSE ($i не е по-голяма от 0) и изпълненито на цикъла ще спре.
Напредналите програмисти на C може би са запознати с една друга употреба на цикъла do-while: в случай че трябва да се спре изпълнението в средата на блокове от код, те се заграждат с do-while (0) и се използва командата break. Следният фрагмент от код демонстрира това:
<?php
do {
if ($i < 5) {
echo "i не е достатъчно голямо";
break;
}
$i *= $factor;
if ($i < $minimum_limit) {
break;
}
echo "i е ОК";
/* работа с i */
} while (0);
?>
Не се притеснявате ако не разберете това веднага или изобщо никога. Можете да пишете скриптове и то мощни скриптове без да използвате това 'свойство'.
Циклите for (за) са най-сложните цикли в PHP. Те се държат по същия начин като техния еквивалент в C. Синтаксисът на цикъл for е:
for (expr1; expr2; expr3) statement
Първият израз (expr1) се изчислява (изпълнява) безусловно веднъж в началото на цикъла.
expr2 се изчислява в началото на всяка итерация. Ако се изчисли на TRUE, цикълът продължава и вложените команди се изпълняват. Ако се изчисли на FALSE, изпълнението на цикъла свършва.
expr3 се изчислява (изпълнява) в края на всяка итерация.
Всеки един от изразите може да бъде празен или да съдържа множество изрази, разделени със запетая. В expr2 се изчисляват всички изрази, разделени със запетая, но резултатът се взима само от последната част. Ако expr2 е празен, това означава, че цикълът ще се изпълнява безкрайно (PHP имплицитно го смята за TRUE, както C). Това би могло и да не бъде толкова безполезно, колкото може би ви се струва, тъй като в много случаи ще искате да прекъснете цикъла посредством команда break, вместо да изполвате истинния израз във for.
Разгледайте следните примери. Всички те извеждат числата от 1 до 10:
<?php
/* пример 1 */
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
/* пример 2 */
for ($i = 1; ; $i++) {
if ($i > 10) {
break;
}
echo $i;
}
/* пример 3 */
$i = 1;
for (; ; ) {
if ($i > 10) {
break;
}
echo $i;
$i++;
}
/* пример 4 */
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
?>
Разбира се, първият пример изглежда най-добре (или може би четвъртият), но вероятно в много случаи ще оцените възможността за използване на празни изрази в цикли for за доста удобна.
PHP поддържа също и заместващия "двуеточен синтаксис" за цикли for.
for (expr1; expr2; expr3):
statement
...
endfor;
Често срещано сред потребителите е да обикалят през масивите като в примера по-долу.
<?php
/*
* Това е масив с данни, които искаме да променим,
* докато работи цикълът for.
*/
$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);
}
?>
Проблемът е във втория израз на for. Този код може да бъде бавен, защото на всяка итерация трябва да изчисли размера на масива. Тъй като размерът не се променя никога, кодът може да бъде оптимизиран лесно посредством междинна променлива, в която да се съхрани размера и в цикъла да се използва тази променлива, вместо sizeof. По-долният пример илюстрира това:
<?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 беше въведена конструкция foreach (за всеки), много наподобяваща тази в Perl и в някои други езици. Тя предоставя лесен начин за обхождане на масиви. foreach работи само с масиви и ще изведе грешка, ако се опитате да я използвате върху променлива от друг тип или върху неинициализирана променлива. Съществуват два синтаксиса; вторият е минимално, но полезно разширение на първия:
foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement
Първата форма обикаля през зададения от array_expression масив. При всяка итерация стойността на текущия елемент се присвоява на $value и вътрешният указател на масива се придвижва с единица (така че при следващата итерация, ще гледате следващия елемент).
Втората форма прави същото нещо, с тази разлика, че ключът на текущия елемент ще бъде присвоен на променливата $key при всяка итерация.
След PHP 5 е възможно също да обхождате и обекти.
Забележка: Когато foreach започва първоначалното си изпълнение, вътрешният указател на масива автоматично се нулира, така че да сочи към първия елемент на масива. Това означава, че няма нужда да извиквате reset() преди цикъл foreach.
Забележка: С изключение на случаите, в които масивът е указан с референция, foreach ще работи с копие от зададения масив, а не със самия масив. foreach има някои странични ефекти върху указателя на масива. Не разчитайте на указателя на масива по време или след изпълнението на foreach без да сте го изчистили изрично.
От PHP 5 нататък лесно можете да променяте елементите на даден масив като предшествате $value с &. Това ще присвои по референция, вместо да копира стойността.
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// в този момент $arr е array(2, 4, 6, 8)
unset($value); // премахване референцията към последния елемент
?>
Това е възможно единствено, в случай че обхожданият масив може да бъде указван с референция (т.е. ако е променлива).
Референцията между $value и последния елемент от масива остава дори и след приключването на цикъла foreach. Препоръчително е да я унищожите посредством unset().
Забележка: foreach не поддържа възможността за подтискане на съобщения за грешка чрез използване на '@'.
Може би сте забелязали, че следните примери са функционално идентични:
<?php
$arr = array("едно", "две", "три");
reset ($arr);
while (list(, $value) = each ($arr)) {
echo "Стойност: $value<br />\n";
}
foreach ($arr as $value) {
echo "Стойност: $value<br />\n";
}
?>
Следните примери са също функционално идентични:
<?php
$arr = array("едно", "две", "три");
reset($arr);
while (list($key, $value) = each ($arr)) {
echo "Ключ: $key; Стойност: $value<br />\n";
}
foreach ($arr as $key => $value) {
echo "Ключ: $key; Стойност: $value<br />\n";
}
?>
Още няколко примера за демонстриране на употребата:
<?php
/* foreach пример 1: само стойност */
$a = array(1, 2, 3, 17);
foreach ($a as $v) {
echo "Текущата стойност на \$a: $v.\n";
}
/* foreach пример 2: value (нагледно, с отпечатване на ръчната нотация) */
$a = array(1, 2, 3, 17);
$i = 0; /* само за нагледни цели */
foreach ($a as $v) {
echo "\$a[$i] => $v.\n";
$i++;
}
/* foreach пример 3: ключ и стойност */
$a = array(
"едно" => 1,
"две" => 2,
"три" => 3,
"седемнадесет" => 17
);
foreach ($a as $k => $v) {
echo "\$a[$k] => $v.\n";
}
/* foreach пример 4: многомерни масиви */
$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 пример 5: динамични масиви */
foreach (array(1, 2, 3, 4, 5) as $v) {
echo "$v\n";
}
?>
break прекъсва изпълнението на текущата структура for, foreach, while, do-while или switch.
break приема незадължителен цифров параметър, който указва колко вложени заграждащи структури да бъдат прекъснати.
<?php
$arr = array('едно', 'две', 'три', 'четири', 'стоп', 'пет');
while (list (, $val) = each ($arr)) {
if ($val == 'стоп') {
break; /* Тук бихте могли да напишете също и 'break 1;'. */
}
echo "$val<br />\n";
}
/* Използване на незадължителния параметър. */
$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "В 5<br />\n";
break 1; /* Изход само от switch. */
case 10:
echo "В 10; излизане<br />\n";
break 2; /* Изход от switch и от while. */
default:
break;
}
}
?>
continue (продължи) се използва в циклични структури, за да се пропусне остатъка от текущата итерация и изпълнението да продължи в проверката на условието и след това в началото на следващата итерация.
Забележка: Забележете, че в PHP конструкцията switch се смята за циклична структура в контекста на continue.
continue приема незадължителен цифров параметър, който указва до края на колко нива на заграждащи цикли трябва да пропусне.
<?php
while (list ($key, $value) = each ($arr)) {
if (!($key % 2)) { // пропускане на нечетните членове
continue;
}
do_something_odd ($value);
}
$i = 0;
while ($i++ < 5) {
echo "Външен<br />\n";
while (1) {
echo " Среден<br />\n";
while (1) {
echo " Вътрешен<br />\n";
continue 3;
}
echo "Това никога няма да бъде изведено.<br />\n";
}
echo "Нито пък това.<br />\n";
}
?>
Пропускането на точката и запетаята след continue може да доведе до объркване. Ето пример за това какво не трябва да правите.
<?php
for ($i = 0; $i < 5; ++$i) {
if ($i == 2)
continue
print "$i\n";
}
?>
Някои ще очакват резултатът да бъде:
0 1 3 4
но скриптът ще изведе:
2
защото връщаната стойност от извикването на print() е int(1), а тя ще изглежда като незадължителния цифров параметър, споменат по-горе.
Kонструкцията switch (пренасочвам) наподобява поредица от конструкции IF върху един и същи израз. В много случаи, ще искате да сравните една и съща променлива (или израз) с много различни стойности и да изпълните различно парче код, в зависимост от това на коя стойност отговаря. Точно за това служи конструкцията switch.
Забележка: Забележете, че за разлика от някои други езици, инструкцията continue важи за switch и работи подобно на break. Ако имате switch вътре в цикъл и искате да продължите със следващата итерация на външния цикъл, използвайте continue 2.
Забележка: Забележете, че switch/case извършва свободно сравнение.
Следващите два примера представляват два различни начина да напишете едно и също нещо, едното чрез изполване на поредица от инструкции if и elseif, а другото - с конструкция switch:
Example #1 Структура switch
<?php
if ($i == 0) {
echo "i е равно на 0";
} elseif ($i == 1) {
echo "i е равно на 1";
} elseif ($i == 2) {
echo "i е равно на 2";
}
switch ($i) {
case 0:
echo "i е равно на 0";
break;
case 1:
echo "i е равно на 1";
break;
case 2:
echo "i е равно на 2";
break;
}
?>
Example #2 Структурата switch работи и с низове
<?php
switch ($i) {
case "ябълка":
echo "i е ябълка";
break;
case "круша":
echo "i е круша";
break;
case "кекс":
echo "i е кекс";
break;
}
?>
За да се избегнат грешки, е важно да се разбере как се изпълнява конструкцията switch. Тя се изпълнява ред по ред (всъщност, инструкция по инструкция). В началото не се изпълнява никакъв код. Чак когато се срещне инструкцията case (случай) със стойност, която да съвпада със стойността на израза switch, PHP започва да изпълнява инструкциите. PHP продължава да ги изпълнява докато не достигне края на switch блока, или до първия път, където види инструкция break. Ако не напишете инструкция break накрая на списъка с инструкции за текущия случай (case), PHP ще продължи с изпълнението на инструкциите в следващия случай. Например:
<?php
switch ($i) {
case 0:
echo "i е равно на 0";
case 1:
echo "i е равно на 1";
case 2:
echo "i е равно на 2";
}
?>
В случая, ако променливата $i е равна на 0, PHP ще изпълни всички инструкции echo! Ако $i е равна на 1, PHP ще изпълни последните две инструкции echo. Ще получите очакваното поведение (ще се изведе 'i е равно на 2') само ако $i е равна на 2. Следователно, е важно да не забравяте изразите break (дори и в случай, че искате да ги пропуснете умишлено при определени обстоятелства).
В конструкция switch условието се изчислява само веднъж и резултатът се сравнява с всяка клауза case. При elseif - условието се изчислява повторно. Ако условието ви е по-сложно от просто сравняване и/или е в тежък цикъл, switch ще бъде по-бърза.
Списъкът с инструкции за даден случай (case) може да бъде и празен, което просто предава управлението на списъка с инструкции в следващия случай.
<?php
switch ($i) {
case 0:
case 1:
case 2:
echo "i е по-малко от 3, но е неотрицателно";
break;
case 3:
echo "i е 3";
}
?>
Специален случай е случая default. Този случай съвпада с всичко, което не е било намерено от другите случаи. Например:
<?php
switch ($i) {
case 0:
echo "i е равно на 0";
break;
case 1:
echo "i е равно на 1";
break;
case 2:
echo "i е равно на 2";
break;
default:
echo "i не е равно нито на 0, нито на 1, нито на 2";
}
?>
Инструкцията case може да бъде всякакъв израз, който се изчислява до прост тип, т.е. цели числа, числа с плаваща запетая или низове. Масиви и обекти не могат да бъдат използвани в този случай, освен ако не се преобразуват до прост тип.
Алтернативният синтаксис за контролни структури се поддържа от switch. За повече информация погледнете Алтернативен синтаксис за контролни структури .
<?php
switch ($i):
case 0:
echo "i е равно на 0";
break;
case 1:
echo "i е равно на 1";
break;
case 2:
echo "i е равно на 2";
break;
default:
echo "i не е равно нито на 0, нито на 1, нито на 2";
endswitch;
?>
Възможно е да използвате точка и запетая вместо двоеточие след case така:
<?php
switch($beer)
{
case 'загорка';
case 'каменица';
case 'шуменско';
echo 'Добър избор';
break;
default;
echo 'Моля изберете отново...';
break;
}
?>
Конструкцията declare се използва за установяване на изпълними директиви за блокове от код. Синтаксисът на declare е подобен на този на другите конструкции за управление на потока:
declare (directive)
statement
Разделът directive позволява да се установява поведението на declare блок. Към момента се разпознават само две директиви: директивата ticks (вж. по-долу за повече информация относно директивата ticks) и директивата encoding (вж. по-долу за повече информация относно директивата encoding).
Забележка: Директивата encoding (кодировка) беше добавена в PHP 5.3.0
Частта statement от блока declare ще бъде изпълнена - как ще се изпълни и какви странични ефекти ще настъпят по време на изпълнението може да зависи от директивата указана в блока directive.
Конструкцията declare може също да се използва и в глобален обхват, като по този начин ще се отрази на целия код, който я следва (ако файлът с declare е бил включен (included), обаче, тя не повлиява родителския файл).
<?php
// тези са равносилни:
// можете да използвате това:
declare(ticks=1) {
// целия скрипт тук
}
// или да използвате това:
declare(ticks=1);
// целия скрипт тук
?>
Туптенето е непрепоръчително от PHP 5.3.0 и ще бъде премахнато в PHP 6.0.0.
Тупване (tick) е събитие, което се случва
на всеки N инструкции от ниско ниво,
изпълнени от синтактичния анализатор в declare блок.
Стойността на N се задава посредством
ticks=N
в рамките на directive на блока
declare.
Събитията, които се случват на всяко тупване, се задават посредством register_tick_function(). За повече подробности, вж. примера по-долу. Забележете, че за едно тупване, могат да настъпят повече от едно събития.
Example #1 Профил на част от PHP код
<?php
// Функция, която записва времето, когато е извикана
function profile($dump = FALSE)
{
static $profile;
// Връща времената, записани в профила и ги изтрива
if ($dump) {
$temp = $profile;
unset ($profile);
return $temp;
}
$profile[] = microtime ();
}
// Установяване на обработчик на туптене
register_tick_function("profile");
// Инициализиране на функцията преди деклариращия блок
profile();
// Пускане на блок от код, хвърляне на тупване на всеки втори израз
declare(ticks=2) {
for ($x = 1; $x < 50; ++$x) {
echo similar_text(md5($x), md5($x*$x)), "<br />;";
}
}
// Показване на данните, записани в профила
print_r(profile (TRUE));
?>
Примерът профилира PHP кода вътре в 'declare' блок, записвайки времето, в което всяка втора инструкция от ниско ниво в блока се изпълнява. След това, тази информация би могла да бъде използвана за откриване на бавни части в дадени откъси код. Тази операция може да бъде изпълнена и посредством други методи, но чрез използване на туптене е най-подходящо и лесно за осъществяване.
Туптенето е подходящо за откриване на грешки, осъществяване на проста многозадачност, фонов вход/изход и други.
Вж. също register_tick_function() и unregister_tick_function().
Кодировката на всеки скрипт може да бъде специфицирана посредством директивата encoding.
Example #2 Деклариране на кодировка за скрипта.
<?php
declare(encoding='ISO-8859-1');
// някакъв код тук
?>
В комбинация с пространства от имена, единственият валиден синтаксис за declare е declare(encoding='...');, където ... е кодировъчната стойност. declare(encoding='...') {} ще доведе до синтактична грешка, когато се комбинира с пространства от имена.
Кодировъчната тойност, указана от declare, се пренебрегва в PHP 5.3, освен ако PHP не е компилиран с --enable-zend-multibyte. В PHP 6.0 директивата encoding ще бъде използвана за уведомяване на синтактичния анализатор с каква кодировка е бил създаден файла. Правилните стойности са имената на кодировки, като UTF-8.
Ако се извиква от функция, инструкцията return() незабавно завършва изпълнението й и връща аргумента си като стойност от извикването на функцията. return() ще прекъсне също и изпълнението на конструкцията eval() или скриптов файл.
Ако се извиква от глобалния обхват, тогава изпълнението на текущия скрипт се прекратява. Ако текущият скриптов файл е бил include()-нат (включен) или require()-нат (изискан), тогава контролът се връща обратно на извикващия файл. Освен това, ако текущият скрипт е бил include()-нат, тогава стойността подадена на return() ще бъде върната като стойност от извикването на include(). Ако return() се извика от главния скрипт, изпълнението на скрипта се прекратява. Ако текущият скрипт е бил описан в конфигурационните опции auto_prepend_file или auto_append_file в php.ini, тогава изпълнението на този скрипт се прекратява.
За повече информация, вж. Връщане на стойности.
Забележка: Забележете, че тъй като return() е езикова конструкция, а не функция, заграждащите скоби не са необходими. Всеприето е скобите да се изпускат и всъщност дори е по-добре да го правите, тъй като в този случай PHP има по-малко работа за вършене.
Забележка: В никакъв случай не трябва да използвате скоби около връщаната променлива, когато се връща по референция, тъй като това няма да работи. По референция можете да връщате единствено променлива, но не и резултат от израз. Когато използвате return ($a);, тогава вие не връщате променлива, а резултата от израза ($a) (който, разбира се, е стойността на $a).
require() е идентична на include(), но при неуспех ще предизвика фатална грешка - E_ERROR. С други думи, тя ще прекъсне скрипта, докато include() само ще изведе предупреждение (E_WARNING), което ще позволи на скрипта да продължи.
Вижте документацията на include() за това как работи.
Инструкцията include() включва и изпълнява даден файл.
Документацията по-долу се отнася също и за require(). Двете конструкции са идентични във всяко едно отношение, с изключение на начина, по който обработват грешки. Те и двете предизвикват предупреждение, но require() предизвиква също и фатална грешка. С други думи, не се колебайте да използвате require() ако искате липсващ файл да спре изпълнението на скрипта. include() не се държи по този начин, скриптът ще продължи независимо от липсата. Трябва също така да сте сигурни, че имате подходяща стойност за include_path. Трябва да знаете, че грешка в синтаксиса на изисквания файл няма да предизвика спиране на изпълнението във версии на PHP преди PHP 4.3.5. От тази версия нататък - ще го предизвика.
Файловете за включване се търсят първо в пътя за включване (include_path) относително спрямо текущата работна директория, а след това - в директорията на текущия скрипт. Например, ако пътят ви за включване е libraries, текущата работна директория е /www/, вие сте включили include/a.php и там има include "b.php" в този файл, за b.php ще бъде търсено първо в /www/libraries/, а после във /www/include/. Ако името на файла започва с ./ или ../, той ще бъде потърсен само в текущата работна директория.
Когато даден файл бива включван, кодът в него наследява областта на действие на променливите на реда, на който става включването. От този момент нататък, всяка променлива, налична на този ред в извикващия файл ще бъде налична и в извиквания файл. Всички функции и класове, дефинирани във включвания файл, ще имат глобална област на действие.
Example #1 Основен пример за include()
vars.php
<?php
$color = 'зелена';
$fruit = 'ябълка';
?>
test.php
<?php
echo "Една $color $fruit"; // Една
include 'vars.php';
echo "Една $color $fruit"; // Една зелена ябълка
?>
Ако включването е вътре във функция в извикващия файл, тогава целият код, който се съдържа в извиквания файл ще се държи сякаш е бил дефиниран вътре в тази функция, така че ще вземе областта на действие на променливите на тази функция. Изключение от това правило са вълшебните константи, които се изчисляват от синтактичния анализатор още преди да се е случило включването (include).
Example #2 Включване във функции
<?php
function foo()
{
global $color;
include 'vars.php';
echo "Една $color $fruit";
}
/* vars.php е в обхвата на of foo(), така че *
* $fruit НЕ е налична извън този обхват *
* $color е налична, защото я декларирахме *
* като глобална. */
foo(); // Една зелена ябълка
echo "Една $color $fruit"; // Една зелена
?>
Когато даден файл бива включван, анализаторът излиза от режим PHP и влиза в режим HTML в началото на съответния файл и се връща обратно в края. Затова кодът във включвания файл, който трябва да бъде изпълнен като PHP код, трябва да бъде заграден с валидни тагове за начало и край в PHP.
Ако "опаковката URL fopen" е включена в PHP (а тя е в конфигурацията по подразбиране), можете да укажете файла, който да бъде включен, посредством URL (през HTTP или друга поддържана опаковка - вижте List of Supported Protocols/Wrappers за списък на протоколите) вместо локален път към файл. Ако отдалеченият сървър интерпретира дадения файл като PHP код, тогава е възможно да се предават променливи към включвания файл, посредством URL низ-заявка както при HTTP GET. Това не е съвсем същото като да се включва файла и той да наследи променливия обхват на родителския файл; всъщност скриптът се пуска на отдалечения сървър и резултатът чак тогава се включва в локалния скрипт.
Windows версиите на PHP преди PHP 4.3.0 не поддържат достъпа до отдалечени файлове посредством тази функция, дори и ако allow_url_fopen е включено.
Example #3 include() през HTTP
<?php
/* Този пример предполага, че www.example.com е конфигуриран да прави разбор на .php
* файлове и да не прави разбор на .txt файлове. Също така, в случая 'Работи' означава, че
* променливите $foo и $bar са налични във включвания файл. */
// Няма да работи; file.txt не се обработва от www.example.com като PHP
include 'http://www.example.com/file.txt?foo=1&bar=2';
// Няма да работи; гледа за файл с име 'file.php?foo=1&bar=2' в
// локалната файлова система.
include 'file.php?foo=1&bar=2';
// Работи.
include 'http://www.example.com/file.php?foo=1&bar=2';
$foo = 1;
$bar = 2;
include 'file.txt'; // Работи.
include 'file.php'; // Работи.
?>
Отдалечен файл може да бъде изпълнен на отдалечения сървър (в зависимост от файловото разширение и от това дали отдалеченият сървър стартира PHP или не) но той все пак трябва да даде валиден PHP скрипт, защото той ще бъде обработен на локалния сървър. Ако файлът от отдалечения сървър трябва да бъде обработен там и просто да бъде изведен, то много по-подходяща за тази работа е функцията readfile(). В противен случай трябва да се вземат специални мерки, за да се осигури, че отдалеченият скрипт дава валиден и желан код.
Вж. също Отдалечени файлове, fopen() и file() за информация по темата.
Обработка на връщания: Възможно е да се изпълни инструкция return() във включван файл, за да се прекъсне изпълнението на този файл и да се предаде контролът към извикващия скрипт. Също така е възможно да се връщат стойности от включвани файлове. Можете да вземете стойността на включвания файл, както бихте го направили с нормална функция. Това обаче не е възможно, когато включвате отдалечени файлове, освен ако отдалеченият файл има валидни тагове за начало и край в PHP (както и за локални файлове). Можете да декларирате нужните променливи в тези тагове и те ще бъдат внесени в точката на включването.
Тъй като include() е специална езикова конструкция, употребата на скоби около аргумента й не е необходима. Бъдете внимателни, когато сравнявате връщаната стойност.
Example #4 Сравнение на връщана стойност от include
<?php
// няма да работи, ще се изчисли като include(('vars.php') == 'OK'), т.е. include('')
if (include('vars.php') == 'OK') {
echo 'OK';
}
// работи
if ((include 'vars.php') == 'OK') {
echo 'OK';
}
?>
Example #5 include() и инструкцията return()
return.php
<?php
$var = 'PHP';
return $var;
?>
noreturn.php
<?php
$var = 'PHP';
?>
testreturns.php
<?php
$foo = include 'return.php';
echo $foo; // отпечатва 'PHP'
$bar = include 'noreturn.php';
echo $bar; // отпечатва 1
?>
$bar има стойност 1, защото включването е било успешно. Отбележете разликата в горните примери. Първият използва return() във включвания файл, докато другият - не. В случай че файлът не може да бъде включен, ще бъде върната стойност FALSE и ще се изведе E_WARNING.
Ако има функции, дефинирани във включвания файл, то те могат да бъдат използвани в главния файл независимо от това дали са преди или след return(). Ако файлът бъде включен повторно, PHP 5 ще изведе фатална грешка, понеже функциите вече са били декларирани, докато PHP 4 няма да се оплаче за функции, дефинирани след return(). Препоръчително е да се използва include_once() вместо да се проверява дали файлът вече е бил включен и да се връща условно във включвания файл.
Друг начин да се "включи" файл от тип PHP в променлива е да се прихване изхода посредством Функциите за контрол на изхода и include(). Например:
Example #6 Буфериране на изхода с цел включване на PHP файл в низ
<?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;
}
?>
Ако искате да включвате файлове автоматично в скриптовете, вижте също конфигурационните директиви auto_prepend_file и auto_append_file в php.ini.
Забележка: Тъй като това е езикова конструкция а не функция, тя не може да бъде извикана посредством променливи функции
Вж. също require(), require_once(), include_once(), get_included_files(), readfile(), virtual() и include_path.
Инструкцията require_once() е идентична на require() с тази разлика, че PHP ще направи проверка дали файлът вече не е бил включен, и ако е бил, няма да го включи повторно.
Вижте документацията на include_once() за информация относно поведението _once (веднъж) и как то се различава от това на съответните им еквиваленти не-_once.
Инструкцията include_once() включва и изпълнява даден файл по време на изпълнението на скрипт. Начинът на работа е подобен на този на include(), с единствената разлика, че ако кодът от файла вече е бил включен, той няма да бъде включен повторно. Както подсказва и името, той ще бъде включен точно веднъж (once).
include_once() би трябвало да бъде използвана на места, където е възможно един и същи файл да бъде включен и изпълнен повече от веднъж по време на специфично изпълнение на скрипт, и когато искате да сте сигурни, че файлът ще бъде включен точно един път, за да се избегнат проблеми с повторно дефиниране на функции, повторно присвояване на променливи, и т.н.
За повече примери, показващи употребата на require_once() и include_once(), разгледайте » PEAR кода, включен в последната дистрибуция на PHP.
Връщаните стойности са същите както при include(). Ако файлът вече е бил включен, тази функция ще върне TRUE
Забележка: include_once() е добавена в PHP 4.0.1
Забележка: Отбележете, че поведението на include_once() и require_once() може да бъде различно от очакваното на операционни системи нечувствителни към регистъра (като Windows).
Example #1 include_once() е нечувствителна към регистъра под Windows
<?php
include_once "a.php"; // това ще включи a.php
include_once "A.php"; // това отново ще включи a.php под Windows! (само в PHP 4)
?>Поведението се промени в PHP 5 - пътят първо се нормализира така, че C:\PROGRA~1\A.php да стане C:\Program Files\a.php, след което файлът се включва еднократно.
Windows версиите на PHP преди PHP 4.3.0 не поддържат достъпа до отдалечени файлове посредством тази функция, дори и ако allow_url_fopen е включено.
Вж. също include(), require(), require_once(), get_required_files(), get_included_files(), readfile() и virtual().
Операторът goto може да бъде използван за скок до друга инструкция в програмата. Желаното място се специфицира с етикет и точка и запетая, а този етикет се поставя след goto.
Example #1 Пример за goto
<?php
goto a;
echo 'Foo';
a:
echo 'Bar';
?>
Примерът по-горе ще изведе:
Bar
Забележка: Операторът goto е наличен от PHP 5.3.
Скачането в цикъл или конструкция switch не е разрешено. В този случай ще бъде изведена фатална грешка.
Функция може да бъде дефинира посредством следния синтаксис:
Example #1 Псевдо-код, демонстриращ употребата на функции
<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
echo "Примерна функция.\n";
return $retval;
}
?>
Във функциите е разрешена употребата на какъвто и да е валиден код PHP, дори и дефиниция на други функции или класове.
Имената на функциите следват същите правила като другите етикети в PHP. Валидното име на функция започва с буква или подчертавка, следвана от произволен брой букви, цифри или подчертавки. Като регулярен израз, това би могло да бъде представено така: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.
Вж. също Userland Naming Guide.
Не е необходимо функциите да бъдат дефинирани преди да бъдат използвани, освен в случаите, когато функцията е дефинирана условно, както в двата примера по-долу.
Когато дадена функция е дефинирна условно, то тя трябва да бъде дефинирана преди да бъде извикана.
Example #2 Условни функции
<?php
$makefoo = true;
/* Не можем да извикаме foo() оттук,
понеже тя все още не съществува,
но можем да извикаме bar() */
bar();
if ($makefoo) {
function foo()
{
echo "Аз не съществувам докато изпълнението на програмата не стигне до мен.\n";
}
}
/* Сега можем спокойно да извикаме foo(),
понеже $makefoo се е изчислила на истина */
if ($makefoo) foo();
function bar()
{
echo "Аз съществувам от стартирането на програмата.\n";
}
?>
Example #3 Функции във функции
<?php
function foo()
{
function bar()
{
echo "Аз не съществувам, докато не се извика foo().\n";
}
}
/* Не можем да извикаме bar() все още,
понеже не съществува. */
foo();
/* Сега можем да извикаме bar(),
изпълнението на foo() я
е направило достъпна. */
bar();
?>
Всички функции и класове в PHP имат глобална област на действие - могат да бъдат извиквани извън функция, дори и да са били дефинирани вътре и обратно.
PHP не поддържа нито претоварване на функции, нито отменянето на дефиницията или повторното дефиниране на функция, която е била дефинирана преди това.
Забележка: Имената на функциите не са чувствителни към регистъра, но все пак е добра практитка функциите да се извикват със същите имена, с които са били дефинирани.
При функциите се поддържат както променливия брой аргументи, така и дефинирането на аргументи по подразбиране. За повече информация вижте документацията на функциите func_num_args(), func_get_arg() и func_get_args().
В PHP е възможно рекурсивното извикване на функции. Все пак избягвайте рекурсивното извикване на функция/метод с повече от 100-200 нива на рекурсия, тъй като това може да доведе до смачкване на стека, което да предизвика прекратяване на скрипта.
Example #4 Рекурсивни функции
<?php
function recursion($a)
{
if ($a < 20) {
echo "$a\n";
recursion($a + 1);
}
}
?>
Към функциите може да бъде предавана информация посредством списък с аргументи под формата на разделен със запетаи списък с изрази.
PHP поддържа предаването на аргументи по стойност (по подразбиране), по референция, както и стойности по подразбиране. Списъци с аргументи с променлива дължина също се поддържат, вж. документацията на функциите func_num_args(), func_get_arg() и func_get_args() за повече информация.
Example #1 Предаване на масиви към функции
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>
По подразбиране аргументите се предават на функциите по стойност (така че ако стойността на даден аргумент бъде променена вътре във функцията, това няма да промени съответната променлива извън нея). За да се разреши на функция да променя аргументите си, те трябва да бъдат предадени по референция.
За да бъде предаван винаги по референция, съответният аргумент на функция трябва да бъде предшестван от амперсанд (&) пред името си в дефиницията на функцията:
Example #2 Предаване на функционални параметри по референция
<?php
function add_some_extra(&$string)
{
$string .= 'и още нещо.';
}
$str = 'Това е низ ';
add_some_extra($str);
echo $str; // извежда 'Това е низ и още нещо.'
?>
Функция може да дефинира стойности по подразбиране за скаларни аргументи, както в C++, така:
Example #3 Употреба на параметри по подразбиране във функции
<?php
function makecoffee($type = "капучино")
{
return "Приготвяне на чаша $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("еспресо");
?>
Изходът от горния откъс е:
PHP позволява също и употребата на масиви и на специалния тип NULL за стойности по подразбиране, например:
Example #4 Употреба на не-скаларни типове за стойности по подразбиране
<?php
function makecoffee($types = array("капучино"), $coffeeMaker = NULL)
{
$device = is_null($coffeeMaker) ? "на ръка" : $coffeeMaker;
return "Приготвяне на чаша ".join(", ", $types)." $device.\n";
}
echo makecoffee();
echo makecoffee(array("капучино", "лаваца"), "с машина за кафе");
?>
Стойността по подразбиране трябва да бъде константа, а не (например) променлива, член на клас или извикване на функция.
Забележете, че когато се използват аргументи по подразбиране, те трябва да бъдат от дясната страна, а тези без стойности по подразбиране - от лявата; в противен случай нещата може да не работят според очакванията. Разгледайте следния откъс:
Example #5 Неправилна употреба на подразбиращи се аргументи
<?php
function makeyogurt($type = "кисело", $flavour)
{
return "Сервиране на чаша $type $flavour.\n";
}
echo makeyogurt("мляко"); // няма да работи според очакваното
?>
Изходът от горния пример е:
Сега сравнете горното с това:
Example #6 Правилна употреба на подразбиращи се аргументи
<?php
function makeyogurt($flavour, $type = "кисело")
{
return "Сервиране на чаша $type $flavour.\n";
}
echo makeyogurt("мляко"); // работи както трябва
?>
Изходът от този пример е:
Забележка: От PHP 5 нататък стойностите по подразбиране могат да бъдат предавани по референция.
От PHP 4 нататък се поддържа списък с аргументи с променлива дължина в потребителски-дефинираните функции. Това е лесно, посредством функциите func_num_args(), func_get_arg() и func_get_args().
Не се изисква специален синтаксис и списъкът с аргументи може да бъде все така изрично предоставян с дефинициите на функциите и те ще работят както трябва.
Връщането на стойности става посредством незадължителната инструкция за връщане (return). Позволено е връщането на всякакви типове, включително списъци и обекти. Това кара функцията да спре незабавно изпълнението си и да предаде контрола обратно на реда, от който е била извикана. Погледнете return() за повече информация.
Example #1 Употреба на return()
<?php
function square($num)
{
return $num * $num;
}
echo square(4); // извежда '16'.
?>
Функцията не може да връща множество стойности, но подобен ефект може да бъде постигнат чрез връщането на масив.
Example #2 Връщане на масив, с цел получаване на множество стойности
<?php
function small_numbers()
{
return array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
?>
За да върнете референция от функция, използвайте референтния оператор & както при декларирането на функцията, така и при присвояването на връщаната стойност на променливата:
Example #3 Връщане на референция от функция
<?php
function &returns_reference()
{
return $someref;
}
$newref =& returns_reference();
?>
За повече информация относно референциите, разгледайте раздел Референции.
PHP поддържа концепцията за променливи функции. Това означава, че ако дадена променлива има скоби в края си, PHP ще потърси за функция с име - стойността на променливата и ще се опита да я изпълни. Освен за друго, това може да бъде използвано и с цел осъществяване на обратни извиквания, функционални таблици и други.
Променливите функции няма да работят с езикови конструкции като echo(), print(), unset(), isset(), empty(), include(), require() и други от този род. Използвайте функции-опаковки, за да можете да използвате някоя от тези езикови конструкции като променлива функция.
Example #1 Пример за променлива функция
<?php
function foo() {
echo "Във foo()<br />\n";
}
function bar($arg = '')
{
echo "В bar(); аргументът беше '$arg'.<br />\n";
}
// Това е функция-опаковка на echo
function echoit($string)
{
echo $string;
}
$func = 'foo';
$func(); // Това извиква foo()
$func = 'bar';
$func('test'); // Това извиква bar()
$func = 'echoit';
$func('test'); // Това извиква echoit()
?>
Методите на обекти също могат да бъдат извиквани посредством синтаксиса за променливи функции.
Example #2 Пример за променлив метод
<?php
class Foo
{
function Variable()
{
$name = 'Bar';
$this->$name(); // Това извиква метода Bar()
}
function Bar()
{
echo "Това е Bar";
}
}
$foo = new Foo();
$funcname = "Variable";
$foo->$funcname(); // Това извиква $foo->Variable()
?>
Вж. също call_user_func(), променливи променливи и function_exists().
PHP стандартно разполага с множество функции и конструкции. Съществуват също и функции, които изискват да бъде компилирано специфично разширение на PHP, в противен случай ще се получат фатални грешки за "недефинирани функции". Например, за да се използват функциите за изображения като imagecreatetruecolor(), е необходимо PHP да бъде компилиран заедно с поддръжка на GD. Или за достъп до mysql_connect(), PHP трябва да бъде компилиран с поддръжка на MySQL. Съществуват и много базови функции, които са включени във всяка версия на PHP като функциите string и variable. Извикване на phpinfo() или get_loaded_extensions() ще покаже кои разширения са заредени в PHP. Също отбележете, че много разширения са включени по подразбиране и че ръководството на PHP е разделено по разширения. Вж. конфигурация, инсталация и отделните глави за разширенията за повече информация как да конфигурирате вашия PHP.
Четенето и разбирането на функционални прототипи е обяснено в раздела, озаглавен как да четем дефиниции на функции. Важно е да се разбере какво връща функцията или дали функцията работи директно върху подадената й стойност. Например, str_replace() ще върне променения низ, докато usort() работи върху действително подадената стойност. Всяка страница в ръководството също съдържа специфична информация за всяка функция като информация за параметрите на функцията, промяна на поведението, връщани стойности при успех или неуспех, както и всякаква друга налична информация. Познаването на тези важни (и понякога едва доловими) разлики е ключово при писането на правилен код на PHP.
Забележка: Ако параметрите, подавани на дадена функция, не са такива, каквито очаква, като например предаването на масив, където се очаква низ, то връщаната стойност от функцията е недефинирана. В този случай най-вероятно тя ще върне NULL, но това е просто конвенция и на това не може да се разчита.
Вж. също function_exists(), функционалния справочник, get_extension_funcs() и dl().
Анонимните функции позволяват създаването на функции без да е необходимо да им се указва име. Те са най-удобни при параметрите с обратно извикване, но могат да бъдат използвани и на много други места.
Example #1 Пример за анонимна функция
<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld
?>
Вътрешно анонимните функции са осъществени посредством класа Closure.
Забележка: Анонимните функции са налични от PHP 5.3.0.
Класът е набор от променливи и функции, които работят с променливите. Променливите се дефинират с ключовата дума var, а функциите с function. Дефиницията на клас има следния синтаксис:
<?php
class Cart {
var $items; // Артикули в нашата пазарска количка
// Добавяне на $num артикули от $artnr към пазарската количка
function add_item($artnr, $num) {
$this->items[$artnr] += $num;
}
// Премахване на $num артикула от $artnr от пазарската количка
function remove_item($artnr, $num) {
if ($this->items[$artnr] > $num) {
$this->items[$artnr] -= $num;
return true;
} elseif ($this->items[$artnr] == $num) {
unset($this->items[$artnr]);
return true;
} else {
return false;
}
}
}
?>
В примера по-горе е дефиниран клас Cart, който се състои от асоциативен масив, от артикули на пазарска количка и две функции за добавяне и премахване на артикули от тази пазарска количка.
Не може дефиницията на клас да се помества в множество файлове. Също така не може дефиницията на клас да се помества в множество блокове PHP, освен ако прекъсването не е в декларацията на метод. Следният пример няма да работи:
<?php
class test {
?>
<?php
function test() {
print 'OK';
}
}
?>
Следното обаче е позволено:
<?php
class test {
function test() {
?>
<?php
print 'OK';
}
}
?>
Следните предупредителни забележки са валидни за PHP 4.
Наименованието stdClass се използва вътрешно от Zend и е запазено. Не можете да имате клас с име stdClass в PHP.
Имената на функциите __sleep и __wakeup са вълшебни в класовете на PHP. Не може да имате функции с тези имена във вашите класове, освен ако не искате да ползвате вълшебната функционалност свързана с тях. Вижте по-долу за повече информация.
PHP запазва всички имена на функции, започващи с __ като вълшебни. Препоръчително е да не използвате имена на функции в PHP, започващи с __, освен ако не искате да ползвате документираната вълшебна функционалност.
В PHP 4 var-променливите на класовете могат да се инициализират само с константни стойности. За да се инициализира променлива с неконстантна стойност, трябва да се използва инициализационна функция, която се извиква автоматично при инстанциирането на класа. Такава функция се нарича конструктор (вижте по-долу).
<?php
class Cart {
/* Нито една от долните конструкции няма да работи в PHP 4. */
var $todays_date = date("Y-m-d");
var $name = $firstname;
var $owner = 'Fred ' . 'Jones';
/* Масивите съдържащи константни стойности ще работят. */
var $items = array("VCR", "TV");
}
/* Това е начинът да се направи. */
class Cart {
var $todays_date;
var $name;
var $owner;
var $items = array("VCR", "TV");
function Cart() {
$this->todays_date = date("Y-m-d");
$this->name = $GLOBALS['firstname'];
/* и т.н. */
}
}
?>
Класовете са типове, което означава, че са шаблони за действителните променливи. Можете да създадете променлива от желаният от вас тип чрез оператора new
<?php
$cart = new Cart;
$cart->add_item("10", 1);
$another_cart = new Cart;
$another_cart->add_item("0815", 3);
?>
В горния пример се създават обектите $cart и $another_cart като и двата са инстанции на класа Cart. Функцията add_item() на обекта $cart се извиква за да се добави един артикул с номер 10 към $cart. Също така се добавят 3 артикула с номер 0815 към $another_cart.
И двата обекта - $cart и $another_cart, притежават функции add_item(), remove_item() и променливи. Можете да си представите обектите като нещо подобно на директориите в една файлова система. В дадена файлова система може да имате 2 отделни файла README.TXT, стига да се намират в различни директории. Също както при директориите ще трябва да въведете пълния път до файла, за да имате достъп до него от главната директория, трябва да зададете пълното име на функцията която искате да извикате: в контекста на PHP - главната директория ще бъде глобалното пространство от имена, а разделителят в името на пътя се явява ->. По този начин $cart->items и $another_cart->items са две различни променливи. Забележете, че променливата е $cart->items, а не $cart->$items, което означава, че името на променливата в PHP трябва да има само един знак $.
<?php
// правилно, единичен $
$cart->items = array("10" => 1);
// невалидно, понеже $cart->$items става $cart->""
$cart->$items = array("10" => 1);
// правилно, но резултата може да не е този, който очакваме:
// $cart->$myvar става $cart->items
$myvar = 'items';
$cart->$myvar = array("10" => 1);
?>
В дефиницията на класа вие не знаете името на обекта който ще го инстанциира: по времето на написването на класа Cart не беше известно, че по-късно обектът ще бъде кръстен $cart или $another_cart. Следователно няма как да напишете $cart->items в самия клас. Вместо това, за да имаме достъп до собствените функции и променливи на класа, може да използваме псевдо-променливата $this, която е референция към обекта, който е инстанциирал класа. Следователно '$this->items[$artnr] += $num' може да бъде прочетено като 'добави $num към брояча $artnr на артикулите на моя масив' или 'добави $num към брояча $artnr на артикулите на масива за текущия обект'.
Забележка: Псевдо-променливата $this обикновено не е дефинирана ако метода в който се намира е извикан статично. Това все пак не е стриктно правило: $this е дефинирана ако метода е извикан статично от друг обект. В този случай, стойността на $this е тази на извикващият обект. Това е илюстрирано със следният пример:
<?php
class A
{
function foo()
{
if (isset($this)) {
echo '$this е дефинирана (';
echo get_class($this);
echo ")\n";
} else {
echo "\$this не е дефинирана.\n";
}
}
}
class B
{
function bar()
{
A::foo();
}
}
$a = new A();
$a->foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>Примерът по-горе ще изведе:
$this е дефинирана (a) $this не е дефинирана. $this е дефинирана (b) $this не е дефинирана.
Забележка: Съществуват няколко функции за работа с класове и обекти. Можете да ги разгледате в раздел Функции за класове и обекти.
Много често имаме нужда от класове с променливи и функции подобни на тези от друг съществуващ клас. Всъщност е добра практика да дефинираме общ клас, който да може да се използва във всичките проекти и да адаптираме този клас за специфичните нужди на конкретния проект. За да се улесни това, класовете могат да наследяват други класове. Производният клас има всички променливи и функции на базовия клас (това се нарича 'наследство', въпреки факта, че никой не е умрял), както и тези които са допълнително дефинирани. Не е възможно да изваждате променливи или функции от производен клас, т.е. да премахвате вече дефинирани функции и променливи. Производният клас винаги наследява от един базов клас, т.е. множествено наследяване не се поддържа. Наследяването на класове се осъществява с ключовата дума 'extends' (разширява).
<?php
class Named_Cart extends Cart {
var $owner;
function set_owner ($name) {
$this->owner = $name;
}
}
?>
В горния пример е дефиниран клас Named_Cart, който притежава всички променливи и функции от Cart, плюс допълнителната променлива $owner и допълнителната функция set_owner(). Може да създадете именувана пазарска количка по нормалния начин и да установите или да върнете като резултат името на собственика й. Можете да използвате и функциите на нормалната пазарска количка върху именуваната такава:
<?php
$ncart = new Named_Cart; // Създаване на именувана пазарска количка
$ncart->set_owner("kris"); // Задаване на име на пазарската количка
print $ncart->owner; // извежда името на собственика на пазарската количка
$ncart->add_item("10", 1); // (наследена функционалност от Cart)
?>
Това също така се нарича отношение родител-наследник. Създавате родителски клас и използвате extends, за да създадете нов клас базиран на родителския: дъщерен клас. Можете да използвате този дъщерен клас, за да дефинират друг клас базиран на него.
Забележка: Класовете трябва да бъдат дефинирани преди да бъдат използвани! Ако искате клас Named_Cart да наследи клас Cart, трябва първо да дефинирате клас Cart. Ако искате да създадете друг клас наречен Yellow_named_cart, наследяващ класа Named_Cart, ще трябва първо да дефинирате Named_Cart. Накратко: редът на дефиниране на класовете е важен.
Конструкторите са функции на класа, които се извикват автоматично при създаване на нова инстанция на съответния клас с ключовата дума new. Дадена функция е конструктор, когато името и съвпада с името на класа. Ако даден клас няма конструктор, то ще се бъде извикан конструктора на базовия му клас (ако съществува).
<?php
class Auto_Cart extends Cart {
function Auto_Cart() {
$this->add_item("10", 1);
}
}
?>
Горният код дефинира клас Auto_Cart, който представлява класа Cart плюс конструктор, който инициализира пазарската количка с артикул номер "10" всеки път, когато се създаде нов обект от тип Auto_Cart с ключовата дума "new". Конструкторите могат да приемат аргументи и тези аргументи могат да бъдат с подразбиращи се стойности, което ги прави още по-полезни. За да е възможно използването на класа без параметри, всички параметри на конструктора трябва да бъдат дефинирани със стойности по подразбиране.
<?php
class Constructor_Cart extends Cart {
function Constructor_Cart($item = "10", $num = 1) {
$this->add_item ($item, $num);
}
}
// Пазаруваме едни и същи стари неща...
$default_cart = new Constructor_Cart;
// Истинско пазаруване...
$different_cart = new Constructor_Cart("20", 17);
?>
Можете да използвате оператора @ за да подтиснете грешките които възникват в тялото на конструктора, т.е @new.
<?php
class A
{
function A()
{
echo "Аз съм конструкторът на клас A.<br />\n";
}
function B()
{
echo "Аз съм нормална функция B в клас A.<br />\n";
echo "Аз не съм конструктор на клас A.<br />\n";
}
}
class B extends A
{
}
// Това ще предизвика извикването на B() като конструктор
$b = new B;
?>
Функция B() в клас A ще се приеме като конструктор в клас B, въпреки че не е проектирана да бъде такава. В PHP 4 няма значение, дали функцията е дефинирана в клас B или е наследена от родителски клас.
В PHP 4 конструктора на базовия клас не се извиква автоматично от конструктора на производния клас. Отговорността за извикването на този конструктор, където е необходимо нагоре по йерархията на класовете, е на програмиста.
Деструкторите са функции, които се извикват автоматично, когато даден обект се унищожи, било то чрез unset() или просто като се излезе от областта на действие на обекта. В PHP не съществуват деструктори. Можете да използвате функцията register_shutdown_function(), за да симулирате голяма част от действието на деструкторите.
Следното е валидно само за PHP 4 и по-нови версии.
Понякога е полезно да се обръщаме към функции и променливи от базовите класове или да се обръщаме към функции, които все още нямат инстанции. В тези случаи се използва оператора ::.
<?php
class A {
function example() {
echo "Аз съм оригиналната функция A::example().<br />\n";
}
}
class B extends A {
function example() {
echo "Аз съм повторно-дефинираната функция B::example().<br />\n";
A::example();
}
}
// няма обект от клас A.
// това ще изведе
// Аз съм оригиналната функция A::example().<br />
A::example();
// създаване на обект от клас B.
$b = new B;
// това ще изведе
// Аз съм повторно-дефинираната функция B::example().<br />
// Аз съм оригиналната функция A::example().<br />
$b->example();
?>
В горния пример се извиква функция example() на клас A, без да е създаден обект от клас A, така че няма как да се напише $a->example() или нещо подобно. Вместо това example() се извиква като функция на класа, която е функция на самия клас, а не на обект от този клас.
Съществуват функции на класа, но не променливи на класа. В действителност, въобще не съществува обект в момента на извикването. По този начин функцията на класа не може да използва променливи на класа (но може да ползва локални или глобални променливи) и изобщо не може да използва $this.
В горния пример в клас B е дефинирана повторно функцията example(). Първоначалната дефиниция в клас А е препокрита и е недостъпна, освен ако не се обърнете изрично към реализацията на example() в клас A посредством оператора ::. Напишете A::example(), за да направите това (всъщност е по-добре да напишете parent::example(), както е показано в следващия раздел.
В контекста на казаното по-горе, съществува текущ обект и той може да има променливи. По този начин, при извикването от тялото на функция, можете да използвате ключовата дума и променливи на обекта.
Може да ви се наложи да пишете код, който се обръща към променливи и методи на базови класове. Това обикновено е така, когато наследеният клас е подобрение или конкретизация на код от базовия клас.
Вместо в кода да използвате конкретното име на базовия клас, можете да използвате специалното име parent, което представлява името на базовия клас, така както е указан в декларацията extends на класа. По този начин се избягва използването на името на базовия клас на повече от едно място. Ако трябва да се промени йерархията при наследяването, това може да се направи като просто се промени декларацията extends на класа.
<?php
class A {
function example() {
echo "Аз съм A::example() и осигурявам базова функционалност.<br />\n";
}
}
class B extends A {
function example() {
echo "Аз съм B::example() и осигурявам допълнителна функционалност.<br />\n";
parent::example();
}
}
$b = new B;
// Следният код ще извика B::example(), който от своя страна ще извика A::example().
$b->example();
?>
serialize() връща низ, съдържащ представяне под формата на byte-stream на всяка стойност, която PHP може да съхранява. unserialize() може да използва този низ, за да върне първоначалната стойност на променливите. При използването на serialize за съхраняване на обект ще се съхранят всички променливи на обекта. Името на класа също ще бъде запазено, но не и функциите на обекта.
За да десериализирате обекта, класът на този обект трябва да бъде дефиниран. По този начин ако имате обект $a от клас A в page1.php и го сериализирате, ще бъде върнат низ, който сочи към клас A и съдържа всички стойности на променливите в $a. Ако искате да десериализирате това в page2.php, възпроизвеждайки $a от клас A, дефиницията на клас A трябва да съществува в page2.php. Това може да бъде направено като дефиницията на клас A се съхрани във файл за вмъкване и този файл се вмъкне в page1.php и page2.php.
<?php
// classa.inc:
class A {
var $one = 1;
function show_one() {
echo $this->one;
}
}
// page1.php:
include("classa.inc");
$a = new A;
$s = serialize($a);
// съхранява $s някъде, където page2.php може да го намери.
$fp = fopen("store", "w");
fwrite($fp, $s);
fclose($fp);
// page2.php:
// това е нужно, за да може unserialize да работи коректно.
include("classa.inc");
$s = implode("", @file("store"));
$a = unserialize($s);
// сега използваме метода show_one() на обекта $a.
$a->show_one();
?>
Ако използвате сесии и session_register() за регистриране на обекти, то тези обекти се сериализират автоматично в края на всяка страница PHP и се десериализират автоматично на всяка от следващите страници. Това означава, че тези обекти могат да бъдат използвани на всяка страница, веднага след като са станали част от вашата сесия.
Горещо се препоръчва да включвате дефинициите на класовете на всички обекти регистрирани по този начин във всички страници, дори и на практика да не използвате тези класове навсякъде. Ако не направите това и даден обект се десериализира без да е налична дефиницията на класа му, то той ще изгуби връзката с класа и ще се интерпретира като обект от клас __PHP_Incomplete_Class_Name, без да са налични никакви методи и така ще стане абсолютно безполезен.
Ако в примера по-горе $a стане част от сесия посредством session_register("a"), файлът classa.inc трябва да бъде включен във всички страници, не само в page1.php и page2.php.
serialize() проверява дали вашият клас има функция с вълшебно име __sleep. Ако има такава, тази функция се изпълнява преди всяка сериализация. Тя може да извършва почистване на обекта и връща масив с имената на всички променливи на обекта, който ще бъде сериализиран. Ако методът не върне нищо, тогава се сериализира стойността NULL и се генерира грешка от тип E_NOTICE.
__sleep може да се използва за затваряне на всички връзки към базите от данни, които са създадени в даден обект, за изпълняване на заявките, които са на изчакване или да извърши други подобни почистващи задачи. Също така функцията може да бъде полезна, ако имате много големи обекти, които не трябва да се съхраняват изцяло.
Функцията unserialize() е обратната на serialize() и проверява за наличието на функцията с вълшебно име __wakeup. Ако е налична, тази функция може да реконструира ресурсите на даден обект.
Замисъла на __wakeup е да възстанови връзките към базите от данни, които са изгубени по време на сериализацията и да извърши други задачи свързани с прединициализирането.
Създаването на референции в конструктора може да доведе до объркващи резултати. Този раздел, написан във вид на ръководство, може да ви помогне да избегнете подобни проблеми.
<?php
class Foo {
function Foo($name) {
// създаване на референция в глобалния масив $globalref
global $globalref;
$globalref[] = &$this;
// установяне на името на предадената стойност
$this->setName($name);
// и извеждане
$this->echoName();
}
function echoName() {
echo "<br />", $this->name;
}
function setName($name) {
$this->name = $name;
}
}
?>
Нека сега да проверим дали има разлика между $bar1, създадена чрез оператора за копиране = и $bar2, създадена чрез оператора за референции - =&
<?php
$bar1 = new Foo('установяване в конструктора');
$bar1->echoName();
$globalref[0]->echoName();
/* изход:
установяване в конструктора
установяване в конструктора
установяване в конструктора */
$bar2 =& new Foo('установяване в конструктора');
$bar2->echoName();
$globalref[1]->echoName();
/* изход:
установяване в конструктора
установяване в конструктора
установяване в конструктора */
?>
Очевидно няма разлика, но всъщност има една значителна разлика: $bar1 и $globalref[0] не са извикани по референция и не са една и съща променлива. Това е така, тъй като операторът "new" по подразбиране връща не референция, а копие.
Забележка: Няма намаляване на производителността (след като от PHP 4 се използва брояч на референциите) при връщане на копия вместо референции. Точно обратното, често е по-добре просто да се работи с копия, вместо с референции, тъй като създаването на референции отнема известно време, докато създаването на копие фактически не отнема време (освен ако никое от тях не е голям масив или обект и един от тях е променен, а в последствие и останалите. В този случай ще бъде по-добре да се използват референции, за да бъдат променени едновременно).
За да докажем написаното по-горе, нека погледнем кода отдолу.
<?php
// сега ще променим името. Какво очаквате да стане?
// можете да очаквате, че $bar1 и $globalref[0] ще са с променени имена...
$bar1->setName('установяване от вън');
// както споменахме по-горе, това няма да стане
$bar1->echoName();
$globalref[0]->echoName();
/* изход:
установяване от вън
установяване в конструктора */
// нека сега видим каква е разликата между $bar2 и $globalref[1]
$bar2->setName('установяване от вън');
// за щастие те не само са равни, те представляват една и съща променлива
// така че, $bar2->name и $globalref[1]->name също са една и съща променлива
$bar2->echoName();
$globalref[1]->echoName();
/* изход:
установяване от вън
установяване от вън */
?>
Още един, последен пример, опитайте се да го разберете.
<?php
class A {
function A($i) {
$this->value = $i;
// опитайте се да разберете защо нямаме нужда от референция тук
$this->b = new B($this);
}
function createRef() {
$this->c = new B($this);
}
function echoValue() {
echo "<br />","class ",get_class($this),': ',$this->value;
}
}
class B {
function B(&$a) {
$this->a = &$a;
}
function echoValue() {
echo "<br />","class ",get_class($this),': ',$this->a->value;
}
}
// опитайте се да разберете, защо използването на обикновено копие тук,
// ще доведе до нежелани резултати в реда отбелязан със *.
$a =& new A(10);
$a->createRef();
$a->echoValue();
$a->b->echoValue();
$a->c->echoValue();
$a->value = 11;
$a->echoValue();
$a->b->echoValue(); // *
$a->c->echoValue();
?>
Примерът по-горе ще изведе:
class A: 10 class B: 10 class B: 10 class A: 11 class B: 11 class B: 11
В PHP 4 обектите се сравняват по много лесен начин, а именно: Две инстанции са равни, ако имат едни и същи атрибути и стойности и са инстанции на един и същ клас. Подобни правила се прилагат и при сравняване на два обекта с оператора за идентичност (===).
Нека разгледаме следния пример:
Example #1 Пример за сравняване на обекти в PHP 4
<?php
function bool2str($bool) {
if ($bool === false) {
return 'FALSE';
} else {
return 'TRUE';
}
}
function compareObjects(&$o1, &$o2) {
echo 'o1 == o2 : '.bool2str($o1 == $o2)."\n";
echo 'o1 != o2 : '.bool2str($o1 != $o2)."\n";
echo 'o1 === o2 : '.bool2str($o1 === $o2)."\n";
echo 'o1 !== o2 : '.bool2str($o1 !== $o2)."\n";
}
class Flag {
var $flag;
function Flag($flag=true) {
$this->flag = $flag;
}
}
class SwitchableFlag extends Flag {
function turnOn() {
$this->flag = true;
}
function turnOff() {
$this->flag = false;
}
}
$o = new Flag();
$p = new Flag(false);
$q = new Flag();
$r = new SwitchableFlag();
echo "Сравняване на инстанции създадени с еднакви параметри\n";
compareObjects($o, $q);
echo "\nСравняване на инстанции създадени с различни параметри\n";
compareObjects($o, $p);
echo "\nСравняване на инстанция на родителски клас с този на дъщерния клас\n";
compareObjects($o, $r);
?>
Примерът по-горе ще изведе:
Сравняване на инстанции създадени с еднакви параметри o1 == o2 : TRUE o1 != o2 : FALSE o1 === o2 : TRUE o1 !== o2 : FALSE Сравняване на инстанции създадени с различни параметри o1 == o2 : FALSE o1 != o2 : TRUE o1 === o2 : FALSE o1 !== o2 : TRUE Сравняване на инстанция на родителски клас с този на дъщерния клас o1 == o2 : FALSE o1 != o2 : TRUE o1 === o2 : FALSE o1 !== o2 : TRUE
Горе е показан очаквания изход, при горните правила за сравнение. Само инстанции, които притежават едни и същи стойности за атрибутите си и са от един и същ клас се считат за равни и идентични.
Дори и в клас, в който имаме композиция на обекти, се прилагат същите правила за сравнение. В примера по-долу създаваме клас, който съдържа асоциативен масив от обекти от тип Flag.
Example #2 Сравняване на съставни обекти в PHP 4
<?php
class FlagSet {
var $set;
function FlagSet($flagArr = array()) {
$this->set = $flagArr;
}
function addFlag($name, $flag) {
$this->set[$name] = $flag;
}
function removeFlag($name) {
if (array_key_exists($name, $this->set)) {
unset($this->set[$name]);
}
}
}
$u = new FlagSet();
$u->addFlag('flag1', $o);
$u->addFlag('flag2', $p);
$v = new FlagSet(array('flag1'=>$q, 'flag2'=>$p));
$w = new FlagSet(array('flag1'=>$q));
echo "\nСъставни обекти u(o,p) и v(q,p)\n";
compareObjects($u, $v);
echo "\nu(o,p) и w(q)\n";
compareObjects($u, $w);
?>
Примерът по-горе ще изведе:
Съставни обекти u(o,p) и v(q,p) o1 == o2 : TRUE o1 != o2 : FALSE o1 === o2 : TRUE o1 !== o2 : FALSE u(o,p) и w(q) o1 == o2 : FALSE o1 != o2 : TRUE o1 === o2 : FALSE o1 !== o2 : TRUE
PHP 5 разполага с нов обектен модел. Управлението на обектите е изцяло преработено, с цел по-добра производителност и по-големи възможности.
Вж. също Userland Naming Guide.
Всяка дефиниция на клас започва с ключовата дума class, последвана от името на класа, което може да бъде всяко име, което не е запазена дума в PHP. Следват чифт фигурни скоби, между които се поставя дефиницията на свойствата и методите на класа. Псевдо-променливата $this е налична, когато се извиква дадено свойство или метод от тялото на класа. $this представлява референция към извикания обект (обикновено обекта, на който принадлежи метода, но може да бъде и друг обект, ако методът се извиква статично в контекста на вторичния обект). Това е илюстрирано в следните примери:
<?php
class A
{
function foo()
{
if (isset($this)) {
echo '$this е дефинирана (';
echo get_class($this);
echo ")\n";
} else {
echo "\$this не е дефинирана.\n";
}
}
}
class B
{
function bar()
{
A::foo();
}
}
$a = new A();
$a->foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>
Примерът по-горе ще изведе:
$this е дефинирана (a) $this не е дефинирана. $this е дефинирана (b) $this не е дефинирана.
Example #1 Проста дефиниция на клас
<?php
class SimpleClass
{
// дефиниция на свойство
public $var = 'стойност по подразбиране';
// дефиниция на метод
public function displayVar() {
echo $this->var;
}
}
?>
Стойността по подразбиране трябва да е константен израз, не (примерно) променлива, метод на клас или извикване на функция.
Example #2 Стойност по подразбиране за член на клас
<?php
class SimpleClass
{
// невалидни декларации на членове:
public $var1 = 'hello '.'world';
public $var2 = <<<EOD
hello world
EOD;
public $var3 = 1+2;
public $var4 = self::myStaticMethod();
public $var5 = $myVar;
// валидни декларации на членове:
public $var6 = myConstant;
public $var7 = self::classConstant;
public $var8 = array(true, false);
}
?>
Забележка: Разработени са много удобни функции за работа с класове и обекти. Можете да ги видите в глава Функции за класове и обекти.
За разлика от heredoc, nowdoc може да се използва в контекста на всякакви статични данни.
Example #3 Пример със статични данни
<?php
class foo {
// От PHP 5.3.0
public $bar = <<<'EOT'
bar
EOT;
}
?>
Забележка: Поддръжката на nowdoc е добавена в PHP 5.3.0.
За да бъде създадена инстанция на клас, трябва да се създаде нов обект и да се присвои на променлива. Когато се създава обект, той винаги ще бъде присвоен на променливата, освен ако няма конструктор, който да хвърля изключение при грешка. Класовете трябва да бъдат дефинирани преди инстанцииране (а в някои случаи това е задължително).
Example #4 Създаване на инстанция
<?php
$instance = new SimpleClass();
?>
В контекста на клас може да се създаде нов обект посредством new self и new parent.
Когато се присвоява вече създадена инстанция на клас към нова променлива, новата променлива ще има достъп до същата инстанция като присвоения обект. Нещата стоят по същия начин и когато се предават инстанции към функции. Копие на вече създаден обект може да се създаде чрез клониране.
Example #5 Присвояване на обект
<?php
$assigned = $instance;
$reference =& $instance;
$instance->var = '$assigned ще приеме тази стойност';
$instance = null; // $instance и $reference приемат стойност null
var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>
Примерът по-горе ще изведе:
NULL
NULL
object(SimpleClass)#1 (1) {
["var"]=>
string(30) "$assigned ще приеме тази стойност"
}
Даден клас може да наследи свойства и методи от друг клас, чрез използването на ключовата дума extends. Не се поддържа множествено наследяване, т.е. даден клас може да има само един базов клас.
Всички наследени свойства и методи могат да бъдат дефинирани отново, чрез повторното им дефиниране със същото име, с което са били дефинирани в родителския клас. Изключение се явяват случаите, когато в родителския клас даден метод е дефиниран като final. Достъпът до повторно дефинираните свойства или до статичните методи на родителския клас се осъществява чрез ключовата дума parent::
Example #6 Просто наследяване на клас
<?php
class ExtendClass extends SimpleClass
{
// Повторно дефиниране на родителския метод
function displayVar()
{
echo "Наследяване на клас\n";
parent::displayVar();
}
}
$extended = new ExtendClass();
$extended->displayVar();
?>
Примерът по-горе ще изведе:
Наследяване на клас стойност по подразбиране
Много разработчици на обектно-ориентирани приложения създават по един PHP файл за всеки клас. Едно от най-досадните неща е създаването на дълъг списък на файловете за включване в началото на всеки скрипт (по един за всеки клас).
В PHP 5 това вече не е необходимо. Можете да дефинирате функция __autoload, която се извиква автоматично, в случай че се опитате да използвате клас/интерфейс, който все още не е дефиниран. Извикването на тази функция е последната възможност на скриптовата машина да зареди този клас преди да бъде генерирана фатална грешка.
Забележка: Изключения, хвърлени от функцията __autoload, не могат да бъдат хванати в блока catch, в следствие на което се генерира фатална грешка.
Забележка: Автоматичното зареждане не е достъпно при използване на PHP в интерактивен режим CLI.
Забележка: Ако се използва име на клас като например при call_user_func(), то може да съдържа някои опасни знаци като ../. Препоръчително е да не използвате данни предоставени от потребителя в такива функции или поне да го проверявате във функцията __autoload().
Example #1 Пример за автоматично зареждане
В този пример се прави опит да се заредят класовете MyClass1 и MyClass2 от файловете MyClass1.php и съответно - MyClass2.php.
<?php
function __autoload($class_name) {
require_once $class_name . '.php';
}
$obj = new MyClass1();
$obj2 = new MyClass2();
?>
Example #2 Друг пример за автоматично зареждане
В този пример се прави опит за зареждане на интерфейс ITest.
<?php
function __autoload($name) {
var_dump($name);
}
class Foo implements ITest {
}
/*
string(5) "ITest"
Fatal error: Interface 'ITest' not found in ...
*/
?>
PHP 5 позволява на разработчиците да декларират конструктори на класовете. Класове, които имат метод-конструктор, извикват този метод при всяко създаване на нов обект, така че той е много подходящ за извършване на инициализации, от които обектът се нуждае преди да бъде използван.
Забележка: Конструкторите на родителските класове не се извикват автоматично, ако в даден дъщерен клас е дефиниран конструктор. За да се изпълни конструкторът на родителския клас, е необходимо да се извика parent::__construct() в тялото на конструктора на дъщерния клас.
Example #1 Използване на нови, унифицирани конструктори
<?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();
?>
Поради обратната съвместимост, ако PHP 5 не може да намери в даден клас метод __construct(), той ще потърси конструктор дефиниран по начина, по който се дефинира конструктор в по-старите версии, т.е. чрез функция с името на самия клас. На практика това означава, че може да възникнат проблеми при съвместимостта, единствено ако класът е имал метод __construct(), който е имал друг смисъл.
В PHP 5 е въведен деструкторен метод, по подобие на другите обектно-ориентирани езици като C++. Деструкторът ще се извика в момента, в който обектът бъде унищожен.
Example #2 Пример за деструктор
<?php
class MyDestructableClass {
function __construct() {
print "In constructor\n";
$this->name = "MyDestructableClass";
}
function __destruct() {
print "Destroying " . $this->name . "\n";
}
}
$obj = new MyDestructableClass();
?>
Също както в случая с конструктора и тук деструкторът на родителския клас няма да бъде извикан автоматично. За да се изпълни деструкторът на родителския клас е необходимо изрично да се извика parent::__destruct() в тялото на деструктора.
Забележка: Деструкторите се извикват по време на спирането на скрипта, при което HTTP заглавките са изпратени. Работната директория по време на процеса на спирането на скрипта може да бъдат различна при някои SAPI-та (като например Apache).
Забележка: Опитът да се хвърли изключение в тялото на деструктор (извикан по време на приключване на работа на скрипта) ще предизвика фатална грешка.
Видимостта на свойство или метод може да бъде дефинирана, чрез използване на ключовите думи public (общодостъпен), protected (защитен) или private (частен). Полетата декларирани като public са достъпни от всякъде. Полетата protected могат да бъдат достъпни от дъщерните и родителските класове (и в класа, в който са дефинирани). Private позволява достъпа само от тялото на класа, в който е дефинирано полето.
Свойствата на даден клас трябва да бъдат декларирани като public, private или protected.
Example #1 Декларация на свойство
<?php
/**
* Дефиниция на 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; // Работи
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Извежда Public, Protected и Private
/**
* Дефиниция на MyClass2
*/
class MyClass2 extends MyClass
{
// Може да се дефинират повторно public и protected методи, но не и private
protected $protected = 'Protected2';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj2 = new MyClass2();
echo $obj2->public; // Работи
echo $obj2->private; // Undefined
echo $obj2->protected; // Fatal Error
$obj2->printHello(); // Извежда Public, Protected2, Undefined
?>
Забележка: Ключавата дума var все още се поддържа от съображения за съвместимост (като синоним на ключовата дума public). В PHP 5 преди 5.1.3 употребата й ще генерира предупреждение от тип E_STRICT.
Методите на даден клас трябва да бъдат декларирани като public, private или protected. Методи без такава декларация ще бъдат дефинирани като public.
Example #2 Декларация на методи
<?php
/**
* Дефиниция на MyClass
*/
class MyClass
{
// Деклариране на public конструктор
public function __construct() { }
// Деклариране на public метод
public function MyPublic() { }
// Деклариране на protected метод
protected function MyProtected() { }
// Деклариране на private метод
private function MyPrivate() { }
// public метод
function Foo()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate();
}
}
$myclass = new MyClass;
$myclass->MyPublic(); // Работи
$myclass->MyProtected(); // Fatal Error
$myclass->MyPrivate(); // Fatal Error
$myclass->Foo(); // Извикват се Public, Protected и Private
/**
* Дефиниция на MyClass2
*/
class MyClass2 extends MyClass
{
// public метод
function Foo2()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate(); // Fatal Error
}
}
$myclass2 = new MyClass2;
$myclass2->MyPublic(); // Works
$myclass2->Foo2(); // Извикват се Public и Protected, но не и 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
?>
Операторът за област на действие (също така, познат като Paamayim Nekudotayim) или просто двойно двоеточие, е символ, който предоставя достъп до статични и повторно-дефинирани свойства и методи на даден клас и константи.
Когато се обръщате към тези полета извън дефиницията на съответния клас, използвайте името на класа.
От PHP 5.3.0 е възможно да се обърнете към клас посредством променлива. Стойността на променливата не може да бъде ключова дума (напр. self, parent и static не са позволени при динамичните референции към класове.
В началото Paamayim Nekudotayim може да ви се стори доста странен избор за име на двойното двоеточие. Докато се пишеше Zend Engine 0.5 (който е в основата на PHP 3), екипът на Zend реши да го кръсти така. Всъщност, това означава двойно двоеточие на иврит.
Example #1 :: извън дефиниция на клас
<?php
class MyClass {
const CONST_VALUE = 'Стойност на константата';
}
$classname = 'MyClass';
echo $classname::CONST_VALUE; // От PHP 5.3.0
echo MyClass::CONST_VALUE;
?>
Съществуват две специални ключови думи - self и parent, които се използват за достъп до свойства или методи вътре в дефиницията на класа.
Example #2 :: в дефиниция на клас
<?php
class OtherClass extends MyClass
{
public static $my_static = 'статична променлива';
public static function doubleColon() {
echo parent::CONST_VALUE . "\n";
echo self::$my_static . "\n";
}
}
$classname = 'OtherClass';
echo $classname::doubleColon(); // От PHP 5.3.0
OtherClass::doubleColon();
?>
Когато в дъщерен клас се дефинира повторно метод от родителски клас, PHP няма да извика родителския метод. Това дали да се извика родителския метод или не, се решава от дъщерния клас. Същото важи и за дефинициите на Конструкторите и деструкторите, Повторно-дефинираните и Вълшебните методи.
Example #3 Извикване на метод на родителски клас
<?php
class MyClass
{
protected function myFunc() {
echo "MyClass::myFunc()\n";
}
}
class OtherClass extends MyClass
{
// Повторно дефиниране на метод на родителския клас
public function myFunc()
{
// Извикване на метода на родителския клас
parent::myFunc();
echo "OtherClass::myFunc()\n";
}
}
$class = new OtherClass();
$class->myFunc();
?>
Декларирането на свойствата и методите на клас като статични, ги прави достъпни без нуждата от инстанцииране на класа. До поле, декларирано като статично, не може да се осъществи достъп от инстанция на обект (може само чрез статичен метод).
От съображения за съвместимост с PHP 4, ако не е използвана декларация за видимост, свойството или методът ще бъдат разглеждани като public.
Поради факта, че статичните методи могат да бъдат извикани без да е нужна инстанция на обект, псевдо-променливата $this не е достъпна в метода деклариран като статичен.
Не е възможно да се осъществи достъп до статичните свойства на обект чрез оператора ->.
Също както всяка статична променлива в PHP, статичните свойства могат да бъдат инициализирани само посредсвтом низ или константа; изрази не са позволени. Така че, статично свойство може да бъде инициализирано примерно с цяло число или масив, но не може да бъде инициализирано с друга променлива, с върната стойност от функция или с обект.
При статичното извикване на нестатичен метод се генерира предупреждение от ниво E_STRICT.
От PHP 5.3.0 е възможно да се обърнете към клас посредством променлива. Стойността на променливата не може да бъде ключова дума (напр. self, parent и static не са позволени при динамичните референции към класове).
Example #1 Пример за статично свойство
<?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"; // Notice: Undefined property: Foo::$my_static
o::$my_static . "\n";
$classname = 'Foo';
print $classname::$my_static . "\n"; // От PHP 5.3.0
print Bar::$my_static . "\n";
$bar = new Bar();
print $bar->fooStatic() . "\n";
?>
Example #2 Пример за статичен метод
<?php
class Foo {
public static function aStaticMethod() {
// ...
}
}
Foo::aStaticMethod();
$classname = 'Foo';
$classname::aStaticMethod(); // От PHP 5.3.0
?>
В контекста на даден клас могат да бъдат дефинирани константи, които остават едни и същи и не търпят промяна. Константите се различават от нормалните променливи по това, че не е нужно да използвате символа $, за да ги дефинирате или използвате.
Стойността трябва да бъде константен израз, т.е. не може да бъде променлива, член на клас, резултат от математическа операция или обръщане към функция.
Интерфейсите също могат да имат константи. За да видите някои примери прегледайте документацията за интерфейсите.
От PHP 5.3.0 е възможно да се обърнете към клас посредством променлива. Стойността на променливата не може да бъде ключова дума (напр. self, parent и static не са позволени при динамичните референции към класове.
Example #1 Дефиниране и използване на константа
<?php
class MyClass
{
const constant = 'стойност на константата';
function showConstant() {
echo self::constant . "\n";
}
}
echo MyClass::constant . "\n";
$classname = "MyClass";
echo $classname::constant . "\n"; // От PHP 5.3.0
$class = new MyClass();
$class->showConstant();
echo $class::constant."\n"; // От PHP 5.3.0
?>
Example #2 Пример със статични данни
<?php
class foo {
// От PHP 5.3.0
const bar = <<<'EOT'
bar
EOT;
}
?>
За разлика от heredoc, nowdoc може да се използва в контекста на всякакви статични данни.
Забележка: Поддръжката на nowdoc е добавена в PHP 5.3.0.
В PHP 5 са реализирани абстрактни класове и методи. Не е възможно инстанциирането на клас дефиниран като абстрактен. Всеки клас, който съдържа поне един абстрактен метод, трябва също да се дефинира като абстрактен. Методите, декларирани като абстрактни, имат прототип, но не и имплементация.
При наследяване от абстрактен клас, всички методи декларирани като абстрактни в родителския клас трябва да бъдат дефинирани в дъщерния клас; освен това, тези методи трябва да бъдат със същата (или по-малко рестриктивна) видимост. Например ако абстрактният метод е дефиниран като protected, имплементацията на функцията трябва да бъде дефинирана като protected или public, но не и private.
Example #1 Пример за абстрактни класове
<?php
abstract class AbstractClass
{
// Методи, които трябва да бъдат дефинирани в дъщерния клас
abstract protected function getValue();
abstract protected function prefixValue($prefix);
// Общ метод
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";
?>
Примерът по-горе ще изведе:
ConcreteClass1 FOO_ConcreteClass1 ConcreteClass2 FOO_ConcreteClass2
Стар код, в който няма потребителски-дефинирани функции или класове с името 'abstract', ще работи без да са нужни промени по него.
Интерфейсите позволяват да се дефинират методите, които даден клас задължително трябва да реализира, без да се декларират самите тела на тези методи.
Интерфейсите се дефинират чрез ключовата дума interface, аналогично на обикновения клас, но без да се декларират телата на методите му.
Всички методи, дефинирани в даден интерфейс, трябва да бъдат public, поради спецификата на интерфейса.
За да се укаже, че даден клас реализира определен интерфейс, се използва операторът implements. Всички методи на интерфейса трябва да бъдат реализирани в класа. Нереализирането на метод предизвиква Фатална грешка. Даден клас може да реализира и повече от един интерфейс, като имената на интерфейсите в този случай се разделят със запетая.
Забележка: Даден клас не може да реализира два интерфейса, ако те имат методи с еднакви имена, тъй като това води до неопределеност.
Забележка: Интерфейсите могат да бъдат разширявани, също какт класовете, посредством оператора extend
Интерфейсите могат да имат константи. Интерфейсните константи работят точно както класовите константи. Те не могат да бъдат предефинирани от класа/интерфейса, който ги наследява.
Example #1 Пример за interface
<?php
// Декларация на интерфейс 'iTemplate'
interface iTemplate
{
public function setVariable($name, $var);
public function getHtml($template);
}
// Реализиране на интерфейса
// Това ще работи
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;
}
}
// Това няма да работи
// 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;
}
}
?>
Example #2 Разширяеми интерфейси
<?php
interface a
{
public function foo();
}
interface b extends a
{
public function baz(Baz $baz);
}
// Това ще работи
class c implements b
{
public function foo()
{
}
public function baz(Baz $baz)
{
}
}
// Това няма да работи и ще предизвика Фатална грешка
class d implements b
{
public function foo()
{
}
public function baz(Foo $foo)
{
}
}
?>
Example #3 Множествено наследяване на интерфейси
<?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()
{
}
}
?>
Example #4 Интерфейси с константи
<?php
interface a
{
const b = 'Интерфейсна константа';
}
// Извежда: Интерфейсна константа
echo a::b;
// Това разбира се няма да работи, тъй като не е позволено
// предефинирането на константи. Концепцията е същата като
// при класовите константи
class b implements a
{
const b = 'Класова константа';
}
?>
Вж. също оператора instanceof.
Предефинирането в PHP осигурява средства за динамично "създаване" на членове и методи. Динамичните елементи се обработват посредством вълшебни методи, които могат да бъдат добавени към даден клас, с цел извършване на различни операции.
Предефиниращите методи се извикват при осъществяване на достъп до членове и методи, които не са декларирани или не са видими в текущата област на действие. По-нататък в раздела ще се използват термините "недостъпни членове" и "недостъпни методи" за указване на това съчетание от декларация и видимост.
Всички предефиниращи методи трябва да се декларират като public.
Забележка: Параметрите на тези вълшебни методи не могат да бъдат предавани по референция.
Забележка: Интерпретирането на "предефинирането" в PHP е различно от това на повечето обектно-ориентирани езици. Предефинирането обикновено предоставя възможността да съществуват множество методи с едно и също име, но с различен брой и тип на параметрите
| Версия | Описание |
|---|---|
| 5.1.0 | Добавени са __isset() и __unset(). |
| 5.3.0 | Добавен е __callStatic(). Добавено е предупреждение за прилагане на public видимост и нестатично деклариране. |
__set() се изпълнява при запис на данни в недостъпни членове.
__get() се използва за четене на данни от недостъпни членове.
__isset() се задейства при извикване на isset() или empty() с недостъпни членове.
__unset() се извиква когато се използва unset() с недостъпни членове.
Параметърът $name указва името на члена, с който се работи. Параметърът $value на метода __set() указва стойността в която трябва да се установи члена $name.
Предефинирането на членове работи само в контекста на обект. Тези вълшебни методи няма да бъдат извикани в контекста на статично извикване, следователно тези методи не могат да бъдат декларирани като статични.
Example #1 Пример за предефиниране с __get, __set, __isset и __unset
<?php
class MemberTest {
/** Място за предефинирани данни. */
private $data = array();
/** Предефиниране не се извършва при декларирани членове. */
public $declared = 1;
/** Предефинирането задейства само при осъществяване на достъп извън тялото на класа. */
private $hidden = 2;
public function __set($name, $value) {
echo "Установяне на '$name' в '$value'\n";
$this->data[$name] = $value;
}
public function __get($name) {
echo "Връщане на стойността на '$name'\n";
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
$trace = debug_backtrace();
trigger_error(
'Недефинирано свойство посредством __get(): ' . $name .
' в ' . $trace[0]['file'] .
' на ред ' . $trace[0]['line'],
E_USER_NOTICE);
return null;
}
/** От PHP 5.1.0 */
public function __isset($name) {
echo "Установен ли е '$name'?\n";
return isset($this->data[$name]);
}
/** От PHP 5.1.0 */
public function __unset($name) {
echo "Унищожаване на '$name'\n";
unset($this->data[$name]);
}
/** Това не е вълшебен метод, просто е тук за пример. */
public function getHidden() {
return $this->hidden;
}
}
echo "<pre>\n";
$obj = new MemberTest;
$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 "Нека да експериментираме с private свойство именувано 'hidden':\n";
echo "Private свойствата са видими в тялото на класа, така че, не се използва __get()...\n";
echo $obj->getHidden() . "\n";
echo "Private свойствата не са видими извън тялото на класа, така че, се използва __get()...\n";
echo $obj->hidden . "\n";
?>
Примерът по-горе ще изведе:
Установяване на 'a' в '1' Вземане на стойността на 'a' 1 Установен ли е 'a'? bool(true) Унищожаване на 'a' Установен ли е 'a'? bool(false) 1 Нека да експериментираме с private свойство именувано 'hidden' Private свойствата са видими в тялото на класа, така че, не се използва __get()... 2 Private свойствата не са видими извън тялото на класа, така че, се използва __get()... Връщане на стойността на 'hidden' Notice: Undefined property via __get(): hidden in <file> on line 70 in <file> on line 29
__call() се задейства при извикване на недостъпни методи в контекста на обект.
__callStatic() се задейства при извикване на недостъпни методи в контекста на статично извикване.
Параметърът $name указва името на метода, който се извиква. Параметърът $arguments е масив, съдържаш параметрите, които са предадени към метода $name.
Example #2 Предефиниране на методи с __call и __callStatic
<?php
class MethodTest {
public function __call($name, $arguments) {
// Забележка: стойността на $name е чувствителна към регистъра.
echo "Извикване на метод на обект '$name' "
. implode(', ', $arguments). "\n";
}
/** От PHP 5.3.0 */
public static function __callStatic($name, $arguments) {
// Забележка: стойността на $name е чувствителна към регистъра.
echo "Извикване на статичен метод '$name' "
. implode(', ', $arguments). "\n";
}
}
$obj = new MethodTest;
$obj->runTest('в контекста на обект');
MethodTest::runTest('в контекста на статично извикване'); // От PHP 5.3.0
?>
Примерът по-горе ще изведе:
Извикване на метод на обект'runTest' в контекста на обект Извикване на статичен метод 'runTest' в контекста на статично извикване
PHP 5 предоставя възможност на обектите да бъдат дефинирани така, че да могат да бъдат итерирани, примерно с цикъл foreach. По подразбиране всички видими свойства ще бъдат използвани при итерирането.
Example #1 Просто итериране на обект
<?php
class MyClass
{
public $var1 = 'стойност 1';
public $var2 = 'стойност 2';
public $var3 = 'стойност 3';
protected $protected = 'protected променлива';
private $private = 'private променлива';
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();
?>
Примерът по-горе ще изведе:
var1 => стойност 1 var2 => стойност 2 var3 => стойност 3 MyClass::iterateVisible: var1 => стойност 1 var2 => стойност 2 var3 => стойност 3 protected => protected променлива private => private променлива
Както показва резултатът, цикълът foreach обхожда всички видими променливи, до които има достъп. Ако отидем една крачка по-напред, можем да реализираме един от вътрешните интерфейси на PHP 5 - Iterator. Реализирането на този интерфейс дава възможност на обекта сам да решава какво и как ще се итерира.
Example #2 Итериране на обект, реализиращ интерфейса Iterator
<?php
class MyIterator implements Iterator
{
private $var = array();
public function __construct($array)
{
if (is_array($array)) {
$this->var = $array;
}
}
public function rewind() {
echo "превъртане\n";
reset($this->var);
}
public function current() {
$var = current($this->var);
echo "текущ: $var\n";
return $var;
}
public function key() {
$var = key($this->var);
echo "ключ: $var\n";
return $var;
}
public function next() {
$var = next($this->var);
echo "следващ: $var\n";
return $var;
}
public function valid() {
$var = $this->current() !== false;
echo "валиден: {$var}\n";
return $var;
}
}
$values = array(1,2,3);
$it = new MyIterator($values);
foreach ($it as $a => $b) {
print "$a: $b\n";
}
?>
Примерът по-горе ще изведе:
превъртане текущ: 1 валиден: 1 текущ: 1 ключ: 0 0: 1 следващ: 2 текущ: 2 валиден: 1 текущ: 2 ключ: 1 1: 2 следващ: 3 текущ: 3 валиден: 1 текущ: 3 ключ: 2 2: 3 следващ: текущ: валиден:
Можете да дефинирате вашия клас така, че да не се налага да дефинирате всички функции от интерфейса Iterator, като реализирате интерфейса IteratorAggregate в PHP 5.
Example #3 Итериране на обект, реализиращ IteratorAggregate
<?php
class MyCollection implements IteratorAggregate
{
private $items = array();
private $count = 0;
// Задължителен за дефиниране метод на интерфейса IteratorAggregate
public function getIterator() {
return new MyIterator($this->items);
}
public function add($value) {
$this->items[$this->count++] = $value;
}
}
$coll = new MyCollection();
$coll->add('стойност 1');
$coll->add('стойност 2');
$coll->add('стойност 3');
foreach ($coll as $key => $val) {
echo "ключ/стойност: [$key -> $val]\n\n";
}
?>
Примерът по-горе ще изведе:
превъртане текущ: стойност 1 валиден: 1 текущ: стойност 1 ключ: 0 ключ/стойност: [0 -> стойност 1] следващ: стойност 2 текущ: стойност 2 валиден: 1 текущ: стойност 2 ключ: 1 ключ/стойност: [1 -> стойност 2] следващ: стойност 3 текущ: стойност 3 валиден: 1 текущ: стойност 3 ключ: 2 ключ/стойност: [2 -> стойност 3] следващ: текущ: валиден:
Забележка: За повече примери относно итераторите погледнете Разширение SPL.
Шаблоните за дизайн са начин да се опишат най-добрите практики и методи на проектиране. Те дават гъвкави решения на често срещани в програмирането проблеми.
Шаблонът Фабрика позволява инстанциирането на обекти по време на изпълнение на програмата. Нарича се метод фабрика, защото е отговорен за "производството" на обектите. При параметризираният метод фабрика (Parameterized Factory) името на класа, който трябва да инстанциира се получава като аргумент.
Example #1 Параметризиран метод фабрика (Parameterized Factory Method)
<?php
class Example
{
// Параметризиран метод фабрика
public static function factory($type)
{
if (include_once 'Drivers/' . $type . '.php') {
$classname = 'Driver_' . $type;
return new $classname;
} else {
throw new Exception ('Драйверът не е намерен');
}
}
}
?>
Дефинирането на този метод в класа позволява на драйверите да бъдат заредени при нужда. Ако класът Example беше клас за абстракция на бази от данни, зареждането на драйверите за MySQL и SQLite щеше да изглежда по следния начин:
<?php
// Зареждане на драйвера за MySQL
$mysql = Example::factory('MySQL');
// Зареждане на драйвера за SQLite
$sqlite = Example::factory('SQLite');
?>
Шаблонът Сек се използва тогава, когато трябва да има точно една инстанция на даден клас. Най-често срещаният пример за това е връзка към база от данни. Реализирането на този шаблон позволява на програмиста да направи тази единствена инстанция лесно достъпна за много други обекти.
Example #2 Сек (Singleton) метод
<?php
class Example
{
// Съдържа единствената инстанция на класа
private static $instance;
// private конструктор; предотвратява директното инстанцииране на класа
private function __construct()
{
echo 'I am constructed';
}
// Сек (Singleton) метод
public static function singleton()
{
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
// Примерен метод
public function bark()
{
echo 'Woof!';
}
// Не позволява на потребителя да клонира инстанцията
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
}
?>
Това позволява да бъде върната само една единствена инстанция на класа Example.
<?php
// При опитът да се инстанциира този клас ще възникне грешка, тъй като конструктора на класа е private
$test = new Example;
// Това винаги ще връща единствената инстанция на класа
$test = Example::singleton();
$test->bark();
// Това ще върне грешка от ниво E_USER_ERROR.
$test_clone = clone $test;
?>
Имената на функциите __construct, __destruct, __call, __callStatic, __get, __set, __isset, __unset, __sleep, __wakeup, __toString, __invoke, __set_state и __clone са вълшебни в класовете на PHP. Не може да създавате функции с тези имена във вашите класове, освен ако не ги използвате по вълшебното им предназначение.
PHP запазва всички имена на функции, започващи с __, като вълшебни. Препоръчително е да не използвате имена на функции, които започват с __ в PHP, освен ако не използвате някоя документирана вълшебна функционалност.
serialize() проверява дали в класа ви има функция с вълшебното име __sleep. Ако открие такава, то тази функция се изпълнява преди всяка сериализация. Тя би могла да изчисти обекта и се очаква да върне масив с имената на всички променливи от този обект, които ще бъдат сериалзирани. Ако методът не върне нищо, тогава се сериализира стойността NULL и се генерира грешка от тип E_NOTICE.
Предназначението на __sleep е да затвори всички връзки към бази от данни, които обектът може да има, да съхрани незаписаните данни или да изпълни други подобни изчистващи задачи. Също така функцията може да се използва и в случай, че имате много големи обекти, които няма нужда да бъдат съхранени изцяло.
Обратно - unserialize() проверява за наличието на функция с вълшебното име __wakeup. Ако тя съществува, функцията може да възстанови всички ресурси, които даден обект може да има.
Употребата на __wakeup има за цел да възстанови всички връзки към бази от данни, които може да са били прекъснати по време на сериализацията и за извършване на други повторно-инициализиращи задачи.
Example #1 Заспиване (sleep) и събуждане (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();
}
}
?>
Методът __toString позволява на даден клас да реши как ще реагира, в случай че бъде преобразуван до низ.
Example #2 Прост пример
<?php
// Дефиниция на клас
class TestClass
{
public $foo;
public function __construct($foo) {
$this->foo = $foo;
}
public function __toString() {
return $this->foo;
}
}
$class = new TestClass('Здравей');
echo $class;
?>
Примерът по-горе ще изведе:
Здравей
Трябва да се отбележи, че до PHP 5.2.0 методът __toString ще бъде извикан, само когато е директно комбиниран с echo() или print(). От PHP 5.2.0 се извиква в контекста на всеки низов тип (например при printf() с модификатора %s), но не и в контекста на други типове (например при модификатора %d). От PHP 5.2.0 при преобразуването на обекти в низ без метода __toString ще се генерира E_RECOVERABLE_ERROR
Методът __invoke се извиква, когато даден скрипт направи опит да извика обект, както се извиква функция. The __invoke method is called when a script tries to call an object as a function.
Забележка: Тази възможност е достъпна от PHP 5.3.0.
Example #3 Употреба на __invoke
<?php
class CallableClass {
function __invoke($x) {
var_dump($x);
}
}
$obj = new CallableClass;
$obj(5);
var_dump(is_callable($obj));
?>
Примерът по-горе ще изведе:
int(5) bool(true)
Този статичен метод се извиква за класове, експортирани от функцията var_export() от PHP 5.1.0.
Единственият параметър на метода е масив, съдържащ експортирани свойства във вида array('property' => value, ...).
Example #4 Употреба на __set_state (от PHP 5.1.0)
<?php
class A
{
public $var1;
public $var2;
public static function __set_state($an_array) // As of PHP 5.1.0
{
$obj = new A;
$obj->var1 = $an_array['var1'];
$obj->var2 = $an_array['var2'];
return $obj;
}
}
$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';
eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
// 'var1' => 5,
// 'var2' => 'foo',
// ));
var_dump($b);
?>
Примерът по-горе ще изведе:
object(A)#2 (2) {
["var1"]=>
int(5)
["var2"]=>
string(3) "foo"
}
В PHP 5 е въведена ключовата дума final, като използването й пред дефиницията на метод от родителски клас предотвратява възможността този метод да бъде дефиниран повторно в дъщерен клас. Ако даден клас е дефиниран като final, то той не може да бъде наследяван.
Example #1 Пример за final метод
<?php
class BaseClass {
public function test() {
echo "BaseClass::test() called\n";
}
final public function moreTesting() {
echo "BaseClass::moreTesting() called\n";
}
}
class ChildClass extends BaseClass {
public function moreTesting() {
echo "ChildClass::moreTesting() called\n";
}
}
// Резултатът ще е Fatal error: Cannot override final method BaseClass::moreTesting()
?>
Example #2 Пример за final клас
<?php
final class BaseClass {
public function test() {
echo "BaseClass::test() called\n";
}
// Тук няма значение дали методът ще е final или не
final public function moreTesting() {
echo "BaseClass::moreTesting() called\n";
}
}
class ChildClass extends BaseClass {
}
// Резултатът ще е Fatal error: Class ChildClass may not inherit from final class (BaseClass)
?>
Създаването на копие на обект с абсолютно идентични свойства не винаги е желаният вариант. Добър пример за необходимостта от копиране на конструкторите е ситуацията, в която имате обект, който представлява GTK прозорец и съдържа ресурсите на този GTK прозорец. Когато създадете копие на този обект, може да искате да създадете нов прозорец със същите свойства и новият обект да съдържа ресурсите на новия прозорец. Като друг пример може да послужи ситуацията, в която вашият обект използва референция към друг обект, който използва и когато създадете копие на родителския обект, искате да се създаде нова инстанция и на другия обект, така че и той да си има свое собствено копие.
Копие на обект се създава посредством ключовата дума clone (която извиква метода __clone() на обекта, ако е възможно). Методът __clone() не може да бъде извикан директно.
$copy_of_object = clone $object;
Когато се създаде копие на обекта, PHP5 ще създаде нова инстанция на обекта, с негово собствено копие на свойствата. Всички свойства, които са референции към други променливи ще си останат референции, т.е. няма да се извърши дълбочинно копиране.
След като клонирането завърши, ако е дефиниран метод __clone(), ще бъде извикан метода __clone() на новосъздадения обект, за да може, ако се налага да се променят стойностите на някои свойства.
Example #1 Клониране на обект
<?php
class SubObject
{
static $instances = 0;
public $instance;
public function __construct() {
$this->instance = ++self::$instances;
}
public function __clone() {
$this->instance = ++self::$instances;
}
}
class MyCloneable
{
public $object1;
public $object2;
function __clone()
{
// Принуждава създаването на копие на $this->object, в противен случай
// ще сочи към същия обект.
$this->object1 = clone $this->object1;
}
}
$obj = new MyCloneable();
$obj->object1 = new SubObject();
$obj->object2 = new SubObject();
$obj2 = clone $obj;
print("Оригинален обект:\n");
print_r($obj);
print("Клониран обект:\n");
print_r($obj2);
?>
Примерът по-горе ще изведе:
Оригинален обект:
MyCloneable Object
(
[object1] => SubObject Object
(
[instance] => 1
)
[object2] => SubObject Object
(
[instance] => 2
)
)
Клониран обект:
MyCloneable Object
(
[object1] => SubObject Object
(
[instance] => 3
)
[object2] => SubObject Object
(
[instance] => 2
)
)
В PHP 5 сравняването на обекти е по-сложен процес, отколкото в PHP 4 и е в съответствие с това, което може да се очаква от един Обектно-ориентиран език (не че PHP 5 е такъв език).
При използването на оператора за сравнение (==), обектите се сравняват по прост начин, а именно: Две инстанции на обект са равни, ако имат едни и същи атрибути и стойности и са инстанции на един и същи клас.
От друга страна, при използването на оператора за идентичност (===), обектите са равни тогава, и само тогава, когато сочат към една и съща инстанция на един и същ клас.
Следващият пример ще изясни тези правила.
Example #1 Пример за сравняване на обекти в PHP 5
<?php
function bool2str($bool)
{
if ($bool === false) {
return 'FALSE';
} else {
return 'TRUE';
}
}
function compareObjects(&$o1, &$o2)
{
echo 'o1 == o2 : ' . bool2str($o1 == $o2) . "\n";
echo 'o1 != o2 : ' . bool2str($o1 != $o2) . "\n";
echo 'o1 === o2 : ' . bool2str($o1 === $o2) . "\n";
echo 'o1 !== o2 : ' . bool2str($o1 !== $o2) . "\n";
}
class Flag
{
public $flag;
function Flag($flag = true) {
$this->flag = $flag;
}
}
class OtherFlag
{
public $flag;
function OtherFlag($flag = true) {
$this->flag = $flag;
}
}
$o = new Flag();
$p = new Flag();
$q = $o;
$r = new OtherFlag();
echo "Две инстанции на един и същи клас\n";
compareObjects($o, $p);
echo "\nДве референции към една и съща инстанция\n";
compareObjects($o, $q);
echo "\nИнстанции на два отделни класа\n";
compareObjects($o, $r);
?>
Примерът по-горе ще изведе:
Две инстанции на един и същ клас o1 == o2 : TRUE o1 != o2 : FALSE o1 === o2 : FALSE o1 !== o2 : TRUE Две референции към една и съща инстанция o1 == o2 : TRUE o1 != o2 : FALSE o1 === o2 : TRUE o1 !== o2 : FALSE Инстанции на два отделни класа o1 == o2 : FALSE o1 != o2 : TRUE o1 === o2 : FALSE o1 !== o2 : TRUE
Забележка: Разширенията могат да дефинират свои собствени правила за сравняване на обекти.
PHP 5 разполага с цялостен API интерфейс за работа с отражения, което добавя възможността за обратно инженерство (reverse engineering) на класове, интерфейси, функции и методи, както и разширения. Освен това API-интерфейсът за отражения предлага начини за извличане на документиращи коментари за функции, класове и методи.
API-интерфейсът за отражения е обектно-ориентирано разширение на Zend Engine, което се състои от следните класове:
<?php
class Reflection { }
interface Reflector { }
class ReflectionException extends Exception { }
class ReflectionFunction extends ReflectionFunctionAbstract implements Reflector { }
class ReflectionParameter implements Reflector { }
class ReflectionMethod extends ReflectionFunctionAbstract implements Reflector { }
class ReflectionClass implements Reflector { }
class ReflectionObject extends ReflectionClass { }
class ReflectionProperty implements Reflector { }
class ReflectionExtension implements Reflector { }
?>
Забележка: За повече информация относно тези класове, вижте следващите глави.
Нека разгледаме следния пример:
Example #1 Проста употреба на API интерфейса за отражения
<?php
Reflection::export(new ReflectionClass('Exception'));
?>
Примерът по-горе ще изведе:
Class [ <internal> class Exception ] {
- Constants [0] {
}
- Static properties [0] {
}
- Static methods [0] {
}
- Properties [6] {
Property [ <default> protected $message ]
Property [ <default> private $string ]
Property [ <default> protected $code ]
Property [ <default> protected $file ]
Property [ <default> protected $line ]
Property [ <default> private $trace ]
}
- Methods [9] {
Method [ <internal> final private method __clone ] {
}
Method [ <internal, ctor> public method __construct ] {
- Parameters [2] {
Parameter #0 [ <optional> $message ]
Parameter #1 [ <optional> $code ]
}
}
Method [ <internal> final public method getMessage ] {
}
Method [ <internal> final public method getCode ] {
}
Method [ <internal> final public method getFile ] {
}
Method [ <internal> final public method getLine ] {
}
Method [ <internal> final public method getTrace ] {
}
Method [ <internal> final public method getTraceAsString ] {
}
Method [ <internal> public method __toString ] {
}
}
}
Reflector е интерфейс, реализиран от всички класове от тип Reflection, които могат да бъдат експортирани.
<?php
interface Reflector
{
public string __toString()
public static string export()
}
?>
ReflectionException наследява стандартното изключение Exception и се хвърля от API-интерфейса за отражения. Няма специфични методи и свойства.
Класът ReflectionFunction позволява извличане на информация за функции.
<?php
class ReflectionFunction extends ReflectionFunctionAbstract implements Reflector
{
final private __clone()
public void __construct(string name)
public string __toString()
public static string export()
public string getName()
public bool isInternal()
public bool isDisabled()
public mixed getClosure() /* От PHP 5.3.0 */
public bool isUserDefined()
public string getFileName()
public int getStartLine()
public int getEndLine()
public string getDocComment()
public array getStaticVariables()
public mixed invoke([mixed args [, ...]])
public mixed invokeArgs(array args)
public bool returnsReference()
public ReflectionParameter[] getParameters()
public int getNumberOfParameters()
public int getNumberOfRequiredParameters()
}
?>
Родителският клас ReflectionFunctionAbstract има същите методи с изключение на invoke(), invokeArgs(), export() и isDisabled().
Забележка: getNumberOfParameters() и getNumberOfRequiredParameters() бяха добавени в PHP 5.0.3, а invokeArgs() беше добавен в PHP 5.1.0.
За да извършите интроспекция на функция, първо трябва да направите инстанция на класа ReflectionFunction. След това може да извикате който и да е от горните методи на тази инстанция.
Example #2 Употреба на класа ReflectionFunction
<?php
/**
* Обикновен брояч
*
* @return int
*/
function counter()
{
static $c = 0;
return $c++;
}
// Създаване на инстанция на класа ReflectionFunction
$func = new ReflectionFunction('counter');
// Извеждане на основна информация
printf(
"===> %s функция '%s'\n".
" декларирана в %s\n".
" на редове от %d до %d\n",
$func->isInternal() ? 'Вътрешна' : 'Дефинирана от потребителя',
$func->getName(),
$func->getFileName(),
$func->getStartLine(),
$func->getEndline()
);
// Извеждане на документиращ коментар
printf("---> Документация:\n %s\n", var_export($func->getDocComment(), 1));
// Извеждане на статичните променливи, ако има такива
if ($statics = $func->getStaticVariables())
{
printf("---> Статични променливи: %s\n", var_export($statics, 1));
}
// Извикване на функция
printf("---> Резултат от извикването: ");
var_dump($func->invoke());
// може да се използва метода export()
echo "\nReflectionFunction::export() резултат:\n";
echo ReflectionFunction::export('counter');
?>
Забележка: Методът invoke() приема произволен брой аргументи, които се предават към функцията точно както при call_user_func().
Класът ReflectionParameter позволява извличане на информация за параметрите на функции и методи.
<?php
class ReflectionParameter implements Reflector
{
final private __clone()
public void __construct(string function, string parameter)
public string __toString()
public static string export()
public string getName()
public bool isPassedByReference()
public ReflectionClass getDeclaringClass()
public ReflectionClass getClass()
public bool isArray()
public bool allowsNull()
public bool isPassedByReference()
public bool isOptional()
public bool isDefaultValueAvailable()
public mixed getDefaultValue()
public int getPosition()
}
?>
Забележка: getDefaultValue(), isDefaultValueAvailable() и isOptional() бяха добавени в PHP 5.0.3, a isArray() беше добавен в PHP 5.1.0. getDeclaringFunction() и getPosition() бяха добавени в PHP 5.2.3.
За да извършите интроспекция на параметрите на функция, първо трябва да направите инстанция на класовете ReflectionFunction или ReflectionMethod и да използвате техните методи getParameters(), за да върнете масива от параметри.
Example #3 Употреба на класа ReflectionParameter
<?php
function foo($a, $b, $c) { }
function bar(Exception $a, &$b, $c) { }
function baz(ReflectionFunction $a, $b = 1, $c = null) { }
function abc() { }
// Създаване на инстанция на ReflectionFunction
// с параметри от командния ред
$reflect = new ReflectionFunction($argv[1]);
echo $reflect;
foreach ($reflect->getParameters() as $i => $param) {
printf(
"-- Параметър #%d: %s {\n".
" Клас: %s\n".
" Позволява NULL: %s\n".
" Предаден по адрес: %s\n".
" Опционален?: %s\n".
"}\n",
$i, // $param->getPosition() може да се използва от PHP 5.2.3
$param->getName(),
var_export($param->getClass(), 1),
var_export($param->allowsNull(), 1),
var_export($param->isPassedByReference(), 1),
$param->isOptional() ? 'да' : 'не'
);
}
?>
Класът ReflectionClass позволява извличане на информация за класове и интерфейси.
<?php
class ReflectionClass implements Reflector
{
final private __clone()
public void __construct(string name)
public string __toString()
public static string export(mixed class, bool return)
public string getName()
public bool isInternal()
public bool isUserDefined()
public bool isInstantiable()
public bool hasConstant(string name)
public bool hasMethod(string name)
public bool hasProperty(string name)
public string getFileName()
public int getStartLine()
public int getEndLine()
public string getDocComment()
public ReflectionMethod getConstructor()
public ReflectionMethod getMethod(string name)
public ReflectionMethod[] getMethods()
public ReflectionProperty getProperty(string name)
public ReflectionProperty[] getProperties()
public array getConstants()
public mixed getConstant(string name)
public ReflectionClass[] getInterfaces()
public bool isInterface()
public bool isAbstract()
public bool isFinal()
public int getModifiers()
public bool isInstance(stdclass object)
public stdclass newInstance(mixed args)
public stdclass newInstanceArgs(array args)
public ReflectionClass getParentClass()
public bool isSubclassOf(ReflectionClass class)
public array getStaticProperties()
public mixed getStaticPropertyValue(string name [, mixed default])
public void setStaticPropertyValue(string name, mixed value)
public array getDefaultProperties()
public bool isIterateable()
public bool implementsInterface(string name)
public ReflectionExtension getExtension()
public string getExtensionName()
}
?>
Забележка: hasConstant(), hasMethod(), hasProperty(), getStaticPropertyValue() и setStaticPropertyValue() бяха добавени в PHP 5.1.0, а newInstanceArgs() беше добавен в PHP 5.1.3.
За да извършите интроспекция на клас, първо трябва да направите инстанция на ReflectionClass. След това може да извикате който и да е от горните методи на тази инстанция.
Example #4 Употреба на класа ReflectionClass
<?php
interface Serializable
{
// ...
}
class Object
{
// ...
}
/**
* Клас Counter
*/
class Counter extends Object implements Serializable
{
const START = 0;
private static $c = Counter::START;
/**
* Извикване на брояча
*
* @access public
* @return int
*/
public function count() {
return self::$c++;
}
}
// Създаване на инстанция на класа ReflectionClass
$class = new ReflectionClass('Counter');
// Извеждане на основна информация
printf(
"===> %s%s%s %s '%s' [наследява %s]\n" .
" деклариран в %s\n" .
" на редове от %d да %d\n" .
" притежава модификатори %d [%s]\n",
$class->isInternal() ? 'Вътрешен' : 'Дефиниран от потребителя',
$class->isAbstract() ? ' абстрактен' : '',
$class->isFinal() ? ' финален' : '',
$class->isInterface() ? ' интерфейс' : ' клас',
$class->getName(),
var_export($class->getParentClass(), 1),
$class->getFileName(),
$class->getStartLine(),
$class->getEndline(),
$class->getModifiers(),
implode(' ', Reflection::getModifierNames($class->getModifiers()))
);
// Извеждане на документиращ коментар
printf("---> Документация:\n %s\n", var_export($class->getDocComment(), 1));
// Извежда интерфейсите реализирани от този клас
printf("---> Реализира:\n %s\n", var_export($class->getInterfaces(), 1));
// Извежда константите на класа
printf("---> Константи: %s\n", var_export($class->getConstants(), 1));
// Извежда свойствата на класа
printf("---> Свойства: %s\n", var_export($class->getProperties(), 1));
// Извежда методите на класа
printf("---> Методи: %s\n", var_export($class->getMethods(), 1));
// Ако класът може да се инстранциира, създава инстранция
if ($class->isInstantiable()) {
$counter = $class->newInstance();
echo '---> $counter е инстанция? ';
echo $class->isInstance($counter) ? 'да' : 'не';
echo "\n---> new Object() е инстанция? ";
echo $class->isInstance(new Object()) ? 'да' : 'не';
}
?>
Забележка: Методът newInstance() приема произволен брой аргументи, които се предават към функцията точно както при call_user_func().
Забележка: $class = new ReflectionClass('Foo'); $class->isInstance($arg) е еквивалентно на $arg instanceof Foo или is_a($arg, 'Foo').
Класът ReflectionObject позволява извършването на обратно инженерство върху обекти.
<?php
class ReflectionObject extends ReflectionClass
{
final private __clone()
public void __construct(mixed object)
public string __toString()
public static string export(mixed object, bool return)
}
?>
Класът ReflectionMethod позволява извличане на информация за методи.
<?php
class ReflectionMethod extends ReflectionFunctionAbstract implements Reflector
{
public void __construct(mixed class, string name)
public string __toString()
public static string export(mixed class, string name, bool return)
public mixed invoke(stdclass object [, mixed args [, ...]])
public mixed invokeArgs(stdclass object, array args)
public bool isFinal()
public bool isAbstract()
public bool isPublic()
public bool isPrivate()
public bool isProtected()
public bool isStatic()
public bool isConstructor()
public bool isDestructor()
public int getModifiers()
public mixed getClosure() /* От PHP 5.3.0 */
public ReflectionClass getDeclaringClass()
// Наследени от ReflectionFunctionAbstract
final private __clone()
public string getName()
public bool isInternal()
public bool isUserDefined()
public string getFileName()
public int getStartLine()
public int getEndLine()
public string getDocComment()
public array getStaticVariables()
public bool returnsReference()
public ReflectionParameter[] getParameters()
public int getNumberOfParameters()
public int getNumberOfRequiredParameters()
}
?>
За да извършите интроспекция на метод, първо трябва да направите инстанция на ReflectionMethod. След това може да извикате който и да е от горните методи на тази инстанция.
Example #5 Употреба на класа ReflectionMethod
<?php
class Counter
{
private static $c = 0;
/**
* Увеличава брояча
*
* @final
* @static
* @access public
* @return int
*/
final public static function increment()
{
return ++self::$c;
}
}
// Създаване на инстанция на класа ReflectionMethod
$method = new ReflectionMethod('Counter', 'increment');
// Извеждане на основна информация
printf(
"===> %s%s%s%s%s%s%s метод '%s' (който е %s)\n" .
" деклариран в %s\n" .
" на редове от %d до %d\n" .
" притежава модификатори %d[%s]\n",
$method->isInternal() ? 'Вътрешен' : 'Дефиниран от потребителя',
$method->isAbstract() ? ' абстрактен' : '',
$method->isFinal() ? ' финален' : '',
$method->isPublic() ? ' public' : '',
$method->isPrivate() ? ' private' : '',
$method->isProtected() ? ' protected' : '',
$method->isStatic() ? ' статичен' : '',
$method->getName(),
$method->isConstructor() ? 'конструктор' : 'нормален метод',
$method->getFileName(),
$method->getStartLine(),
$method->getEndline(),
$method->getModifiers(),
implode(' ', Reflection::getModifierNames($method->getModifiers()))
);
// Извеждане на документиращ коментар
printf("---> Документация:\n %s\n", var_export($method->getDocComment(), 1));
// Извежда статичните променливи ако съществуват
if ($statics= $method->getStaticVariables()) {
printf("---> Статични променливи: %s\n", var_export($statics, 1));
}
// Извиква метода
printf("---> Резултат от извикването: ");
var_dump($method->invoke(NULL));
?>
Example #6 Getting closure using ReflectionMethod class
<?php
class Example {
static function printer () {
echo "Hello World!\n";
}
}
$class = new ReflectionClass('Example');
$method = $class->getMethod('printer');
$closure = $method->getClosure(); /* От PHP 5.3.0 */
$closure(); // Hello World!
?>
Забележка: Опитът да се извика private, protected или абстрактен метод ще доведе до генериране на изключение от метода invoke().
Забележка: Както се вижда от примера по-горе, при статични методи, трябва да се предава NULL като първи аргумент на invoke(). При нестатични методи, се предава инстанцията на класа.
Класът ReflectionProperty позволява извличане на информация за свойства.
<?php
class ReflectionProperty implements Reflector
{
final private __clone()
public void __construct(mixed class, string name)
public string __toString()
public static string export(mixed class, string name, bool return)
public string getName()
public bool isPublic()
public bool isPrivate()
public bool isProtected()
public bool isStatic()
public bool isDefault()
public void setAccessible() /* От PHP 5.3.0 */
public int getModifiers()
public mixed getValue(stdclass object)
public void setValue(stdclass object, mixed value)
public ReflectionClass getDeclaringClass()
public string getDocComment()
}
?>
Забележка: getDocComment() беше добавен в PHP 5.1.0. setAccessible() беше добавен в PHP 5.3.0.
За да извършите интроспекция на свойство, първо трябва да направите инстанция на ReflectionProperty. След това може да извикате който и да е от горните методи на тази инстанция.
Example #7 Употреба на класа ReflectionProperty
<?php
class String
{
public $length = 5;
}
// Създаване на инстанция на класа ReflectionProperty
$prop = new ReflectionProperty('String', 'length');
// Извеждане на основна информация
printf(
"===> %s%s%s%s свойството '%s' (което беше %s)\n" .
" притежава модификатори %s\n",
$prop->isPublic() ? ' public' : '',
$prop->isPrivate() ? ' private' : '',
$prop->isProtected() ? ' protected' : '',
$prop->isStatic() ? ' статичен' : '',
$prop->getName(),
$prop->isDefault() ? 'декларирано по време на компилация' : 'създадено по време на стартиране',
var_export(Reflection::getModifierNames($prop->getModifiers()), 1)
);
// Създаване на инстанция на String
$obj= new String();
// Връщане на текущата стойност
printf("---> Стойността е: ");
var_dump($prop->getValue($obj));
// Променяне на стойността
$prop->setValue($obj, 10);
printf("---> Установяване а стойността в 10, новата стойност е: ");
var_dump($prop->getValue($obj));
// Dump на обекта
var_dump($obj);
?>
Example #8 Връщане на стойност от private и protected свойство посредством класа ReflectionProperty
<?php
class Foo {
public $x = 1;
protected $y = 2;
private $z = 3;
}
$obj = new Foo;
$prop = new ReflectionProperty('Foo', 'y');
$prop->setAccessible(true); /* От PHP 5.3.0 */
var_dump($prop->getValue($obj)); // int(2)
$prop = new ReflectionProperty('Foo', 'z');
$prop->setAccessible(true); /* От PHP 5.3.0 */
var_dump($prop->getValue($obj)); // int(2)
?>
Забележка: Опитът да се вземе или установи стойнстта на private или protected свойсво на клас ще предизвика генериране на изключение.
Класът ReflectionExtension позволява извличане на информация за разширения. Можете да извлечете всички заредени разширения по време на изпълнение чрез get_loaded_extensions().
<?php
class ReflectionExtension implements Reflector {
final private __clone()
public void __construct(string name)
public string __toString()
public static string export(string name, bool return)
public string getName()
public string getVersion()
public ReflectionFunction[] getFunctions()
public array getConstants()
public array getINIEntries()
public ReflectionClass[] getClasses()
public array getClassNames()
public string info()
}
?>
За да извършите интроспекция на разширение, първо трябва да направите инстанция на ReflectionExtension. След това може да извикате който и да е от горните методи на тази инстанция.
Example #9 Употреба на класа ReflectionExtension
<?php
// Създаване на инстанция на класа ReflectionExtension
$ext = new ReflectionExtension('standard');
// Извеждане на основна информация
printf(
"Наименование : %s\n" .
"Версия : %s\n" .
"Функции : [%d] %s\n" .
"Константи : [%d] %s\n" .
"INI стойности : [%d] %s\n" .
"Класове : [%d] %s\n",
$ext->getName(),
$ext->getVersion() ? $ext->getVersion() : 'NO_VERSION',
sizeof($ext->getFunctions()),
var_export($ext->getFunctions(), 1),
sizeof($ext->getConstants()),
var_export($ext->getConstants(), 1),
sizeof($ext->getINIEntries()),
var_export($ext->getINIEntries(), 1),
sizeof($ext->getClassNames()),
var_export($ext->getClassNames(), 1)
);
?>
В случай че искате да създадете специализирани версии на вградените класове (примерно за да оцветите кода HTML при експортиране посредством лесни за достъп свойства вместо чрез методи или чрез прилагането на методи от тип utility), можете спокойно да ги наследите.
Example #10 Наследяване на вградени класове
<?php
/**
* Клас My_Reflection_Method
*/
class My_Reflection_Method extends ReflectionMethod
{
public $visibility = array();
public function __construct($o, $m)
{
parent::__construct($o, $m);
$this->visibility= Reflection::getModifierNames($this->getModifiers());
}
}
/**
* Демонстрационен клас #1
*
*/
class T {
protected function x() {}
}
/**
* Демонстрационен клас #2
*
*/
class U extends T {
function x() {}
}
// Извеждане на информацията
var_dump(new My_Reflection_Method('U', 'x'));
?>
Забележка: Внимание: Ако предефинирате конструктор, не забравяйте да извикате конструктора на родителския клас преди всякакъв друг код. В противен случай резултатът ще е следния: Fatal error: Internal error: Failed to retrieve the reflection object
В PHP 5 е въведено подсказване на тип. Функциите вече могат да принуждават параметрите да бъдат обекти (като се укаже името на класа преди наименованието на параметъра в дефиницията) или масиви (от PHP 5.1). Все пак, ако като стойност по подразбиране на параметъра се използва NULL, ще може да се използва като аргумент при всяко последващо извикване.
Example #1 Примери за подсказване на тип
<?php
// Примерен клас
class MyClass
{
/**
* Тестова функция
*
* Първият параметър трябва да бъде обект от тип OtherClass
*/
public function test(OtherClass $otherclass) {
echo $otherclass->var;
}
/**
* Друга тестова функция
*
* Първият параметър трябва да бъде масив
*/
public function test_array(array $input_array) {
print_r($input_array);
}
}
// Друг примерен клас
class OtherClass {
public $var = 'Hello World';
}
?>
Ако параметърът не удовлетворява подсказването за типа, изпълнението ще прекъсне с Фатална грешка, която може да бъде прихваната.
<?php
// Създаване на инстанция за всеки клас
$myclass = new MyClass;
$otherclass = new OtherClass;
// Fatal Error: Argument 1 must be an object of class OtherClass
$myclass->test('hello');
// Fatal Error: Argument 1 must be an instance of OtherClass
$foo = new stdClass;
$myclass->test($foo);
// Fatal Error: Argument 1 must not be null
$myclass->test(null);
// Работи: Извежда Hello World
$myclass->test($otherclass);
// Fatal Error: Argument 1 must be an array
$myclass->test_array('a string');
// Работи: Извежда масива
$myclass->test_array(array('a', 'b', 'c'));
?>
Подсказването на тип също така работи и с функции:
<?php
// Примерен клас
class MyClass {
public $var = 'Hello World';
}
/**
* Тестова функция
*
* Първият параметър трябва да бъде обект от тип MyClass
*/
function MyFunction (MyClass $foo) {
echo $foo->var;
}
// Работи
$myclass = new MyClass;
MyFunction($myclass);
?>
Подсказване на типове с употреба на стойност NULL:
<?php
/* Присвояване на стойност NULL */
function test(stdClass $obj = NULL) {
}
test(NULL);
test(new stdClass);
?>
Подсказването на типове може да бъде само за обекти и масиви (от PHP 5.1). Традиционното подсказване на тип с променливи от тип int и string не се поддържа.
От PHP 5.3.0 в PHP е реализирано късно статично свързване, което може да се използва за обръщане към извикания клас в контекста на статичното наследяване.
Тази възможност неслучайно е наречена "късно статично свързване". "Късно свързване" идва от факта, че static:: вече няма да сочи към класа, в който е дефиниран методът, а ще бъде изчисляван на базата на информацията по време на изпълнение на скрипта. Също така е наречено "статично свързване", тъй като може да се използва (без да е ограничено само в тази употреба) за извикване на статични методи.
Статичните референции към текущия клас като self:: и __CLASS__ се извикват на базата на това на кой клас принадлежи методът, т.е. къде е дефиниран:
Example #1 Употреба на self::
<?php
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
self::who();
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();
?>
Примерът по-горе ще изведе:
A
С късното статично свързване се прави опит да се премахне това ограничение чрез въвеждането на нова ключова дума, която да сочи към класа, който първоначално е бил извикан по време на изпълнение. На практика това е ключовата дума, която би позволила да се извика B от test() в предишния пример. Веше решено вместо да се въвежда нова ключова дума, да се използва static, която така или иначе вече е запазена.
Example #2 Проста употреба на static::
<?php
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
static::who(); // Here comes Late Static Bindings
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();
?>
Примерът по-горе ще изведе:
B
Забележка: static:: не работи еквивалентно на $this за статични методи! $this-> следва правилата на наследяването, за разлика от static::. Тази разлика е обяснена по-подробно малко по-късно.
Example #3 Употреба на static:: в нестатичен контекст
<?php
class TestChild extends TestParent {
public function __construct() {
static::who();
}
public function test() {
$o = new TestParent();
}
public static function who() {
echo __CLASS__."\n";
}
}
class TestParent {
public function __construct() {
static::who();
}
public static function who() {
echo __CLASS__."\n";
}
}
$o = new TestChild;
$o->test();
?>
Примерът по-горе ще изведе:
TestChild TestParent
Забележка: Решението кой метод да се изпълни при късното статично свързване ще бъде взето при напълно определено статично извикване, без връщане. От друга страна, статичните извиквани посредством ключовите думи като parent:: и self:: ще препратят извикващата информация.
Example #4 Препращащи и непрепращащи извиквания
<?php
class A {
public static function foo() {
static::who();
}
public static function who() {
echo __CLASS__."\n";
}
}
class B extends A {
public static function test() {
A::foo();
parent::foo();
self::foo();
}
public static function who() {
echo __CLASS__."\n";
}
}
class C extends B {
public static function who() {
echo __CLASS__."\n";
}
}
C::test();
?>Примерът по-горе ще изведе:
A C C
Съществуват редица различни начини да се извика метод в PHP, като например - обратни извиквания и вълшебни методи. Тъй като, при късното статично свързване, решението кой метод да се изпълни се базира на информацията по време на изпълнение, това може да доведе до неочаквани резултати при т.н. крайни случаи.
Example #5 Късно статично свързване във вълшебни методи
<?php
class A {
protected static function who() {
echo __CLASS__."\n";
}
public function __get($var) {
return static::who();
}
}
class B extends A {
protected static function who() {
echo __CLASS__."\n";
}
}
$b = new B;
$b->foo;
?>
Примерът по-горе ще изведе:
B
One of the key-points of PHP5 OOP that is often mentioned is that "objects are passed by references by default". This is not completely true. This section rectifies that general thought using some examples.
A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.
Example #1 References and Objects
<?php
class A {
public $foo = 1;
}
$a = new A;
$b = $a; // $a and $b are copies of the same identifier
// ($a) = ($b) = <id>
$b->foo = 2;
echo $a->foo."\n";
$c = new A;
$d = &$c; // $c and $d are references
// ($c,$d) = <id>
$d->foo = 2;
echo $c->foo."\n";
$e = new A;
function foo($obj) {
// ($obj) = ($e) = <id>
$obj->foo = 2;
}
foo($e);
echo $e->foo."\n";
?>
Примерът по-горе ще изведе:
2 2 2
Пространствата от имена в PHP са проектирани с цел решаване на проблеми, свързани с областта на действие в големи библиотеки на PHP. В PHP всички дефиниции на класове са глобални. Затова, когато авторът на библиотеката създава множество помощни класове или такива за директно използване в дадена библиотека, той трябва да е наясно, че може да съществуват и други библиотеки с подобна функционалност и по тази причина да избере уникални наименования за своите класове, за да могат тези библиотеки да се използват съвместно. Обикновено този проблем се решава с поставяне на представка - уникален низ, като например класовете, свързани с бази от данни, могат да имат представка My_Library_DB и т.н. С развитието на библиотеката се добавят още представки, което води до появата на твърде дълги имена на класове.
Пространствата от имена позволяват на разработчика да управлява именуването в съответния обхват, без да използва дълги имена всеки път, когато има обръщение към даден клас и решават проблема с поделеното глобално пространство, без кодът да става нечетим.
Пространствата от имена са достъпни от PHP 5.3.0. Този раздел е експериментален и подлежи на промени.
Пространство от имена се декларира посредством ключовата дума namespace, която трябва да бъде в самото начало на файла. Пример:
Example #1 Дефиниране на пространство от имена
<?php
namespace MyProject::DB;
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
?>
Едно и също пространство от имена може да бъде използвано в множество файлове.
Дадено пространство от имена може да съдържа клас, дефиниции на константи и функции, но не и отделен код.
Дефиницията на пространство от имена прави следното:
Непълното име на клас (което не съдържа ::) се определя по време на изпълнение по следния начин:
За непълното име на функция (което не съдържа ::) се извършва търсене първо в текущото пространство от имена, а след това и в глобалното.
За непълното име на константа се извършва търсене първо в текущото пространство от имена, а след това и в глобалното.
Вж. също пълните правила за определяне на имена.
Към всеки клас или функция, намиращи се в пространство от имена, може да се извърши обръщение посредством пълно име - например MyProject::DB::Connection или MyProject::DB::connect, по всяко време.
Example #1 Употреба на име с пространство от имена
<?php
require 'MyProject/Db/Connection.php';
$x = new MyProject::DB::Connection;
MyProject::DB::connect();
?>
Пространствата от имена могат да бъдат внасяни в глобален контекст или в контекста на дадено пространство от имена посредством оператора use. Синтаксисът за този оператор е:
<?php
/* ... */
use Some::Name as Othername;
// Опростената употреба:
use Foo::Bar;
// което е същото като :
use Foo::Bar as Bar;
?>
Внесеното име работи по следния начин: всеки път, когато компилаторът срещне локалното име Othername (като отделно име или като представка на по-дългото име, разделено от ::), той го замества с внесеното име Some::Name.
use може да се използва само в глобалната област на действие, но не и във функция или клас. Внесените имена имат област на действие от точката на внасяне до края на текущия файл. Препоръчително е внасянията да се поставят в началото на файла, за да се избегнат обърквания.
Example #2 Внасяне и осъществяване на достъп до пространство от имена
<?php
require 'MyProject/Db/Connection.php';
use MyProject::DB;
use MyProject::DB::Connection as DbConnection;
$x = new MyProject::DB::Connection();
$y = new DB::connection();
$z = new DbConnection();
DB::connect();
?>
Забележка: Операцията по внасяне се изпълнява само по време на компилация, всички локални имена се преобразуват до пълните им еквиваленти от компилатора. Забележете, че имената в низове няма да бъдат преобразувани, така че обратните извиквания не могат да разчитат на тези правила за вмъкване.
Ако нямат дефиниция на пространство от имена, дефинициите на всички класове и функции се разполагат в глобалното пространство - както беше в PHP преди да се добави поддръжката на пространства от имена. Използването на представка :: пред името указва, че се използва име от глобалното пространство, дори и в контекста на пространството от имена.
Example #1 Употреба на указването на имена от глобалното пространство
<?php
namespace A::B::C;
/* Това е функция A::B::C::fopen */
function fopen() {
/* ... */
$f = ::fopen(...); // извикване на глобалния fopen
return $f;
}
?>
Константата, създадена по време на компилация - __NAMESPACE__, указва името на текущото пространство от имена. Извън контекста на пространство от имена константата има стойност празен низ. Константата е полезна, когато трябва да се състави пълното име на локални имена.
Example #1 Употреба на __NAMESPACE__
<?php
namespace A::B::C;
function foo() {
// върши някакви неща
}
set_error_handler(__NAMESPACE__ . "::foo");
?>
Имената се определят съгласно следните правила за определяне:
C::D::e()
се преобразува до A::B::C::D::e().
new C() ще се преобразува до new A::B::C().
new C():
new ::C().
new A::B::C() сочи към клас C
от пространството от имена A::B.
Example #1 Примери за определянето на имена
<?php
namespace A;
// извиквания на функции
foo(); // първо се прави опит за извикване на "foo", дефинирана в пространството от имена "A"
// след това извиква вътрешната функция "foo"
::foo(); // извиква функция "foo", дефинирана в глобалната област на действие
// референции към класове
new B(); // първо се прави опит за създаване на обект от клас "B", дефиниран в пространството от имена "A"
// след което създава обект от вътрешния клас "B"
new ::B(); // създава обект от клас "B", дефиниран в глобалната област на действие
// статични методи/функции на пространството от имена от друго пространство от имена
B::foo(); // първо се прави опит за извикване на функция "foo" от пространството от имена "A::B"
// след това извиква метод "foo" от вътрешния клас "B"
::B::foo(); // първо се прави опит за извикване на функция "foo" от пространството от имена "B"
// след това извиква метод "foo" от клас "B" на глобалната област на действие
// статични методи/функции на пространството от имена от текущото пространство от имена
A::foo(); // първо се прави опит за извикване на функция "foo" от пространството от имена "A::A"
// след това се прави опит за извикване на метод "foo" от клас "A" от пространството от имена "A"
// след това се прави опит за извикване на функция "foo" от пространството от имена "A"
// след това извиква метод "foo" от вътрешния клас "A"
::A::foo(); // първо се прави опит за извикване на функция "foo" от пространството от имена "A"
// след това извиква метод "foo" от клас "A" на глобалната област на действие
?>
Потребителски дефиниран клас за изключения може да бъде дефиниран, като се наследи базовия клас за изключения. Членовете и свойствата по-долу показват какво е достъпно в класа наследник, наследяващ базовия клас за изключения.
Example #1 Базов клас за изключения
<?php
class Exception
{
protected $message = 'Неизвестно изключение'; // съобщение на изключението
protected $code = 0; // потребителски дефиниран код на изключението
protected $file; // име на файл с кода на изключението
protected $line; // ред в кода на изключението
function __construct($message = null, $code = 0);
final function getMessage(); // съобщение на изключението
final function getCode(); // код на изключението
final function getFile(); // име на файл с кода
final function getLine(); // ред в кода
final function getTrace(); // масив с backtrace() - обратно проследяване
final function getTraceAsString(); // форматиран низ на проследяването
/* Предифинируем */
function __toString(); // форматиран низ за показване
}
?>
Ако даден клас наследява базовия клас за изключения и повторно дефинира конструктора, е силно препоръчително да се извика също и parent::__construct(), за да се осигури правилното присвояване на всички налични данни. Методът __toString() може да бъде дефиниран повторно, за да се предостави поръчков изход, когато обектът е представен като низ.
Example #2 Наследяване на класа за изключения
<?php
/**
* Поръчково дефиниране на клас за изключения
*/
class MyException extends Exception
{
// Повторно дефиниране на изключението, така че низът да бъде задължителен
public function __construct($message, $code = 0) {
// някакъв код
// осигуряване на правилното присвояване на всичко
parent::__construct($message, $code);
}
// поръчково низово представяне на обекта
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
public function customFunction() {
echo "Поръчкова функция за този тип изключение\n";
}
}
/**
* Създаване на клас за проверка на изключението
*/
class TestException
{
public $var;
const THROW_NONE = 0;
const THROW_CUSTOM = 1;
const THROW_DEFAULT = 2;
function __construct($avalue = self::THROW_NONE) {
switch ($avalue) {
case self::THROW_CUSTOM:
// хвърляне на поръчково изключение
throw new MyException('1 е невалиден параметър', 5);
break;
case self::THROW_DEFAULT:
// изключение по подразбиране.
throw new Exception('2 не се разрешава като параметър', 6);
break;
default:
// Няма изключение, обектът ше бъде създаден.
$this->var = $avalue;
break;
}
}
}
// Пример 1
try {
$o = new TestException(TestException::THROW_CUSTOM);
} catch (MyException $e) { // Ще бъде хванато
echo "Хванато е моето изключение\n", $e;
$e->customFunction();
} catch (Exception $e) { // Skipped
echo "Хванато е изключението по подразбиране\n", $e;
}
// Продължаване на изпълнението
var_dump($o);
echo "\n\n";
// Пример 2
try {
$o = new TestException(TestException::THROW_DEFAULT);
} catch (MyException $e) { // Не съвпада с този тип
echo "Хванато е моето изключение\n", $e;
$e->customFunction();
} catch (Exception $e) { // Ще бъде хванато
echo "Хванато е изключението по подразбиране\n", $e;
}
// Продължаване на изпълнението
var_dump($o);
echo "\n\n";
// Пример 3
try {
$o = new TestException(TestException::THROW_CUSTOM);
} catch (Exception $e) { // Ще бъде хванато
echo "Хванато е изключението по подразбиране\n", $e;
}
// Продължаване на изпълнението
var_dump($o);
echo "\n\n";
// Пример 4
try {
$o = new TestException();
} catch (Exception $e) { // Пропуска се, няма изключение
echo "Хванато е изключението по подразбиране\n", $e;
}
// Продължаване на изпълнението
var_dump($o);
echo "\n\n";
?>
PHP 5 има модел за изключения подобен на този в други езици за програмиране. Изключенията могат да бъдат хвърляни (throw) и хващани (catch) в PHP. Кодът може да бъде обграден от блок try (изпробвам), за да се улесни прихващането на потенциални изключения. Всеки try трябва да има поне един съответстващ блок catch. Многобройни блокове catch могат да бъдат използвани за прихващане на различни класове от изключения. Нормалното изпълнение (когато няма хвърлено изключение в блока try или когато catch, съвпадащ с класа на хвърленото изключение, не е наличен) ще продължи след последния прихващащ блок, дефиниран в поредицата. Изключенията могат да бъдат хвърляни (throw) (или повторно хвърляни) в рамките на даден блок catch.
Когато някое изключение бива хвърлено, кодът след инструкцията няма да бъде изпълнен и PHP ще опита да намери първия съвпадащ хващащ блок (catch). Ако изключението не бъде прихванато, в PHP ще бъде изведена фатална грешка (Fatal Error) със съобщение за "Неприхванато изключение (Uncaught Exception) ...", освен ако не е бил дефиниран обработчик посредством set_exception_handler().
Забележка: Вътрешните функции на PHP използват предимно докладване на грешки, само новите обектно-ориентирани разширения ползват изключения. Все пак, грешките лесно могат да бъдат преобразувани в изключения с помощта на ErrorException.
Стандартизираната библиотека на PHP (SPL) предоставя полезен набор от вградени изключения.
Example #1 Хвърляне на изключения
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Деление на нула.');
}
else return 1/$x;
}
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Прихванато изключение: ', $e->getMessage(), "\n";
}
// Изпълнението продължава
echo 'Здравей свят';
?>
Примерът по-горе ще изведе:
0.2 Прихванато изключение: Деление на нула. Здравей свят
Example #2 Вложени изключения
<?php
class MyException extends Exception { }
class Test {
public function testing() {
try {
try {
throw new MyException('foo!');
} catch (MyException $e) {
/* хвърли го повторно */
throw $e;
}
} catch (Exception $e) {
var_dump($e->getMessage());
}
}
}
$foo = new Test;
$foo->testing();
?>
Примерът по-горе ще изведе:
string(4) "foo!"
Референциите в PHP са начин за достъп до едно и също променливо съдържание посредством различни имена. Те не са като указателите в C, а представляват символни псевдоними. Трябва да се има предвид, че в PHP имената на променливите и тяхното съдържание са различни, така че едно и също съдържание може да има множество различни имена. Най-близката аналогия е с файловете и техните имена в UNIX - имената на променливите са елементите на дадена директория, а съдържанието - самите файлове. Референциите могат да се сравнят със символни връзки във файловите системи на UNIX.
Референциите в PHP позволяват две променливи да сочат към едно и също съдържание. Така че когато правите:
<?php
$a =& $b
?>
това означава, че $a и $b сочат към едно и също съдържание.
Забележка: В случая $a и $b са напълно еднакви - нито $a сочи към $b, нито обратното - просто $a и $b сочат към едно и също място.
Забележка: Ако бъдат копирани масиви с референции, техните стойности не се дереференсират (не им се премахва референцията). Това се отнася също и за масиви, предадени по стойност във функции.
Забележка: Ако присвоите, предадете или върнете недефинирана променлива по референция, тя ще бъде създадена.
Example #1 Използване на референции с недефинирани променливи
<?php
function foo(&$var) { }
foo($a); // $a се "създава" и установява в null
$b = array();
foo($b['b']);
var_dump(array_key_exists('b', $b)); // bool(true)
$c = new StdClass;
foo($c->d);
var_dump(property_exists($c, 'd')); // bool(true)
?>
Същият синтаксис може да бъде използван и с функции, които връщат референции, както и с оператора new (след PHP 4.0.4):
<?php
$bar =& new fooclass();
$foo =& find_var ($bar);
?>
След PHP 5 new автоматично връща референция, така че използването на =& в този контекст е непрепоръчително и предизвиква съобщение за грешка от ниво E_STRICT.
Забележка: Неизползването на оператора & създава копие на обекта. Ако използвате $this в клас, той ще оперира върху текущата инстанция на класа. Присвояването без & ще копира инстанцията (т.е. класа) и $this ще оперира върху копието, което не винаги е желано. Обикновено ще искате да работите с една единствена инстанция с цел бързина и пестене на памет.
Въпреки че можете да използвате оператора @, за да подтиснете каквито и да е грешки в конструктора с @new, това няма да работи, в случай, че се използва израза &new. Това е ограничение в Zend Engine и поради това ще доведе до грешка на синтактичния анализатор (parser error).
Ако присвоите референция на променлива, декларирана като global (глобална) в тялото на функцията, референцията ще бъде видима единствено вътре във функцията. Можете да избегнете това като използвате масива $GLOBALS.
Example #2 Рефериране на глобални променливи в тялото на функции
<?php
$var1 = "Примерна променлива";
$var2 = "";
function global_references($use_globals)
{
global $var1, $var2;
if (!$use_globals) {
$var2 =& $var1; // видима единствено в тялото на функцията
} else {
$GLOBALS["var2"] =& $var1; // видима също и в глобален контекст
}
}
global_references(false);
echo "var2 е установена в '$var2'\n"; // var2 е установена в ''
global_references(true);
echo "var2 е установена в '$var2'\n"; // var2 е установена в 'Примерна променлива'
?>
Мислете за global $var; като съкращение на $var =& $GLOBALS['var'];. Така присвояването на друга референция във $var променя единствено референцията на локалната променлива.
Забележка: Ако присвоявате стойност на променлива чрез референции в конструкцията foreach, референциите се променят също.
Example #3 Референции и конструкцията foreach
<?php
$ref = 0;
$row =& $ref;
foreach (array(1, 2, 3) as $row) {
// прави нещо
}
echo $ref; // 3 - последния елемент от итерирания масив
?>
Второто нещо, което правят референциите, е да предават променливи по референция. Това става чрез насочването на локалната променлива във функцията и променливата в извикващия обхват към едно и също съдържание. Пример:
<?php
function foo (&$var)
{
$var++;
}
$a=5;
foo ($a);
?>
ще увеличи $a на 6. Това се случва, защото във функцията foo променливата $var сочи към същото съдържание като $a. За повече информация вижте раздел предаване по референция.
Третото нещо, което референцията прави е връщане по референция.
Както беше споменато, референциите не са указатели. Това означава, че тази конструкция няма да направи това, което очаквате:
<?php
function foo (&$var)
{
$var =& $GLOBALS["baz"];
}
foo($bar);
?>
Това, което се случва е, че $var във foo ще бъде обвързана с $bar в извикването, но след това ще бъде повторно обвързана с $GLOBALS["baz"]. Няма начин $bar в извикващия обхват да се свърже с нещо друго посредством механизма на референциите, тъй като $bar не е налична във функцията foo (тя е представена от $var, но $var притежава единствено съдържанието, но не и връзката име-стойност в извикващата символна таблица). Можете да използвате връщане по референция, за да реферирате избрани във функцията поменливи.
Можете да предавате променлива към функция по референция, така че функцията да може да я променя. Синтаксисът е както следва:
<?php
function foo(&$var)
{
$var++;
}
$a=5;
foo ($a);
// на това място $a е 6
?>
Забележете, че няма знак за референция в извикването на функцията, а единствено в дефиницията й. Дефиницията на функцията сама по себе си е достатъчна за правилното предаване на аргумент по референция. В по-скорошни версии на PHP ще получите предупреждение, споменаващо, че "Предаването по референция по време на извикване" ("Call-time pass-by-reference") е непрепоръчително, когато използвате & във foo(&$a);.
Следните неща могат да бъдат предавани по референция:
Референции, върнати от функции:
<?php
function &bar()
{
$a = 5;
return $a;
}
foo(bar());
?>
Вижте повече относно връщането по референция.
По референция не бива да бъдат предавани никакви други изрази, тъй като резултатът е недефиниран. Следният пример с предаване по референция е невалиден:
<?php
function bar() // Отбележете липсващия &
{
$a = 5;
return $a;
}
foo(bar()); // Предизвиква фатална грешка след PHP 5.0.5
foo($a = 5); // Израз, а не променлива
foo(5); // Предизвиква фатална грешка
?>
Тези изисквания са за PHP 4.0.4 и по-късни.
Връщането по референция е полезно, когато искате да използвате функция, за да намерите към коя променлива да се привърже референцията. Не използвайте връщането по референция, за да ускорите изпълнението. PHP ще оптимизира такива места сам. Връщайте референции единствено в случай, че имате добра техническа причина да го правите! За да върнете референция, използвайте този синтаксис:
<?php
class foo {
public $value = 42;
public function &getValue() {
return $this->value;
}
}
$obj = new foo;
$myValue = &$obj->getValue(); // $myValue е референция към $obj->value, която е 42.
$obj->value = 2;
echo $myValue; // отпечатва новата стойност на $obj->value, т.е. 2.
?>
В този пример ще бъде присвоено свойството на обекта, върнат от функцията getValue, а не копието, както щеше да бъде без използване на референтен синтаксис.
Забележка: За разлика от предаването на параметри, тук трябва да използвате & и на двете места - да укажете, че искате да върнете по референция, а не копие, и да укажете, че трябва да бъде извършено референтно свързване, вместо нормално присвояване на $myValue.
Забележка: Ако се опитате да върнете референция от функция със синтаксиса: return ($this->value); това няма да проработи, защото по този начин се опитвате да върнете по референция израз, а не променлива. По референция можете да връщате единствено променливи - нищо друго. След PHP 4.4.0, в разклонението PHP4, и PHP 5.1.0, в разклонението PHP5, се извежда грешка от ниво E_NOTICE, в случай че кодът се опита да върне динамичен израз или резултат от оператора new.
Когато унищожите референция, вие просто прекъсвате свързването между променливо име и променливо съдържание. Това не означава, че променливото съдържание ще бъде унищожено. Например:
<?php
$a = 1;
$b =& $a;
unset ($a);
?>
няма да унищожи $b, само $a.
Отново може да се направи аналогия с извикването на unlink в Unix.
Много синтактични конструкции в PHP са осъществени посредством референтни механизми, така че всичко споменато дотук относно референтното свързване се отнася също и за тези конструкции. Някои конструкции като предаване и връщане по референция са споменати по-горе. Други конструкции, които използват референции са:
Когато декларирате променлива като global $var, вие всъщност създавате референция към глобална променлива. Това е еквивалентно на:
<?php
$var =& $GLOBALS["var"];
?>
Това означава, че изтриването на $var няма да изтрие глобалната променлива.
В метод на обект, $this винаги е референция към обекта.
Свръхглобални — Свръхглобалните са вградени променливи, които са налични винаги и във всеки обхват
Има няколко предварително-дефинирани променливи в PHP, които са "свръхглобални", което означава, че те са налични във всеки обхват навсякъде в скрипта. Няма нужда да се прави global $variable;, за да се достъпват в рамките на функции или методи.
Тези свръхглобални променливи са:
| Версия | Описание |
|---|---|
| 4.1.0 | Свръхглобалните са въведени в PHP. |
Забележка: Променлива наличност
По подразбиране всички свръхглобални са налични, но има директиви, които въздействат на тази наличност. За повече информация, вижте документацията за variables_order.
Забележка: Работа с register_globals
Ако непрепоръчителната директива register_globals е включена (установена на on), тогава променливите вътре също ще бъдат налични в глобалния обхват на скрипта. Например $_POST['foo'] ще съществува също и като $foo.
За информация по въпроса, вижте раздела от FAQ, озаглавен "Как ми въздейства register_globals?"
Забележка: Променливи променливи
Свръхглобалните не могат да бъдат използвани като променливи променливи в рамките на функции или методи на клас.
$GLOBALS — Съдържа референция към всички променливи, налични в глобалния обхват
Асоциативен масив, съдържащ референции към всички променливи, които текущо са дефинирани в глобалната област на действие на скрипта. Имената на променливите са ключове в масива.
Example #1 Пример с $GLOBALS
<?php
function test() {
$foo = "локална променлива";
echo '$foo в глобален обхват: ' . $GLOBALS["foo"] . "\n";
echo '$foo в текущия обхват: ' . $foo . "\n";
}
$foo = "Примерно съдържание";
test();
?>
Примерът по-горе ще изведе нещо подобно на:
$foo в глобален обхват: Примерно съдържание $foo в текущия обхват: локална променлива
Забележка: Това е 'свръхглобална' или автоматично глобална променлива. Това просто означава, че тя е налична във всички обхвати навсякъде из скрипта. Не е нобходимо да правите global $variable;, за да я достъпвате от тялото на функции и методи.
Забележка: Наличност на променливата
За разлика от останалите свръхглобални, $GLOBALS винаги е била налична в PHP.
$_SERVER -- $HTTP_SERVER_VARS [непрепоръчителна] — Информация от обкръжението на сървъра и изпълнението
$_SERVER е масив, съдържащ информация като заглавки, пътеки за достъп и местоположения на скриптове. Елементите в този масив се създават от уеб сървъра. Няма гаранция, че всеки уеб сървър ще предостави който и да е от тях; сървърите може да пропуснат някои, или да предоставят други, които не са описани тук. Имайки предвид това, все пак голям набор от тези променливи са описани в » спецификация CGI 1.1, така че би трябвало да очаквате тяхното наличие.
$HTTP_SERVER_VARS съдържа същата начална информация, но не е свръхглобална. (Забележете, че $HTTP_SERVER_VARS и $_SERVER са две различни променливи и PHP ги третира като такива)
Ще можете (или пък няма да можете) да намерите някой от следните елементи на $_SERVER. Забележете, че малка част, ако изобщо има някой от тези, ще бъдат налични (или ще имат изобщо смисъл) ако пускате PHP от командния ред.
Забележка: Скриптът се прекратява след изпращане на заглавките (с други думи - след извеждане на нещо без буфериране на изхода), ако заявковият метод е бил HEAD.
Забележка: Отбележете, че когато използвате ISAPI с IIS, стойността ще бъде off, ако заявката не е била направена през протокола HTTPS.
Забележка: Вашият уеб сървър трябва да бъде допълнително конфигуриран, за да създаде тази променлива. Например в Apache ще ви трябва HostnameLookups On в httpd.conf, за да я има. Вж. също gethostbyaddr().
Абсолютния файлов път на текущо-изпълнявания скрипт.
Забележка: Ако скриптът се изпълнява посредством CLI, като относителен път, като file.php или ../file.php, $_SERVER['SCRIPT_FILENAME'] ще съдържа относителния път, зададен от потребителя.
Забележка: От PHP 4.3.2 PATH_TRANSLATED вече не се попълва безусловно при Apache 2 SAPI, за разлика от ситуацията при Apache 1, където се попълва със стойността на сървърната променлива SCRIPT_FILENAME. Тази промяна бе направена, с цел придържане към спецификацията CGI, според която PATH_TRANSLATED трябва да съществува единствено ако PATH_INFO е дефинирана. Потребителите на Apache 2 могат да използват AcceptPathInfo = On в httpd.conf, за да дефинират PATH_INFO.
| Версия | Описание |
|---|---|
| 4.1.0 | Въвеждане на $_SERVER, за сметка на непрепоръчителната $HTTP_SERVER_VARS. |
Example #1 Пример със $_SERVER
<?php
echo $_SERVER['SERVER_NAME'];
?>
Примерът по-горе ще изведе нещо подобно на:
www.example.com
Забележка: Това е 'свръхглобална' или автоматично глобална променлива. Това просто означава, че тя е налична във всички обхвати навсякъде из скрипта. Не е нобходимо да правите global $variable;, за да я достъпвате от тялото на функции и методи.
$_GET -- $HTTP_GET_VARS [непрепоръчителна] — Променливи от тип HTTP GET
Асоциативен масив с променливи, предоставени на текущия скрипт посредством метода GET на HTTP.
$HTTP_GET_VARS съдържа същата начална информация, но не е свръхглобална. (Забележете, че $HTTP_GET_VARS и $_GET са две различни променливи и PHP ги третира като такива)
| Версия | Описание |
|---|---|
| 4.1.0 | Въведена е $_GET, за сметка на непрепоръчителната $HTTP_GET_VARS. |
Example #1 Пример с $_GET
<?php
echo 'Здравей ' . htmlspecialchars($_GET["name"]) . '!';
?>
Приемаме, че потребителят е въвел http://example.com/?name=Ники
Примерът по-горе ще изведе нещо подобно на:
Здравей Ники!
Забележка: Това е 'свръхглобална' или автоматично глобална променлива. Това просто означава, че тя е налична във всички обхвати навсякъде из скрипта. Не е нобходимо да правите global $variable;, за да я достъпвате от тялото на функции и методи.
$_POST -- $HTTP_POST_VARS [непрепоръчителна] — Променливи от тип HTTP POST
Асоциативен масив с променливи, предоставени на текущия скрипт посредством метода POST на HTTP.
$HTTP_POST_VARS съдържа същата начална информация, но не е свръхглобална. (Забележете, че $HTTP_POST_VARS и $_POST са две различни променливи и PHP ги третира като такива)
| Версия | Описание |
|---|---|
| 4.1.0 | Въведена е $_POST, за сметка на непрепоръчителната $HTTP_POST_VARS. |
Example #1 Пример с $_POST
<?php
echo 'Здравей ' . htmlspecialchars($_POST["name"]) . '!';
?>
Приемаме, че потребителят е предоставил name=Ники
Примерът по-горе ще изведе нещо подобно на:
Здравей Ники!
Забележка: Това е 'свръхглобална' или автоматично глобална променлива. Това просто означава, че тя е налична във всички обхвати навсякъде из скрипта. Не е нобходимо да правите global $variable;, за да я достъпвате от тялото на функции и методи.
$_FILES -- $HTTP_POST_FILES [непрепоръчителна] — Променливи при качване на файл с HTTP
Асоциативен масив с нещата, качени към текущия скрипт посредством метода POST на HTTP.
$HTTP_POST_FILES съдържа същата начална информация, но не е свръхглобална. (Забележете, че $HTTP_POST_FILES и $_FILES са две различни променливи и PHP ги третира като такива)
| Версия | Описание |
|---|---|
| 4.1.0 | Въведена е $_FILES, за сметка на непрепоръчителната $HTTP_POST_FILES. |
Забележка: Това е 'свръхглобална' или автоматично глобална променлива. Това просто означава, че тя е налична във всички обхвати навсякъде из скрипта. Не е нобходимо да правите global $variable;, за да я достъпвате от тялото на функции и методи.
$_REQUEST — Променливи от HTTP заявката
| Версия | Описание |
|---|---|
| 5.3.0 | Въведена е request_order. Тази директива повлиява съдържанието на $_REQUEST. |
| 4.3.0 | Информацията за $_FILES е премахната от $_REQUEST. |
| 4.1.0 | Въведена е $_REQUEST. |
Забележка: Това е 'свръхглобална' или автоматично глобална променлива. Това просто означава, че тя е налична във всички обхвати навсякъде из скрипта. Не е нобходимо да правите global $variable;, за да я достъпвате от тялото на функции и методи.
Забележка: При работа на командния ред , argv и argc няма да бъдат включени в масива $_REQUEST. Те са налични в $_SERVER.
Забележка: Променливите в $_REQUEST са предоставени на скрипта посредством входящите механизми GET, POST и COOKIE и следователно биха могли да бъдат променяни от отдалечения потребител, което означава, че на тях не може да се има доверие. Наличието и редът на включване на променливи в този масив се дефинират съгласно конфигурационната директива на PHP variables_order.
$_SESSION -- $HTTP_SESSION_VARS [непрепоръчителна] — Сесийни променливи
Асоциативен масив, съдържащ сесийните променливи, налични в текущия скрипт. Вижте документацията за Сесийни функции за повече информация как се използва.
$HTTP_SESSION_VARS съдържа същата начална информация, но не е свръхглобална. (Забележете, че $HTTP_SESSION_VARS и $_SESSION са две различни променливи и PHP ги третира като такива)
| Версия | Описание |
|---|---|
| 4.1.0 | Въведена е $_SESSION, за сметка на непрепоръчителната $HTTP_SESSION_VARS. |
Забележка: Това е 'свръхглобална' или автоматично глобална променлива. Това просто означава, че тя е налична във всички обхвати навсякъде из скрипта. Не е нобходимо да правите global $variable;, за да я достъпвате от тялото на функции и методи.
$_ENV -- $HTTP_ENV_VARS [непрепоръчителна] — Променливи от обкръжението
Асоциативен масив с променливи, предоставени на текущия скрипт посредством метода на обкръжението.
Тези променливи се внасят в глобалното пространство от имена на PHP от обкръжението, в което работи синтактичният анализатор на PHP. Голяма част се предоставят от обвивката (shell), в която работи PHP, а различните системи имат различни видове обвивки, така че изготвянето на пълен списък не е възможно. Моля, вижте документацията на вашата обвивка за списък с дефинираните променливи от обкръжението.
Други променливи от обкръжението включват променливите от CGI, които идват независимо от това дали PHP работи като сървърен модул или CGI препроцесор.
$HTTP_ENV_VARS съдържа същата начална информация, но не е свръхглобална. (Забележете, че $HTTP_ENV_VARS и $_ENV са две различни променливи и PHP ги третира като такива)
| Версия | Описание |
|---|---|
| 4.1.0 | Въведена е $_ENV, за сметка на непрепоръчителната $HTTP_ENV_VARS. |
Example #1 Пример с $_ENV
<?php
echo 'Моето потребителско име е ' .$_ENV["USER"] . '!';
?>
Приемаме, че "john" изпълнява този скрипт
Примерът по-горе ще изведе нещо подобно на:
Моето потребителско име е john!
Забележка: Това е 'свръхглобална' или автоматично глобална променлива. Това просто означава, че тя е налична във всички обхвати навсякъде из скрипта. Не е нобходимо да правите global $variable;, за да я достъпвате от тялото на функции и методи.
$php_errormsg — Предишното съобщение за грешка
$php_errormsg е променлива, която съдържа текстът на последното съобщение за грешка, създадено от PHP. Тази променлива ще бъде налична единствено в обхвата, в който се е случила грешката и единствено ако конфигурационната опция track_errors е включена (по подразбиране не е).
Забележка: Тази променлива е налична единствено, когато track_errors е включена в php.ini.
Ако има настроен потребителски дефиниран обработчик на грешки, $php_errormsg ще бъде попълнена единствено ако обработчикът на грешки върне FALSE
Example #1 Пример за $php_errormsg
<?php
@strpos();
echo $php_errormsg;
?>
Примерът по-горе ще изведе нещо подобно на:
Wrong parameter count for strpos()
$HTTP_RAW_POST_DATA — Сурови данни от тип POST
$HTTP_RAW_POST_DATA съдържа суровите данни от тип POST. Вж. always_populate_raw_post_data
$http_response_header — Заглавките-отговор от тип HTTP
Масивът $http_response_header е подобен на функция get_headers(). Когато се използва HTTP опаковка, $http_response_header ще бъде попълнена с отговарящите заглавки от тип HTTP.
Example #1 Пример за $http_response_header
<?php
file_get_contents("http://example.com");
var_dump($http_response_header);
?>
Примерът по-горе ще изведе нещо подобно на:
array(9) {
[0]=>
string(15) "HTTP/1.1 200 OK"
[1]=>
string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT"
[2]=>
string(29) "Server: Apache/2.2.3 (CentOS)"
[3]=>
string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"
[4]=>
string(27) "ETag: "280100-1b6-80bfd280""
[5]=>
string(20) "Accept-Ranges: bytes"
[6]=>
string(19) "Content-Length: 438"
[7]=>
string(17) "Connection: close"
[8]=>
string(38) "Content-Type: text/html; charset=UTF-8"
}
$argc — Броят аргументи, подадени на скрипта
Съдържа броя аргументи, подадени на скрипта, когато е пуснат от командния ред.
Забележка: Името на скрипта винаги се предава като аргумент към скрипта, така че минималната стойност на $argc е 1.
Забележка: Тази променлива е налична единствено, когато register_argc_argv е включена.
Example #1 Пример с $argc
<?php
var_dump($argc);
?>
Когато се изпълнява примера с: php script.php arg1 arg2 arg3
Примерът по-горе ще изведе нещо подобно на:
int(4)
$argv — Масив с аргументите, подадени на скрипта
Съдържа масив с всички аргументи, подадени на скрипта, когато е пуснат на командния ред.
Забележка: Първият аргумент винаги е файловото име на текущия скрипт, така че $argv[0] представлява името на скрипта.
Забележка: Тази променлива е налична единствено, когато register_argc_argv е включена.
Example #1 Пример с $argv
<?php
var_dump($argv);
?>
Когато се изпълнява примера с: php script.php arg1 arg2 arg3
Примерът по-горе ще изведе нещо подобно на:
array(4) {
[0]=>
string(10) "script.php"
[1]=>
string(4) "arg1"
[2]=>
string(4) "arg2"
[3]=>
string(4) "arg3"
}
PHP предоставя голям брой предварително-дефинирани променливи във всеки скрипт. Променливите представляват всичко - от външни променливи, до вградени променливи от обкръжението, последни съобщения за грешка и последно получени заглавки.
Вижте също раздела от FAQ, озаглавен "Как ми въздейства register_globals?"
(PHP 5 >= 5.1.0)
Exception::__construct — Конструира изключението
Конструира изключението.
Съобщението на изключението, което ще бъде хвърлено.
Кода на изключението.
Предишното изключение, използвано в навързването на изключения.
| Версия | Описание |
|---|---|
| 5.3.0 | Добавен е параметърът previous . |
(PHP 5 >= 5.1.0)
Exception::getMessage — Взима съобщението на изключението
Връща съобщението на изключението.
Тази функция няма параметри.
Връща съобщението на изключението под формата на низ.
Example #1 Пример за Exception::getMessage()
<?php
try {
throw new Exception("Някакво съобщение за грешка");
} catch(Exception $e) {
echo $e->getMessage();
}
?>
Примерът по-горе ще изведе нещо подобно на:
Някакво съобщение за грешка
(PHP 5 >= 5.1.0)
Exception::getCode — Взима кода на изключението
Връща кода на изключението.
Тази функция няма параметри.
Връща кода на изключението като integer.
Example #1 Пример за Exception::getCode()
<?php
try {
throw new Exception("Някакво съобщение за грешка", 30);
} catch(Exception $e) {
echo "Кодът на изключението е: " . $e->getCode();
}
?>
Примерът по-горе ще изведе нещо подобно на:
Кодът на изключението е: 30
(PHP 5 >= 5.1.0)
Exception::getFile — Взима файла, в който е станало изключението
Взима името на файла, от който е било хвърлено изключението.
Тази функция няма параметри.
Връща името на файла, в който е било хвърлено изключението.
Example #1 Пример за Exception::getFile()
<?php
try {
throw new Exception;
} catch(Exception $e) {
echo $e->getFile();
}
?>
Примерът по-горе ще изведе нещо подобно на:
/home/bjori/tmp/ex.php
(PHP 5 >= 5.1.0)
Exception::getLine — Взима реда, на който е станало изключението
Връща номера на реда, на който е било хвърлено изключението.
Тази функция няма параметри.
Връща номера на реда, на който е било хвърлено изключението.
Example #1 Пример за Exception::getLine()
<?php
try {
throw new Exception("Някакво съобщение за грешка");
} catch(Exception $e) {
echo "Съобщението беше хвърлено на ред: " . $e->getLine();
}
?>
Примерът по-горе ще изведе нещо подобно на:
Съобщението беше хвърлено на ред: 3
(PHP 5 >= 5.1.0)
Exception::getTrace — Взима проследяването на стека
Връща проследяването на стека (stack trace) на изключението.
Тази функция няма параметри.
Връща проследяването на стека под формата на масив (array).
Example #1 Пример за Exception::getTrace()
<?php
function test() {
throw new Exception;
}
try {
test();
} catch(Exception $e) {
var_dump($e->getTrace());
}
?>
Примерът по-горе ще изведе нещо подобно на:
array(1) {
[0]=>
array(4) {
["file"]=>
string(22) "/home/bjori/tmp/ex.php"
["line"]=>
int(7)
["function"]=>
string(4) "test"
["args"]=>
array(0) {
}
}
}
(PHP 5 >= 5.1.0)
Exception::getTraceAsString — Взима проследяването на стека като низ
Връща проследяването на стека под формата на низ.
Тази функция няма параметри.
Връща проследяването на стека като низ.
Example #1 Пример за Exception::getTraceAsString()
<?php
function test() {
throw new Exception;
}
try {
test();
} catch(Exception $e) {
echo $e->getTraceAsString();
}
?>
Примерът по-горе ще изведе нещо подобно на:
#0 /home/bjori/tmp/ex.php(7): test()
#1 {main}
(PHP 5 >= 5.1.0)
Exception::__toString — Низово представяне на изключението
Връща изключението под формата на низ (string).
Тази функция няма параметри.
Връща низовото представяне на изключението.
Example #1 Пример за Exception::__toString()
<?php
try {
throw new Exception("Някакво съобщение за грешка");
} catch(Exception $e) {
echo $e;
}
?>
Примерът по-горе ще изведе нещо подобно на:
exception 'Exception' with message 'Some error message' in /home/bjori/tmp/ex.php:3
Stack trace:
#0 {main}
(PHP 5 >= 5.1.0)
Exception::__clone — Клонира изключението
Опитва да клонира изключението, което води до Фатална грешка.
Тази функция няма параметри.
Няма връщана стойност.
Изключенията не могат да бъдат клонирани.
Exception е базовият клас за всички изключения.
Съобщението на изключението
Вътрешното име на изключението
Кода на изключението
Името на файла, където изключението е било хвърлено
Реда, на който изключението е било хвърлено
Проследяване на стека (stack trace)
(PHP 5 >= 5.1.0)
ErrorException::__construct — Конструира изключението
Конструира изключението.
Съобщението на изключението, което ще бъде хвърлено.
Кода на изключението.
Нивото на строгост на изключението.
Името на файла, в който се хвърля изключението.
Реда, на който се хвърля изключението.
(PHP 5 >= 5.1.0)
ErrorException::getSeverity — Взима строгостта на изключението
Връща строгостта на изключението.
Тази функция няма параметри.
Връща нивото на строгост на изключението.
Example #1 Пример за ErrorException()
<?php
try {
throw new ErrorException("Съобщение на изключението", 0, 75);
} catch(ErrorException $e) {
echo "Нивото на строгост на това изключение е: " . $e->getSeverity();
}
?>
Примерът по-горе ще изведе нещо подобно на:
Нивото на строгост на това изключение е: 75
Изключение за грешка.
Строгост на изключението
Example #1 Превключване на всички съобщения за грешка в ErrorException.
<?php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
/* Trigger exception */
strpos();
?>
Примерът по-горе ще изведе нещо подобно на:
Fatal error: Uncaught exception 'ErrorException' with message 'Wrong parameter count for strpos()' in /home/bjori/tmp/ex.php:8
Stack trace:
#0 [internal function]: exception_error_handler(2, 'Wrong parameter...', '/home/bjori/php...', 8, Array)
#1 /home/bjori/php/cleandocs/test.php(8): strpos()
#2 {main}
thrown in /home/bjori/tmp/ex.php on line 8
Interface to detect if a class is traversable using foreach.
Abstract base interface that cannot be implemented alone. Instead it must be implemented by either IteratorAggregate or Iterator.
Забележка: Internal (built-in) classes that implement this interface can be used in a foreach construct and do not need to implement IteratorAggregate or Iterator.
Забележка: This is an internal engine interface which cannot be implemented in PHP scripts. Either IteratorAggregate or Iterator must be used instead.
This interface has no methods, its only purpose is to be the base interface for all traversable classes.
(PHP 5 >= 5.1.0)
Iterator::current — Return the current element
Тази функция няма параметри.
Can return any type.
(PHP 5 >= 5.1.0)
Iterator::key — Return the key of the current element
Returns the key of the current element.
Тази функция няма параметри.
Returns scalar on success, integer 0 on failure.
Issues E_WARNING on failure.
(PHP 5 >= 5.1.0)
Iterator::next — Move forward to next element
Moves the current position to the next element.
Забележка: This method is called after each foreach loop.
Тази функция няма параметри.
Any returned value is ignored.
(PHP 5 >= 5.1.0)
Iterator::rewind — Rewind the Iterator to the first element
Rewinds back to the first element of the Iterator.
Забележка: This is the first method called when starting a foreach loop. It will not be executed after foreach loops.
Тази функция няма параметри.
Any returned value is ignored.
(PHP 5 >= 5.1.0)
Iterator::valid — Checks if current position is valid
This method is called after Iterator::rewind and Iterator::next to check if the current position is valid.
Тази функция няма параметри.
The return value will be casted to boolean and then evaluated. Връща TRUE при успех или FALSE при неуспех.
Interface for external iterators or objects that can be iterated themselves internally.
Example #1 Basic usage
This example demonstrates in which order methods are called when using foreach with an iterator.
<?php
class myIterator implements Iterator {
private $position = 0;
private $array = array(
"firstelement",
"secondelement",
"lastelement",
);
public function __construct() {
$this->position = 0;
}
function rewind() {
var_dump(__METHOD__);
$this->position = 0;
}
function current() {
var_dump(__METHOD__);
return $this->array[$this->position];
}
function key() {
var_dump(__METHOD__);
return $this->position;
}
function next() {
var_dump(__METHOD__);
++$this->position;
}
function valid() {
var_dump(__METHOD__);
return isset($this->array[$this->position]);
}
}
$it = new myIterator;
foreach($it as $key => $value) {
var_dump($key, $value);
echo "\n";
}
?>
Примерът по-горе ще изведе нещо подобно на:
string(18) "myIterator::rewind" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(0) string(12) "firstelement" string(16) "myIterator::next" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(1) string(13) "secondelement" string(16) "myIterator::next" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(2) string(11) "lastelement" string(16) "myIterator::next" string(17) "myIterator::valid"
(PHP 5 >= 5.1.0)
IteratorAggregate::getIterator — Retrieve an external iterator
Returns an external iterator.
Тази функция няма параметри.
An instance of an object implementing Iterator or Traversable
Throws an Exception on failure.
Interface to create an external Iterator.
Example #1 Basic usage
<?php
class myData implements IteratorAggregate {
public $property1 = "Public property one";
public $property2 = "Public property two";
public $property3 = "Public property three";
public function __construct() {
$this->property4 = "last property";
}
public function getIterator() {
return new ArrayIterator($this);
}
}
$obj = new myData;
foreach($obj as $key => $value) {
var_dump($key, $value);
echo "\n";
}
?>
Примерът по-горе ще изведе нещо подобно на:
string(9) "property1" string(19) "Public property one" string(9) "property2" string(19) "Public property two" string(9) "property3" string(21) "Public property three" string(9) "property4" string(13) "last property"
(PHP 5 >= 5.1.0)
ArrayAccess::offsetExists — Whether a offset exists
Whether or not an offset exists.
This method is executed when using isset() or empty() on objects implementing ArrayAccess.
Забележка: When using empty() ArrayAccess::offsetGet() will be called and checked if empty only if ArrayAccess::offsetExists() returns TRUE.
An offset to check for.
Връща TRUE при успех или FALSE при неуспех.
Забележка: The return value will be casted to boolean if non-boolean was returned.
Example #1 ArrayAccess::offsetExists() example
<?php
class obj implements arrayaccess {
public function offsetSet($offset, $value) {
var_dump(__METHOD__);
}
public function offsetExists($var) {
var_dump(__METHOD__);
if ($var == "foobar") {
return true;
}
return false;
}
public function offsetUnset($var) {
var_dump(__METHOD__);
}
public function offsetGet($var) {
var_dump(__METHOD__);
return "value";
}
}
$obj = new obj;
echo "Runs obj::offsetExists()\n";
var_dump(isset($obj["foobar"]));
echo "\nRuns obj::offsetExists() and obj::offsetGet()\n";
var_dump(empty($obj["foobar"]));
echo "\nRuns obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get\n";
var_dump(empty($obj["foobaz"]));
?>
Примерът по-горе ще изведе нещо подобно на:
Runs obj::offsetExists() string(17) "obj::offsetExists" bool(true) Runs obj::offsetExists() and obj::offsetGet() string(17) "obj::offsetExists" string(14) "obj::offsetGet" bool(false) Runs obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get string(17) "obj::offsetExists" bool(true)
(PHP 5 >= 5.1.0)
ArrayAccess::offsetGet — Offset to retrieve
Returns the value at specified offset.
This method is executed when checking if offset is empty().
The offset to retrieve.
Can return all value types.
(PHP 5 >= 5.1.0)
ArrayAccess::offsetSet — Offset to set
Assigns a value to the specified offset.
The offset to assign the value to.
The value to set.
Няма връщана стойност.
(PHP 5 >= 5.1.0)
ArrayAccess::offsetUnset — Offset to unset
Unsets an offset.
Забележка: This method will not be called when type-casting to (unset)
The offset to unset.
Няма връщана стойност.
Interface to provide accessing objects as arrays.
Example #1 Basic usage
<?php
class obj implements arrayaccess {
private $container = array();
public function __construct() {
$this->container = array(
"one" => 1,
"two" => 2,
"three" => 3,
);
}
public function offsetSet($offset, $value) {
$this->container[$offset] = $value;
}
public function offsetExists($offset) {
return isset($this->container[$offset]);
}
public function offsetUnset($offset) {
unset($this->container[$offset]);
}
public function offsetGet($offset) {
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
}
$obj = new obj;
var_dump(isset($obj["two"]));
var_dump($obj["two"]);
unset($obj["two"]);
var_dump(isset($obj["two"]));
$obj["two"] = "A value";
var_dump($obj["two"]);
?>
Примерът по-горе ще изведе нещо подобно на:
bool(true) int(2) bool(false) string(7) "A value"
(PHP 5 >= 5.1.0)
Serializable::serialize — String representation of object
Should return the string representation of the object.
Забележка: This method acts as the destructor of the object. The __destruct() method will not be called after this method.
Тази функция няма параметри.
Returns the string representation of the object or NULL
Throws Exception when returning other types then strings and NULL
FTP context options — FTP context option listing
Context options for ftp:// and ftps:// transports.
| Версия | Описание |
|---|---|
| 5.1.0 | Added proxy . |
| 5.0.0 | Added overwrite and resume_pos . |
Забележка: Underlying socket stream context options
Additional context options may be supported by the underlying transport For ftp:// streams, refer to context options for the tcp:// transport. For ftps:// streams, refer to context options for the ssl:// transport.
(PHP 5 >= 5.1.0)
Serializable::unserialize — Constructs the object
Called during unserialization of the object.
Забележка: This method acts as the constructor of the object. The __construct() method will not be called after this method.
The string representation of the object.
Returns the original value unserialized.
Interface for customized serializing.
Classes that implement this interface no longer support __sleep() and __wakeup(). The method serialize is called whenever an instance needs to be serialized. This does not invoke __destruct() or has any other side effect unless programmed inside the method. When the data is unserialized the class is known and the appropriate unserialize() method is called as a constructor instead of calling __construct(). If you need to execute the standard constructor you may do so in the method.
Example #1 Basic usage
<?php
class obj implements Serializable {
private $data;
public function __construct() {
$this->data = "My private data";
}
public function serialize() {
return serialize($this->data);
}
public function unserialize($data) {
$this->data = unserialize($data);
}
public function getData() {
return $this->data;
}
}
$obj = new obj;
$ser = serialize($obj);
$newobj = unserialize($ser);
var_dump($newobj->getData());
?>
Примерът по-горе ще изведе нещо подобно на:
string(15) "My private data"
See also the SPL Interfaces
Socket context options — Socket context option listing
Socket context options are available for all wrappers that work over sockets, like tcp, http and ftp.
| Версия | Описание |
|---|---|
| 5.1.0 | Added bindto. |
Example #1 Basic bindto usage example
<?php
// connect to the internet using the '192.168.0.100' IP
$opts = array(
'socket' => array(
'bindto' => '192.168.0.100:0',
),
);
// connect to the internet using the '192.168.0.100' IP and port '7000'
$opts = array(
'socket' => array(
'bindto' => '192.168.0.100:7000',
),
);
// connect to the internet using port '7000'
$opts = array(
'socket' => array(
'bindto' => '0:7000',
),
);
// create the context...
$context = stream_context_create($opts);
// ...and use it to fetch the data
echo file_get_contents('http://www.example.com', false, $context);
?>
HTTP context options — HTTP context option listing
Context options for http:// and https:// transports.
| Версия | Описание |
|---|---|
| 5.3.0 | The protocol_version supports chunked transfer decoding when set to 1.1. |
| 5.2.10 | Added ignore_errors . |
| 5.2.1 | Added timeout . |
| 5.2.10 | The header can now be an numerically indexed array. |
| 5.1.0 | Added HTTPS proxying through HTTP proxies. |
| 5.1.0 | Added max_redirects . |
| 5.1.0 | Added protocol_version . |
Example #1 Fetch a page and send POST data
<?php
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
?>
Забележка: Underlying socket stream context options
Additional context options may be supported by the underlying transport For http:// streams, refer to context options for the tcp:// transport. For https:// streams, refer to context options for the ssl:// transport.
SSL context options — SSL context option listing
Context options for ssl:// and tls:// transports.
| Версия | Описание |
|---|---|
| 5.0.0 | Added capture_peer_cert , capture_peer_chain and ciphers . |
Забележка: Because ssl:// is the underlying transport for the https:// and ftps:// wrappers, any context options which apply to ssl:// also apply to https:// and ftps://.
CURL context options — CURL context option listing
CURL context options are available when the CURL extension was compiled using the --with-curlwrappers configure option.
Example #1 Fetch a page and send POST data
<?php
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
?>
Phar context options — Phar context option listing
Context options for phar:// wrapper.
Context parameters — Context parameter listing
These parameters can be set on a context using the stream_context_set_params() function.
PHP offers various context options and parameters which can be used with all filesystem and stream wrappers. The context is created with stream_context_create(). Options are set with stream_context_set_option() and parameters with stream_context_set_params().
PHP е мощен език и интерпретаторът, независимо дали е интегриран като модул в уеб-сървър или се изпълнява като отделно CGI-приложение, има достъп до файлове, може да изпълнява команди и да установява връзки по мрежата от сървъра. Тези свойства правят всичко, което се изпълнява на уеб-сървър, несигурно по подразбиране. PHP е замислен специално като по-сигурен език за CGI програми, отколкото Perl или C и с правилно подбрани опции по време на компилацията и по време на изпълнението и правилни програмистки навици може да ви даде комбинацията от свобода и надеждност, от която се нуждаете.
Както има много различни начини да използвате PHP, така има и много конфигурационни директиви, контролиращи поведението му. Богатият избор на опции гарантира възможността да използвате PHP за много цели, но в същотото време означава, че има комбинации от тези опции и сървърни конфигурации, които са несигурни.
Гъвкавостта на настройките в PHP е сравнима с гъвкавостта на кода. PHP може да се използва за създаване на цялостни сървърски приложения с цялата мощ на потребител от системата или за елементарни сървърски включвания (server-side includes) с малък риск в строго контролирана среда. Как е изградена средата и до колко е сигурна тя зависи до голяма степен от програмиста на PHP.
Тази глава започва с някои общи съвети по въпросите на сигурността, обяснява различните комбинации от конфигурационни опции и случаите, в които е безопасно да се използват и описва различните съображения при писането на код за различните нива на сигурност.
A completely secure system is a virtual impossibility, so an approach often used in the security profession is one of balancing risk and usability. If every variable submitted by a user required two forms of biometric validation (such as a retinal scan and a fingerprint), you would have an extremely high level of accountability. It would also take half an hour to fill out a fairly complex form, which would tend to encourage users to find ways of bypassing the security.
The best security is often unobtrusive enough to suit the requirements without the user being prevented from accomplishing their work, or over-burdening the code author with excessive complexity. Indeed, some security attacks are merely exploits of this kind of overly built security, which tends to erode over time.
A phrase worth remembering: A system is only as good as the weakest link in a chain. If all transactions are heavily logged based on time, location, transaction type, etc. but the user is only verified based on a single cookie, the validity of tying the users to the transaction log is severely weakened.
When testing, keep in mind that you will not be able to test all possibilities for even the simplest of pages. The input you may expect will be completely unrelated to the input given by a disgruntled employee, a cracker with months of time on their hands, or a housecat walking across the keyboard. This is why it's best to look at the code from a logical perspective, to discern where unexpected data can be introduced, and then follow how it is modified, reduced, or amplified.
The Internet is filled with people trying to make a name for themselves by breaking your code, crashing your site, posting inappropriate content, and otherwise making your day interesting. It doesn't matter if you have a small or large site, you are a target by simply being online, by having a server that can be connected to. Many cracking programs do not discern by size, they simply trawl massive IP blocks looking for victims. Try not to become one.
Using PHP as a CGI binary is an option for setups that for some reason do not wish to integrate PHP as a module into server software (like Apache), or will use PHP with different kinds of CGI wrappers to create safe chroot and setuid environments for scripts. This setup usually involves installing executable PHP binary to the web server cgi-bin directory. CERT advisory » CA-96.11 recommends against placing any interpreters into cgi-bin. Even if the PHP binary can be used as a standalone interpreter, PHP is designed to prevent the attacks this setup makes possible:
If your server does not have any content that is not restricted by password or ip based access control, there is no need for these configuration options. If your web server does not allow you to do redirects, or the server does not have a way to communicate to the PHP binary that the request is a safely redirected request, you can specify the option --enable-force-cgi-redirect to the configure script. You still have to make sure your PHP scripts do not rely on one or another way of calling the script, neither by directly http://my.host/cgi-bin/php/dir/script.php nor by redirection http://my.host/dir/script.php.
Redirection can be configured in Apache by using AddHandler and Action directives (see below).
This compile-time option prevents anyone from calling PHP directly with a URL like http://my.host/cgi-bin/php/secretdir/script.php. Instead, PHP will only parse in this mode if it has gone through a web server redirect rule.
Usually the redirection in the Apache configuration is done with the following directives:
Action php-script /cgi-bin/php AddHandler php-script .php
This option has only been tested with the Apache web server, and relies on Apache to set the non-standard CGI environment variable REDIRECT_STATUS on redirected requests. If your web server does not support any way of telling if the request is direct or redirected, you cannot use this option and you must use one of the other ways of running the CGI version documented here.
To include active content, like scripts and executables, in the web server document directories is sometimes considered an insecure practice. If, because of some configuration mistake, the scripts are not executed but displayed as regular HTML documents, this may result in leakage of intellectual property or security information like passwords. Therefore many sysadmins will prefer setting up another directory structure for scripts that are accessible only through the PHP CGI, and therefore always interpreted and not displayed as such.
Also if the method for making sure the requests are not redirected, as described in the previous section, is not available, it is necessary to set up a script doc_root that is different from web document root.
You can set the PHP script document root by the configuration directive doc_root in the configuration file, or you can set the environment variable PHP_DOCUMENT_ROOT. If it is set, the CGI version of PHP will always construct the file name to open with this doc_root and the path information in the request, so you can be sure no script is executed outside this directory (except for user_dir below).
Another option usable here is user_dir. When user_dir is unset, only thing controlling the opened file name is doc_root . Opening a URL like http://my.host/~user/doc.php does not result in opening a file under users home directory, but a file called ~user/doc.php under doc_root (yes, a directory name starting with a tilde [~]).
If user_dir is set to for example public_php, a request like http://my.host/~user/doc.php will open a file called doc.php under the directory named public_php under the home directory of the user. If the home of the user is /home/user, the file executed is /home/user/public_php/doc.php.
user_dir expansion happens regardless of the doc_root setting, so you can control the document root and user directory access separately.
A very secure option is to put the PHP parser binary somewhere outside of the web tree of files. In /usr/local/bin, for example. The only real downside to this option is that you will now have to put a line similar to:
#!/usr/local/bin/php
as the first line of any file containing PHP tags. You will also need to make the file executable. That is, treat it exactly as you would treat any other CGI script written in Perl or sh or any other common scripting language which uses the #! shell-escape mechanism for launching itself.
To get PHP to handle PATH_INFO and PATH_TRANSLATED information correctly with this setup, the PHP parser should be compiled with the --enable-discard-path configure option.
When PHP is used as an Apache module it inherits Apache's user permissions (typically those of the "nobody" user). This has several impacts on security and authorization. For example, if you are using PHP to access a database, unless that database has built-in access control, you will have to make the database accessible to the "nobody" user. This means a malicious script could access and modify the database, even without a username and password. It's entirely possible that a web spider could stumble across a database administrator's web page, and drop all of your databases. You can protect against this with Apache authorization, or you can design your own access model using LDAP, .htaccess files, etc. and include that code as part of your PHP scripts.
Often, once security is established to the point where the PHP user (in this case, the apache user) has very little risk attached to it, it is discovered that PHP is now prevented from writing any files to user directories. Or perhaps it has been prevented from accessing or changing databases. It has equally been secured from writing good and bad files, or entering good and bad database transactions.
A frequent security mistake made at this point is to allow apache root permissions, or to escalate apache's abilities in some other way.
Escalating the Apache user's permissions to root is extremely dangerous and may compromise the entire system, so sudo'ing, chroot'ing, or otherwise running as root should not be considered by those who are not security professionals.
There are some simpler solutions. By using open_basedir you can control and restrict what directories are allowed to be used for PHP. You can also set up apache-only areas, to restrict all web based activity to non-user, or non-system, files.
As PHP uses the underlying C functions for filesystem related operations, it may handle null bytes in a quite unexpected way. As null bytes denote the end of a string in C, strings containing them won't be considered entirely but rather only until a null byte occurs. The following example shows a vulnerable code that demonstrates this problem:
Example #1 Script vulnerable to null bytes
<?php
$file = $_GET['file']; // "../../etc/passwd\0"
if (file_exists('/home/wwwrun/'.$file.'.php')) {
// file_exists will return true as the file /home/wwwrun/../../etc/passwd exists
include '/home/wwwrun/'.$file.'.php';
// the file /etc/passwd will be included
}
?>
Therefore, any tainted string that is used in a filesystem operation should always be validated properly. Here is a better version of the previous example:
Example #2 Correctly validating the input
<?php
$file = $_GET['file'];
// Whitelisting possible values
switch ($file) {
case 'main':
case 'foo':
case 'bar':
include '/home/wwwrun/include/'.$file.'.php';
break;
default:
include '/home/wwwrun/include/main.php';
}
?>
PHP is subject to the security built into most server systems with respect to permissions on a file and directory basis. This allows you to control which files in the filesystem may be read. Care should be taken with any files which are world readable to ensure that they are safe for reading by all users who have access to that filesystem.
Since PHP was designed to allow user level access to the filesystem, it's entirely possible to write a PHP script that will allow you to read system files such as /etc/passwd, modify your ethernet connections, send massive printer jobs out, etc. This has some obvious implications, in that you need to ensure that the files that you read from and write to are the appropriate ones.
Consider the following script, where a user indicates that they'd like to delete a file in their home directory. This assumes a situation where a PHP web interface is regularly used for file management, so the Apache user is allowed to delete files in the user home directories.
Example #1 Poor variable checking leads to....
<?php
// remove a file from the user's home directory
$username = $_POST['user_submitted_name'];
$userfile = $_POST['user_submitted_filename'];
$homedir = "/home/$username";
unlink("$homedir/$userfile");
echo "The file has been deleted!";
?>
Since the username and the filename are postable from a user form, they can submit a username and a filename belonging to someone else, and delete it even if they're not supposed to be allowed to do so. In this case, you'd want to use some other form of authentication. Consider what could happen if the variables submitted were "../etc/" and "passwd". The code would then effectively read:
Example #2 ... A filesystem attack
<?php
// removes a file from anywhere on the hard drive that
// the PHP user has access to. If PHP has root access:
$username = $_POST['user_submitted_name']; // "../etc"
$userfile = $_POST['user_submitted_filename']; // "passwd"
$homedir = "/home/$username"; // "/home/../etc"
unlink("$homedir/$userfile"); // "/home/../etc/passwd"
echo "The file has been deleted!";
?>
There are two important measures you should take to prevent these issues.
Here is an improved script:
Example #3 More secure file name checking
<?php
// removes a file from the hard drive that
// the PHP user has access to.
$username = $_SERVER['REMOTE_USER']; // using an authentication mechanisim
$userfile = basename($_POST['user_submitted_filename']);
$homedir = "/home/$username";
$filepath = "$homedir/$userfile";
if (file_exists($filepath) && unlink($filepath)) {
$logstring = "Deleted $filepath\n";
} else {
$logstring = "Failed to delete $filepath\n";
}
$fp = fopen("/home/logging/filedelete.log", "a");
fwrite($fp, $logstring);
fclose($fp);
echo htmlentities($logstring, ENT_QUOTES);
?>
However, even this is not without its flaws. If your authentication system allowed users to create their own user logins, and a user chose the login "../etc/", the system is once again exposed. For this reason, you may prefer to write a more customized check:
Example #4 More secure file name checking
<?php
$username = $_SERVER['REMOTE_USER']; // using an authentication mechanisim
$userfile = $_POST['user_submitted_filename'];
$homedir = "/home/$username";
$filepath = "$homedir/$userfile";
if (!ctype_alnum($username) || !preg_match('/^(?:[a-z0-9_-]|\.(?!\.))+$/iD', $userfile)) {
die("Bad username/filename");
}
//etc...
?>
Depending on your operating system, there are a wide variety of files which you should be concerned about, including device entries (/dev/ or COM1), configuration files (/etc/ files and the .ini files), well known file storage areas (/home/, My Documents), etc. For this reason, it's usually easier to create a policy where you forbid everything except for what you explicitly allow.
The first step is always to create the database, unless you want to use one from a third party. When a database is created, it is assigned to an owner, who executed the creation statement. Usually, only the owner (or a superuser) can do anything with the objects in that database, and in order to allow other users to use it, privileges must be granted.
Applications should never connect to the database as its owner or a superuser, because these users can execute any query at will, for example, modifying the schema (e.g. dropping tables) or deleting its entire content.
You may create different database users for every aspect of your application with very limited rights to database objects. The most required privileges should be granted only, and avoid that the same user can interact with the database in different use cases. This means that if intruders gain access to your database using your applications credentials, they can only effect as many changes as your application can.
You are encouraged not to implement all the business logic in the web application (i.e. your script), instead do it in the database schema using views, triggers or rules. If the system evolves, new ports will be intended to open to the database, and you have to re-implement the logic in each separate database client. Over and above, triggers can be used to transparently and automatically handle fields, which often provides insight when debugging problems with your application or tracing back transactions.
You may want to establish the connections over SSL to encrypt client/server communications for increased security, or you can use ssh to encrypt the network connection between clients and the database server. If either of these is used, then monitoring your traffic and gaining information about your database will be difficult for a would-be attacker.
SSL/SSH protects data travelling from the client to the server, SSL/SSH does not protect the persistent data stored in a database. SSL is an on-the-wire protocol.
Once an attacker gains access to your database directly (bypassing the webserver), the stored sensitive data may be exposed or misused, unless the information is protected by the database itself. Encrypting the data is a good way to mitigate this threat, but very few databases offer this type of data encryption.
The easiest way to work around this problem is to first create your own encryption package, and then use it from within your PHP scripts. PHP can assist you in this with several extensions, such as Mcrypt and Mhash, covering a wide variety of encryption algorithms. The script encrypts the data before inserting it into the database, and decrypts it when retrieving. See the references for further examples of how encryption works.
In case of truly hidden data, if its raw representation is not needed (i.e. not be displayed), hashing may also be taken into consideration. The well-known example for the hashing is storing the MD5 hash of a password in a database, instead of the password itself. See also crypt() and md5().
Example #1 Using hashed password field
<?php
// storing password hash
$query = sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
pg_escape_string($username), md5($password));
$result = pg_query($connection, $query);
// querying if user submitted the right password
$query = sprintf("SELECT 1 FROM users WHERE name='%s' AND pwd='%s';",
pg_escape_string($username), md5($password));
$result = pg_query($connection, $query);
if (pg_num_rows($result) > 0) {
echo 'Welcome, $username!';
} else {
echo 'Authentication failed for $username.';
}
?>
Many web developers are unaware of how SQL queries can be tampered with, and assume that an SQL query is a trusted command. It means that SQL queries are able to circumvent access controls, thereby bypassing standard authentication and authorization checks, and sometimes SQL queries even may allow access to host operating system level commands.
Direct SQL Command Injection is a technique where an attacker creates or alters existing SQL commands to expose hidden data, or to override valuable ones, or even to execute dangerous system level commands on the database host. This is accomplished by the application taking user input and combining it with static parameters to build a SQL query. The following examples are based on true stories, unfortunately.
Owing to the lack of input validation and connecting to the database on behalf of a superuser or the one who can create users, the attacker may create a superuser in your database.
Example #1 Splitting the result set into pages ... and making superusers (PostgreSQL)
<?php
$offset = $argv[0]; // beware, no input validation!
$query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
$result = pg_query($conn, $query);
?>
Normal users click on the 'next', 'prev' links where the $offset is encoded into the URL. The script expects that the incoming $offset is a decimal number. However, what if someone tries to break in by appending a urlencode()'d form of the following to the URL
0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
select 'crack', usesysid, 't','t','crack'
from pg_shadow where usename='postgres';
--
If it happened, then the script would present a superuser access to him. Note that 0; is to supply a valid offset to the original query and to terminate it.
Забележка: It is common technique to force the SQL parser to ignore the rest of the query written by the developer with -- which is the comment sign in SQL.
A feasible way to gain passwords is to circumvent your search result pages. The only thing the attacker needs to do is to see if there are any submitted variables used in SQL statements which are not handled properly. These filters can be set commonly in a preceding form to customize WHERE, ORDER BY, LIMIT and OFFSET clauses in SELECT statements. If your database supports the UNION construct, the attacker may try to append an entire query to the original one to list passwords from an arbitrary table. Using encrypted password fields is strongly encouraged.
Example #2 Listing out articles ... and some passwords (any database server)
<?php
$query = "SELECT id, name, inserted, size FROM products
WHERE size = '$size'
ORDER BY $order LIMIT $limit, $offset;";
$result = odbc_exec($conn, $query);
?>
The static part of the query can be combined with another SELECT statement which reveals all passwords:
' union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable; --
If this query (playing with the ' and --) were assigned to one of the variables used in $query, the query beast awakened.
SQL UPDATE's are also susceptible to attack. These queries are also threatened by chopping and appending an entirely new query to it. But the attacker might fiddle with the SET clause. In this case some schema information must be possessed to manipulate the query successfully. This can be acquired by examining the form variable names, or just simply brute forcing. There are not so many naming conventions for fields storing passwords or usernames.
Example #3 From resetting a password ... to gaining more privileges (any database server)
<?php
$query = "UPDATE usertable SET pwd='$pwd' WHERE uid='$uid';";
?>
But a malicious user sumbits the value ' or uid like'%admin%'; -- to $uid to change the admin's password, or simply sets $pwd to "hehehe', admin='yes', trusted=100 " (with a trailing space) to gain more privileges. Then, the query will be twisted:
<?php
// $uid == ' or uid like'%admin%'; --
$query = "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%'; --";
// $pwd == "hehehe', admin='yes', trusted=100 "
$query = "UPDATE usertable SET pwd='hehehe', admin='yes', trusted=100 WHERE
...;";
?>
A frightening example how operating system level commands can be accessed on some database hosts.
Example #4 Attacking the database hosts operating system (MSSQL Server)
<?php
$query = "SELECT * FROM products WHERE id LIKE '%$prod%'";
$result = mssql_query($query);
?>
If attacker submits the value a%' exec master..xp_cmdshell 'net user test testpass /ADD' -- to $prod, then the $query will be:
<?php
$query = "SELECT * FROM products
WHERE id LIKE '%a%'
exec master..xp_cmdshell 'net user test testpass /ADD'--";
$result = mssql_query($query);
?>
MSSQL Server executes the SQL statements in the batch including a command to add a new user to the local accounts database. If this application were running as sa and the MSSQLSERVER service is running with sufficient privileges, the attacker would now have an account with which to access this machine.
Забележка: Some of the examples above is tied to a specific database server. This does not mean that a similar attack is impossible against other products. Your database server may be similarly vulnerable in another manner.
You may plead that the attacker must possess a piece of information about the database schema in most examples. You are right, but you never know when and how it can be taken out, and if it happens, your database may be exposed. If you are using an open source, or publicly available database handling package, which may belong to a content management system or forum, the intruders easily produce a copy of a piece of your code. It may be also a security risk if it is a poorly designed one.
These attacks are mainly based on exploiting the code not being written with security in mind. Never trust any kind of input, especially that which comes from the client side, even though it comes from a select box, a hidden input field or a cookie. The first example shows that such a blameless query can cause disasters.
If the application waits for numerical input, consider verifying data with is_numeric(), or silently change its type using settype(), or use its numeric representation by sprintf().
Example #5 A more secure way to compose a query for paging
<?php
settype($offset, 'integer');
$query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
// please note %d in the format string, using %s would be meaningless
$query = sprintf("SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET %d;",
$offset);
?>
Besides these, you benefit from logging queries either within your script or by the database itself, if it supports logging. Obviously, the logging is unable to prevent any harmful attempt, but it can be helpful to trace back which application has been circumvented. The log is not useful by itself, but through the information it contains. More detail is generally better than less.
Nowadays, databases are cardinal components of any web based application by enabling websites to provide varying dynamic content. Since very sensitive or secret information can be stored in a database, you should strongly consider protecting your databases.
To retrieve or to store any information you need to connect to the database, send a legitimate query, fetch the result, and close the connection. Nowadays, the commonly used query language in this interaction is the Structured Query Language (SQL). See how an attacker can tamper with an SQL query.
As you can surmise, PHP cannot protect your database by itself. The following sections aim to be an introduction into the very basics of how to access and manipulate databases within PHP scripts.
Keep in mind this simple rule: defense in depth. The more places you take action to increase the protection of your database, the less probability of an attacker succeeding in exposing or abusing any stored information. Good design of the database schema and the application deals with your greatest fears.
With PHP security, there are two sides to error reporting. One is beneficial to increasing security, the other is detrimental.
A standard attack tactic involves profiling a system by feeding it improper data, and checking for the kinds, and contexts, of the errors which are returned. This allows the system cracker to probe for information about the server, to determine possible weaknesses. For example, if an attacker had gleaned information about a page based on a prior form submission, they may attempt to override variables, or modify them:
Example #1 Attacking Variables with a custom HTML page
<form method="post" action="attacktarget?username=badfoo&password=badfoo"> <input type="hidden" name="username" value="badfoo" /> <input type="hidden" name="password" value="badfoo" /> </form>
The PHP errors which are normally returned can be quite helpful to a developer who is trying to debug a script, indicating such things as the function or file that failed, the PHP file it failed in, and the line number which the failure occurred in. This is all information that can be exploited. It is not uncommon for a php developer to use show_source(), highlight_string(), or highlight_file() as a debugging measure, but in a live site, this can expose hidden variables, unchecked syntax, and other dangerous information. Especially dangerous is running code from known sources with built-in debugging handlers, or using common debugging techniques. If the attacker can determine what general technique you are using, they may try to brute-force a page, by sending various common debugging strings:
Example #2 Exploiting common debugging variables
<form method="post" action="attacktarget?errors=Y&showerrors=1&debug=1"> <input type="hidden" name="errors" value="Y" /> <input type="hidden" name="showerrors" value="1" /> <input type="hidden" name="debug" value="1" /> </form>
Regardless of the method of error handling, the ability to probe a system for errors leads to providing an attacker with more information.
For example, the very style of a generic PHP error indicates a system is running PHP. If the attacker was looking at an .html page, and wanted to probe for the back-end (to look for known weaknesses in the system), by feeding it the wrong data they may be able to determine that a system was built with PHP.
A function error can indicate whether a system may be running a specific database engine, or give clues as to how a web page or programmed or designed. This allows for deeper investigation into open database ports, or to look for specific bugs or weaknesses in a web page. By feeding different pieces of bad data, for example, an attacker can determine the order of authentication in a script, (from the line number errors) as well as probe for exploits that may be exploited in different locations in the script.
A filesystem or general PHP error can indicate what permissions the web server has, as well as the structure and organization of files on the web server. Developer written error code can aggravate this problem, leading to easy exploitation of formerly "hidden" information.
There are three major solutions to this issue. The first is to scrutinize all functions, and attempt to compensate for the bulk of the errors. The second is to disable error reporting entirely on the running code. The third is to use PHP's custom error handling functions to create your own error handler. Depending on your security policy, you may find all three to be applicable to your situation.
One way of catching this issue ahead of time is to make use of PHP's own error_reporting(), to help you secure your code and find variable usage that may be dangerous. By testing your code, prior to deployment, with E_ALL, you can quickly find areas where your variables may be open to poisoning or modification in other ways. Once you are ready for deployment, you should either disable error reporting completely by setting error_reporting() to 0, or turn off the error display using the php.ini option display_errors, to insulate your code from probing. If you choose to do the latter, you should also define the path to your log file using the error_log ini directive, and turn log_errors on.
Example #3 Finding dangerous variables with E_ALL
<?php
if ($username) { // Not initialized or checked before usage
$good_login = 1;
}
if ($good_login == 1) { // If above test fails, not initialized or checked before usage
readfile ("/highly/sensitive/data/index.html");
}
?>
Тази възможност е НЕПРЕПОРЪЧИТЕЛНА от PHP 5.3.0 и ПРЕМАХНАТА след PHP 6.0.0. Да се разчита на тази възможност е силно непрепоръчително.
Perhaps the most controversial change in PHP is when the default value for the PHP directive register_globals went from ON to OFF in PHP » 4.2.0. Reliance on this directive was quite common and many people didn't even know it existed and assumed it's just how PHP works. This page will explain how one can write insecure code with this directive but keep in mind that the directive itself isn't insecure but rather it's the misuse of it.
When on, register_globals will inject your scripts with all sorts of variables, like request variables from HTML forms. This coupled with the fact that PHP doesn't require variable initialization means writing insecure code is that much easier. It was a difficult decision, but the PHP community decided to disable this directive by default. When on, people use variables yet really don't know for sure where they come from and can only assume. Internal variables that are defined in the script itself get mixed up with request data sent by users and disabling register_globals changes this. Let's demonstrate with an example misuse of register_globals:
Example #1 Example misuse with register_globals = on
<?php
// define $authorized = true only if user is authenticated
if (authenticated_user()) {
$authorized = true;
}
// Because we didn't first initialize $authorized as false, this might be
// defined through register_globals, like from GET auth.php?authorized=1
// So, anyone can be seen as authenticated!
if ($authorized) {
include "/highly/sensitive/data.php";
}
?>
When register_globals = on, our logic above may be compromised. When off, $authorized can't be set via request so it'll be fine, although it really is generally a good programming practice to initialize variables first. For example, in our example above we might have first done $authorized = false. Doing this first means our above code would work with register_globals on or off as users by default would be unauthorized.
Another example is that of sessions. When register_globals = on, we could also use $username in our example below but again you must realize that $username could also come from other means, such as GET (through the URL).
Example #2 Example use of sessions with register_globals on or off
<?php
// We wouldn't know where $username came from but do know $_SESSION is
// for session data
if (isset($_SESSION['username'])) {
echo "Hello <b>{$_SESSION['username']}</b>";
} else {
echo "Hello <b>Guest</b><br />";
echo "Would you like to login?";
}
?>
It's even possible to take preventative measures to warn when forging is being attempted. If you know ahead of time exactly where a variable should be coming from, you can check to see if the submitted data is coming from an inappropriate kind of submission. While it doesn't guarantee that data has not been forged, it does require an attacker to guess the right kind of forging. If you don't care where the request data comes from, you can use $_REQUEST as it contains a mix of GET, POST and COOKIE data. See also the manual section on using variables from external sources.
Example #3 Detecting simple variable poisoning
<?php
if (isset($_COOKIE['MAGIC_COOKIE'])) {
// MAGIC_COOKIE comes from a cookie.
// Be sure to validate the cookie data!
} elseif (isset($_GET['MAGIC_COOKIE']) || isset($_POST['MAGIC_COOKIE'])) {
mail("admin@example.com", "Possible breakin attempt", $_SERVER['REMOTE_ADDR']);
echo "Security violation, admin has been alerted.";
exit;
} else {
// MAGIC_COOKIE isn't set through this REQUEST
}
?>
Of course, simply turning off register_globals does not mean your code is secure. For every piece of data that is submitted, it should also be checked in other ways. Always validate your user data and initialize your variables! To check for uninitialized variables you may turn up error_reporting() to show E_NOTICE level errors.
For information about emulating register_globals being On or Off, see this FAQ.
Забележка: Superglobals: availability note
От PHP 4.1.0, superglobal масивите като $_GET , $_POST, и $_SERVER, и т.н. са достъпни. За повече информация, прочетете раздела от ръководството в superglobals
The greatest weakness in many PHP programs is not inherent in the language itself, but merely an issue of code not being written with security in mind. For this reason, you should always take the time to consider the implications of a given piece of code, to ascertain the possible damage if an unexpected variable is submitted to it.
Example #1 Dangerous Variable Usage
<?php
// remove a file from the user's home directory... or maybe
// somebody else's?
unlink ($evil_var);
// Write logging of their access... or maybe an /etc/passwd entry?
fwrite ($fp, $evil_var);
// Execute something trivial.. or rm -rf *?
system ($evil_var);
exec ($evil_var);
?>
You should always carefully examine your code to make sure that any variables being submitted from a web browser are being properly checked, and ask yourself the following questions:
By adequately asking these questions while writing the script, rather than later, you prevent an unfortunate re-write when you need to increase your security. By starting out with this mindset, you won't guarantee the security of your system, but you can help improve it.
You may also want to consider turning off register_globals, magic_quotes, or other convenience settings which may confuse you as to the validity, source, or value of a given variable. Working with PHP in error_reporting(E_ALL) mode can also help warn you about variables being used before they are checked or initialized (so you can prevent unusual data from being operated upon).
When on, all ' (single-quote), " (double quote), \ (backslash) and NULL characters are escaped with a backslash automatically. This is identical to what addslashes() does.
There are three magic quote directives:
Тази възможност е НЕПРЕПОРЪЧИТЕЛНА от PHP 5.3.0 и ПРЕМАХНАТА след PHP 6.0.0. Да се разчита на тази възможност е силно непрепоръчително.
Тази възможност е НЕПРЕПОРЪЧИТЕЛНА от PHP 5.3.0 и ПРЕМАХНАТА след PHP 6.0.0. Да се разчита на тази възможност е силно непрепоръчително.
Тази възможност е НЕПРЕПОРЪЧИТЕЛНА от PHP 5.3.0 и ПРЕМАХНАТА след PHP 6.0.0. Да се разчита на тази възможност е силно непрепоръчително.
The magic_quotes_gpc directive may only be disabled at the system level, and not at runtime. In otherwords, use of ini_set() is not an option.
Example #1 Disabling magic quotes server side
An example that sets the value of these directives to Off in php.ini. For additional details, read the manual section titled How to change configuration settings.
; Magic quotes ; ; Magic quotes for incoming GET/POST/Cookie data. magic_quotes_gpc = Off ; Magic quotes for runtime-generated data, e.g. data from SQL, from exec(), etc. magic_quotes_runtime = Off ; Use Sybase-style magic quotes (escape ' with '' instead of \'). magic_quotes_sybase = Off
If access to the server configuration is unavailable, use of .htaccess is also an option. For example:
php_flag magic_quotes_gpc Off
In the interest of writing portable code (code that works in any environment), like if setting at the server level is not possible, here's an example to disable magic_quotes_gpc at runtime. This method is inefficient so it's preferred to instead set the appropriate directives elsewhere.
Example #2 Disabling magic quotes at runtime
<?php
if (get_magic_quotes_gpc()) {
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
$_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}
?>
Тази възможност е НЕПРЕПОРЪЧИТЕЛНА от PHP 5.3.0 и ПРЕМАХНАТА след PHP 6.0.0. Да се разчита на тази възможност е силно непрепоръчително.
Magic Quotes is a process that automagically escapes incoming data to the PHP script. It's preferred to code with magic quotes off and to instead escape the data at runtime, as needed.
In general, security by obscurity is one of the weakest forms of security. But in some cases, every little bit of extra security is desirable.
A few simple techniques can help to hide PHP, possibly slowing down an attacker who is attempting to discover weaknesses in your system. By setting expose_php to off in your php.ini file, you reduce the amount of information available to them.
Another tactic is to configure web servers such as apache to parse different filetypes through PHP, either with an .htaccess directive, or in the apache configuration file itself. You can then use misleading file extensions:
Example #1 Hiding PHP as another language
# Make PHP code look like other code types AddType application/x-httpd-php .asp .py .pl
Or obscure it completely:
Example #2 Using unknown types for PHP extensions
# Make PHP code look like unknown types AddType application/x-httpd-php .bop .foo .133t
Or hide it as HTML code, which has a slight performance hit because all HTML will be parsed through the PHP engine:
Example #3 Using HTML types for PHP extensions
# Make all PHP code look like HTML AddType application/x-httpd-php .htm .html
For this to work effectively, you must rename your PHP files with the above extensions. While it is a form of security through obscurity, it's a minor preventative measure with few drawbacks.
PHP, like any other large system, is under constant scrutiny and improvement. Each new version will often include both major and minor changes to enhance security and repair any flaws, configuration mishaps, and other issues that will affect the overall security and stability of your system.
Like other system-level scripting languages and programs, the best approach is to update often, and maintain awareness of the latest versions and their changes.
The HTTP Authentication hooks in PHP are only available when it is running as an Apache module and is hence not available in the CGI version. In an Apache module PHP script, it is possible to use the header() function to send an "Authentication Required" message to the client browser causing it to pop up a Username/Password input window. Once the user has filled in a username and a password, the URL containing the PHP script will be called again with the predefined variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE set to the user name, password and authentication type respectively. These predefined variables are found in the $_SERVER and $HTTP_SERVER_VARS arrays. Both "Basic" and "Digest" (since PHP 5.1.0) authentication methods are supported. See the header() function for more information.
Забележка: PHP Version Note
Superglobals, such as $_SERVER, became available in PHP » 4.1.0.
An example script fragment which would force client authentication on a page is as follows:
Example #1 Basic HTTP Authentication example
<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Text to send if user hits Cancel button';
exit;
} else {
echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>
Example #2 Digest HTTP Authentication example
This example shows you how to implement a simple Digest HTTP authentication script. For more information read the » RFC 2617.
<?php
$realm = 'Restricted area';
//user => password
$users = array('admin' => 'mypass', 'guest' => 'guest');
if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
die('Text to send if user hits Cancel button');
}
// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
!isset($users[$data['username']]))
die('Wrong Credentials!');
// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);
if ($data['response'] != $valid_response)
die('Wrong Credentials!');
// ok, valid username & password
echo 'Your are logged in as: ' . $data['username'];
// function to parse the http auth header
function http_digest_parse($txt)
{
// protect against missing data
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
$data = array();
$keys = implode('|', array_keys($needed_parts));
preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$data[$m[1]] = $m[3] ? $m[3] : $m[4];
unset($needed_parts[$m[1]]);
}
return $needed_parts ? false : $data;
}
?>
Забележка: Compatibility Note
Please be careful when coding the HTTP header lines. In order to guarantee maximum compatibility with all clients, the keyword "Basic" should be written with an uppercase "B", the realm string must be enclosed in double (not single) quotes, and exactly one space should precede the 401 code in the HTTP/1.0 401 header line. Authentication parameters have to be comma-separated as seen in the digest example above.
Instead of simply printing out PHP_AUTH_USER and PHP_AUTH_PW, as done in the above example, you may want to check the username and password for validity. Perhaps by sending a query to a database, or by looking up the user in a dbm file.
Watch out for buggy Internet Explorer browsers out there. They seem very picky about the order of the headers. Sending the WWW-Authenticate header before the HTTP/1.0 401 header seems to do the trick for now.
As of PHP 4.3.0, in order to prevent someone from writing a script which reveals the password for a page that was authenticated through a traditional external mechanism, the PHP_AUTH variables will not be set if external authentication is enabled for that particular page and защитен режим is enabled. Regardless, REMOTE_USER can be used to identify the externally-authenticated user. So, you can use $_SERVER['REMOTE_USER'].
Забележка: Configuration Note
PHP uses the presence of an AuthType directive to determine whether external authentication is in effect.
Note, however, that the above does not prevent someone who controls a non-authenticated URL from stealing passwords from authenticated URLs on the same server.
Both Netscape Navigator and Internet Explorer will clear the local browser window's authentication cache for the realm upon receiving a server response of 401. This can effectively "log out" a user, forcing them to re-enter their username and password. Some people use this to "time out" logins, or provide a "log-out" button.
Example #3 HTTP Authentication example forcing a new name/password
<?php
function authenticate() {
header('WWW-Authenticate: Basic realm="Test Authentication System"');
header('HTTP/1.0 401 Unauthorized');
echo "You must enter a valid login ID and password to access this resource\n";
exit;
}
if (!isset($_SERVER['PHP_AUTH_USER']) ||
($_POST['SeenBefore'] == 1 && $_POST['OldAuth'] == $_SERVER['PHP_AUTH_USER'])) {
authenticate();
} else {
echo "<p>Welcome: {$_SERVER['PHP_AUTH_USER']}<br />";
echo "Old: {$_REQUEST['OldAuth']}";
echo "<form action='{$_SERVER['PHP_SELF']}' METHOD='post'>\n";
echo "<input type='hidden' name='SeenBefore' value='1' />\n";
echo "<input type='hidden' name='OldAuth' value='{$_SERVER['PHP_AUTH_USER']}' />\n";
echo "<input type='submit' value='Re Authenticate' />\n";
echo "</form></p>\n";
}
?>
This behavior is not required by the HTTP Basic authentication standard, so you should never depend on this. Testing with Lynx has shown that Lynx does not clear the authentication credentials with a 401 server response, so pressing back and then forward again will open the resource as long as the credential requirements haven't changed. The user can press the '_' key to clear their authentication information, however.
Also note that until PHP 4.3.3, HTTP Authentication did not work using Microsoft's IIS server with the CGI version of PHP due to a limitation of IIS. In order to get it to work in PHP 4.3.3+, you must edit your IIS configuration "Directory Security". Click on "Edit" and only check "Anonymous Access", all other fields should be left unchecked.
Another limitation is if you're using the IIS module (ISAPI) and PHP 4, you may not use the PHP_AUTH_* variables but instead, the variable HTTP_AUTHORIZATION is available. For example, consider the following code: list($user, $pw) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
Забележка: IIS Note:
For HTTP Authentication to work with IIS, the PHP directive cgi.rfc2616_headers must be set to 0 (the default value).
Забележка: If safe mode is enabled, the uid of the script is added to the realm part of the WWW-Authenticate header.
PHP има прозрачна поддръжка на HTTP-бисквитки. Бисквитките са механизъм за съхранение на определени данни на клиентски браузър като по този начин могат да се следят и идентифицират върналите се потребители. Можете да установите бисквитки с една от двете функции setcookie() или setrawcookie(). Бисквитките са част от заглавката (header) на HTTP и съответно функцията setcookie() трябва да бъде извикана преди каквито и да е изходни данни да бъдат изпратени към браузъра. Същото ограничение има и функцията header(). Можете да използвате функциите за контрол на изхода, за да забавите изходните данни от скрипта, докато не решите дали ще установите някакви бисквитки, или ще изпратите някоя заглавка.
Всички бисквитки, които изпратите, ще бъдат включени автоматично в глобалния масив $_COOKIE, ако variables_order съдържа "C". Ако искате да включите множество стойности към една бисквитка, просто добавете [] към името на бисквитката.
В зависимост от register_globals, в PHP могат да бъдат създадени обикновени променливи от бисквитки. Независимо от това използването им не е препоръчително, тъй като от съображения за сигурност тази опция много често бива изключена. $HTTP_COOKIE_VARS също е установена в по-ранни версии на PHP, когато конфигурационната променлива track_vars е включена. (Тази опция е включена по подразбиране от PHP 4.0.3.)
За повече информация, включително бележки за програмни грешки в браузърите, вижте функциите setcookie() и setrawcookie().
Поддръжката на сесия в PHP се състои в това да бъдат запазени определени данни за по удобно последващо използване. Това ви позволява да създавате приложения, конфигурирани според вашите нужди и да увеличите привлекателността на страницата си. Вижте цялата информация за сесиите в раздел Функции за сесии.
» XForms defines a variation on traditional webforms which allows them to be used on a wider variety of platforms and browsers or even non-traditional media such as PDF documents.
The first key difference in XForms is how the form is sent to the client. » XForms for HTML Authors contains a detailed description of how to create XForms, for the purpose of this tutorial we'll only be looking at a simple example.
Example #1 A simple XForms search form
<h:html xmlns:h="http://www.w3.org/1999/xhtml"
xmlns="http://www.w3.org/2002/xforms">
<h:head>
<h:title>Search</h:title>
<model>
<submission action="http://example.com/search"
method="post" id="s"/>
</model>
</h:head>
<h:body>
<h:p>
<input ref="q"><label>Find</label></input>
<submit submission="s"><label>Go</label></submit>
</h:p>
</h:body>
</h:html>
The above form displays a text input box (named q ), and a submit button. When the submit button is clicked, the form will be sent to the page referred to by action.
Here's where it starts to look different from your web application's point of view. In a normal HTML form, the data would be sent as application/x-www-form-urlencoded, in the XForms world however, this information is sent as XML formatted data.
If you're choosing to work with XForms then you probably want that data as XML, in that case, look in $HTTP_RAW_POST_DATA where you'll find the XML document generated by the browser which you can pass into your favorite XSLT engine or document parser.
If you're not interested in formatting and just want your data to be loaded into the traditional $_POST variable, you can instruct the client browser to send it as application/x-www-form-urlencoded by changing the method attribute to urlencoded-post.
Example #2 Using an XForm to populate $_POST
<h:html xmlns:h="http://www.w3.org/1999/xhtml"
xmlns="http://www.w3.org/2002/xforms">
<h:head>
<h:title>Search</h:title>
<model>
<submission action="http://example.com/search"
method="urlencoded-post" id="s"/>
</model>
</h:head>
<h:body>
<h:p>
<input ref="q"><label>Find</label></input>
<submit submission="s"><label>Go</label></submit>
</h:p>
</h:body>
</h:html>
Забележка: As of this writing, many browsers do not support XForms. Check your browser version if the above examples fails.
This feature lets people upload both text and binary files. With PHP's authentication and file manipulation functions, you have full control over who is allowed to upload and what is to be done with the file once it has been uploaded.
PHP is capable of receiving file uploads from any RFC-1867 compliant browser (which includes Netscape Navigator 3 or later, Microsoft Internet Explorer 3 with a patch from Microsoft, or later without a patch).
Забележка: Related Configurations Note
See also the file_uploads, upload_max_filesize, upload_tmp_dir, post_max_size and max_input_time directives in php.ini
PHP also supports PUT-method file uploads as used by Netscape Composer and W3C's Amaya clients. See the PUT Method Support for more details.
Example #1 File Upload Form
A file upload screen can be built by creating a special form which looks something like this:
<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<!-- Name of input element determines name in $_FILES array -->
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
The __URL__ in the above example should be replaced, and point to a PHP file.
The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file input field, and its value is the maximum filesize accepted by PHP. This form element should always be used as it saves users the trouble of waiting for a big file being transferred only to find that it was too large and the transfer failed. Keep in mind: fooling this setting on the browser side is quite easy, so never rely on files with a greater size being blocked by this feature. It is merely a convenience feature for users on the client side of the application. The PHP settings (on the server side) for maximum-size, however, cannot be fooled.
Забележка: Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.
The global $_FILES exists as of PHP 4.1.0 (Use $HTTP_POST_FILES instead if using an earlier version). These arrays will contain all the uploaded file information.
The contents of $_FILES from the example form is as follows. Note that this assumes the use of the file upload name userfile, as used in the example script above. This can be any name.
The original name of the file on the client machine.
The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.
The size, in bytes, of the uploaded file.
The temporary filename of the file in which the uploaded file was stored on the server.
The error code associated with this file upload. This element was added in PHP 4.2.0
Files will, by default be stored in the server's default temporary directory, unless another location has been given with the upload_tmp_dir directive in php.ini. The server's default directory can be changed by setting the environment variable TMPDIR in the environment in which PHP runs. Setting it using putenv() from within a PHP script will not work. This environment variable can also be used to make sure that other operations are working on uploaded files, as well.
Example #2 Validating file uploads
See also the function entries for is_uploaded_file() and move_uploaded_file() for further information. The following example will process the file upload that came from a form.
<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
The PHP script which receives the uploaded file should implement whatever logic is necessary for determining what should be done with the uploaded file. You can, for example, use the $_FILES['userfile']['size'] variable to throw away any files that are either too small or too big. You could use the $_FILES['userfile']['type'] variable to throw away any files that didn't match a certain type criteria, but use this only as first of a series of checks, because this value is completely under the control of the client and not checked on the PHP side. As of PHP 4.2.0, you could use $_FILES['userfile']['error'] and plan your logic according to the error codes. Whatever the logic, you should either delete the file from the temporary directory or move it elsewhere.
If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none.
The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed.
Example #3 Uploading array of files
PHP supports HTML array feature even with files.
<form action="" method="post" enctype="multipart/form-data"> <p>Pictures: <input type="file" name="pictures[]" /> <input type="file" name="pictures[]" /> <input type="file" name="pictures[]" /> <input type="submit" value="Send" /> </p> </form>
<?php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "data/$name");
}
}
?>
File upload progress bar can be implemented by apc.rfc1867.
Since PHP 4.2.0, PHP returns an appropriate error code along with the file array. The error code can be found in the error segment of the file array that is created during the file upload by PHP. In other words, the error might be found in $_FILES['userfile']['error'].
Value: 0; There is no error, the file uploaded with success.
Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
Value: 3; The uploaded file was only partially uploaded.
Value: 4; No file was uploaded.
Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.
Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.
Value: 8; File upload stopped by extension. Introduced in PHP 5.2.0.
Забележка: These became PHP constants in PHP 4.3.0.
The MAX_FILE_SIZE item cannot specify a file size greater than the file size that has been set in the upload_max_filesize in the php.ini file. The default is 2 megabytes.
If a memory limit is enabled, a larger memory_limit may be needed. Make sure you set memory_limit large enough.
If max_execution_time is set too small, script execution may be exceeded by the value. Make sure you set max_execution_time large enough.
Забележка: max_execution_time only affects the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), the sleep() function, database queries, time taken by the file upload process, etc. is not included when determining the maximum time that the script has been running.
max_input_time sets the maximum time, in seconds, the script is allowed to receive input; this includes file uploads. For large or multiple files, or users on slower connections, the default of 60 seconds may be exceeded.
If post_max_size is set too small, large files cannot be uploaded. Make sure you set post_max_size large enough.
Not validating which file you operate on may mean that users can access sensitive information in other directories.
Please note that the CERN httpd seems to strip off everything starting at the first whitespace in the content-type mime header it gets from the client. As long as this is the case, CERN httpd will not support the file upload feature.
Due to the large amount of directory listing styles we cannot guarantee that files with exotic names (like containing spaces) are handled properly.
A developer may not mix normal input fields and file upload fields in the same form variable (by using an input name like foo[]).
Multiple files can be uploaded using different name for input.
It is also possible to upload multiple files simultaneously and have the information organized automatically in arrays for you. To do so, you need to use the same array submission syntax in the HTML form as you do with multiple selects and checkboxes:
Example #1 Uploading multiple files
<form action="file-upload.php" method="post" enctype="multipart/form-data"> Send these files:<br /> <input name="userfile[]" type="file" /><br /> <input name="userfile[]" type="file" /><br /> <input type="submit" value="Send files" /> </form>
When the above form is submitted, the arrays $_FILES['userfile'], $_FILES['userfile']['name'], and $_FILES['userfile']['size'] will be initialized (as well as in $HTTP_POST_FILES for PHP versions prior to 4.1.0). When register_globals is on, globals for uploaded files are also initialized. Each of these will be a numerically indexed array of the appropriate values for the submitted files.
For instance, assume that the filenames /home/test/review.html and /home/test/xwp.out are submitted. In this case, $_FILES['userfile']['name'][0] would contain the value review.html, and $_FILES['userfile']['name'][1] would contain the value xwp.out. Similarly, $_FILES['userfile']['size'][0] would contain review.html's file size, and so forth.
$_FILES['userfile']['name'][0], $_FILES['userfile']['tmp_name'][0], $_FILES['userfile']['size'][0], and $_FILES['userfile']['type'][0] are also set.
PHP provides support for the HTTP PUT method used by some clients to store files on a server. PUT requests are much simpler than a file upload using POST requests and they look something like this:
PUT /path/filename.html HTTP/1.1
This would normally mean that the remote client would like to save the content that follows as: /path/filename.html in your web tree. It is obviously not a good idea for Apache or PHP to automatically let everybody overwrite any files in your web tree. So, to handle such a request you have to first tell your web server that you want a certain PHP script to handle the request. In Apache you do this with the Script directive. It can be placed almost anywhere in your Apache configuration file. A common place is inside a <Directory> block or perhaps inside a <VirtualHost> block. A line like this would do the trick:
Script PUT /put.php
This tells Apache to send all PUT requests for URIs that match the context in which you put this line to the put.php script. This assumes, of course, that you have PHP enabled for the .php extension and PHP is active. The destination resource for all PUT requests to this script has to be the script itself, not a filename the uploaded file should have.
With PHP you would then do something like the following in your put.php. This would copy the contents of the uploaded file to the file myputfile.ext on the server. You would probably want to perform some checks and/or authenticate the user before performing this file copy.
Example #1 Saving HTTP PUT files
<?php
/* PUT data comes in on the stdin stream */
$putdata = fopen("php://input", "r");
/* Open a file for writing */
$fp = fopen("myputfile.ext", "w");
/* Read the data 1 KB at a time
and write to the file */
while ($data = fread($putdata, 1024))
fwrite($fp, $data);
/* Close the streams */
fclose($fp);
fclose($putdata);
?>
Ако настройката allow_url_fopen от php.ini е включена, можете да използвате HTTP и FTP URL с повечето от функциите, които приемат име на файл като параметър. Също така URL може да бъде използвано със заявките include(), include_once(), require() и require_once() (от версия 5.2.0 нататък, опцията allow_url_include трябва да е активна за да се използват последните). Вижте List of Supported Protocols/Wrappers за повече информация относно протоколите, които поддържа PHP.
Забележка: В PHP 4.0.3 и по-стари версии, за да използвате URL опаковка, беше задължително да конфигурирате PHP с опцията --enable-url-fopen-wrapper.
Забележка: Версиите на PHP за Windows по-стари от 4.3 не поддържаха достъп до отдалечен файл със следните функции: include(), include_once(),require(), require_once(), както и функциите на imagecreatefromXXX от разширението GD and Image Функции.
Например, можете да използвате тази функционалност, за да отворите файл на отдалечен уеб-сървър, да анализирате съдържанието му за данните, от които се нуждаете и след това да ги вложите в заявка към база от данни, или просто да ги визуализирате на страницата ви.
Example #1 Взимане на заглавие от отдалечена страница
<?php
$file = fopen ("http://www.example.com/", "r");
if (!$file) {
echo "<p>Unable to open remote file.\n";
exit;
}
while (!feof ($file)) {
$line = fgets ($file, 1024);
/* Това работи само ако заглавието и неговите тагове са на един ред */
if (eregi ("<title>(.*)</title>", $line, $out)) {
$title = $out[1];
break;
}
}
fclose($file);
?>
Също така можете да записвате файлове на FTP сървър (ако разбира се сте се свързали към него с валидни потребителско име и парола и имате съответните права). Използвайки този метод, вие можете да създавате само нови файлове; ако опитате да актуализирате съдържанието на предварително създаден файл, извикването на fopen() ще се провали.
За да се свържете като потребител, различен от 'anonymous', трябва да упоменете потребителско име (и вероятно парола) вътре в URL адреса, например 'ftp://user:password@ftp.example.com/path/to/file'.(Използвайте същия синтаксис, за да осъществите достъп до файлове през HTTP, когато се изисква основна идентификация.)
Example #2 Записване на данни на отдалечен сървър
<?php
$file = fopen ("ftp://ftp.example.com/incoming/outputfile", "w");
if (!$file) {
echo "<p>Unable to open remote file for writing.\n";
exit;
}
/* Записваме данните тук. */
fwrite ($file, $_SERVER['HTTP_USER_AGENT'] . "\n");
fclose ($file);
?>
Забележка: Може да ви хрумне да използвате примера отгоре, за да записвате отдалечен журнален файл (log file). За съжаление това няма да работи, понеже извикването на fopen() ще се провали, ако въпросният отдалечен журнален файл вече съществува. За да осъществите подобно отдалечено попълване на журнален файл, прегледайте функцията syslog().
Internally in PHP a connection status is maintained. There are 3 possible states:
When a PHP script is running normally the NORMAL state, is active. If the remote client disconnects the ABORTED state flag is turned on. A remote client disconnect is usually caused by the user hitting his STOP button. If the PHP-imposed time limit (see set_time_limit()) is hit, the TIMEOUT state flag is turned on.
You can decide whether or not you want a client disconnect to cause your script to be aborted. Sometimes it is handy to always have your scripts run to completion even if there is no remote browser receiving the output. The default behaviour is however for your script to be aborted when the remote client disconnects. This behaviour can be set via the ignore_user_abort php.ini directive as well as through the corresponding php_value ignore_user_abort Apache httpd.conf directive or with the ignore_user_abort() function. If you do not tell PHP to ignore a user abort and the user aborts, your script will terminate. The one exception is if you have registered a shutdown function using register_shutdown_function(). With a shutdown function, when the remote user hits his STOP button, the next time your script tries to output something PHP will detect that the connection has been aborted and the shutdown function is called. This shutdown function will also get called at the end of your script terminating normally, so to do something different in case of a client disconnect you can use the connection_aborted() function. This function will return TRUE if the connection was aborted.
Your script can also be terminated by the built-in script timer. The default timeout is 30 seconds. It can be changed using the max_execution_time php.ini directive or the corresponding php_value max_execution_time Apache httpd.conf directive as well as with the set_time_limit() function. When the timer expires the script will be aborted and as with the above client disconnect case, if a shutdown function has been registered it will be called. Within this shutdown function you can check to see if a timeout caused the shutdown function to be called by calling the connection_status() function. This function will return 2 if a timeout caused the shutdown function to be called.
One thing to note is that both the ABORTED and the TIMEOUT states can be active at the same time. This is possible if you tell PHP to ignore user aborts. PHP will still note the fact that a user may have broken the connection, but the script will keep running. If it then hits the time limit it will be aborted and your shutdown function, if any, will be called. At this point you will find that connection_status() returns 3.
Постоянните връзки са връзки, които не прекъсват при приключване на работата на скрипта. Когато бъде заявена постоянна връзка, PHP проверява дали вече съществува идентична постоянна връзка (която е заявена и оставена непрекъсната от по-рано) и ако такава съществува, тя бива използвана. Ако такава връзка не съществува, тя ще бъде създадена. "Идентична" връзка е такава, която е отворена от същия хост, със същото потребителско име и същата парола (където е приложима такава).
Хората, които не са напълно запознати с естеството на работа на уеб-сървърите и начина, по който те разпределят натоварването, могат да объркат постоянните връзки с това което те не са. По-специално те не ви дават възможност да правите 'потребителски сесии' в същата връзка, не ви дават възможност да увеличите ефективността на транзакциите, не ви дават възможност да правите и един куп други неща. Всъщност, за да бъдем пределно ясни, постоянните връзки не дават никаква допълнителна функционалност, която техните непостоянни еквиваленти да не могат да ви предоставят.
Защо?
Проблемът е обвързан с естеството на работа на уеб-сървърите. Има три начина уеб-сървърът да накара PHP да генерира уеб-страници.
Първият метод е PHP да се използва като "опаковка" от тип CGI. По този начин при всяка заявка към (PHP страница на) уеб сървъра ви се създава и унищожава една инстанция на интерпретатора на PHP. Точно поради унищожаването на тази инстанция след всяка заявка, всеки ресурс, който тя използва (например връзка към база от данни) също бива унищожен. В този случай не печелите нищо от употребата на постоянни връзки - те не остават отворени.
Вторият и най-популярен метод е стартирането на PHP като модул на уеб-сървър в многопроцесен режим, което понастоящем включва единствено Apache. Обикновено уеб сървърът в многопроцесен режим има един процес (родителски), който координира група процеси (наследници), които всъщност извършват генерирането на уеб-страници. Когато постъпи заявка от потребител, тя бива прехващана от някой от процесите наследници, който в момента не обслужва друг потребител. Това означава, че когато същият потребител направи друга заявка впоследствие, той може да бъде обслужен от различен процес наследник от този, който го е обслужвал преди това. При отварянето на постоянна връзка, всяка заявка към база от данни направена от този потребител, използва един и същи ресурс за връзка с нея.
Последният метод е PHP да се използва като приставка към многонишков уеб-сървър. Понастоящем PHP4 има поддръжка за ISAPI, WSAPI, и NSAPI (за Windows), всеки от които позволява PHP да се използва като приставка за многонишков сървър, като например Netscape FastTrack (iPlanet), Microsoft's Internet Information Server (IIS) и O'Reilly's WebSite Pro. Поведението е съвсем същото като при многопроцесния модел описан по-горе.
След като постоянните връзки нямат никаква допълнителна функционалност, защо трябва да ги използваме?
Отговорът е изключително прост - ефективност. Постоянните връзки са подходящи в случаите, когато усилието за осъществяване на връзка с базата от данни е голямо. А дали това усилие е голямо или не се определя от много фактори. Например, каква е базата от данни, дали работи на същата машина на която работи и вашия уеб-сървър, колко натоварена е тя и т.н. Равносметката е, че при голямо натоварване и голям трафик към базата от данни, постоянните връзки повишават ефективността значително. Причината е, че на процеса наследник му се налага да осъществи връзка към базата от данни само веднъж и той я използва през цялото врема на работа, вместо да осъществява връзка всеки път когато се обработва страница. Това означава също така, че на всеки процес наследник, който е отворил постоянна връзка, се полага по една такава. Например, ако имате 20 различни наследствени процеса, всеки един от които е образувал постоянна връзка към база от данни, ще имате 20 различни дълготрайни връзки, по една от всеки процес наследник.
Забележете, че това може да има някои недостатъци, ако използвате база от данни с ограничен брой налични отворени връзки и този брой е надхвърлен от броя на процесите, които се опитват да осъществят връзка. Ако базата от данни има ограничение от 16 връзки, а точно в този момент 17 процеса заявяват връзка с нея, един от тях няма да успее. Ако има програмни грешки във вашия скрипт, които не позволяват на връзките да бъдат спрени (например при безкрайни цикли), базата от данни със само 16 отворени връзки може да бъде блокирана. Потърсете информация за обработка на изоставени или чакащи връзки в документацията на базата от данни, която използвате.
Има няколко неща, които трябва да имате наум, когато използвате постоянни връзки. На първо място, когато използвате заключване на таблица заедно с постоянна връзка, ако скриптът по някаква причина не може да отключи таблицата, то тогава последващите скриптове, използващи същата постоянна връзка, ще бъдат блокирани. Ще ви се наложи да рестартирате уеб-сървъра или сървъра на базата от данни. Също така, когато използвате транзакции, имайте предвид, че транзакционният блок ще се пренесе върху следващия изпълнен скрипт, ако изпълнението на скрипта приключи преди да е приключило изпълнението на транзакцията. В който и да е от тези случаи, използвайте register_shutdown_function(), за да стартирате почистваща функция, която да отключи заключените ви таблици или да превърти транзакциите ви. Най-добре не използвайте постоянни връзки, когато използвате заключване на таблици или транзакции (можете да ги използвате при всички останали случаи).
Важна информация. Постоянните връзки са проектирани да имат съвсем същата функционалност, каквато имат и обикновените такива. Това означава, че би трябвало при всички случаи да можете да замените постоянните връзки с непостоянни и това да не промени по никакъв начин начина на работа на скриптовете ви. Това може да доведе до промяна на ефективността (и вероятно ще доведе), но не и до промяна на крайния резултат.
Вж. още fbsql_pconnect(), ibase_pconnect(), ifx_pconnect(), ingres_pconnect(), msql_pconnect(), mssql_pconnect(), mysql_pconnect(), ociplogon(), odbc_pconnect(), ora_plogon(), pfsockopen(), pg_pconnect() и sybase_pconnect().
| Име | По подразбиране | Промяна във | Промени |
|---|---|---|---|
| safe_mode | "0" | PHP_INI_SYSTEM | Премахнато в PHP 6.0.0. |
| safe_mode_gid | "0" | PHP_INI_SYSTEM | Достъпно от PHP 4.1.0. Премахнато в PHP 6.0.0. |
| safe_mode_include_dir | NULL | PHP_INI_SYSTEM | Достъпно от PHP 4.1.0. Премахнато в PHP 6.0.0. |
| safe_mode_exec_dir | "" | PHP_INI_SYSTEM | Премахнато в PHP 6.0.0. |
| safe_mode_allowed_env_vars | "PHP_" | PHP_INI_SYSTEM | Премахнато в PHP 6.0.0. |
| safe_mode_protected_env_vars | "LD_LIBRARY_PATH" | PHP_INI_SYSTEM | Премахнато в PHP 6.0.0. |
| open_basedir | NULL | PHP_INI_ALL | PHP_INI_SYSTEM в PHP < 6. |
| disable_functions | "" | php.ini only | Достъпно от PHP 4.0.1. |
| disable_classes | "" | php.ini only | Достъпно от PHP 4.3.2. |
За повече подробности и дефиниция на константите PHP_INI_* вижте ini_set().
Тук има кратко описание на конфигурационните директиви.
Указва включване на защитен режим.
По подразбиране защитният режим прави сравнителна проверка по потребителско име (UID) при отваряне на файл. Ако желаете вместо това да се прави проверка по група (GID), установете safe_mode_gid в on. Указва проверка на UID (FALSE) или GID (TRUE) при достъп до файл.
Проверките UID/GID се пропускат, когато включените файлове са от текущата директория и нейните под-папки (директорията трябва също така да бъде в include_path или трябва да се посочи пълния път).
От PHP 4.2.0 тази директива може да приема разделен с двоеточие (или точка и запетая в Windows) път, също както и include_path, вместо единична директория. Указаният път всъщност е представка, а не име на директория. Това означава, че "safe_mode_include_dir = /dir/incl" позволява достъп и до "/dir/include" и "/dir/incls", ако те разбира се съществуват. Когато искате да ограничите достъпа само до конкретна директория, завършвайте пътя с наклонена черта. Например: "safe_mode_include_dir = /dir/incl/" Ако стойността на тази директива е празна, никакви файлове с различен UID/GID не могат да бъдат включени в PHP 4.2.3 до PHP 4.3.3. В по-ранни версии, всички файлове могат да бъдат включвани.Ако PHP е стартирано в защитен режим, функцията system() и други функции стартиращи системни програми отказват да стартират програми, които не са в тази директория. Трябва да използвате / като разделител на пътя на всички операционни системи, включително и Windows.
Указването на конкретни системни променливи може да доведе до потенциален пробив в сигурността. Тази директива съдържа разделен със запетайки списък с представки. В защитен режим потребителят може да променя само тези системни променливи, които са с представката указана тук. По подразбиране на потребителите е разрешено да променят само системни променливи започващи с PHP_ (например PHP_FOO=BAR).
Забележка: Ако тази директива е празна, PHP ще позволи на потребителите да променят ВСИЧКИ системни променливи!
Тази директива съдържа разделен със запетаи списък на системни променливи, които потребителят няма да може да променя чрез функцията putenv(). Тези променливи ще бъдат защитени, дори и ако safe_mode_allowed_env_vars позволява променянето им.
Ограничава файловете, които могат да бъдат отваряни от PHP в определеното дърво от папки, включващо самия файл. Тази директива НЕ се влияе от това дали защитният режим е включен или не.
Когато даден скрипт опита да отвори файл, например чрез функцията fopen() или gzopen(), местоположението на файла бива проверено. Ако файлът е извън указаното дърво от папки, PHP няма да го отвори. Всички символни връзки се анализират, така че няма да можете да избегнете това ограничение чрез символна връзка. Ако файлът не съществува, символната връзка не може да бъде анализирана и тогава името на файла се сравнява с (анализиран) open_basedir .
Специалната стойност .
показва, че работната директория на скрипта ще бъде използвана като
базова. Това обаче е малко опасно, тъй като работната директория може да
бъде сменена лесно чрез chdir().
В httpd.conf, open_basedir може да бъде изключена (например при някои виртуални хостове) по същия начин както всяка друга конфигурационна директива с "php_admin_value open_basedir none".
В Windows разделяйте папките с точка и запетая. При всички други системи разделяйте директориите с двоеточие. Като модул на Apache, пътищата open_basedir на родителските папки се наследяват автоматично.
Указаният път всъщност е представка, а не име на директория. Това означава, че "safe_mode_include_dir = /dir/incl" позволява достъп и до "/dir/include" и "/dir/incls" ако те разбира се съществуват. Когато искате да ограничите достъпа само до конкретна директория, завършвайте пътя с наклонена черта. Например: "safe_mode_include_dir = /dir/incl/"
Забележка: Поддръжката на множество папки е добавена във версия 3.0.7.
По подразбиране всички файлове са разрешени за отваряне.
Забележка: Бележка за достъпност
Тази директива е достъпна от версия PHP 4.3.2
Вж. още: register_globals, display_errors и log_errors.
Когато защитният режим е включен, PHP проверява дали собственикът на изпълнявания скрипт е собственик и на редактирания файл или на директорията, в която е той. Например:
-rw-rw-r-- 1 rasmus rasmus 33 Jul 1 19:20 script.php -rw-r--r-- 1 root root 1116 May 26 18:01 /etc/passwd
Пускаме script.php:
<?php
readfile('/etc/passwd');
?>
резултатът е тази грешка, когато защитният режим е включен:
Warning: SAFE MODE Restriction in effect. The script whose uid is 500 is not allowed to access /etc/passwd owned by uid 0 in /docroot/script.php on line 2
Може обаче да има системи, където стриктната проверка по UID не е подходяща и не толкова стриктната проверка по GID е достатъчна. Това се контролира от директивата safe_mode_gid. Установяването й на On, указва по-хлабавата проверка по GID, а установяването й на Off (по подразбиране) - по UID.
Ако вместо защитен режим, установите директория open_basedir, тогава всички файлови операции ще бъдат ограничени за файлове, които са в указаната директория. Например (Apache httpd.conf):
<Directory /docroot> php_admin_value open_basedir /docroot </Directory>
Ако стартирате същия script.php с тази директива open_basedir, резултатът ще бъде следния:
Warning: open_basedir restriction in effect. File is in wrong directory in /docroot/script.php on line 2
Можете също да забранявате индивидуални функции. Забележете, че директивата disable_functions не може да бъде използвана извън файла php.ini, което означава, че не можете да имате различни забранени функции за различни виртуални хостове или папки във вашия файл httpd.conf. Ако добавим това в нашия файл php.ini :
disable_functions = readfile,system
Ще получим следния резултат:
Warning: readfile() has been disabled for security reasons in
/docroot/script.php on line 2
Разбира се, тези ограничения в PHP не важат за стартираните бинарни файлове.
Това е вероятно все още непълен и неправилен списък на функциите, ограничавани от защитния режим.
| Функция | Ограничения |
|---|---|
| dbmopen() | Проверява дали файловете или директориите, с които се работи, са със същия UID (собственик) като скрипта, който се изпълнява. |
| dbase_open() | Проверява дали файловете или директориите, с които се работи, са със същия UID (собственик) като скрипта, който се изпълнява. |
| filepro() | Проверява дали файловете или директориите, с които се работи, са със същия UID (собственик) като скрипта, който се изпълнява. |
| filepro_rowcount() | Проверява дали файловете или директориите, с които се работи, са със същия UID (собственик) като скрипта, който се изпълнява. |
| filepro_retrieve() | Проверява дали файловете или директориите, с които се работи, са със същия UID (собственик) като скрипта, който се изпълнява. |
| ifx_* | ограничения за sql_safe_mode, (!= защитен режим) |
| ingres_* | ограничения за sql_safe_mode, (!= защитен режим) |
| mysql_* | ограничения за sql_safe_mode, (!= защитен режим) |
| pg_lo_import() | Проверява дали файловете или директориите, с които се работи, са със същия UID (собственик) като скрипта, който се изпълнява. |
| posix_mkfifo() | Проверява дали работната директория е със същия UID (собственик) като изпълнявания скрипт. |
| putenv() | Осланя се на инициализационните директиви safe_mode_protected_env_vars и safe_mode_allowed_env_vars. За повече информация вижте документацията на putenv() |
| move_uploaded_file() | Проверява дали файловете или директориите, с които се работи, са със същия UID (собственик) като скрипта, който се изпълнява. |
| chdir() | Проверява дали работната директория е със същия UID (собственик) като изпълнявания скрипт. |
| dl() | Тази функция е забранена, когато PHP работи в защитен режим. |
| backtick operator | Тази функция е забранена, когато PHP работи в защитен режим. |
| shell_exec() (еквивалент на символите (``) във вид на функция. | Тази функция е забранена, когато PHP работи в защитен режим. |
| exec() | Можете да стартирате изпълними файлове само в директорията safe_mode_exec_dir. По практически съображения не се разрешава да имате символите .. в пътя към изпълнимия файл. Върху аргумента на тази функция се прилага escapeshellcmd(). |
| system() | Можете да стартирате изпълними файлове само в директорията safe_mode_exec_dir. По практически съображения не се разрешава да имате символите .. в пътя към изпълнимия файл. Върху аргумента на тази функция се прилага escapeshellcmd(). |
| passthru() | Можете да стартирате изпълними файлове само в директорията safe_mode_exec_dir. По практически съображения не се разрешава да имате символите .. в пътя към изпълнимия файл. Върху аргумента на тази функция се прилага escapeshellcmd(). |
| popen() | Можете да стартирате изпълними файлове само в директорията safe_mode_exec_dir. По практически съображения не се разрешава да имате символите .. в пътя към изпълнимия файл. Върху аргумента на тази функция се прилага escapeshellcmd(). |
| fopen() | Проверява дали работната директория е със същия UID (собственик) като изпълнявания скрипт. |
| mkdir() | Проверява дали работната директория е със същия UID (собственик) като изпълнявания скрипт. |
| rmdir() | Проверява дали работната директория е със същия UID (собственик) като изпълнявания скрипт. |
| rename() | Проверява дали файловете или директориите, с които се работи, са със същия UID (собственик) като скрипта, който се изпълнява. Проверява дали работната директория е със същия UID (собственик) като изпълнявания скрипт. |
| unlink() | Проверява дали файловете или директориите, с които се работи, са със същия UID (собственик) като скрипта, който се изпълнява. Проверява дали работната директория е със същия UID (собственик) като изпълнявания скрипт. |
| copy() | Проверява дали файловете или директориите, с които се работи, са със същия UID (собственик) като скрипта, който се изпълнява. Проверява дали работната директория е със същия UID (собственик) като изпълнявания скрипт. (на source и target ) |
| chgrp() | Проверява дали файловете или директориите, с които се работи, са със същия UID (собственик) като скрипта, който се изпълнява. |
| chown() | Проверява дали файловете или директориите, с които се работи, са със същия UID (собственик) като скрипта, който се изпълнява. |
| chmod() | Проверява дали файловете или директориите, с които се работи, са със същия UID (собственик) като скрипта, който се изпълнява. Освен това, не можете да указвате SUID, SGID и sticky битове |
| touch() | Проверява дали файловете или директориите, с които се работи, са със същия UID (собственик) като скрипта, който се изпълнява. Проверява дали работната директория е със същия UID (собственик) като изпълнявания скрипт. |
| symlink() | Проверява дали файловете или директориите, с които се работи, са със същия UID (собственик) като скрипта, който се изпълнява. Проверява дали работната директория е със същия UID (собственик) като изпълнявания скрипт. (забележка: само целта е проверявана) |
| link() | Проверява дали файловете или директориите, с които се работи, са със същия UID (собственик) като скрипта, който се изпълнява. Проверява дали работната директория е със същия UID (собственик) като изпълнявания скрипт. (забележка: само целта е проверявана) |
| apache_request_headers() | В защитния режим, не се връщат заглавки, започващи с 'authorization' (нечувствително към регистъра). |
| header() | В защитния режим, uid на скрипта е добавено към realm на хедъра WWW-Authenticate, ако укажете тази заглавка (използвана за HTTP автентификация). |
| PHP_AUTH variables | В защитния режим променливите PHP_AUTH_USER, PHP_AUTH_PW, и AUTH_TYPE са недостъпни в масива $_SERVER. Въпреки това, можете да използвате REMOTE_USER за USER. (забележка: важи само за версии на PHP след 4.3.0) |
| highlight_file(), show_source() | Проверява дали файловете или директориите, с които се работи, са със същия UID (собственик) като скрипта, който се изпълнява. Проверява дали работната директория е със същия UID (собственик) като изпълнявания скрипт. (забележка: важи само за версии на PHP след 4.2.1) |
| parse_ini_file() | Проверява дали файловете или директориите, с които се работи, са със същия UID (собственик) като скрипта, който се изпълнява. Проверява дали работната директория е със същия UID (собственик) като изпълнявания скрипт. (забележка: важи само за версии на PHP след 4.2.1) |
| set_time_limit() | Няма ефект когато PHP е стартирано в защитен режим. |
| max_execution_time | Няма ефект когато PHP е стартирано в защитен режим. |
| mail() | В защитен режим петият параметър е изключен. (забележка: важи само за версии на PHP след 4.2.3) |
| Всички функции, които използват php4/main/fopen_wrappers.c | ?? |
Защитният режим в PHP е опит да се реши проблема със сигурността при сървърите със споделени ресурси. Принципно, неправилно е да се решава този проблем на ниво PHP, но тъй като алтернативите на ниво операционна система и уеб-сървър не са особено удачни, много хора и най-вече доставчиците на интернет услуги използват защитния режим на PHP.
Поддръжката на защитен режим е спряна в PHP 6.0.
As of version 4.3.0, PHP supports a new SAPI type (Server Application Programming Interface) named CLI which means Command Line Interface. As the name implies, this SAPI type main focus is on developing shell (or desktop as well) applications with PHP. There are quite a few differences between the CLI SAPI and other SAPIs which are explained in this chapter. It's worth mentioning that CLI and CGI are different SAPI's although they do share many of the same behaviors.
The CLI SAPI was released for the first time with PHP 4.2.0, but was still experimental and had to be explicitly enabled with --enable-cli when running ./configure. Since PHP 4.3.0 the CLI SAPI is no longer experimental and the option --enable-cli is on by default. You may use --disable-cli to disable it.
As of PHP 4.3.0, the name, location and existence of the CLI/CGI binaries will differ depending on how PHP is installed on your system. By default when executing make, both the CGI and CLI are built and placed as sapi/cgi/php-cgi and sapi/cli/php respectively, in your PHP source directory. You will note that both are named php. What happens during make install depends on your configure line. If a module SAPI is chosen during configure, such as apxs, or the --disable-cgi option is used, the CLI is copied to {PREFIX}/bin/php during make install otherwise the CGI is placed there. So, for example, if --with--apxs is in your configure line then the CLI is copied to {PREFIX}/bin/php during make install. If you want to override the installation of the CGI binary, use make install-cli after make install. Alternatively you can specify --disable-cgi in your configure line.
Забележка: Because both --enable-cli and --enable-cgi are enabled by default, simply having --enable-cli in your configure line does not necessarily mean the CLI will be copied as {PREFIX}/bin/php during make install.
The Windows packages between PHP 4.2.0 and PHP 4.2.3 distributed the CLI as php-cli.exe, living in the same folder as the CGI php.exe. Starting with PHP 4.3.0 the Windows package distributes the CLI as php.exe in a separate folder named cli, so cli/php.exe . Starting with PHP 5, the CLI is distributed in the main folder, named php.exe. The CGI version is distributed as php-cgi.exe.
As of PHP 5, a new php-win.exe file is distributed. This is equal to the CLI version, except that php-win doesn't output anything and thus provides no console (no "dos box" appears on the screen). This behavior is similar to php-gtk. You should configure with --enable-cli-win32.
Забележка: What SAPI do I have?
From a shell, typing php -v will tell you whether php is CGI or CLI. See also the function php_sapi_name() and the constant PHP_SAPI.
Забележка: A Unix manual page was added in PHP 4.3.2. You may view this by typing man php in your shell environment.
Remarkable differences of the CLI SAPI compared to other SAPIs:
Unlike the CGI SAPI, no headers are written to the output.
Though the CGI SAPI provides a way to suppress HTTP headers, there's no equivalent switch to enable them in the CLI SAPI.
CLI is started up in quiet mode by default, though the -q and --no-header switches are kept for compatibility so that you can use older CGI scripts.
It does not change the working directory to that of the script. (-C and --no-chdir switches kept for compatibility)
Plain text error messages (no HTML formatting).
There are certain php.ini directives which are overridden by the CLI SAPI because they do not make sense in shell environments:
| Directive | CLI SAPI default value | Comment |
|---|---|---|
| html_errors | FALSE | It can be quite hard to read the error message in your shell when it's cluttered with all those meaningless HTML tags, therefore this directive defaults to FALSE. |
| implicit_flush | TRUE | It is desired that any output coming from print(), echo() and friends is immediately written to the output and not cached in any buffer. You still can use output buffering if you want to defer or manipulate standard output. |
| max_execution_time | 0 (unlimited) | Due to endless possibilities of using PHP in shell environments, the maximum execution time has been set to unlimited. Whereas applications written for the web are often executed very quickly, shell application tend to have a much longer execution time. |
| register_argc_argv | TRUE |
Because this setting is TRUE you will always have access to argc (number of arguments passed to the application) and argv (array of the actual arguments) in the CLI SAPI. As of PHP 4.3.0, the PHP variables $argc and $argv are registered and filled in with the appropriate values when using the CLI SAPI. Prior to this version, the creation of these variables behaved as they do in CGI and MODULE versions which requires the PHP directive register_globals to be on. Regardless of version or register_globals setting, you can always go through either $_SERVER or $HTTP_SERVER_VARS. Example: $_SERVER['argv'] |
Забележка: These directives cannot be initialized with another value from the configuration file php.ini or a custom one (if specified). This is a limitation because those default values are applied after all configuration files have been parsed. However, their value can be changed during runtime (which does not make sense for all of those directives, e.g. register_argc_argv).
To ease working in the shell environment, the following constants are defined:
| Constant | Description |
|---|---|
| STDIN |
An already opened stream to stdin. This saves opening it with
<?phpIf you want to read single line from stdin, you can use
<?php
|
| STDOUT | An already opened stream to stdout. This saves opening it with
<?php
|
| STDERR |
An already opened stream to stderr. This saves opening it with
<?php
|
Given the above, you don't need to open e.g. a stream for stderr yourself but simply use the constant instead of the stream resource:
php -r 'fwrite(STDERR, "stderr\n");'
You do not need to explicitly close these streams, as they are closed automatically by PHP when your script ends.
Забележка: These constants are not available in case of reading PHP script from stdin.
The CLI SAPI does not change the current directory to the directory of the executed script!
Example showing the difference to the CGI SAPI:
<?php
// Our simple test application named test.php
echo getcwd(), "\n";
?>
When using the CGI version, the output is:
$ pwd /tmp $ php -q another_directory/test.php /tmp/another_directory
This clearly shows that PHP changes its current directory to the one of the executed script.
Using the CLI SAPI yields:
$ pwd /tmp $ php -f another_directory/test.php /tmp
This allows greater flexibility when writing shell tools in PHP.
Забележка: The CGI SAPI supports this CLI SAPI behaviour by means of the -C switch when run from the command line.
The list of command line options provided by the PHP binary can be queried anytime by running PHP with the -h switch:
Usage: php [options] [-f] <file> [--] [args...]
php [options] -r <code> [--] [args...]
php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]
php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]
php [options] -- [args...]
php [options] -a
-a Run interactively
-c <path>|<file> Look for php.ini file in this directory
-n No php.ini file will be used
-d foo[=bar] Define INI entry foo with value 'bar'
-e Generate extended information for debugger/profiler
-f <file> Parse and execute <file>.
-h This help
-i PHP information
-l Syntax check only (lint)
-m Show compiled in modules
-r <code> Run PHP <code> without using script tags <?..?>
-B <begin_code> Run PHP <begin_code> before processing input lines
-R <code> Run PHP <code> for every input line
-F <file> Parse and execute <file> for every input line
-E <end_code> Run PHP <end_code> after processing all input lines
-H Hide any passed arguments from external tools.
-s Display colour syntax highlighted source.
-v Version number
-w Display source with stripped comments and whitespace.
-z <file> Load Zend extension <file>.
args... Arguments passed to script. Use -- args when first argument
starts with - or script is read from stdin
--ini Show configuration file names
--rf <name> Show information about function <name>.
--rc <name> Show information about class <name>.
--re <name> Show information about extension <name>.
--ri <name> Show configuration for extension <name>.
The CLI SAPI has three different ways of getting the PHP code you want to execute:
Telling PHP to execute a certain file.
php my_script.php php -f my_script.php
Both ways (whether using the -f switch or not) execute the file my_script.php. You can choose any file to execute - your PHP scripts do not have to end with the .php extension but can have any name or extension you wish.
Забележка: If you need to pass arguments to your scripts you need to pass -- as the first argument when using the -f switch.
Pass the PHP code to execute directly on the command line.
php -r 'print_r(get_defined_constants());'
Special care has to be taken in regards of shell variable substitution and quoting usage.
Забележка: Read the example carefully, there are no beginning or ending tags! The -r switch simply does not need them. Using them will lead to a parser error.
Provide the PHP code to execute via standard input (stdin).
This gives the powerful ability to dynamically create PHP code and feed it to the binary, as shown in this (fictional) example:
$ some_application | some_filter | php | sort -u >final_output.txt
You cannot combine any of the three ways to execute code.
Like every shell application, the PHP binary accepts a number of arguments but your PHP script can also receive arguments. The number of arguments which can be passed to your script is not limited by PHP (the shell has a certain size limit in the number of characters which can be passed; usually you won't hit this limit). The arguments passed to your script are available in the global array $argv. The zero index always contains the script name (which is - in case the PHP code is coming from either standard input or from the command line switch -r). The second registered global variable is $argc which contains the number of elements in the $argv array (not the number of arguments passed to the script).
As long as the arguments you want to pass to your script do not start with the - character, there's nothing special to watch out for. Passing an argument to your script which starts with a - will cause trouble because PHP itself thinks it has to handle it. To prevent this, use the argument list separator --. After this separator has been parsed by PHP, every argument following it is passed untouched to your script.
# This will not execute the given code but will show the PHP usage
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] <file> [args...]
[...]
# This will pass the '-h' argument to your script and prevent PHP from showing it's usage
$ php -r 'var_dump($argv);' -- -h
array(2) {
[0]=>
string(1) "-"
[1]=>
string(2) "-h"
}
However, there's another way of using PHP for shell scripting. You can write a script where the first line starts with #!/usr/bin/php. Following this you can place normal PHP code included within the PHP starting and end tags. Once you have set the execution attributes of the file appropriately (e.g. chmod +x test) your script can be executed like a normal shell or perl script:
Example #1 Execute PHP script as shell script
#!/usr/bin/php
<?php
var_dump($argv);
?>
Assuming this file is named test in the current directory, we can now do the following:
$ chmod +x test
$ ./test -h -- foo
array(4) {
[0]=>
string(6) "./test"
[1]=>
string(2) "-h"
[2]=>
string(2) "--"
[3]=>
string(3) "foo"
}
As you see, in this case no care needs to be taken when passing parameters which start with - to your script.
Long options are available since PHP 4.3.3.
| Option | Long Option | Description |
|---|---|---|
| -a | --interactive |
Runs PHP interactively. If you compile PHP with the Readline extension (which is not available on Windows), you'll have a nice shell, including a completion feature (e.g. you can start typing a variable name, hit the TAB key and PHP completes its name) and a typing history that can be accessed using the arrow keys. The history is saved in the ~/.php_history file.
|
| -c | --php-ini |
This option can either specify a directory where to look for php.ini or specify a custom INI file (which does not need to be named php.ini), e.g.: $ php -c /custom/directory/ my_script.php $ php -c /custom/directory/custom-file.ini my_script.php If you don't specify this option, file is searched in default locations. |
| -n | --no-php-ini |
Ignore php.ini at all. This switch is available since PHP 4.3.0. |
| -d | --define |
This option allows you to set a custom value for any of the configuration directives allowed in php.ini. The syntax is: -d configuration_directive[=value] Examples (lines are wrapped for layout reasons):
# Omitting the value part will set the given configuration directive to "1"
$ php -d max_execution_time
-r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(1) "1"
# Passing an empty value part will set the configuration directive to ""
php -d max_execution_time=
-r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(0) ""
# The configuration directive will be set to anything passed after the '=' character
$ php -d max_execution_time=20
-r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(2) "20"
$ php
-d max_execution_time=doesntmakesense
-r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(15) "doesntmakesense"
|
| -e | --profile-info |
Activate the extended information mode, to be used by a debugger/profiler. |
| -f | --file |
Parses and executes the given filename to the -f option. This switch is optional and can be left out. Only providing the filename to execute is sufficient.
|
| -h and -? | --help and --usage | With this option, you can get information about the actual list of command line options and some one line descriptions about what they do. |
| -i | --info | This command line option calls phpinfo(), and prints out the results. If PHP is not working correctly, it is advisable to use php -i and see whether any error messages are printed out before or in place of the information tables. Beware that when using the CGI mode the output is in HTML and therefore quite huge. |
| -l | --syntax-check |
This option provides a convenient way to only perform a syntax check on the given PHP code. On success, the text No syntax errors detected in <filename> is written to standard output and the shell return code is 0. On failure, the text Errors parsing <filename> in addition to the internal parser error message is written to standard output and the shell return code is set to -1. This option won't find fatal errors (like undefined functions). Use -f if you would like to test for fatal errors too.
|
| -m | --modules |
Using this option, PHP prints out the built in (and loaded) PHP and Zend modules: $ php -m [PHP Modules] xml tokenizer standard session posix pcre overload mysql mbstring ctype [Zend Modules] |
| -r | --run |
This option allows execution of PHP right from within the command line. The PHP start and end tags (<?php and ?>) are not needed and will cause a parser error if present.
|
| -B | --process-begin |
PHP code to execute before processing stdin. Added in PHP 5. |
| -R | --process-code |
PHP code to execute for every input line. Added in PHP 5. There are two special variables available in this mode: $argn and $argi. $argn will contain the line PHP is processing at that moment, while $argi will contain the line number. |
| -F | --process-file |
PHP file to execute for every input line. Added in PHP 5. |
| -E | --process-end |
PHP code to execute after processing the input. Added in PHP 5. Example #2 Using the -B, -R and -E options to count the number of lines of a project. $ find my_proj | php -B '$l=0;' -R '$l += count(@file($argn));' -E 'echo "Total Lines: $l\n";' Total Lines: 37328 |
| -s | --syntax-highlight and --syntax-highlighting |
Display colour syntax highlighted source. This option uses the internal mechanism to parse the file and produces a HTML highlighted version of it and writes it to standard output. Note that all it does it to generate a block of <code> [...] </code> HTML tags, no HTML headers.
|
| -v | --version |
Writes the PHP, PHP SAPI, and Zend version to standard output, e.g. $ php -v PHP 4.3.0 (cli), Copyright (c) 1997-2002 The PHP Group Zend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies |
| -w | --strip |
Display source with stripped comments and whitespace.
|
| -z | --zend-extension |
Load Zend extension. If only a filename is given, PHP tries to load this extension from the current default library path on your system (usually specified /etc/ld.so.conf on Linux systems). Passing a filename with an absolute path information will not use the systems library search path. A relative filename with a directory information will tell PHP only to try to load the extension relative to the current directory. |
| --ini |
Shows configuration file names and scanned directories. Available as of PHP 5.2.3. Example #3 --ini example $ php --ini Configuration File (php.ini) Path: /usr/dev/php/5.2/lib Loaded Configuration File: /usr/dev/php/5.2/lib/php.ini Scan for additional .ini files in: (none) Additional .ini files parsed: (none)
|
|
| --rf | --rfunction |
Shows information about the given function or class method (e.g. number and name of the parameters). Available as of PHP 5.1.2. This option is only available if PHP was compiled with Reflection support.
Example #4 basic --rf usage $ php --rf var_dump
Function [ <internal> public function var_dump ] {
- Parameters [2] {
Parameter #0 [ <required> $var ]
Parameter #1 [ <optional> $... ]
}
}
|
| --rc | --rclass |
Show information about the given class (list of constants, properties and methods). Available as of PHP 5.1.2. This option is only available if PHP was compiled with Reflection support.
Example #5 --rc example $ php --rc Directory
Class [ <internal:standard> class Directory ] {
- Constants [0] {
}
- Static properties [0] {
}
- Static methods [0] {
}
- Properties [0] {
}
- Methods [3] {
Method [ <internal> public method close ] {
}
Method [ <internal> public method rewind ] {
}
Method [ <internal> public method read ] {
}
}
}
|
| --re | --rextension |
Show information about the given extension (list of php.ini options, defined functions, constants and classes). Available as of PHP 5.1.2. This option is only available if PHP was compiled with Reflection support.
Example #6 --re example $ php --re json
Extension [ <persistent> extension #19 json version 1.2.1 ] {
- Functions {
Function [ <internal> function json_encode ] {
}
Function [ <internal> function json_decode ] {
}
}
}
|
| --ri | --rextinfo |
Shows the configuration information for the given extension (the same information that is returned by phpinfo()). Available as of PHP 5.2.2. The core configuration information are available using "main" as extension name.
Example #7 --ri example $ php --ri date date date/time support => enabled "Olson" Timezone Database Version => 2007.5 Timezone Database => internal Default timezone => Europe/Oslo Directive => Local Value => Master Value date.timezone => Europe/Oslo => Europe/Oslo date.default_latitude => 59.22482 => 59.22482 date.default_longitude => 11.018084 => 11.018084 date.sunset_zenith => 90.583333 => 90.583333 date.sunrise_zenith => 90.583333 => 90.583333
|
The PHP executable can be used to run PHP scripts absolutely independent from the web server. If you are on a Unix system, you should add a special first line to your PHP script, and make it executable, so the system will know, what program should run the script. On a Windows platform you can associate php.exe with the double click option of the .php files, or you can make a batch file to run the script through PHP. The first line added to the script to work on Unix won't hurt on Windows, so you can write cross platform programs this way. A simple example of writing a command line PHP program can be found below.
Example #8 Script intended to be run from command line (script.php)
#!/usr/bin/php
<?php
if ($argc != 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
?>
This is a command line PHP script with one option.
Usage:
<?php echo $argv[0]; ?> <option>
<option> can be some word you would like
to print out. With the --help, -help, -h,
or -? options, you can get this help.
<?php
} else {
echo $argv[1];
}
?>
In the script above, we used the special first line to indicate that this file should be run by PHP. We work with a CLI version here, so there will be no HTTP header printouts. There are two variables you can use while writing command line applications with PHP: $argc and $argv. The first is the number of arguments plus one (the name of the script running). The second is an array containing the arguments, starting with the script name as number zero ($argv[0]).
In the program above we checked if there are less or more than one arguments. Also if the argument was --help, -help, -h or -?, we printed out the help message, printing the script name dynamically. If we received some other argument we echoed that out.
If you would like to run the above script on Unix, you need to make it executable, and simply call it as script.php echothis or script.php -h. On Windows, you can make a batch file for this task:
Example #9 Batch file to run a command line PHP script (script.bat)
@echo OFF "C:\php\php.exe" script.php %*
Assuming you named the above program script.php, and you have your CLI php.exe in C:\php\php.exe this batch file will run it for you with your added options: script.bat echothis or script.bat -h.
See also the Readline extension documentation for more functions you can use to enhance your command line applications in PHP.
If you are on Windows, PHP can be configured to run without the need to supply the C:\php\php.exe or the .php extension, as descibed in Command Line PHP on Microsoft Windows.
The Alternative PHP Cache (APC) is a free and open opcode cache for PHP. Its goal is to provide a free, open, and robust framework for caching and optimizing PHP intermediate code.
Не са необходими външни библиотеки, за да се пусне това разширение.
Това » PECL разширение не е част от пакета на PHP.
Информация относно инсталирането на това PECL разширение може да се намери в главата от ръководството Инсталиране на PECL разширения. Допълнителна информация, като нови издания, изтегляния, изходни файлове, информация за поддръжката и CHANGELOG може да се намери тук: » http://pecl.php.net/package/apc.
DLL файла на това разширение може да бъде изтеглен или от страницата за » изтегляне на PHP или от » http://pecl4win.php.net/
Забележка: On Windows, APC needs a temp path to exist, and be writable by the web server. It checks TMP, TEMP, USERPROFILE environment variables in that order and finally tries the WINDOWS directory if none of those are set.
Забележка: For more in-depth, highly technical implementation details, see the » developer-supplied TECHNOTES file .
Поведението на тези функции зависи от настройките в php.ini.
Although the default APC settings are fine for many installations, serious users should consider tuning the following parameters.
There are two primary decisions to be made configuring APC. First, how much memory is going to be allocated to APC; and second, whether APC will check if a file has been modified on every request. The two ini directives that control these settings are apc.shm_size and apc.stat, respectively. Read the sections on these two directive carefully below.
Once the server is running, the apc.php script that is bundled with the extension should be copied somewhere into the docroot and viewed with a browser as it provides a detailed analysis of the internal workings of APC. If GD is enabled in PHP, it will even display some interesting graphs. The first thing to ensure, of course, is that it is actually caching files. If APC is working, the Cache full count number (on the left) will display the number of times the cache has reached maximum capacity and has had to forcefully clean any entries that haven't been accessed in the last apc.ttl seconds. This number is minimized in a well-configured cache. If the cache is constantly being filled, and thusly forcefully freed, the resulting churning will have disparaging effects on script performance. The easiest way to minimize this number is to allocate more memory for APC. Barring that, the apc.filters ought to be used to cache fewer scripts.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| apc.enabled | "1" | PHP_INI_SYSTEM | PHP_INI_SYSTEM in APC 2. PHP_INI_ALL in APC <= 3.0.12. |
| apc.shm_segments | "1" | PHP_INI_SYSTEM | |
| apc.shm_size | "30" | PHP_INI_SYSTEM | |
| apc.optimization | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in APC 2. Removed in APC 3.0.13. |
| apc.num_files_hint | "1000" | PHP_INI_SYSTEM | |
| apc.user_entries_hint | "4096" | PHP_INI_SYSTEM | Available since APC 3.0.0. |
| apc.ttl | "0" | PHP_INI_SYSTEM | Available since APC 3.0.0. |
| apc.user_ttl | "0" | PHP_INI_SYSTEM | Available since APC 3.0.0. |
| apc.gc_ttl | "3600" | PHP_INI_SYSTEM | |
| apc.cache_by_default | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in APC <= 3.0.12. Available since APC 3.0.0. |
| apc.filters | NULL | PHP_INI_SYSTEM | |
| apc.mmap_file_mask | NULL | PHP_INI_SYSTEM | |
| apc.slam_defense | "0" | PHP_INI_SYSTEM | Available since APC 3.0.0. |
| apc.file_update_protection | "2" | PHP_INI_SYSTEM | Available since APC 3.0.6. |
| apc.enable_cli | "0" | PHP_INI_SYSTEM | Available since APC 3.0.7. |
| apc.max_file_size | "1M" | PHP_INI_SYSTEM | Available since APC 3.0.7. |
| apc.stat | "1" | PHP_INI_SYSTEM | Available since APC 3.0.10. |
| apc.write_lock | "1" | PHP_INI_SYSTEM | Available since APC 3.0.11. |
| apc.report_autofilter | "0" | PHP_INI_SYSTEM | Available since APC 3.0.11. |
| apc.include_once_override | "0" | PHP_INI_SYSTEM | Available since APC 3.0.12. |
| apc.rfc1867 | "0" | PHP_INI_SYSTEM | Available since APC 3.0.13. |
| apc.rfc1867_prefix | "upload_" | PHP_INI_SYSTEM | |
| apc.rfc1867_name | "APC_UPLOAD_PROGRESS" | PHP_INI_SYSTEM | |
| apc.rfc1867_freq | "0" | PHP_INI_SYSTEM | |
| apc.localcache | "0" | PHP_INI_SYSTEM | Available since APC 3.0.14. |
| apc.localcache.size | "512" | PHP_INI_SYSTEM | Available since APC 3.0.14. |
| apc.coredump_unmap | "0" | PHP_INI_SYSTEM | Available since APC 3.0.16. |
| apc.stat_ctime | "0" | PHP_INI_SYSTEM | Available since APC 3.0.13. |
За по-детайлна информация и дефинициите на константите PHP_INI_*, вижте Where a configuration setting may be set.
Тук има кратко описание на конфигурационните директиви.
apc.enabled can be set to 0 to disable APC. This is primarily useful when APC is statically compiled into PHP, since there is no other way to disable it (when compiled as a DSO, the extension line in php.ini can just be commented-out).
The number of shared memory segments to allocate for the compiler cache. If APC is running out of shared memory but apc.shm_size is set as high as the system allows, raising this value might prevent APC from exhausting its memory.
The size of each shared memory segment in MB. By default, some systems (including most BSD variants) have very low limits on the size of a shared memory segment.
The optimization level. Zero disables the optimizer, and higher values use more aggressive optimizations. Expect very modest speed improvements. This is experimental.
A "hint" about the number of distinct source files that will be included or requested on your web server. Set to zero or omit if unsure; this setting is mainly useful for sites that have many thousands of source files.
Just like apc.num_files_hint, a "hint" about the number of distinct user cache variables to store. Set to zero or omit if not sure.
The number of seconds a cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that APC's cache could potentially fill up with stale entries while newer entries won't be cached. In the event of a cache running out of available memory, the cache will be completely expunged if ttl is equal to 0. Otherwise, if the ttl is greater than 0, APC will attempt to remove expired entries.
The number of seconds a cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that APC's cache could potentially fill up with stale entries while newer entries won't be cached. In the event of a cache running out of available memory, the cache will be completely expunged if ttl is equal to 0. Otherwise, if the ttl is greater than 0, APC will attempt to remove expired entries.
The number of seconds that a cache entry may remain on the garbage-collection list. This value provides a fail-safe in the event that a server process dies while executing a cached source file; if that source file is modified, the memory allocated for the old version will not be reclaimed until this TTL reached. Set to zero to disable this feature.
On by default, but can be set to off and used in conjunction with positive apc.filters so that files are only cached if matched by a positive filter.
A comma-separated list of POSIX extended regular expressions. If any pattern matches the source filename, the file will not be cached. Note that the filename used for matching is the one passed to include/require, not the absolute path. If the first character of the expression is a + then the expression will be additive in the sense that any files matched by the expression will be cached, and if the first character is a - then anything matched will not be cached. The - case is the default, so it can be left off.
If compiled with MMAP support by using --enable-mmap this is the mktemp-style file_mask to pass to the mmap module for determining whether your mmap'ed memory region is going to be file-backed or shared memory backed. For straight file-backed mmap, set it to something like /tmp/apc.XXXXXX (exactly 6 Xs). To use POSIX-style shm_open/mmap put a .shm somewhere in your mask. e.g. /apc.shm.XXXXXX You can also set it to /dev/zero to use your kernel's /dev/zero interface to anonymous mmap'ed memory. Leaving it undefined will force an anonymous mmap.
On very busy servers whenever you start the server or modify files you can create a race of many processes all trying to cache the same file at the same time. This option sets the percentage of processes that will skip trying to cache an uncached file. Or think of it as the probability of a single process to skip caching. For example, setting apc.slam_defense to 75 would mean that there is a 75% chance that the process will not cache an uncached file. So, the higher the setting the greater the defense against cache slams. Setting this to 0 disables this feature.
Deprecated by apc.write_lock.
When a file is modified on a live web server it really ought to be done in an atomic manner. That is, written to a temporary file and renamed (mv) the file into its permanent position when it is ready. Many text editors, cp, tar and other such programs don't do this. This means that there is a chance that a file is accessed (and cached) while it is still being written to. This apc.file_update_protection setting puts a delay on caching brand new files. The default is 2 seconds, which means that if the modification timestamp (mtime) on a file shows that it is less than 2 seconds old when it is accessed, it will not be cached. The unfortunate person who accessed this half-written file will still see weirdness, but at least it won't persist. If all of the webserver's files are atomically updated, via some method like rsync (which updates correctly), this protection can be disabled by setting this directive to 0. If the system is flooded with i/o and some update procedures are taking longer than 2 seconds, this setting should be increased to enable the protection on those slower update operations.
Mostly for testing and debugging. Setting this enables APC for the CLI version of PHP. Under normal circumstances, it is not ideal to create, populate and destroy the APC cache on every CLI request, but for various test scenarios it is useful to be able to enable APC for the CLI version of PHP easily.
Prevent files larger than this value from getting cached. Defaults to 1M.
Be careful changing this setting. This defaults to on, forcing APC to stat (check) the script on each request to determine if it has been modified. If it has been modified it will recompile and cache the new version. If this setting is off, APC will not check, which usually means that to force APC to recheck files, the web server will have to be restarted or the cache will have to be manually cleared. Note that FastCGI web server configurations may not clear the cache on restart. On a production server where the script files rarely change, a significant performance boost can be achieved by disabled stats.
For included/required files this option applies as well, but note that for relative path includes (any path that doesn't start with / on Unix) APC has to check in order to uniquely identify the file. If you use absolute path includes APC can skip the stat and use that absolute path as the unique identifier for the file.
On busy servers, when the web server is first started, or when many files have been modified at the same time, APC may try to compile and cache the same file multiple times. Write_lock guarantees that only one process will attempt to compile and cache an uncached script. The other processes attempting to use the script will run without using the opcode cache, rather than locking and waiting for the cache to prime.
Logs any scripts that were automatically excluded from being cached due to early/late binding issues.
Optimize include_once() and require_once() calls and avoid the expensive system calls used.
RFC1867 File Upload Progress hook handler is only available if APC was compiled against PHP 5.2.0 or later. When enabled, any file uploads which includes a field called APC_UPLOAD_PROGRESS before the file field in an upload form will cause APC to automatically create an upload_key user cache entry where key is the value of the APC_UPLOAD_PROGRESS form entry.
Note that the hidden field specified by APC_UPLOAD_PROGRESS must come before the file field, otherwise the upload progress will not work correctly.
Note that the file upload tracking is not threadsafe at this point, so new uploads that happen while a previous one is still going will disable the tracking for the previous.
Example #1 An apc.rfc1867 example
<?php
print_r(apc_fetch("upload_$_POST[APC_UPLOAD_PROGRESS]"));
?>
Примерът по-горе ще изведе нещо подобно на:
Array
(
[total] => 1142543
[current] => 1142543
[rate] => 1828068.8
[filename] => test
[name] => file
[temp_filename] => /tmp/php8F
[cancel_upload] => 0
[done] => 1
)
Key prefix to use for the user cache entry generated by rfc1867 upload progress functionality.
Specify the hidden form entry name that activates APC upload progress and specifies the user cache key suffix.
The frequency that updates should be made to the user cache entry for upload progress. This can take the form of a percentage of the total file size or a size in bytes optionally suffixed with "k", "m", or "g" for kilobytes, megabytes, or gigabytes respectively (case insensitive). A setting of 0 updates as often as possible, which may cause slower uploads.
This enables a lock-free local process shadow-cache which reduces lock contention when the cache is being written to.
The size of the local process shadow-cache, should be set to a sufficiently large value, approximately half of apc.num_files_hint.
Enables APC handling of signals, such as SIGSEGV, that write core files when signaled. When these signals are received, APC will attempt to unmap the shared memory segment in order to exclude it from the core file. This setting may improve system stability when fatal signals are received and a large APC shared memory segment is configured.
This feature is potentially dangerous. Unmapping the shared memory segment in a fatal signal handler may cause undefined behaviour if a fatal error occurs.
Забележка: Although some kernels may provide a facility to ignore various types of shared memory when generating a core dump file, these implementations may also ignore important shared memory segments such as the Apache scoreboard.
Verification with ctime will avoid problems caused by programs such as svn or rsync by making sure inodes haven't changed since the last stat. APC will normally only check mtime.
Това разширение няма дефинирани ресурсни типове.
Това разширение няма дефинирани константи.
(PECL apc >= 3.0.13)
apc_add — Cache a variable in the data store
Caches a variable in the data store, only if it's not already stored.
Забележка: Unlike many other mechanisms in PHP, variables stored using apc_add() will persist between requests (until the value is removed from the cache).
Store the variable using this name. key s are cache-unique, so attempting to use apc_add() to store data with a key that already exists will not overwrite the existing data, and will instead return FALSE. (This is the only difference between apc_add() and apc_store().)
The variable to store
Time To Live; store var in the cache for ttl seconds. After the ttl has passed, the stored variable will be expunged from the cache (on the next request). If no ttl is supplied (or if the ttl is 0), the value will persist until it is removed from the cache manually, or otherwise fails to exist in the cache (clear, restart, etc.).
Връща TRUE при успех или FALSE при неуспех.
Example #1 A apc_add() example
<?php
$bar = 'BAR';
apc_add('foo', $bar);
var_dump(apc_fetch('foo'));
echo "\n";
$bar = 'NEVER GETS SET';
apc_add('foo', $bar);
var_dump(apc_fetch('foo'));
echo "\n";
?>
Примерът по-горе ще изведе:
string(3) "BAR" string(3) "BAR"
(PECL apc >= 2.0.0)
apc_cache_info — Retrieves cached information from APC's data store
Retrieves cached information and meta-data from APC's data store.
Array of cached data (and meta-data), or FALSE on failure
Забележка: apc_cache_info() will raise a warning if it is unable to retrieve APC cache data. This typically occurs when APC is not enabled.
If cache_type is "user", information about the user cache will be returned.
If cache_type is "filehits", information about which files have been served from the bytecode cache for the current request will be returned. This feature must be enabled at compile time using --enable-filehits.
If an invalid or no cache_type is specified, information about the system cache (cached files) will be returned.
If limited is TRUE, the return value will exclude the individual list of cache entries. This is useful when trying to optimize calls for statistics gathering.
| Версия | Описание |
|---|---|
| 3.0.11 | The limited parameter was introduced. |
| 3.0.16 | The "filehits" option for the cache_type parameter was introduced. |
Example #1 A apc_cache_info() example
<?php
print_r(apc_cache_info());
?>
Примерът по-горе ще изведе нещо подобно на:
Array
(
[num_slots] => 2000
[ttl] => 0
[num_hits] => 9
[num_misses] => 3
[start_time] => 1123958803
[cache_list] => Array
(
[0] => Array
(
[filename] => /path/to/apc_test.php
[device] => 29954
[inode] => 1130511
[type] => file
[num_hits] => 1
[mtime] => 1123960686
[creation_time] => 1123960696
[deletion_time] => 0
[access_time] => 1123962864
[ref_count] => 1
[mem_size] => 677
)
[1] => Array (...iterates for each cached file)
)
(PECL apc >= 2.0.0)
apc_clear_cache — Clears the APC cache
Clears the user/system cache.
Връща TRUE при успех или FALSE при неуспех.
If cache_type is "user", the user cache will be cleared; otherwise, the system cache (cached files) will be cleared.
(PECL apc >= 3.0.13)
apc_compile_file — Stores a file in the bytecode cache, bypassing all filters.
Stores a file in the bytecode cache, bypassing all filters.
Full or relative path to a PHP file that will be compiled and stored in the bytecode cache.
Връща TRUE при успех или FALSE при неуспех.
(PECL apc >= 3.0.0)
apc_define_constants — Defines a set of constants for retrieval and mass-definition
define() is notoriously slow. Since the main benefit of APC is to increase the performance of scripts/applications, this mechanism is provided to streamline the process of mass constant definition. However, this function does not perform as well as anticipated.
For a better-performing solution, try the » hidef extension from PECL.
Забележка: To remove a set of stored constants (without clearing the entire cache), an empty array may be passed as the constants parameter, effectively clearing the stored value(s).
The key serves as the name of the constant set being stored. This key is used to retrieve the stored constants in apc_load_constants().
An associative array of constant_name => value pairs. The constant_name must follow the normal constant naming rules. value must evaluate to a scalar value.
The default behaviour for constants is to be declared case-sensitive; i.e. CONSTANT and Constant represent different values. If this parameter evaluates to FALSE the constants will be declared as case-insensitive symbols.
Връща TRUE при успех или FALSE при неуспех.
Example #1 apc_define_constants() example
<?php
$constants = array(
'ONE' => 1,
'TWO' => 2,
'THREE' => 3,
);
apc_define_constants('numbers', $constants);
echo ONE, TWO, THREE;
?>
Примерът по-горе ще изведе:
123
(PECL apc >= 3.0.0)
apc_delete — Removes a stored variable from the cache
Removes a stored variable from the cache.
Връща TRUE при успех или FALSE при неуспех.
Example #1 A apc_delete() example
<?php
$bar = 'BAR';
apc_store('foo', $bar);
apc_delete('foo');
// this is obviously useless in this form
?>
(PECL apc >= 3.0.0)
apc_fetch — Fetch a stored variable from the cache
Fetchs a stored variable from the cache.
The key used to store the value (with apc_store()).
Set to TRUE in success and FALSE in failure.
The stored variable on success; FALSE on failure
Example #1 A apc_fetch() example
<?php
$bar = 'BAR';
apc_store('foo', $bar);
var_dump(apc_fetch('foo'));
?>
Примерът по-горе ще изведе:
string(3) "BAR"
(PECL apc >= 3.0.0)
apc_load_constants — Loads a set of constants from the cache
Loads a set of constants from the cache.
The name of the constant set (that was stored with apc_define_constants()) to be retrieved.
The default behaviour for constants is to be declared case-sensitive; i.e. CONSTANT and Constant represent different values. If this parameter evaluates to FALSE the constants will be declared as case-insensitive symbols.
Връща TRUE при успех или FALSE при неуспех.
Example #1 apc_load_constants() example
<?php
$constants = array(
'ONE' => 1,
'TWO' => 2,
'THREE' => 3,
);
apc_define_constants('numbers', $constants);
apc_load_constants('numbers');
echo ONE, TWO, THREE;
?>
Примерът по-горе ще изведе:
123
(PECL apc >= 2.0.0)
apc_sma_info — Retrieves APC's Shared Memory Allocation information
Retrieves APC's Shared Memory Allocation information.
When set to FALSE (default) apc_sma_info() will return a detailed information about each segment.
Array of Shared Memory Allocation data; FALSE on failure.
Example #1 A apc_sma_info() example
<?php
print_r(apc_sma_info());
?>
Примерът по-горе ще изведе нещо подобно на:
Array
(
[num_seg] => 1
[seg_size] => 31457280
[avail_mem] => 31448408
[block_lists] => Array
(
[0] => Array
(
[0] => Array
(
[size] => 31448408
[offset] => 8864
)
)
)
)
(PECL apc >= 3.0.0)
apc_store — Cache a variable in the data store
Cache a variable in the data store.
Забележка: Unlike many other mechanisms in PHP, variables stored using apc_store() will persist between requests (until the value is removed from the cache).
Store the variable using this name. key s are cache-unique, so storing a second value with the same key will overwrite the original value.
The variable to store
Time To Live; store var in the cache for ttl seconds. After the ttl has passed, the stored variable will be expunged from the cache (on the next request). If no ttl is supplied (or if the ttl is 0), the value will persist until it is removed from the cache manually, or otherwise fails to exist in the cache (clear, restart, etc.).
Връща TRUE при успех или FALSE при неуспех.
Example #1 A apc_store() example
<?php
$bar = 'BAR';
apc_store('foo', $bar);
var_dump(apc_fetch('foo'));
?>
Примерът по-горе ще изведе:
string(3) "BAR"
APD is the Advanced PHP Debugger. It was written to provide profiling and debugging capabilities for PHP code, as well as to provide the ability to print out a full stack backtrace. APD supports interactive debugging, but by default it writes data to trace files. It also offers event based logging so that varying levels of information (including function calls, arguments passed, timings, etc.) can be turned on or off for individual scripts.
APD is a Zend Extension, modifying the way the internals of PHP handle function calls, and thus may or may not be compatible with other Zend Extensions (for example Zend Optimizer).
Не са необходими външни библиотеки, за да се пусне това разширение.
APD is currently available as a PECL extension from » http://pecl.php.net/package/apd.
Run the following command to download, build, and install the latest stable version of APD:
pear install apd
This automatically installs the APD Zend module into your PHP extensions directory. It is not mandatory to keep it there; you can store the module in any directory PHP can read as long as you set the zend_extension parameter accordingly.
Windows users will enable php_apd.dll inside of php.ini in order to use these functions. DLL файла на това разширение може да бъде изтеглен или от страницата за » изтегляне на PHP или от » http://pecl4win.php.net/
In your INI file, add the following lines:
zend_extension = /absolute/path/to/apd.so apd.dumpdir = /absolute/path/to/trace/directory apd.statement_tracing = 0
Depending on your PHP build, the zend_extension directive can be one of the following:
zend_extension (non ZTS, non debug build) zend_extension_ts ( ZTS, non debug build) zend_extension_debug (non ZTS, debug build) zend_extension_debug_ts ( ZTS, debug build)
To build APD under Windows you need a working PHP compilation environment as described on http://php.net/ -- basically, it requires you to have Microsoft Visual C++, win32build.zip, bison/flex, and some know how to get it to work. Also ensure that adp.dsp has DOS line endings; if it has unix line endings, Microsoft Visual C++ will complain about it.
Поведението на тези функции зависи от настройките в php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| apd.dumpdir | NULL | PHP_INI_ALL | |
| apd.statement_tracing | "0" | PHP_INI_ALL | Available since apd 0.9. |
За по-детайлна информация и дефинициите на константите PHP_INI_*, вижте Where a configuration setting may be set.
Тук има кратко описание на конфигурационните директиви.
Sets the directory in which APD writes profile dump files. You can specify an absolute path or a relative path.
You can specify a different directory as an argument to apd_set_pprof_trace().
Specfies whether or not to do per-line tracings. Turning this on (1) will impact the performance of your application.
Това разширение няма дефинирани ресурсни типове.
Константите по-долу са дефинирани в това разширение и ще бъдат налични единствено, когато това разширение е компилирано в PHP или пуснато динамично по време на изпълнение.
| Constant | Value | Description |
|---|---|---|
| FUNCTION_TRACE (integer) | 1 | |
| ARGS_TRACE (integer) | 2 | |
| ASSIGNMENT_TRACE (integer) | 4 | |
| STATEMENT_TRACE (integer) | 8 | |
| MEMORY_TRACE (integer) | 16 | |
| TIMING_TRACE (integer) | 32 | |
| SUMMARY_TRACE (integer) | 64 | |
| ERROR_TRACE (integer) | 128 | |
| PROF_TRACE (integer) | 256 | |
| APD_VERSION (string) | example: 1.0.2-dev |
As the first line of your PHP script, call the apd_set_pprof_trace() function to start the trace:
apd_set_pprof_trace();
You can insert the line anywhere in your script, but if you do not start tracing at the beginning of your script you discard profile data that might otherwise lead you to a performance bottleneck.
Now run your script. The dump output will be written to apd.dumpdir/pprof_pid.ext.
If you're running the CGI version of PHP, you will need to add the '-e'
flag to enable extended information for apd to work properly. For
example:
php -e -f script.php
To display formatted profile data, issue the pprofp command with the sort and display options of your choice. The formatted output will look something like:
bash-2.05b$ pprofp -R /tmp/pprof.22141.0 Trace for /home/dan/testapd.php Total Elapsed Time = 0.00 Total System Time = 0.00 Total User Time = 0.00 Real User System secs/ cumm %Time (excl/cumm) (excl/cumm) (excl/cumm) Calls call s/call Memory Usage Name -------------------------------------------------------------------------------------- 100.0 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0000 0.0009 0 main 56.9 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0005 0.0005 0 apd_set_pprof_trace 28.0 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 preg_replace 14.3 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 str_replace
The -R option used in this example sorts the profile table by the amount of real time the script spent executing a given function. The "cumm call" column reveals how many times each function was called, and the "s/call" column reveals how many seconds each call to the function required, on average.
To generate a calltree file that you can import into the KCacheGrind profile analysis application, issue the pprof2calltree comand.
(PECL apd >= 0.2)
apd_breakpoint — Stops the interpreter and waits on a CR from the socket
This can be used to stop the running of your script, and await responses on the connected socket. To step the program, just send enter (a blank line), or enter a php command to be executed.
Цяло число, образувано при добавянето на XXX_TRACE константите.
Не се препоръчва употребата на MEMORY_TRACE. Много е бавно и не е много точно. ASSIGNMENT_TRACE все още не е реализирана.
За да включите всички ункционални трасировки (TIMING, FUNCTIONS, ARGS SUMMARY (като strace -c)) използвайте стойността 99
Връща TRUE при успех или FALSE при неуспех.
Example #1 Typical session using tcplisten
bash#tcplisten localhost 7777
APD - Advanced PHP Debugger Trace File
---------------------------------------------------------------------------
Process Pid (6118)
Trace Begun at Sun Mar 10 23:13:12 2002
---------------------------------------------------------------------------
( 0.000000): apd_set_session_trace called at /home/alan/Projects/project2/test.
php:5
( 0.074824): apd_set_session_trace_socket() at /home/alan/Projects/project2/tes
t.php:5 returned. Elapsed (0.074824)
( 0.074918): apd_breakpoint() /home/alan/Projects/project2/test.php:7
++ argv[0] $(??) = 9
apd_breakpoint() at /home/alan/Projects/project2/test.php:7 returned. Elapsed (
-2089521468.1073275368)
>\n
statement: /home/alan/Projects/project2/test.php:8
>\n
statement: /home/alan/Projects/project2/test.php:8
>\n
statement: /home/alan/Projects/project2/test.php:10
>apd_echo($i);
EXEC: apd_echo($i);
0
>apd_echo(serialize(apd_get_active_symbols()));
EXEC: apd_echo(serialize(apd_get_active_symbols()));
a:47:{i:0;s:4:"PWD";i:1;s:10:"COLORFGBG";i:2;s:11:"XAUTHORITY";i:3;s:14:"
COLORTERM_BCE";i:4;s:9:"WINDOWID";i:5;s:14:"ETERM_VERSION";i:6;s:16:"SE
SSION_MANAGER";i:7;s:4:"PS1";i:8;s:11:"GDMSESSION";i:9;s:5:"USER";i:10;s:5:"
MAIL";i:11;s:7:"OLDPWD";i:12;s:5:"LANG";i:13;s:10:"COLORTERM";i:14;s:8:"DISP
LAY";i:15;s:8:"LOGNAME";i:16;s:6:"
>apd_echo(system('ls /home/mydir'));
........
>apd_continue(0);
(PECL apd 0.2-0.4)
apd_callstack — Returns the current call stack as an array
Returns the current call stack as an array
An array containing the current call stack.
Example #1 apd_callstack() example
<?php
print_r(apd_callstack());
?>
(PECL apd 0.2-0.4)
apd_clunk — Throw a warning and a callstack
Behaves like perl's Carp::cluck. Throw a warning and a callstack.
The warning to throw.
The delimiter. Default to <BR />.
Няма връщана стойност.
Example #1 apd_clunk() example
<?php
apd_clunk("Some Warning", "<br/>");
?>
(PECL apd >= 0.2)
apd_continue — Restarts the interpreter
Usually sent via the socket to restart the interpreter.
Цяло число, образувано при добавянето на XXX_TRACE константите.
Не се препоръчва употребата на MEMORY_TRACE. Много е бавно и не е много точно. ASSIGNMENT_TRACE все още не е реализирана.
За да включите всички ункционални трасировки (TIMING, FUNCTIONS, ARGS SUMMARY (като strace -c)) използвайте стойността 99
Връща TRUE при успех или FALSE при неуспех.
Example #1 apd_continue() example
<?php
apd_continue(0);
?>
(PECL apd 0.2-0.4)
apd_croak — Throw an error, a callstack and then exit
Behaves like perl's Carp::croak. Throw an error, a callstack and then exit.
The warning to throw.
The delimiter. Default to <BR />.
Няма връщана стойност.
Example #1 apd_croak() example
<?php
apd_croak("Some Warning","<P>");
?>
(Unknown)
apd_dump_function_table — Outputs the current function table
Outputs the current function table.
Няма връщана стойност.
Example #1 apd_dump_function_table() example
<?php
apd_dump_function_table();
?>
(PECL apd 0.2-0.4)
apd_dump_persistent_resources — Return all persistent resources as an array
Return all persistent resources as an array.
An array containing the current call stack.
Example #1 apd_dump_persistent_resources() example
<?php
print_r(apd_dump_persistent_resources());
?>
(PECL apd 0.2-0.4)
apd_dump_regular_resources — Return all current regular resources as an array
Return all current regular resources as an array.
An array containing the current regular resources.
Example #1 apd_dump_regular_resources() example
<?php
print_r(apd_dump_regular_resources());
?>
(PECL apd >= 0.2)
apd_echo — Echo to the debugging socket
Usually sent via the socket to request information about the running script.
The debugged variable.
Връща TRUE при успех или FALSE при неуспех.
Example #1 apd_echo() example
<?php
apd_echo($i);
?>
(PECL apd 0.2)
apd_get_active_symbols — Get an array of the current variables names in the local scope
Returns the names of all the variables defined in the active scope, (not their values).
A multidimensional array with all the variables.
Example #1 apd_get_active_symbols() example
<?php
apd_echo(apd_get_active_symbols());
?>
(PECL apd >= 0.2)
apd_set_pprof_trace — Starts the session debugging
Starts debugging to pprof_{process_id} in the dump directory.
The directory in which the profile dump file is written. If not set, the apd.dumpdir setting from the php.ini file is used.
Returns path of the destination file.
Example #1 apd_set_pprof_trace() example
<?php
apd_set_pprof_trace();
?>
(PECL apd >= 0.2)
apd_set_session_trace_socket — Starts the remote session debugging
Connects to the specified tcp_server (eg. tcplisten) and sends debugging data to the socket.
IP or Unix Domain socket (like a file) of the TCP server.
Can be AF_UNIX for file based sockets or APD_AF_INET for standard tcp/ip.
You can use any port, but higher numbers are better as most of the lower numbers may be used by other system services.
Цяло число, образувано при добавянето на XXX_TRACE константите.
Не се препоръчва употребата на MEMORY_TRACE. Много е бавно и не е много точно. ASSIGNMENT_TRACE все още не е реализирана.
За да включите всички ункционални трасировки (TIMING, FUNCTIONS, ARGS SUMMARY (като strace -c)) използвайте стойността 99
Връща TRUE при успех или FALSE при неуспех.
Example #1 apd_set_session_trace_socket() example
<?php
apd_set_session_trace_socket("127.0.0.1",APD_AF_INET,7112,0);
?>
(PECL apd 0.2-0.4)
apd_set_session_trace — Starts the session debugging
Starts debugging to apd_dump_{process_id} in the dump directory.
Цяло число, образувано при добавянето на XXX_TRACE константите.
Не се препоръчва употребата на MEMORY_TRACE. Много е бавно и не е много точно. ASSIGNMENT_TRACE все още не е реализирана.
За да включите всички ункционални трасировки (TIMING, FUNCTIONS, ARGS SUMMARY (като strace -c)) използвайте стойността 99
The directory in which the profile dump file is written. If not set, the apd.dumpdir setting from the php.ini file is used.
Няма връщана стойност.
Example #1 apd_set_session_trace() example
<?php
apd_set_session_trace(99);
?>
(PECL apd 0.2-0.4)
apd_set_session — Changes or sets the current debugging level
This can be used to increase or decrease debugging in a different area of your application.
Цяло число, образувано при добавянето на XXX_TRACE константите.
Не се препоръчва употребата на MEMORY_TRACE. Много е бавно и не е много точно. ASSIGNMENT_TRACE все още не е реализирана.
За да включите всички ункционални трасировки (TIMING, FUNCTIONS, ARGS SUMMARY (като strace -c)) използвайте стойността 99
Няма връщана стойност.
Example #1 apd_set_session() example
<?php
apd_set_session(9);
?>
(PECL apd >= 0.2)
override_function — Overrides built-in functions
Overrides built-in functions by replacing them in the symbol table.
The function to override.
The function arguments, as a coma separated string.
Usually you will want to pass this parameter, as well as the function_code parameter, as a single quote delimited string. The reason for using single quoted strings, is to protect the variable names from parsing, otherwise, if you use double quotes there will be a need to escape the variable names, e.g. \$your_var.
The new code for the function.
Връща TRUE при успех или FALSE при неуспех.
Example #1 override_function() example
<?php
override_function('test', '$a,$b', 'echo "DOING TEST"; return $a * $b;');
?>
(PECL apd >= 0.2)
rename_function — Renames orig_name to new_name in the global function table
Renames a orig_name to new_name in the global function table. Useful for temporarily overriding built-in functions.
The original function name.
The new name for the original_name function.
Връща TRUE при успех или FALSE при неуспех.
Example #1 rename_function() example
<?php
rename_function('mysql_connect', 'debug_mysql_connect' );
?>
If you have comments, bugfixes, enhancements or want to help developing this beast, you can send an mail to » apd@mail.communityconnect.com. Any help is very welcome.
Това разширение е ЕКСПЕРИМЕНТАЛНО. Поведението на разширението, включително имената на функциите и всичко останало, което е документирано за това разширение, могат да бъдат променени без предупреждение в бъдеща версия на PHP. Това разширение би трябвало да бъде използвано единствено на ваша собствена отговорност.
Bcompiler was written for several reasons:
The first of these goals is achieved using the bcompiler_write_header(), bcompiler_write_file() and bcompiler_write_footer() functions. The bytecode files can be written as either uncompressed or plain. To use the generated bytecode, you can simply include it with include or require statements.
The second of these goals is achieved using the bcompiler_write_header(), bcompiler_write_class(), bcompiler_write_footer(), bcompiler_read(), and bcompiler_load() functions. The bytecode files can be written as either uncompressed or plain. The bcompiler_load() reads a bzip compressed bytecode file, which tends to be 1/3 of the size of the original file.
To create EXE type files, bcompiler has to be used with a modified sapi file or a version of PHP which has been compiled as a shared library. In this scenario, bcompiler reads the compressed bytecode from the end of the exe file.
bcompiler can improve performance by about 30% when used with uncompressed bytecodes only. But keep in mind that uncompressed bytecode can be up to 5 times larger than the original source code. Using bytecode compression can save your space, but decompression requires much more time than parsing a source. bcompiler also does not do any bytecode optimization, this could be added in the future...
In terms of code protection, it is safe to say that it would be impossible to recreate the exact source code that it was built from, and without the accompanying source code comments. It would effectively be useless to use the bcompiler bytecodes to recreate and modify a class. However it is possible to retrieve data from a bcompiled bytecode file - so don't put your private passwords or anything in it.
Не са необходими външни библиотеки, за да се пусне това разширение.
short installation note:
Това разширение няма дефинирани конфигурационни директиви в php.ini.
Това разширение няма дефинирани ресурсни типове.
Това разширение няма дефинирани константи.
(PECL bcompiler >= 0.4)
bcompiler_load_exe — Reads and creates classes from a bcompiler exe file
Reads data from a bcompiler exe file and creates classes from the bytecodes.
The exe file path, as a string.
Връща TRUE при успех или FALSE при неуспех.
Example #1 bcompiler_load_exe() example
<?php
bcompiler_load_exe("/tmp/example.exe");
print_r(get_defined_classes());
?>
Тази функция е ЕКСПЕРИМЕНТАЛНА. Поведението на функцията, името й, както и съпътстващата документация, могат да бъдат променени без предупреждение в бъдеща версия на PHP. Тази функция би трябвало да бъде използвана единствено на ваша собствена отговорност.
(PECL bcompiler >= 0.4)
bcompiler_load — Reads and creates classes from a bz compressed file
Reads data from a bzcompressed file and creates classes from the bytecodes.
The bzcompressed file path, as a string.
Връща TRUE при успех или FALSE при неуспех.
Example #1 bcompiler_load() example
<?php
bcompiler_load("/tmp/example");
print_r(get_defined_classes());
?>
Тази функция е ЕКСПЕРИМЕНТАЛНА. Поведението на функцията, името й, както и съпътстващата документация, могат да бъдат променени без предупреждение в бъдеща версия на PHP. Тази функция би трябвало да бъде използвана единствено на ваша собствена отговорност.
Забележка: Please use include or require statements to parse bytecodes, it's more portable and convenient way than using this function.
Please note that this function won't execute script body code contained in the bytecode file.
(PECL bcompiler >= 0.4)
bcompiler_parse_class — Reads the bytecodes of a class and calls back to a user function
Reads the bytecodes of a class and calls back to a user function.
The class name, as a string.
Връща TRUE при успех или FALSE при неуспех.
Example #1 bcompiler_parse_class() example
<?php
function readByteCodes($data) {
print_r($data);
}
bcompiler_parse_class("DB","readByteCodes");
?>
Тази функция е ЕКСПЕРИМЕНТАЛНА. Поведението на функцията, името й, както и съпътстващата документация, могат да бъдат променени без предупреждение в бъдеща версия на PHP. Тази функция би трябвало да бъде използвана единствено на ваша собствена отговорност.
Забележка: This function has been removed from bcompiler and is no longer available as of bcompiler 0.5.
(PECL bcompiler >= 0.4)
bcompiler_read — Reads and creates classes from a filehandle
Reads data from a open file handle and creates classes from the bytecodes.
Връща TRUE при успех или FALSE при неуспех.
Example #1 bcompiler_read() example
<?php
$fh = fopen("/tmp/example","r");
bcompiler_read($fh);
fclose($fh);
print_r(get_defined_classes());
?>
Тази функция е ЕКСПЕРИМЕНТАЛНА. Поведението на функцията, името й, както и съпътстващата документация, могат да бъдат променени без предупреждение в бъдеща версия на PHP. Тази функция би трябвало да бъде използвана единствено на ваша собствена отговорност.
Забележка: Please use include or require statements to parse bytecodes, it's more portable and convenient way than using this function.
Please note that this function won't execute script body code contained in the bytecode file.
(PECL bcompiler >= 0.4)
bcompiler_write_class — Writes an defined class as bytecodes
Reads the bytecodes from PHP for an existing class, and writes them to the open file handle.
A file handle as returned by fopen().
The class name, as a string.
Връща TRUE при успех или FALSE при неуспех.
Example #1 bcompiler_write_class() example
<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
// you must write DB_common before DB_mysql, as DB_mysql extends DB_common.
bcompiler_write_class($fh,"DB_common");
bcompiler_write_class($fh,"DB_mysql");
bcompiler_write_footer($fh);
fclose($fh);
?>
Тази функция е ЕКСПЕРИМЕНТАЛНА. Поведението на функцията, името й, както и съпътстващата документация, могат да бъдат променени без предупреждение в бъдеща версия на PHP. Тази функция би трябвало да бъде използвана единствено на ваша собствена отговорност.
Забележка: This function does not perform dependency checking, so make sure you write the classes in an order that will not result in an undefined class error occurring when you load it.
(PECL bcompiler >= 0.5)
bcompiler_write_constant — Writes a defined constant as bytecodes
Reads the bytecodes from PHP for an existing constant, and writes them to the open file handle.
A file handle as returned by fopen().
The name of the defined constant, as a string.
Връща TRUE при успех или FALSE при неуспех.
Example #1 bcompiler_write_constant() example
<?php
define("MODULE_MAX", 30);
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_constant($fh,"MODULE_MAX");
bcompiler_write_footer($fh);
fclose($fh);
?>
Тази функция е ЕКСПЕРИМЕНТАЛНА. Поведението на функцията, името й, както и съпътстващата документация, могат да бъдат променени без предупреждение в бъдеща версия на PHP. Тази функция би трябвало да бъде използвана единствено на ваша собствена отговорност.
(PECL bcompiler >= 0.6)
bcompiler_write_file — Writes a php source file as bytecodes
This function complies specified source file into bytecodes, and writes them to the open file handle.
A file handle as returned by fopen().
The source file path, as a string.
Връща TRUE при успех или FALSE при неуспех.
Example #1 bcompiler_write_file() example
<?php
$fh = fopen("example.phb", "w");
bcompiler_write_header($fh);
bcompiler_write_file($fh, "example.php");
bcompiler_write_footer($fh);
fclose($fh);
/* the following should be equivalent:
include "example.php";
and
include "example.phb";
*/
?>
Тази функция е ЕКСПЕРИМЕНТАЛНА. Поведението на функцията, името й, както и съпътстващата документация, могат да бъдат променени без предупреждение в бъдеща версия на PHP. Тази функция би трябвало да бъде използвана единствено на ваша собствена отговорност.
(PECL bcompiler >= 0.5)
bcompiler_write_function — Writes an defined function as bytecodes
Reads the bytecodes from PHP for an existing function, and writes them to the open file handle. Order is not important, (eg. if function b uses function a, and you compile it like the example below, it will work perfectly OK).
A file handle as returned by fopen().
The function name, as a string.
Връща TRUE при успех или FALSE при неуспех.
Example #1 bcompiler_write_function() example
<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_function($fh,"my_function_a");
bcompiler_write_function($fh,"my_function_b");
bcompiler_write_footer($fh);
fclose($fh);
?>
Тази функция е ЕКСПЕРИМЕНТАЛНА. Поведението на функцията, името й, както и съпътстващата документация, могат да бъдат променени без предупреждение в бъдеща версия на PHP. Тази функция би трябвало да бъде използвана единствено на ваша собствена отговорност.
(PECL bcompiler >= 0.5)
bcompiler_write_functions_from_file — Writes all functions defined in a file as bytecodes
Searches for all functions declared in the given file, and writes their correspondent bytecodes to the open file handle.
A file handle as returned by fopen().
The file to be compiled. You must always include or require the file you intend to compile.
Връща TRUE при успех или FALSE при неуспех.
Example #1 bcompiler_write_functions_from_file() example
<?php
require('module.php');
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_functions_from_file($fh,'module.php');
bcompiler_write_footer($fh);
fclose($fh);
?>
Тази функция е ЕКСПЕРИМЕНТАЛНА. Поведението на функцията, името й, както и съпътстващата документация, могат да бъдат променени без предупреждение в бъдеща версия на PHP. Тази функция би трябвало да бъде използвана единствено на ваша собствена отговорност.
(PECL bcompiler >= 0.3)
bcompiler_write_header — Writes the bcompiler header
Writes the header part of a bcompiler file.
A file handle as returned by fopen().
Can be used to write bytecode in a previously used format, so that you can use it with older versions of bcompiler.
Връща TRUE при успех или FALSE при неуспех.
Example #1 bcompiler_write_header() example
<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
bcompiler_write_footer($fh);
fclose($fh);
?>
Тази функция е ЕКСПЕРИМЕНТАЛНА. Поведението на функцията, името й, както и съпътстващата документация, могат да бъдат променени без предупреждение в бъдеща версия на PHP. Тази функция би трябвало да бъде използвана единствено на ваша собствена отговорност.
(PECL bcompiler >= 0.5)
bcompiler_write_included_filename — Writes an included file as bytecodes
Към момента тази функция не е документирана; наличен е единствено списъкът с аргументите й.
Връща TRUE при успех или FALSE при неуспех.
Тази функция е ЕКСПЕРИМЕНТАЛНА. Поведението на функцията, името й, както и съпътстващата документация, могат да бъдат променени без предупреждение в бъдеща версия на PHP. Тази функция би трябвало да бъде използвана единствено на ваша собствена отговорност.
If you have comments, bugfixes, enhancements or want to help developing this beast, you can drop me a mail at » alan_k@php.net. Any help is very welcome.
These are functions dealing with error handling and logging. They allow you to define your own error handling rules, as well as modify the way the errors can be logged. This allows you to change and enhance error reporting to suit your needs.
With the logging functions, you can send messages directly to other machines, to an email (or email to pager gateway!), to system logs, etc., so you can selectively log and monitor the most important parts of your applications and websites.
The error reporting functions allow you to customize what level and kind of error feedback is given, ranging from simple notices to customized functions returned during errors.
Не са необходими външни библиотеки, за да се пусне това разширение.
Не е необходимо инсталиране, за да се използват тези функции. Те са част от ядрото на PHP.
Поведението на тези функции зависи от настройките в php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| error_reporting | NULL | PHP_INI_ALL | |
| display_errors | "1" | PHP_INI_ALL | |
| display_startup_errors | "0" | PHP_INI_ALL | |
| log_errors | "0" | PHP_INI_ALL | |
| log_errors_max_len | "1024" | PHP_INI_ALL | Available since PHP 4.3.0. |
| ignore_repeated_errors | "0" | PHP_INI_ALL | Available since PHP 4.3.0. |
| ignore_repeated_source | "0" | PHP_INI_ALL | Available since PHP 4.3.0. |
| report_memleaks | "1" | PHP_INI_ALL | Available since PHP 4.3.0. |
| track_errors | "0" | PHP_INI_ALL | |
| html_errors | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP <= 4.2.3. |
| xmlrpc_errors | "0" | PHP_INI_SYSTEM | Available since PHP 4.1.0. |
| xmlrpc_error_number | "0" | PHP_INI_ALL | Available since PHP 4.1.0. |
| docref_root | "" | PHP_INI_ALL | Available since PHP 4.3.0. |
| docref_ext | "" | PHP_INI_ALL | Available since PHP 4.3.2. |
| error_prepend_string | NULL | PHP_INI_ALL | |
| error_append_string | NULL | PHP_INI_ALL | |
| error_log | NULL | PHP_INI_ALL |
За по-детайлна информация и дефинициите на константите PHP_INI_*, вижте Where a configuration setting may be set.
Тук има кратко описание на конфигурационните директиви.
Set the error reporting level. The parameter is either an integer representing a bit field, or named constants. The error_reporting levels and constants are described in Predefined Constants, and in php.ini. To set at runtime, use the error_reporting() function. See also the display_errors directive.
In PHP 4 and PHP 5 the default value is E_ALL & ~E_NOTICE. This setting does not show E_NOTICE level errors. You may want to show them during development.
Забележка: Enabling E_NOTICE during development has some benefits. For debugging purposes: NOTICE messages will warn you about possible bugs in your code. For example, use of unassigned values is warned. It is extremely useful to find typos and to save time for debugging. NOTICE messages will warn you about bad style. For example, $arr[item] is better to be written as $arr['item'] since PHP tries to treat "item" as constant. If it is not a constant, PHP assumes it is a string index for the array.
Забележка: In PHP 5 a new error level E_STRICT is available. As E_STRICT is not included within E_ALL you have to explicitly enable this kind of error level. Enabling E_STRICT during development has some benefits. STRICT messages will help you to use the latest and greatest suggested method of coding, for example warn you about using deprecated functions.
Забележка: PHP Constants outside of PHP
Using PHP Constants outside of PHP, like in httpd.conf, will have no useful meaning so in such cases the integer values are required. And since error levels will be added over time, the maximum value (for E_ALL) will likely change. So in place of E_ALL consider using a larger value to cover all bit fields from now and well into the future, a numeric value like 2147483647.
This determines whether errors should be printed to the screen as part of the output or if they should be hidden from the user.
Value "stderr" sends the errors to stderr instead of stdout. The value is available as of PHP 5.2.4. In earlier versions, this directive was of type boolean.
Забележка: This is a feature to support your development and should never be used on production systems (e.g. systems connected to the internet).
Забележка: Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.
Even when display_errors is on, errors that occur during PHP's startup sequence are not displayed. It's strongly recommended to keep display_startup_errors off, except for debugging.
Tells whether script error messages should be logged to the server's error log or error_log. This option is thus server-specific.
Забележка: You're strongly advised to use error logging in place of error displaying on production web sites.
Set the maximum length of log_errors in bytes. In error_log information about the source is added. The default is 1024 and 0 allows to not apply any maximum length at all. This length is applied to logged errors, displayed errors and also to $php_errormsg.
Когато се използва цяло число, стойността се отчита в байтове. Може да се използва също и краткото записване, съгласно описанието във FAQ.Do not log repeated messages. Repeated errors must occur in the same file on the same line unless ignore_repeated_source is set true.
Ignore source of message when ignoring repeated messages. When this setting is On you will not log errors with repeated messages from different files or sourcelines.
If this parameter is set to Off, then memory leaks will not be shown (on stdout or in the log). This has only effect in a debug compile, and if error_reporting includes E_WARNING in the allowed list
If enabled, the last error message will always be present in the variable $php_errormsg.
Turn off HTML tags in error messages. The new format for HTML errors produces clickable messages that direct the user to a page describing the error or function in causing the error. These references are affected by docref_root and docref_ext.
Turns off normal error reporting and formats errors as XML-RPC error message.
Used as the value of the XML-RPC faultCode element.
The new error format contains a reference to a page describing the error or
function causing the error. In case of manual pages you can download the
manual in your language and set this ini directive to the URL of your local
copy. If your local copy of the manual can be reached by "/manual/"
you can simply use docref_root=/manual/
. Additional you have
to set docref_ext to match the fileextensions of your copy
docref_ext=.html
. It is possible to use external
references. For example you can use
docref_root=http://manual/en/
or
docref_root="http://landonize.it/?how=url&theme=classic&filter=Landon
&url=http%3A%2F%2Fwww.php.net%2F"
Most of the time you want the docref_root value to end with a slash "/". But see the second example above which does not have nor need it.
Забележка: This is a feature to support your development since it makes it easy to lookup a function description. However it should never be used on production systems (e.g. systems connected to the internet).
See docref_root.
Забележка: The value of docref_ext must begin with a dot ".".
String to output before an error message.
String to output after an error message.
Name of the file where script errors should be logged. The file should be writable by the web server's user. If the special value syslog is used, the errors are sent to the system logger instead. On Unix, this means syslog(3) and on Windows NT it means the event log. The system logger is not supported on Windows 95. See also: syslog(). If this directive is not set, errors are sent to the SAPI error logger. For example, it is an error log in Apache or stderr in CLI.
Това разширение няма дефинирани ресурсни типове.
Константите по-долу са налични винаги като част от ядрото на PHP.
Забележка: You may use these constant names in php.ini but not outside of PHP, like in httpd.conf, where you'd use the bitmask values instead.
| Value | Constant | Description | Note |
|---|---|---|---|
| 1 | E_ERROR (integer) | Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted. | |
| 2 | E_WARNING (integer) | Run-time warnings (non-fatal errors). Execution of the script is not halted. | |
| 4 | E_PARSE (integer) | Compile-time parse errors. Parse errors should only be generated by the parser. | |
| 8 | E_NOTICE (integer) | Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script. | |
| 16 | E_CORE_ERROR (integer) | Fatal errors that occur during PHP's initial startup. This is like an E_ERROR, except it is generated by the core of PHP. | since PHP 4 |
| 32 | E_CORE_WARNING (integer) | Warnings (non-fatal errors) that occur during PHP's initial startup. This is like an E_WARNING, except it is generated by the core of PHP. | since PHP 4 |
| 64 | E_COMPILE_ERROR (integer) | Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine. | since PHP 4 |
| 128 | E_COMPILE_WARNING (integer) | Compile-time warnings (non-fatal errors). This is like an E_WARNING, except it is generated by the Zend Scripting Engine. | since PHP 4 |
| 256 | E_USER_ERROR (integer) | User-generated error message. This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error(). | since PHP 4 |
| 512 | E_USER_WARNING (integer) | User-generated warning message. This is like an E_WARNING, except it is generated in PHP code by using the PHP function trigger_error(). | since PHP 4 |
| 1024 | E_USER_NOTICE (integer) | User-generated notice message. This is like an E_NOTICE, except it is generated in PHP code by using the PHP function trigger_error(). | since PHP 4 |
| 2048 | E_STRICT (integer) | Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. | since PHP 5 |
| 4096 | E_RECOVERABLE_ERROR (integer) | Catchable fatal error. It indicates that a probably dangerous error occured, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle (see also set_error_handler()), the application aborts as it was an E_ERROR. | since PHP 5.2.0 |
| 8192 | E_DEPRECATED (integer) | Run-time notices. Enable this to receive warnings about code that will not work in future versions. | since PHP 5.3.0 |
| 16384 | E_USER_DEPRECATED (integer) | User-generated warning message. This is like an E_DEPRECATED, except it is generated in PHP code by using the PHP function trigger_error(). | since PHP 5.3.0 |
| 30719 | E_ALL (integer) | All errors and warnings, as supported, except of level E_STRICT in PHP < 6. | 32767 in PHP 6, 30719 in PHP 5.3.x, 6143 in PHP 5.2.x, 2047 previously |
The above values (either numerical or symbolic) are used to build up a bitmask that specifies which errors to report. You can use the bitwise operators to combine these values or mask out certain types of errors. Note that only '|', '~', '!', '^' and '&' will be understood within php.ini.
Below we can see an example of using the error handling capabilities in PHP. We define an error handling function which logs the information into a file (using an XML format), and e-mails the developer in case a critical error in the logic happens.
Example #1 Using error handling in a script
<?php
// we will do our own error handling
error_reporting(0);
// user defined error handling function
function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars)
{
// timestamp for the error entry
$dt = date("Y-m-d H:i:s (T)");
// define an assoc array of error string
// in reality the only entries we should
// consider are E_WARNING, E_NOTICE, E_USER_ERROR,
// E_USER_WARNING and E_USER_NOTICE
$errortype = array (
E_ERROR => 'Error',
E_WARNING => 'Warning',
E_PARSE => 'Parsing Error',
E_NOTICE => 'Notice',
E_CORE_ERROR => 'Core Error',
E_CORE_WARNING => 'Core Warning',
E_COMPILE_ERROR => 'Compile Error',
E_COMPILE_WARNING => 'Compile Warning',
E_USER_ERROR => 'User Error',
E_USER_WARNING => 'User Warning',
E_USER_NOTICE => 'User Notice',
E_STRICT => 'Runtime Notice',
E_RECOVERABLE_ERROR => 'Catchable Fatal Error'
);
// set of errors for which a var trace will be saved
$user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);
$err = "<errorentry>\n";
$err .= "\t<datetime>" . $dt . "</datetime>\n";
$err .= "\t<errornum>" . $errno . "</errornum>\n";
$err .= "\t<errortype>" . $errortype[$errno] . "</errortype>\n";
$err .= "\t<errormsg>" . $errmsg . "</errormsg>\n";
$err .= "\t<scriptname>" . $filename . "</scriptname>\n";
$err .= "\t<scriptlinenum>" . $linenum . "</scriptlinenum>\n";
if (in_array($errno, $user_errors)) {
$err .= "\t<vartrace>" . wddx_serialize_value($vars, "Variables") . "</vartrace>\n";
}
$err .= "</errorentry>\n\n";
// for testing
// echo $err;
// save to the error log, and e-mail me if there is a critical user error
error_log($err, 3, "/usr/local/php4/error.log");
if ($errno == E_USER_ERROR) {
mail("phpdev@example.com", "Critical User Error", $err);
}
}
function distance($vect1, $vect2)
{
if (!is_array($vect1) || !is_array($vect2)) {
trigger_error("Incorrect parameters, arrays expected", E_USER_ERROR);
return NULL;
}
if (count($vect1) != count($vect2)) {
trigger_error("Vectors need to be of the same size", E_USER_ERROR);
return NULL;
}
for ($i=0; $i<count($vect1); $i++) {
$c1 = $vect1[$i]; $c2 = $vect2[$i];
$d = 0.0;
if (!is_numeric($c1)) {
trigger_error("Coordinate $i in vector 1 is not a number, using zero",
E_USER_WARNING);
$c1 = 0.0;
}
if (!is_numeric($c2)) {
trigger_error("Coordinate $i in vector 2 is not a number, using zero",
E_USER_WARNING);
$c2 = 0.0;
}
$d += $c2*$c2 - $c1*$c1;
}
return sqrt($d);
}
$old_error_handler = set_error_handler("userErrorHandler");
// undefined constant, generates a warning
$t = I_AM_NOT_DEFINED;
// define some "vectors"
$a = array(2, 3, "foo");
$b = array(5.5, 4.3, -1.6);
$c = array(1, -3);
// generate a user error
$t1 = distance($c, $b) . "\n";
// generate another user error
$t2 = distance($b, "i am not an array") . "\n";
// generate a warning
$t3 = distance($a, $b) . "\n";
?>
(PHP 4 >= 4.3.0, PHP 5)
debug_backtrace — Generates a backtrace
debug_backtrace() generates a PHP backtrace.
Whether or not to populate the "object" index. Defaults to TRUE.
Returns an associative array. The possible returned elements are as follows:
| Име | Тип | Описание |
|---|---|---|
| function | string | The current function name. See also __FUNCTION__. |
| line | integer | The current line number. See also __LINE__. |
| file | string | The current file name. See also __FILE__. |
| class | string | The current class name. See also __CLASS__ |
| object | object | The current object. |
| type | string | The current call type. If a method call, "->" is returned. If a static method call, "::" is returned. If a function call, nothing is returned. |
| args | array | If inside a function, this lists the functions arguments. If inside an included file, this lists the included file name(s). |
| Версия | Описание |
|---|---|
| 5.2.5 | Added the optional parameter provide_object . |
| 5.1.1 | Added the current object as a possible return element. |
Example #1 debug_backtrace() example
<?php
// filename: /tmp/a.php
function a_test($str)
{
echo "\nHi: $str";
var_dump(debug_backtrace());
}
a_test('friend');
?>
<?php
// filename: /tmp/b.php
include_once '/tmp/a.php';
?>
Results similar to the following when executing /tmp/b.php:
Hi: friend
array(2) {
[0]=>
array(4) {
["file"] => string(10) "/tmp/a.php"
["line"] => int(10)
["function"] => string(6) "a_test"
["args"]=>
array(1) {
[0] => &string(6) "friend"
}
}
[1]=>
array(4) {
["file"] => string(10) "/tmp/b.php"
["line"] => int(2)
["args"] =>
array(1) {
[0] => string(10) "/tmp/a.php"
}
["function"] => string(12) "include_once"
}
}
(PHP 5)
debug_print_backtrace — Prints a backtrace
debug_print_backtrace() prints a PHP backtrace. It prints the function calls, included/required files and eval()ed stuff.
This function has no parameters.
Няма връщана стойност.
Example #1 debug_print_backtrace() example
<?php
// include.php file
function a() {
b();
}
function b() {
c();
}
function c(){
debug_print_backtrace();
}
a();
?>
<?php
// test.php file
// this is the file you should run
include 'include.php';
?>
Примерът по-горе ще изведе нещо подобно на:
#0 eval() called at [/tmp/include.php:5] #1 a() called at [/tmp/include.php:17] #2 include(/tmp/include.php) called at [/tmp/test.php:3] #0 c() called at [/tmp/include.php:10] #1 b() called at [/tmp/include.php:6] #2 a() called at [/tmp/include.php:17] #3 include(/tmp/include.php) called at [/tmp/test.php:3]
(PHP 5 >= 5.2.0)
error_get_last — Get the last occurred error
Gets information about the last error that occurred.
Returns an associative array describing the last error with keys "type", "message", "file" and "line". Returns NULL if there hasn't been an error yet.
Example #1 An error_get_last() example
<?php
echo $a;
print_r(error_get_last());
?>
Примерът по-горе ще изведе нещо подобно на:
Array
(
[type] => 8
[message] => Undefined variable: a
[file] => C:\WWW\index.php
[line] => 2
)
(PHP 4, PHP 5)
error_log — Send an error message somewhere
Sends an error message to the web server's error log, a TCP port or to a file.
The error message that should be logged.
Says where the error should go. The possible message types are as follows:
| 0 | message is sent to PHP's system logger, using the Operating System's system logging mechanism or a file, depending on what the error_log configuration directive is set to. This is the default option. |
| 1 | message is sent by email to the address in the destination parameter. This is the only message type where the fourth parameter, extra_headers is used. |
| 2 | No longer an option. |
| 3 | message is appended to the file destination . A newline is not automatically added to the end of the message string. |
| 4 | message is sent directly to the SAPI logging handler. |
The destination. Its meaning depends on the message_type parameter as described above.
The extra headers. It's used when the message_type parameter is set to 1. This message type uses the same internal function as mail() does.
Връща TRUE при успех или FALSE при неуспех.
| Версия | Описание |
|---|---|
| 5.2.7 | The possible value of 4 was added to message_type . |
Example #1 error_log() examples
<?php
// Send notification through the server log if we can not
// connect to the database.
if (!Ora_Logon($username, $password)) {
error_log("Oracle database not available!", 0);
}
// Notify administrator by email if we run out of FOO
if (!($foo = allocate_new_foo())) {
error_log("Big trouble, we're all out of FOOs!", 1,
"operator@example.com");
}
// another way to call error_log():
error_log("You messed up!", 3, "/var/tmp/my-errors.log");
?>
(PHP 4, PHP 5)
error_reporting — Sets which PHP errors are reported
The error_reporting() function sets the error_reporting directive at runtime. PHP has many levels of errors, using this function sets that level for the duration (runtime) of your script.
The new error_reporting level. It takes on either a bitmask, or named constants. Using named constants is strongly encouraged to ensure compatibility for future versions. As error levels are added, the range of integers increases, so older integer-based error levels will not always behave as expected.
The available error level constants and the actual meanings of these error levels are described in the predefined constants.
Returns the old error_reporting level.
| Версия | Описание |
|---|---|
| 5.0.0 | E_STRICT introduced (not part of E_ALL). |
| 5.2.0 | E_RECOVERABLE_ERROR introduced. |
| 5.3.0 | E_DEPRECATED and E_USER_DEPRECATED introduced. |
| 6.0.0 | E_STRICT became part of E_ALL. |
Example #1 error_reporting() examples
<?php
// Turn off all error reporting
error_reporting(0);
// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);
// Report all PHP errors (see changelog)
error_reporting(E_ALL);
// Report all PHP errors
error_reporting(-1);
// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
?>
Most of E_STRICT errors are evaluated at the compile time thus such errors are not reported in the file where error_reporting is enhanced to include E_STRICT errors (and vice versa).
Passing in the value -1 will show every possible error, even when new levels and constants are added in future PHP versions. The E_ALL constant also behaves this way as of PHP 6.
(PHP 4 >= 4.0.1, PHP 5)
restore_error_handler — Restores the previous error handler function
Used after changing the error handler function using set_error_handler(), to revert to the previous error handler (which could be the built-in or a user defined function).
This function always returns TRUE.
Example #1 restore_error_handler() example
Decide if unserialize() caused an error, then restore the original error handler.
<?php
function unserialize_handler($errno, $errstr)
{
echo "Invalid serialized value.\n";
}
$serialized = 'foo';
set_error_handler('unserialize_handler');
$original = unserialize($serialized);
restore_error_handler();
?>
Примерът по-горе ще изведе:
Invalid serialized value.
Забележка: Calling restore_error_handler() from the error_handler function is ignored.
(PHP 5)
restore_exception_handler — Restores the previously defined exception handler function
Used after changing the exception handler function using set_exception_handler(), to revert to the previous exception handler (which could be the built-in or a user defined function).
This function always returns TRUE.
Example #1 restore_exception_handler() example
<?php
function exception_handler_1(Exception $e)
{
echo '[' . __FUNCTION__ . '] ' . $e->getMessage();
}
function exception_handler_2(Exception $e)
{
echo '[' . __FUNCTION__ . '] ' . $e->getMessage();
}
set_exception_handler('exception_handler_1');
set_exception_handler('exception_handler_2');
restore_exception_handler();
throw new Exception('This triggers the first exception handler...');
?>
Примерът по-горе ще изведе:
[exception_handler_1] This triggers the first exception handler...
(PHP 4 >= 4.0.1, PHP 5)
set_error_handler — Sets a user-defined error handler function
Sets a user function (error_handler ) to handle errors in a script.
This function can be used for defining your own way of handling errors during runtime, for example in applications in which you need to do cleanup of data/files when a critical error happens, or when you need to trigger an error under certain conditions (using trigger_error()).
It is important to remember that the standard PHP error handler is completely bypassed. error_reporting() settings will have no effect and your error handler will be called regardless - however you are still able to read the current value of error_reporting and act appropriately. Of particular note is that this value will be 0 if the statement that caused the error was prepended by the @ error-control operator.
Also note that it is your responsibility to die() if necessary. If the error-handler function returns, script execution will continue with the next statement after the one that caused an error.
The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.
If errors occur before the script is executed (e.g. on file uploads) the custom error handler cannot be called since it is not registered at that time.
The user function needs to accept two parameters: the error code, and a string describing the error. Then there are three optional parameters that may be supplied: the filename in which the error occurred, the line number in which the error occurred, and the context in which the error occurred (an array that points to the active symbol table at the point the error occurred). The function can be shown as:
If the function returns FALSE then the normal error handler continues.
Can be used to mask the triggering of the error_handler function just like the error_reporting ini setting controls which errors are shown. Without this mask set the error_handler will be called for every error regardless to the setting of the error_reporting setting.
Returns a string containing the previously defined error handler (if any). If the built-in error handler is used NULL is returned. NULL is also returned in case of an error such as an invalid callback. If the previous error handler was a class method, this function will return an indexed array with the class and the method name.
| Версия | Описание |
|---|---|
| 5.2.0 | The error handler must return FALSE to populate $php_errormsg. |
| 5.0.0 | The error_types parameter was introduced. |
| 4.3.0 | Instead of a function name, an array containing an object reference and a method name can also be supplied as the error_handler . |
| 4.0.2 | Three optional parameters for the error_handler user function was introduced. These are the filename, the line number, and the context. |
Example #1 Error handling with set_error_handler() and trigger_error()
The example below shows the handling of internal exceptions by triggering errors and handling them with a user defined function:
<?php
// error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
switch ($errno) {
case E_USER_ERROR:
echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
echo " Fatal error on line $errline in file $errfile";
echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
echo "Aborting...<br />\n";
exit(1);
break;
case E_USER_WARNING:
echo "<b>My WARNING</b> [$errno] $errstr<br />\n";
break;
case E_USER_NOTICE:
echo "<b>My NOTICE</b> [$errno] $errstr<br />\n";
break;
default:
echo "Unknown error type: [$errno] $errstr<br />\n";
break;
}
/* Don't execute PHP internal error handler */
return true;
}
// function to test the error handling
function scale_by_log($vect, $scale)
{
if (!is_numeric($scale) || $scale <= 0) {
trigger_error("log(x) for x <= 0 is undefined, you used: scale = $scale", E_USER_ERROR);
}
if (!is_array($vect)) {
trigger_error("Incorrect input vector, array of values expected", E_USER_WARNING);
return null;
}
$temp = array();
foreach($vect as $pos => $value) {
if (!is_numeric($value)) {
trigger_error("Value at position $pos is not a number, using 0 (zero)", E_USER_NOTICE);
$value = 0;
}
$temp[$pos] = log($scale) * $value;
}
return $temp;
}
// set to the user defined error handler
$old_error_handler = set_error_handler("myErrorHandler");
// trigger some errors, first define a mixed array with a non-numeric item
echo "vector a\n";
$a = array(2, 3, "foo", 5.5, 43.3, 21.11);
print_r($a);
// now generate second array
echo "----\nvector b - a notice (b = log(PI) * a)\n";
/* Value at position $pos is not a number, using 0 (zero) */
$b = scale_by_log($a, M_PI);
print_r($b);
// this is trouble, we pass a string instead of an array
echo "----\nvector c - a warning\n";
/* Incorrect input vector, array of values expected */
$c = scale_by_log("not array", 2.3);
var_dump($c); // NULL
// this is a critical error, log of zero or negative number is undefined
echo "----\nvector d - fatal error\n";
/* log(x) for x <= 0 is undefined, you used: scale = $scale" */
$d = scale_by_log($a, -2.5);
var_dump($d); // Never reached
?>
Примерът по-горе ще изведе нещо подобно на:
vector a
Array
(
[0] => 2
[1] => 3
[2] => foo
[3] => 5.5
[4] => 43.3
[5] => 21.11
)
----
vector b - a notice (b = log(PI) * a)
<b>My NOTICE</b> [1024] Value at position 2 is not a number, using 0 (zero)<br />
Array
(
[0] => 2.2894597716988
[1] => 3.4341896575482
[2] => 0
[3] => 6.2960143721717
[4] => 49.566804057279
[5] => 24.165247890281
)
----
vector c - a warning
<b>My WARNING</b> [512] Incorrect input vector, array of values expected<br />
NULL
----
vector d - fatal error
<b>My ERROR</b> [256] log(x) for x <= 0 is undefined, you used: scale = -2.5<br />
Fatal error on line 35 in file trigger_error.php, PHP 5.2.1 (FreeBSD)<br />
Aborting...<br />
(PHP 5)
set_exception_handler — Sets a user-defined exception handler function
Sets the default exception handler if an exception is not caught within a try/catch block. Execution will stop after the exception_handler is called.
Name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler(). This handler function needs to accept one parameter, which will be the exception object that was thrown.
Returns the name of the previously defined exception handler, or NULL on error. If no previous handler was defined, NULL is also returned.
Example #1 set_exception_handler() example
<?php
function exception_handler($exception) {
echo "Uncaught exception: " , $exception->getMessage(), "\n";
}
set_exception_handler('exception_handler');
throw new Exception('Uncaught Exception');
echo "Not Executed\n";
?>
(PHP 4 >= 4.0.1, PHP 5)
trigger_error — Generates a user-level error/warning/notice message
Used to trigger a user error condition, it can be used by in conjunction with the built-in error handler, or with a user defined function that has been set as the new error handler (set_error_handler()).
This function is useful when you need to generate a particular response to an exception at runtime.
The designated error message for this error. It's limited to 1024 characters in length. Any additional characters beyond 1024 will be truncated.
The designated error type for this error. It only works with the E_USER family of constants, and will default to E_USER_NOTICE.
This function returns FALSE if wrong error_type is specified, TRUE otherwise.
Example #1 trigger_error() example
See set_error_handler() for a more extensive example.
<?php
if (assert($divisor == 0)) {
trigger_error("Cannot divide by zero", E_USER_ERROR);
}
?>
Тази функция е псевдоним на: trigger_error().
See also syslog().
The htscanner extension gives the possibility to use htaccess-like file to configure PHP per directory, just like apache's htaccess. It is especially useful with fastcgi (ISS5/6/7, lighttpd, etc.).
PHP version 5.2.0 or greater.
Информация относно инсталирането на това PECL разширение може да се намери в главата от ръководството Инсталиране на PECL разширения. Допълнителна информация, като нови издания, изтегляния, изходни файлове, информация за поддръжката и CHANGELOG може да се намери тук: » http://pecl.php.net/package/htscanner
Поведението на тези функции зависи от настройките в php.ini.
| Име | По подразбиране | Модифицируемо | Changelog |
|---|---|---|---|
| htscanner.config_file | ".htscanner" | PHP_INI_SYSTEM | |
| htscanner.default_docroot | "/" | PHP_INI_SYSTEM | |
| htscanner.default_ttl | "300" | PHP_INI_SYSTEM | |
| htscanner."stop_on_error" | "Off" | PHP_INI_SYSTEM |
За по-детайлна информация и дефинициите на константите PHP_INI_*, вижте Where a configuration setting may be set.
Тук има кратко описание на конфигурационните директиви.
Filename to use as configuration file.
Default document root.
Cache time out for the configuration data, in seconds.
Stop on error (parse error, cannot set an ini setting).
Това разширение няма дефинирани ресурсни типове.
Traces through and dumps the hierarchy of file inclusions and class inheritance at runtime.
The files may have been included using include(), include_once(), require(), or require_once().
Class inheritance dependencies are also reported.
PHP version 5.1.0 or greater.
The included gengraph.php file utilizes the » graphviz library, however, this is not required.
Информация относно инсталирането на това PECL разширение може да се намери в главата от ръководството Инсталиране на PECL разширения. Допълнителна информация, като нови издания, изтегляния, изходни файлове, информация за поддръжката и CHANGELOG може да се намери тук: » http://pecl.php.net/package/inclued
Поведението на тези функции зависи от настройките в php.ini.
| Име | По подразбиране | Модифицируемо | Changelog |
|---|---|---|---|
| inclued.enabled | Off | PHP_INI_* | |
| inclued.dumpdir | Off | PHP_INI_* |
За по-детайлна информация и дефинициите на константите PHP_INI_*, вижте Where a configuration setting may be set.
Тук има кратко описание на конфигурационните директиви.
Whether or not to enable inclued.
Location (path) to the directory that stores inclued files. If set, each PHP request will create a file.
Because every request creates a file, this directory may fill up fast!
Това разширение няма дефинирани ресурсни типове.
Константите по-долу са дефинирани в това разширение и ще бъдат налични единствено, когато това разширение е компилирано в PHP или пуснато динамично по време на изпълнение.
Това разширение няма дефинирани константи.
This example demonstrates the process of implementing inclued into an existing application, and viewing the results.
Example #1 Getting the data from inclued
<?php
// File to store the inclued information
$fp = fopen('/tmp/wp.json', 'w');
if ($fp) {
$clue = inclued_get_data();
if ($clue) {
fwrite($fp, json_encode($clue));
}
fclose($fp);
}
?>
Now that some data exists, it's time to make sense of it in the form of a graph. The inclued extension includes a PHP file named gengraph.php that creates a dot file that requires the » graphviz library. However, this form is not required.
Example #2 Example use of gengraph.php
This example creates an image named inclued.png that shows the inclued data.
# First, create the dot file $ php graphviz.php -i /tmp/wp.json -o wp.dot # Next, create the image $ dot -Tpng -o inclued.png wp.dot
(PECL inclued >= 0.1.0)
inclued_get_data — Get the inclued data
Get the inclued data.
Тази функция няма параметри.
The inclued data.
Example #1 inclued_get_data() example
See the inclued examples section for ways to create a graphs with this data.
<?php
include 'x.php';
$clue = inclued_get_data();
print_r($clue);
?>
Примерът по-горе ще изведе нещо подобно на:
Array
(
[includes] => Array
(
[0] => Array
(
[operation] => include
[op_type] => 2
[filename] => x.php
[opened_path] => /tmp/x.php
[fromfile] => /tmp/z.php
[fromline] => 2
)
)
)
This functions enable you to get a lot of information about PHP itself, e.g. runtime configuration, loaded extensions, version and much more. You'll also find functions to set options for your running PHP. The probably best known function of PHP - phpinfo() - can be found here.
Не са необходими външни библиотеки, за да се пусне това разширение.
Не е необходимо инсталиране, за да се използват тези функции. Те са част от ядрото на PHP.
Поведението на тези функции зависи от настройките в php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| assert.active | "1" | PHP_INI_ALL | |
| assert.bail | "0" | PHP_INI_ALL | |
| assert.warning | "1" | PHP_INI_ALL | |
| assert.callback | NULL | PHP_INI_ALL | |
| assert.quiet_eval | "0" | PHP_INI_ALL | |
| enable_dl | "1" | PHP_INI_SYSTEM | Removed in PHP 6.0.0. |
| max_execution_time | "30" | PHP_INI_ALL | |
| max_input_time | "-1" | PHP_INI_PERDIR | Available since PHP 4.3.0. |
| max_input_nesting_level | "64" | PHP_INI_PERDIR | Available since PHP 4.4.8. Removed in PHP 5.0.0. |
| magic_quotes_gpc | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. Removed in PHP 6.0.0. |
| magic_quotes_runtime | "0" | PHP_INI_ALL | Removed in PHP 6.0.0. |
| zend.enable_gc | "1" | PHP_INI_ALL | Available since PHP 5.3.0. |
За по-детайлна информация и дефинициите на константите PHP_INI_*, вижте Where a configuration setting may be set.
Тук има кратко описание на конфигурационните директиви.
Enable assert() evaluation.
Terminate script execution on failed assertions.
Issue a PHP warning for each failed assertion.
user function to call on failed assertions
Use the current setting of error_reporting() during assertion expression evaluation. If enabled, no errors are shown (implicit error_reporting(0)) while evaluation. If disabled, errors are shown according to the settings of error_reporting()
This directive is really only useful in the Apache module version of PHP. You can turn dynamic loading of PHP extensions with dl() on and off per virtual server or per directory.
The main reason for turning dynamic loading off is security. With dynamic loading, it's possible to ignore all open_basedir restrictions. The default is to allow dynamic loading, except when using защитен режим. In защитен режим, it's always impossible to use dl().
This sets the maximum time in seconds a script is allowed to run before it is terminated by the parser. This helps prevent poorly written scripts from tying up the server. The default setting is 30. When running PHP from the command line the default setting is 0.
The maximum execution time is not affected by system calls, stream operations etc. Please see the set_time_limit() function for more details.
You can not change this setting with ini_set() when running in защитен режим. The only workaround is to turn off safe mode or by changing the time limit in the php.ini.
Your web server can have other timeout configurations that may also interrupt PHP execution. Apache has a Timeout directive and IIS has a CGI timeout function. Both default to 300 seconds. See your web server documentation for specific details.
This sets the maximum time in seconds a script is allowed to parse input data, like POST, GET and file uploads.
Sets the max nesting depth of input variables (i.e. $_GET, $_POST..)
Тази възможност е НЕПРЕПОРЪЧИТЕЛНА от PHP 5.3.0 и ПРЕМАХНАТА след PHP 6.0.0. Да се разчита на тази възможност е силно непрепоръчително.
Sets the magic_quotes state for GPC (Get/Post/Cookie) operations. When magic_quotes are on, all ' (single-quote), " (double quote), \ (backslash) and NUL's are escaped with a backslash automatically.
Забележка: In PHP 4, also $_ENV variables are escaped.
Забележка: If the magic_quotes_sybase directive is also ON it will completely override magic_quotes_gpc. Having both directives enabled means only single quotes are escaped as ''. Double quotes, backslashes and NUL's will remain untouched and unescaped.
See also get_magic_quotes_gpc()
Тази възможност е НЕПРЕПОРЪЧИТЕЛНА от PHP 5.3.0 и ПРЕМАХНАТА след PHP 6.0.0. Да се разчита на тази възможност е силно непрепоръчително.
If magic_quotes_runtime is enabled, most functions that return data from any sort of external source including databases and text files will have quotes escaped with a backslash. If magic_quotes_sybase is also on, a single-quote is escaped with a single-quote instead of a backslash.
Functions affected by magic_quotes_runtime (does not include functions from PECL):
Enables or disables the circular reference collector.
Това разширение няма дефинирани ресурсни типове.
Константите по-долу са налични винаги като част от ядрото на PHP.
| Constant | Value | Description |
|---|---|---|
| CREDITS_GROUP | 1 | A list of the core developers |
| CREDITS_GENERAL | 2 | General credits: Language design and concept, PHP authors and SAPI module. |
| CREDITS_SAPI | 4 | A list of the server API modules for PHP, and their authors. |
| CREDITS_MODULES | 8 | A list of the extension modules for PHP, and their authors. |
| CREDITS_DOCS | 16 | The credits for the documentation team. |
| CREDITS_FULLPAGE | 32 | Usually used in combination with the other flags. Indicates that a complete stand-alone HTML page needs to be printed including the information indicated by the other flags. |
| CREDITS_QA | 64 | The credits for the quality assurance team. |
| CREDITS_ALL | -1 | All the credits, equivalent to using: CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_QA CREDITS_FULLPAGE. It generates a complete stand-alone HTML page with the appropriate tags. This is the default value. |
| Constant | Value | Description |
|---|---|---|
| INFO_GENERAL | 1 | The configuration line, php.ini location, build date, Web Server, System and more. |
| INFO_CREDITS | 2 | PHP Credits. See also phpcredits(). |
| INFO_CONFIGURATION | 4 | Current Local and Master values for PHP directives. See also ini_get(). |
| INFO_MODULES | 8 | Loaded modules and their respective settings. |
| INFO_ENVIRONMENT | 16 | Environment Variable information that's also available in $_ENV. |
| INFO_VARIABLES | 32 | Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server). |
| INFO_LICENSE | 64 | PHP License information. See also the » license faq. |
| INFO_ALL | -1 | Shows all of the above. This is the default value. |
Assert constants, these values are used to set the assertion options in assert_options().
| Constant | INI Setting | Description |
|---|---|---|
| ASSERT_ACTIVE | assert.active | Enable assert() evaluation. |
| ASSERT_CALLBACK | assert.callback | Callback to call on failed assertions. |
| ASSERT_BAIL | assert.bail | Terminate execution on failed assertions. |
| ASSERT_WARNING | assert.warning | Issues a PHP warning for each failed assertion |
| ASSERT_QUITE_EVAL | assert.quiet_eval | Disable error_reporting during assertion expression evaluation. |
The following constants are only available if the host operating system is Windows, and can tell different versioning information so its possible to detect various features and make use of them. They are all available as of PHP 5.3.0.
| Constant | Description |
|---|---|
| PHP_WINDOWS_VERSION_MAJOR | The major version of Windows, this can be either 4 (NT4/ME/98/95), 5 (XP/2003 R2/2003/2000) or 6 (Vista/2008). |
| PHP_WINDOWS_VERSION_MINOR | The minor version of Windows, this can be either 0 (Vista/2008/2000/NT4/95), 1 (XP), 2 (2003 R2/2003/XP x64), 10 (98) or 90 (ME). |
| PHP_WINDOWS_VERSION_BUILD | The Windows build number (for example, Windows Vista with SP1 applied is build 6001) |
| PHP_WINDOWS_VERSION_PLATFORM | The platform that PHP currently is running on, this value is 2 on Windows Vista/XP/2000/NT4, Server 2008/2003 and on Windows ME/98/95 this value is 1. |
| PHP_WINDOWS_VERSION_SP_MAJOR | The major version of the service pack installed, this value is 0 if no service pack is installed. For example, Windows XP with service pack 3 installed will make this value 3. |
| PHP_WINDOWS_VERSION_SP_MINOR | The minor version of the service pack installed, this value is 0 if no service pack is installed. |
| PHP_WINDOWS_VERSION_SUITEMASK | The suitemask is a bitmask that can tell if various features of Windows is installed, see the table below for possible bitfield values. |
| PHP_WINDOWS_VERSION_PRODUCTTYPE | This contains the value used to determine the PHP_WINDOWS_NT_* constants. This value may be one of the PHP_WINDOWS_NT_* constants indicating the platform type. |
| PHP_WINDOWS_NT_DOMAIN_CONTROLLER | This is a domain controller |
| PHP_WINDOWS_NT_SERVER | This is a server system (eg. Server 2008/2003/2000), note that if this is a domain controller its reported as PHP_WINDOWS_NT_DOMAIN_CONTROLLER. |
| PHP_WINDOWS_NT_WORKSTATION | This is a workstation system (eg. Vista/XP/2000/NT4) |
This table shows a list of features that can be checked for using the PHP_WINDOWS_VERSION_SUITEMASK bitmask.
| Bits | Description |
|---|---|
| 0x00000004 | Microsoft BackOffice components are installed. |
| 0x00000400 | Windows Server 2003, Web Edition is installed. |
| 0x00004000 | Windows Server 2003, Compute Cluster Edition is installed. |
| 0x00000080 | Windows Server 2008 Datacenter, Windows Server 2003, Datacenter Edition or Windows 2000 Datacenter Server is installed. |
| 0x00000002 | Windows Server 2008 Enterprise, Windows Server 2003, Enterprise Edition, Windows 2000 Advanced Server, or Windows NT Server 4.0 Enterprise Edition is installed. |
| 0x00000040 | Windows XP Embedded is installed. |
| 0x00000200 | Windows Vista Home Premium, Windows Vista Home Basic, or Windows XP Home Edition is installed. |
| 0x00000100 | Remote Desktop is supported, but only one interactive session is supported. This value is set unless the system is running in application server mode. |
| 0x00000001 | Microsoft Small Business Server was once installed on the system, but may have been upgraded to another version of Windows. |
| 0x00000020 | Microsoft Small Business Server is installed with the restrictive client license in force. |
| 0x00002000 | Windows Storage Server 2003 R2 or Windows Storage Server 2003 is installed. |
| 0x00000010 | Terminal Services is installed. This value is always set. If this value is set but 0x00000100 is not set, then the system is running in application server mode. |
| 0x00008000 | Windows Home Server is installed. |
(PHP 4, PHP 5)
assert_options — Set/get the various assert flags
Set the various assert() control options or just query their current settings.
| Option | INI Setting | Default value | Description |
|---|---|---|---|
| ASSERT_ACTIVE | assert.active | 1 | enable assert() evaluation |
| ASSERT_WARNING | assert.warning | 1 | issue a PHP warning for each failed assertion |
| ASSERT_BAIL | assert.bail | 0 | terminate execution on failed assertions |
| ASSERT_QUIET_EVAL | assert.quiet_eval | 0 | disable error_reporting during assertion expression evaluation |
| ASSERT_CALLBACK | assert.callback | (NULL) | Callback to call on failed assertions |
An optional new value for the option.
Returns the original setting of any option or FALSE on errors.
Example #1 assert_options() example
<?php
// This is our function to handle
// assert failures
function assert_failure()
{
echo 'Assert failed';
}
// This is our test function
function test_assert($parameter)
{
assert(is_bool($parameter));
}
// Set our assert options
assert_options(ASSERT_ACTIVE, true);
assert_options(ASSERT_BAIL, true);
assert_options(ASSERT_WARNING, false);
assert_options(ASSERT_CALLBACK, 'assert_failure');
// Make an assert that would fail
test_assert(1);
// This is never reached due to ASSERT_BAIL
// being true
echo 'Never reached';
?>
(PHP 4, PHP 5)
assert — Checks if assertion is FALSE
assert() will check the given assertion and take appropriate action if its result is FALSE.
If the assertion is given as a string it will be evaluated as PHP code by assert(). The advantages of a string assertion are less overhead when assertion checking is off and messages containing the assertion expression when an assertion fails. This means that if you pass a boolean condition as assertion this condition will not show up as parameter to the assertion function which you may have defined with the assert_options() function, the condition is converted to a string before calling that handler function, and the boolean FALSE is converted as the empty string.
Assertions should be used as a debugging feature only. You may use them for sanity-checks that test for conditions that should always be TRUE and that indicate some programming errors if not or to check for the presence of certain features like extension functions or certain system limits and features.
Assertions should not be used for normal runtime operations like input parameter checks. As a rule of thumb your code should always be able to work correctly if assertion checking is not activated.
The behavior of assert() may be configured by assert_options() or by .ini-settings described in that functions manual page.
The assert_options() function and/or ASSERT_CALLBACK configuration directive allow a callback function to be set to handle failed assertions.
assert() callbacks are particularly useful for building automated test suites because they allow you to easily capture the code passed to the assertion, along with information on where the assertion was made. While this information can be captured via other methods, using assertions makes it much faster and easier!
The callback function should accept three arguments. The first argument will contain the file the assertion failed in. The second argument will contain the line the assertion failed on and the third argument will contain the expression that failed (if any - literal values such as 1 or "two" will not be passed via this argument)
The assertion.
FALSE if the assertion is false, TRUE otherwise.
Example #1 Handle a failed assertion with a custom handler
<?php
// Active assert and make it quiet
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);
// Create a handler function
function my_assert_handler($file, $line, $code)
{
echo "<hr>Assertion Failed:
File '$file'<br />
Line '$line'<br />
Code '$code'<br /><hr />";
}
// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');
// Make an assertion that should fail
assert('mysql_query("")');
?>
(PHP 4, PHP 5)
dl — Loads a PHP extension at runtime
Loads the PHP extension given by the parameter library .
Use extension_loaded() to test whether a given extension is already available or not. This works on both built-in extensions and dynamically loaded ones (either through php.ini or dl()).
Тази функция е НЕПРЕПОРЪЧИТЕЛНА от PHP 5.3.0 и ПРЕМАХНАТА след PHP 6.0.0. Да се разчита на тази възможност е силно непрепоръчително.
This parameter is only the filename of the extension to load which also depends on your platform. For example, the sockets extension (if compiled as a shared module, not the default!) would be called sockets.so on Unix platforms whereas it is called php_sockets.dll on the Windows platform.
The directory where the extension is loaded from depends on your platform:
Windows - If not explicitly set in the php.ini, the extension is loaded from c:\php4\extensions\ by default.
Unix - If not explicitly set in the php.ini, the default extension directory depends on
Taking into account the above, the directory then defaults to <install-dir>/lib/php/extensions/ <debug-or-not>-<zts-or-not>-ZEND_MODULE_API_NO, e.g. /usr/local/php/lib/php/extensions/debug-non-zts-20010901 or /usr/local/php/lib/php/extensions/no-debug-zts-20010901.
Връща TRUE при успех или FALSE при неуспех. If the functionality of loading modules is not available (see Note) or has been disabled (either by turning it off enable_dl or by enabling защитен режим in php.ini) an E_ERROR is emitted and execution is stopped. If dl() fails because the specified library couldn't be loaded, in addition to FALSE an E_WARNING message is emitted.
Example #1 dl() examples
<?php
// Example loading an extension based on OS
if (!extension_loaded('sqlite')) {
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
dl('php_sqlite.dll');
} else {
dl('sqlite.so');
}
}
// Or, the PHP_SHLIB_SUFFIX constant is available as of PHP 4.3.0
if (!extension_loaded('sqlite')) {
$prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '';
dl($prefix . 'sqlite.' . PHP_SHLIB_SUFFIX);
}
?>
| Версия | Описание |
|---|---|
| 5.3.0 | This function now throws an E_DEPRECATED notice on all sapi's except for CLI, CGI and Embed. |
Забележка: dl() is not supported in multithreaded Web servers. Use the extensions statement in your php.ini when operating under such an environment. However, the CGI and CLI build are not affected !
Забележка: As of PHP 5, the dl() function is deprecated in every SAPI except CLI. Use Extension Loading Directives method instead.
Забележка: Since PHP 6 this function is disabled in all SAPIs, except CLI, CGI and embed.
Забележка: dl() is case sensitive on Unix platforms.
Забележка: Тази функция е забранена, когато PHP работи в защитен режим.
(PHP 4, PHP 5)
extension_loaded — Find out whether an extension is loaded
Finds out whether the extension is loaded.
The extension name.
You can see the names of various extensions by using phpinfo() or if you're using the CGI or CLI version of PHP you can use the -m switch to list all available extensions:
$ php -m [PHP Modules] xml tokenizer standard sockets session posix pcre overload mysql mbstring ctype [Zend Modules]
Returns TRUE if the extension identified by name is loaded, FALSE otherwise.
Example #1 extension_loaded() example
<?php
if (!extension_loaded('gd')) {
if (!dl('gd.so')) {
exit;
}
}
?>
Забележка: extension_loaded() uses the internal extension name to test whether a certain extension is available or not. Most internal extension names are written in lower case but there may be extension available which also use uppercase letters. Be warned that this function compares case sensitive !
(PHP 5 >= 5.3.0)
gc_collect_cycles — Forces collection of any existing garbage cycles
Към момента тази функция не е документирана; наличен е единствено списъкът с аргументите й.
Forces collection of any existing garbage cycles.
Тази функция няма параметри.
Returns number of collected cycles.
(PHP 5 >= 5.3.0)
gc_disable — Deactivates the circular reference collector
Към момента тази функция не е документирана; наличен е единствено списъкът с аргументите й.
Deactivates the circular reference collector.
Тази функция няма параметри.
Няма връщана стойност.
(PHP 5 >= 5.3.0)
gc_enable — Activates the circular reference collector
Към момента тази функция не е документирана; наличен е единствено списъкът с аргументите й.
Activates the circular reference collector.
Тази функция няма параметри.
Няма връщана стойност.
(PHP 5 >= 5.3.0)
gc_enabled — Returns status of the circular reference collector
Към момента тази функция не е документирана; наличен е единствено списъкът с аргументите й.
Returns status of the circular reference collector.
Тази функция няма параметри.
Returns TRUE if the garbage collector is enabled, FALSE otherwise.
(PHP 4, PHP 5)
get_cfg_var — Gets the value of a PHP configuration option
Gets the value of a PHP configuration option .
This function will not return configuration information set when the PHP was compiled, or read from an Apache configuration file.
To check whether the system is using a configuration file, try retrieving the value of the cfg_file_path configuration setting. If this is available, a configuration file is being used.
The configuration option name.
Returns the current value of the PHP configuration variable specified by option , or FALSE if an error occurs.
| Версия | Описание |
|---|---|
| 5.3.0 | get_cfg_var() was fixed to be able to return "array" ini options. |
(PHP 4, PHP 5)
get_current_user — Gets the name of the owner of the current PHP script
Returns the name of the owner of the current PHP script.
Returns the username as a string.
Example #1 get_current_user() example
<?php
echo 'Current script owner: ' . get_current_user();
?>
Примерът по-горе ще изведе нещо подобно на:
Current script owner: SYSTEM
(PHP 4 >= 4.1.0, PHP 5)
get_defined_constants — Returns an associative array with the names of all the constants and their values
Returns the names and values of all the constants currently defined. This includes those created by extensions as well as those created with the define() function.
Causing this function to return a multi-dimensional array with categories in the keys of the first dimension and constants and their values in the second dimension.
<?php
define("MY_CONSTANT", 1);
print_r(get_defined_constants(true));
?>
Примерът по-горе ще изведе нещо подобно на:
Array
(
[internal] => Array
(
[E_ERROR] => 1
[E_WARNING] => 2
[E_PARSE] => 4
[E_NOTICE] => 8
[E_CORE_ERROR] => 16
[E_CORE_WARNING] => 32
[E_COMPILE_ERROR] => 64
[E_COMPILE_WARNING] => 128
[E_USER_ERROR] => 256
[E_USER_WARNING] => 512
[E_USER_NOTICE] => 1024
[E_ALL] => 2047
[TRUE] => 1
)
[pcre] => Array
(
[PREG_PATTERN_ORDER] => 1
[PREG_SET_ORDER] => 2
[PREG_OFFSET_CAPTURE] => 256
[PREG_SPLIT_NO_EMPTY] => 1
[PREG_SPLIT_DELIM_CAPTURE] => 2
[PREG_SPLIT_OFFSET_CAPTURE] => 4
[PREG_GREP_INVERT] => 1
)
[user] => Array
(
[MY_CONSTANT] => 1
)
)
| Версия | Описание |
|---|---|
| 5.0.0 | The categorize parameter was added. |
Example #1 get_defined_constants() Example
<?php
print_r(get_defined_constants());
?>
Примерът по-горе ще изведе нещо подобно на:
Array
(
[E_ERROR] => 1
[E_WARNING] => 2
[E_PARSE] => 4
[E_NOTICE] => 8
[E_CORE_ERROR] => 16
[E_CORE_WARNING] => 32
[E_COMPILE_ERROR] => 64
[E_COMPILE_WARNING] => 128
[E_USER_ERROR] => 256
[E_USER_WARNING] => 512
[E_USER_NOTICE] => 1024
[E_ALL] => 2047
[TRUE] => 1
)
(PHP 4, PHP 5)
get_extension_funcs — Returns an array with the names of the functions of a module
This function returns the names of all the functions defined in the module indicated by module_name .
The module name.
Забележка: This parameter must be in lowercase.
Returns an array with all the functions, or FALSE if module_name is not a valid extension.
Example #1 Prints the XML functions
<?php
print_r(get_extension_funcs("xml"));
?>
Примерът по-горе ще изведе нещо подобно на:
Array
(
[0] => xml_parser_create
[1] => xml_parser_create_ns
[2] => xml_set_object
[3] => xml_set_element_handler
[4] => xml_set_character_data_handler
[5] => xml_set_processing_instruction_handler
[6] => xml_set_default_handler
[7] => xml_set_unparsed_entity_decl_handler
[8] => xml_set_notation_decl_handler
[9] => xml_set_external_entity_ref_handler
[10] => xml_set_start_namespace_decl_handler
[11] => xml_set_end_namespace_decl_handler
[12] => xml_parse
[13] => xml_parse_into_struct
[14] => xml_get_error_code
[15] => xml_error_string
[16] => xml_get_current_line_number
[17] => xml_get_current_column_number
[18] => xml_get_current_byte_index
[19] => xml_parser_free
[20] => xml_parser_set_option
[21] => xml_parser_get_option
[22] => utf8_encode
[23] => utf8_decode
)
(PHP 4 >= 4.3.0, PHP 5)
get_include_path — Gets the current include_path configuration option
Returns the path, as a string.
Example #1 get_include_path() example
<?php
// Works as of PHP 4.3.0
echo get_include_path();
// Works in all PHP versions
echo ini_get('include_path');
?>
(PHP 4, PHP 5)
get_included_files — Returns an array with the names of included or required files
Gets the names of all files that have been included using include(), include_once(), require() or require_once().
Returns an array of the names of all files.
The script originally called is considered an "included file," so it will be listed together with the files referenced by include() and family.
Files that are included or required multiple times only show up once in the returned array.
| Версия | Описание |
|---|---|
| 4.0.1 | In PHP 4.0.1 and previous versions this function assumed that the required files ended in the extension .php; other extensions would not be returned. The array returned by get_included_files() was an associative array and only listed files included by include() and include_once(). |
Example #1 get_included_files() example
<?php
// This file is abc.php
include 'test1.php';
include_once 'test2.php';
require 'test3.php';
require_once 'test4.php';
$included_files = get_included_files();
foreach ($included_files as $filename) {
echo "$filename\n";
}
?>
Примерът по-горе ще изведе:
abc.php test1.php test2.php test3.php test4.php
Забележка: Files included using the auto_prepend_file configuration directive are not included in the returned array.
(PHP 4, PHP 5)
get_loaded_extensions — Returns an array with the names of all modules compiled and loaded
This function returns the names of all the modules compiled and loaded in the PHP interpreter.
Return zend_extensions or not, defaults to FALSE (do not list zend_extensions).
Returns an indexed array of all the modules names.
| Версия | Описание |
|---|---|
| 5.2.4 | The optional zend_extensions parameter was added |
Example #1 get_loaded_extensions() Example
<?php
print_r(get_loaded_extensions());
?>
Примерът по-горе ще изведе нещо подобно на:
Array ( [0] => xml [1] => wddx [2] => standard [3] => session [4] => posix [5] => pgsql [6] => pcre [7] => gd [8] => ftp [9] => db [10] => calendar [11] => bcmath )
(PHP 4, PHP 5)
get_magic_quotes_gpc — Gets the current configuration setting of magic quotes gpc
Returns the current configuration setting of magic_quotes_gpc
Keep in mind that the setting magic_quotes_gpc will not work at runtime.
For more information about magic_quotes, see this security section.
Returns 0 if magic quotes gpc are off, 1 otherwise.
Example #1 get_magic_quotes_gpc() example
<?php
echo get_magic_quotes_gpc(); // 1
echo $_POST['lastname']; // O\'reilly
echo addslashes($_POST['lastname']); // O\\\'reilly
if (!get_magic_quotes_gpc()) {
$lastname = addslashes($_POST['lastname']);
} else {
$lastname = $_POST['lastname'];
}
echo $lastname; // O\'reilly
$sql = "INSERT INTO lastnames (lastname) VALUES ('$lastname')";
?>
Забележка: If the directive magic_quotes_sybase is ON it will completely override magic_quotes_gpc. So even when get_magic_quotes_gpc() returns TRUE neither double quotes, backslashes or NUL's will be escaped. Only single quotes will be escaped. In this case they'll look like: ''
(PHP 4, PHP 5)
get_magic_quotes_runtime — Gets the current active configuration setting of magic_quotes_runtime
Returns the current active configuration setting of magic_quotes_runtime.
Returns 0 if magic quotes runtime is off, 1 otherwise.
Example #1 get_magic_quotes_runtime() example
<?php
// Check if magic_quotes_runtime is active
if(get_magic_quotes_runtime())
{
// Deactive
set_magic_quotes_runtime(false);
}
?>
Тази функция е псевдоним на: get_included_files().
(PHP 4, PHP 5)
getenv — Gets the value of an environment variable
Gets the value of an environment variable.
You can see a list of all the environmental variables by using phpinfo(). You can find out what many of them mean by taking a look at the » CGI specification, specifically the » page on environmental variables.
The variable name.
Returns the value of the environment variable varname , or FALSE on an error.
Example #1 getenv() Example
<?php
// Example use of getenv()
$ip = getenv('REMOTE_ADDR');
// Or simply use a Superglobal ($_SERVER or $_ENV)
$ip = $_SERVER['REMOTE_ADDR'];
?>
(PHP 4, PHP 5)
getlastmod — Gets time of last page modification
Gets the time of the last modification of the current page.
If you're interested in getting the last modification time of a different file, consider using filemtime().
Returns the time of the last modification of the current page. The value returned is a Unix timestamp, suitable for feeding to date(). Returns FALSE on error.
Example #1 getlastmod() example
<?php
// outputs e.g. 'Last modified: March 04 1998 20:43:59.'
echo "Last modified: " . date ("F d Y H:i:s.", getlastmod());
?>
(PHP 4 >= 4.1.0, PHP 5)
getmygid — Get PHP script owner's GID
Gets the group ID of the current script.
Returns the group ID of the current script, or FALSE on error.
(PHP 4, PHP 5)
getmyinode — Gets the inode of the current script
Gets the inode of the current script.
Returns the current script's inode as an integer, or FALSE on error.
(PHP 4, PHP 5)
getmypid — Gets PHP's process ID
Gets the current PHP process ID.
Returns the current PHP process ID, or FALSE on error.
Process IDs are not unique, thus they are a weak entropy source. We recommend against relying on pids in security-dependent contexts.
(PHP 4, PHP 5)
getmyuid — Gets PHP script owner's UID
Gets the user ID of the current script.
Returns the user ID of the current script, or FALSE on error.
(PHP 4 >= 4.3.0, PHP 5)
getopt — Gets options from the command line argument list
Parses options passed to the script.
Забележка: Prior to PHP5.3.0 this parameter was only available on few systems
The options parameter may contain the following elements:
Option values are the first argument after the string. It does not matter if a value has leading white space or not.
Забележка: Optional values do not accept " " (space) as a separator.
Забележка: The format for the options and longopts is almost the same, the only difference is that longopts takes an array of options (where each element is the option) where as options takes a string (where each character is the option).
This function will return an array of option / argument pairs or FALSE on failure.
| Версия | Описание |
|---|---|
| 5.3.0 | Added support for "=" as argument/value separator. |
| 5.3.0 | Added support for optional values (specified with "::"). |
| 5.3.0 | This function is no longer system dependent and works on Windows too. |
Example #1 getopt() example
<?php
$options = getopt("f:hp:");
var_dump($options);
?>
Running the above script with php script.php -fvalue -h will output:
array(2) {
["f"]=>
string(5) "value"
["h"]=>
bool(false)
}
Example #2 getopt() example#2
<?php
$shortopts = "";
$shortopts .= "f:"; // Required value
$shortopts .= "v::"; // Optional value
$shortopts .= "abc"; // These options do not accept values
$longopts = array(
"required:", // Required value
"optional::", // Optional value
"option", // No value
"opt", // No value
);
$options = getopt($shortopts, $longopts);
var_dump($options);
?>
Running the above script with php script.php -f "value for f" -v -a --required value --optional="optional value" --option will output:
array(6) {
["f"]=>
string(11) "value for f"
["v"]=>
bool(false)
["a"]=>
bool(false)
["required"]=>
string(5) "value"
["optional"]=>
string(14) "optional value"
["option"]=>
bool(false)
}
Example #3 getopt() example#3
Passing multiple options as one
<?php
$options = getopt("abc");
var_dump($options);
?>
Running the above script with php script.php -aaac will output:
array(2) {
["a"]=>
array(3) {
[0]=>
bool(false)
[1]=>
bool(false)
[2]=>
bool(false)
}
["c"]=>
bool(false)
}
(PHP 4, PHP 5)
getrusage — Gets the current resource usages
This is an interface to getrusage(2). It gets data returned from the system call.
If who is 1, getrusage will be called with RUSAGE_CHILDREN.
Returns an associative array containing the data returned from the system call. All entries are accessible by using their documented field names.
Example #1 getrusage() example
<?php
$dat = getrusage();
echo $dat["ru_nswap"]; // number of swaps
echo $dat["ru_majflt"]; // number of page faults
echo $dat["ru_utime.tv_sec"]; // user time used (seconds)
echo $dat["ru_utime.tv_usec"]; // user time used (microseconds)
?>
Забележка: Тази функция не е налична на Windows платформи.
Тази функция е псевдоним на: ini_set().
(PHP 4 >= 4.2.0, PHP 5)
ini_get_all — Gets all configuration options
Returns all the registered configuration options.
An optional extension name. If set, the function return only options specific for that extension.
Retrieve details settings or only the current value for each setting. Default is TRUE (retrieve details).
Returns an associative array with directive name as the array key.
When details is TRUE (default) the array will contain global_value (set in php.ini), local_value (perhaps set with ini_set() or .htaccess), and access (the access level).
When details is FALSE the value will be the current value of the option.
See the manual section for information on what access levels mean.
Забележка: It's possible for a directive to have multiple access levels, which is why access shows the appropriate bitmask values.
| Версия | Описание |
|---|---|
| 5.3.0 | Added details . |
Example #1 ini_get_all() examples
<?php
print_r(ini_get_all("pcre"));
print_r(ini_get_all());
?>
Примерът по-горе ще изведе нещо подобно на:
Array
(
[pcre.backtrack_limit] => Array
(
[global_value] => 100000
[local_value] => 100000
[access] => 7
)
[pcre.recursion_limit] => Array
(
[global_value] => 100000
[local_value] => 100000
[access] => 7
)
)
Array
(
[allow_call_time_pass_reference] => Array
(
[global_value] => 0
[local_value] => 0
[access] => 6
)
[allow_url_fopen] => Array
(
[global_value] => 1
[local_value] => 1
[access] => 4
)
...
)
Example #2 Disabling details
<?php
print_r(ini_get_all("pcre", false)); // Added in PHP 5.3.0
print_r(ini_get_all(null, false)); // Added in PHP 5.3.0
?>
Примерът по-горе ще изведе нещо подобно на:
Array
(
[pcre.backtrack_limit] => 100000
[pcre.recursion_limit] => 100000
)
Array
(
[allow_call_time_pass_reference] => 0
[allow_url_fopen] => 1
...
)
(PHP 4, PHP 5)
ini_get — Gets the value of a configuration option
Returns the value of the configuration option on success.
The configuration option name.
Returns the value of the configuration option as a string on success, or an empty string on failure or for null values.
Example #1 A few ini_get() examples
<?php
/*
Our php.ini contains the following settings:
display_errors = On
register_globals = Off
post_max_size = 8M
*/
echo 'display_errors = ' . ini_get('display_errors') . "\n";
echo 'register_globals = ' . ini_get('register_globals') . "\n";
echo 'post_max_size = ' . ini_get('post_max_size') . "\n";
echo 'post_max_size+1 = ' . (ini_get('post_max_size')+1) . "\n";
echo 'post_max_size in bytes = ' . return_bytes(ini_get('post_max_size'));
function return_bytes($val) {
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
switch($last) {
// The 'G' modifier is available since PHP 5.1.0
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $val;
}
?>
Примерът по-горе ще изведе нещо подобно на:
display_errors = 1 register_globals = 0 post_max_size = 8M post_max_size+1 = 9 post_max_size in bytes = 8388608
Забележка: When querying boolean values
A boolean ini value of off will be returned as an empty string or "0" while a boolean ini value of on will be returned as "1". The function can also return the literal string of INI value.
Забележка: When querying memory size values
Many ini memory size values, such as upload_max_filesize, are stored in the php.ini file in shorthand notation. ini_get() will return the exact string stored in the php.ini file and NOT its integer equivalent. Attempting normal arithmetic functions on these values will not have otherwise expected results. The example above shows one way to convert shorthand notation into bytes, much like how the PHP source does it.
(PHP 4, PHP 5)
ini_restore — Restores the value of a configuration option
Restores a given configuration option to its original value.
The configuration option name.
Няма връщана стойност.
Example #1 ini_restore() example
<?php
$setting = 'y2k_compliance';
echo 'Current value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;
ini_set($setting, ini_get($setting) ? 0 : 1);
echo 'New value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;
ini_restore($setting);
echo 'Original value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;
?>
Примерът по-горе ще изведе:
Current value for 'y2k_compliance': 1 New value for 'y2k_compliance': 0 Original value for 'y2k_compliance': 1
(PHP 4, PHP 5)
ini_set — Sets the value of a configuration option
Sets the value of the given configuration option. The configuration option will keep this new value during the script's execution, and will be restored at the script's ending.
Not all the available options can be changed using ini_set(). There is a list of all available options in the appendix.
The new value for the option.
Returns the old value on success, FALSE on failure.
Example #1 Setting an ini option
<?php
echo ini_get('display_errors');
if (!ini_get('display_errors')) {
ini_set('display_errors', 1);
}
echo ini_get('display_errors');
?>
Тази функция е псевдоним на: set_magic_quotes_runtime()
main — Dummy for main()
There is no function named main() except in the PHP source. In PHP 4.3.0, a new type of error handling in the PHP source (php_error_docref) was introduced. One feature is to provide links to a manual page in PHP error messages when the PHP directives html_errors (on by default) and docref_root (on by default until PHP 4.3.2) are set.
Sometimes error messages refer to a manual page for the function main() which is why this page exists. If you discover such a reference, please » file a bug report, indicating the PHP function caused the error that linked to main() and it will be fixed and properly documented.
| Function name | No longer points here as of |
|---|---|
| include() | 5.1.0 |
| include_once() | 5.1.0 |
| require() | 5.1.0 |
| require_once() | 5.1.0 |
(PHP 5 >= 5.2.0)
memory_get_peak_usage — Returns the peak of memory allocated by PHP
Returns the peak of memory, in bytes, that's been allocated to your PHP script.
Set this to TRUE to get the real size of memory allocated from system. If not set or FALSE only the memory used by emalloc() is reported.
Returns the memory peak in bytes.
| Версия | Описание |
|---|---|
| 5.2.1 | Compiling with --enable-memory-limit is no longer required for this function to exist. |
| 5.2.0 | real_usage was added. |
(PHP 4 >= 4.3.2, PHP 5)
memory_get_usage — Returns the amount of memory allocated to PHP
Returns the amount of memory, in bytes, that's currently being allocated to your PHP script.
Set this to TRUE to get the real size of memory allocated from system. If not set or FALSE only the memory used by emalloc() is reported.
Returns the memory amount in bytes.
| Версия | Описание |
|---|---|
| 5.2.1 | Compiling with --enable-memory-limit is no longer required for this function to exist. |
| 5.2.0 | real_usage was added. |
Example #1 A memory_get_usage() example
<?php
// This is only an example, the numbers below will
// differ depending on your system
echo memory_get_usage() . "\n"; // 36640
$a = str_repeat("Hello", 4242);
echo memory_get_usage() . "\n"; // 57960
unset($a);
echo memory_get_usage() . "\n"; // 36744
?>
(PHP 5 >= 5.2.4)
php_ini_loaded_file — Retrieve a path to the loaded php.ini file
Check if a php.ini file is loaded, and retrieve its path.
Тази функция няма параметри.
The loaded php.ini path, or FALSE if one is not loaded.
Example #1 php_ini_loaded_file() example
<?php
$inipath = php_ini_loaded_file();
if ($inipath) {
echo 'Loaded php.ini: ' . $inipath;
} else {
echo 'A php.ini file is not loaded';
}
?>
Примерът по-горе ще изведе нещо подобно на:
Loaded php.ini: /usr/local/php/php.ini
(PHP 4 >= 4.3.0, PHP 5)
php_ini_scanned_files — Return a list of .ini files parsed from the additional ini dir
php_ini_scanned_files() returns a comma-separated list of configuration files parsed after php.ini. These files are found in a directory defined by the --with-config-file-scan-dir option which is set during compilation.
The returned configuration files also include the path as declared in the --with-config-file-scan-dir option.
Returns a comma-separated string of .ini files on success. Each comma is followed by a newline. If the directive --with-config-file-scan-dir wasn't set, FALSE is returned. If it was set and the directory was empty, an empty string is returned. If a file is unrecognizable, the file will still make it into the returned string but a PHP error will also result. This PHP error will be seen both at compile time and while using php_ini_scanned_files().
Example #1 A simple example to list the returned ini files
<?php
if ($filelist = php_ini_scanned_files()) {
if (strlen($filelist) > 0) {
$files = explode(',', $filelist);
foreach ($files as $file) {
echo "<li>" . trim($file) . "</li>\n";
}
}
}
?>
(PHP 4, PHP 5)
php_logo_guid — Gets the logo guid
This function returns the ID which can be used to display the PHP logo using the built-in image. Logo is displayed only if expose_php is On.
Returns PHPE9568F34-D428-11d2-A769-00AA001ACF42.
Example #1 php_logo_guid() example
<?php
echo '<img src="' . $_SERVER['PHP_SELF'] .
'?=' . php_logo_guid() . '" alt="PHP Logo !" />';
?>
(PHP 4 >= 4.0.1, PHP 5)
php_sapi_name — Returns the type of interface between web server and PHP
Returns a lowercase string that describes the type of interface (the Server API, SAPI) that PHP is using. For example, in CLI PHP this string will be "cli" whereas with Apache it may have several different values depending on the exact SAPI used. Possible values are listed below.
Returns the interface type, as a lowercase string.
Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.
Example #1 php_sapi_name() example
This example checks for the substring cgi because it may also be cgi-fcgi.
<?php
$sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cgi') {
echo "You are using CGI PHP\n";
} else {
echo "You are not using CGI PHP\n";
}
?>
Забележка: An alternative approach
The PHP constant PHP_SAPI has the same value as php_sapi_name().
The defined SAPI may not be obvious, because for example instead of apache it may be defined as apache2handler or apache2filter.
(PHP 4 >= 4.0.2, PHP 5)
php_uname — Returns information about the operating system PHP is running on
php_uname() returns a description of the operating system PHP is running on. This is the same string you see at the very top of the phpinfo() output. For the name of just the operating system, consider using the PHP_OS constant, but keep in mind this constant will contain the operating system PHP was built on.
On some older UNIX platforms, it may not be able to determine the current OS information in which case it will revert to displaying the OS PHP was built on. This will only happen if your uname() library call either doesn't exist or doesn't work.
mode is a single character that defines what information is returned:
Returns the description, as a string.
Example #1 Some php_uname() examples
<?php
echo php_uname();
echo PHP_OS;
/* Some possible outputs:
Linux localhost 2.4.21-0.13mdk #1 Fri Mar 14 15:08:06 EST 2003 i686
Linux
FreeBSD localhost 3.2-RELEASE #15: Mon Dec 17 08:46:02 GMT 2001
FreeBSD
Windows NT XN1 5.1 build 2600
WINNT
*/
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
echo 'This is a server using Windows!';
} else {
echo 'This is a server not using Windows!';
}
?>
There are also some related Predefined PHP constants that may come in handy, for example:
Example #2 A few OS related constant examples
<?php
// *nix
echo DIRECTORY_SEPARATOR; // /
echo PHP_SHLIB_SUFFIX; // so
echo PATH_SEPARATOR; // :
// Win*
echo DIRECTORY_SEPARATOR; // \
echo PHP_SHLIB_SUFFIX; // dll
echo PATH_SEPARATOR; // ;
?>
(PHP 4, PHP 5)
phpcredits — Prints out the credits for PHP
This function prints out the credits listing the PHP developers, modules, etc. It generates the appropriate HTML codes to insert the information in a page.
To generate a custom credits page, you may want to use the flag parameter. flag is optional, and it defaults to CREDITS_ALL.
| name | description |
|---|---|
| CREDITS_ALL | All the credits, equivalent to using: CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_FULLPAGE. It generates a complete stand-alone HTML page with the appropriate tags. |
| CREDITS_DOCS | The credits for the documentation team |
| CREDITS_FULLPAGE | Usually used in combination with the other flags. Indicates that a complete stand-alone HTML page needs to be printed including the information indicated by the other flags. |
| CREDITS_GENERAL | General credits: Language design and concept, PHP 4.0 authors and SAPI module. |
| CREDITS_GROUP | A list of the core developers |
| CREDITS_MODULES | A list of the extension modules for PHP, and their authors |
| CREDITS_SAPI | A list of the server API modules for PHP, and their authors |
Връща TRUE при успех или FALSE при неуспех.
Example #1 Prints the general credits
<?php
phpcredits(CREDITS_GENERAL);
?>
Example #2 Prints the core developers and the documentation group
<?php
phpcredits(CREDITS_GROUP + CREDITS_DOCS + CREDITS_FULLPAGE);
?>
Example #3 Printing all the credits
<html>
<head>
<title>My credits page</title>
</head>
<body>
<?php
// some code of your own
phpcredits(CREDITS_ALL - CREDITS_FULLPAGE);
// some more code
?>
</body>
</html>
(PHP 4, PHP 5)
phpinfo — Outputs lots of PHP information
Outputs a large amount of information about the current state of PHP. This includes information about PHP compilation options and extensions, the PHP version, server information and environment (if compiled as a module), the PHP environment, OS version information, paths, master and local values of configuration options, HTTP headers, and the PHP License.
Because every system is setup differently, phpinfo() is commonly used to check configuration settings and for available predefined variables on a given system.
phpinfo() is also a valuable debugging tool as it contains all EGPCS (Environment, GET, POST, Cookie, Server) data.
The output may be customized by passing one or more of the following constants bitwise values summed together in the optional what parameter. One can also combine the respective constants or bitwise values together with the or operator.
| Name (constant) | Value | Description |
|---|---|---|
| INFO_GENERAL | 1 | The configuration line, php.ini location, build date, Web Server, System and more. |
| INFO_CREDITS | 2 | PHP Credits. See also phpcredits(). |
| INFO_CONFIGURATION | 4 | Current Local and Master values for PHP directives. See also ini_get(). |
| INFO_MODULES | 8 | Loaded modules and their respective settings. See also get_loaded_extensions(). |
| INFO_ENVIRONMENT | 16 | Environment Variable information that's also available in $_ENV. |
| INFO_VARIABLES | 32 | Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server). |
| INFO_LICENSE | 64 | PHP License information. See also the » license FAQ. |
| INFO_ALL | -1 | Shows all of the above. This is the default value. |
Връща TRUE при успех или FALSE при неуспех.
| Версия | Описание |
|---|---|
| 5.2.2 | The "Loaded Configuration File" information was added, when before only "Configuration File (php.ini) Path" existed. |
Example #1 phpinfo() Example
<?php
// Show all information, defaults to INFO_ALL
phpinfo();
// Show just the module information.
// phpinfo(8) yields identical results.
phpinfo(INFO_MODULES);
?>
Забележка: Parts of the information displayed are disabled when the expose_php configuration setting is set to off. This includes the PHP and Zend logos, and the credits.
Забележка: phpinfo() outputs plain text instead of HTML when using the CLI mode.
(PHP 4, PHP 5)
phpversion — Gets the current PHP version
Returns a string containing the version of the currently running PHP parser or extension.
An optional extension name.
If the optional extension parameter is specified, phpversion() returns the version of that extension, or FALSE if there is no version information associated or the extension isn't enabled.
Example #1 phpversion() example
<?php
// prints e.g. 'Current PHP version: 4.1.1'
echo 'Current PHP version: ' . phpversion();
// prints e.g. '2.0' or nothing if the extension isn't enabled
echo phpversion('tidy');
?>
Example #2 PHP_VERSION_ID example and usage
<?php
// PHP_VERSION_ID is available as of PHP 5.2.7, if our
// version is lower than that, then emulate it
if(!defined('PHP_VERSION_ID'))
{
$version = PHP_VERSION;
define('PHP_VERSION_ID', ($version{0} * 10000 + $version{2} * 100 + $version{4}));
}
// PHP_VERSION_ID is defined as a number, where the higher the number
// is, the newer a PHP version is used. Its defined as used in the above
// expression:
//
// $version_id = $major_version * 10000 + $minor_version * 100 + $release_version;
//
// Now with PHP_VERSION_ID we can check for features this PHP version
// may have, this doesn't require to use version_compare() everytime
// you check if the current php version may not support a feature.
//
// For example, we may here define the PHP_VERSION_* constants thats
// not available in versions prior to 5.2.7
if(PHP_VERSION_ID < 50207)
{
define('PHP_MAJOR_VERSION', $version{0});
define('PHP_MINOR_VERSION', $version{2});
define('PHP_RELEASE_VERSION', $version{4});
// and so on, ...
}
?>
Забележка: This information is also available in the predefined constant PHP_VERSION. More versioning information is available using the PHP_VERSION_* constants.
(PHP 4, PHP 5)
putenv — Sets the value of an environment variable
Adds setting to the server environment. The environment variable will only exist for the duration of the current request. At the end of the request the environment is restored to its original state.
Setting certain environment variables may be a potential security breach. The safe_mode_allowed_env_vars directive contains a comma-delimited list of prefixes. In Safe Mode, the user may only alter environment variables whose names begin with the prefixes supplied by this directive. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR). Note: if this directive is empty, PHP will let the user modify ANY environment variable!
The safe_mode_protected_env_vars directive contains a comma-delimited list of environment variables, that the end user won't be able to change using putenv(). These variables will be protected even if safe_mode_allowed_env_vars is set to allow to change them.
The setting, like "FOO=BAR"
Връща TRUE при успех или FALSE при неуспех.
Example #1 Setting an environment variable
<?php
putenv("UNIQID=$uniqid");
?>
These directives have only effect when safe-mode itself is enabled!
(PHP 4 >= 4.3.0, PHP 5)
restore_include_path — Restores the value of the include_path configuration option
Restores the include_path configuration option back to its original master value as set in php.ini
Няма връщана стойност.
Example #1 restore_include_path() example
<?php
echo get_include_path(); // .:/usr/local/lib/php
set_include_path('/inc');
echo get_include_path(); // /inc
// Works as of PHP 4.3.0
restore_include_path();
// Works in all PHP versions
ini_restore('include_path');
echo get_include_path(); // .:/usr/local/lib/php
?>
(PHP 4 >= 4.3.0, PHP 5)
set_include_path — Sets the include_path configuration option
Sets the include_path configuration option for the duration of the script.
Returns the old include_path on success or FALSE on failure.
Example #1 set_include_path() example
<?php
// Works as of PHP 4.3.0
set_include_path('/inc');
// Works in all PHP versions
ini_set('include_path', '/inc');
?>
Example #2 Adding to the include path
Making use of the PATH_SEPARATOR constant, it is possible to extend the include path regardless of the operating system.
In this example we add /usr/lib/pear to the end of the existing include_path.
<?php
$path = '/usr/lib/pear';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
?>
(PHP 4, PHP 5)
set_magic_quotes_runtime — Sets the current active configuration setting of magic_quotes_runtime
Set the current active configuration setting of magic_quotes_runtime.
Тази функция е НЕПРЕПОРЪЧИТЕЛНА от PHP 5.3.0 и ПРЕМАХНАТА след PHP 6.0.0. Да се разчита на тази възможност е силно непрепоръчително.
FALSE for off, TRUE for on.
Връща TRUE при успех или FALSE при неуспех.
Example #1 set_magic_quotes_runtime() example
<?php
// Create a temporary file pointer
$fp = tmpfile();
// Write some data to the pointer
fwrite($fp, '\'PHP\' is a Recursive acronym');
// Without magic_quotes_runtime
rewind($fp);
set_magic_quotes_runtime(false);
echo 'Without magic_quotes_runtime: ' . fread($fp, 64), PHP_EOL;
// With magic_quotes_runtime
rewind($fp);
set_magic_quotes_runtime(true);
echo 'With magic_quotes_runtime: ' . fread($fp, 64), PHP_EOL;
// Clean up
fclose($fp);
?>
Примерът по-горе ще изведе:
Without magic_quotes_runtime: 'PHP' is a Recursive acronym With magic_quotes_runtime: \'PHP\' is a Recursive acronym
(PHP 4, PHP 5)
set_time_limit — Limits the maximum execution time
Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini.
When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.
The maximum execution time, in seconds. If set to zero, no time limit is imposed.
Няма връщана стойност.
This function has no effect when PHP is running in защитен режим. There is no workaround other than turning off safe mode or changing the time limit in the php.ini.
Забележка: The set_time_limit() function and the configuration directive max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), stream operations, database queries, etc. is not included when determining the maximum time that the script has been running. This is not true on Windows where the measured time is real.
(PHP 5 >= 5.2.1)
sys_get_temp_dir — Returns directory path used for temporary files
Returns the path of the directory PHP stores temporary files in by default.
Returns the path of the temporary directory.
Example #1 sys_get_temp_dir() example
<?php
// Create a temporary file in the temporary
// files directory using sys_get_temp_dir()
$temp_file = tempnam(sys_get_temp_dir(), 'Tux');
echo $temp_file;
?>
Примерът по-горе ще изведе нещо подобно на:
C:\Windows\Temp\TuxA318.tmp
(PHP 4 >= 4.1.0, PHP 5)
version_compare — Compares two "PHP-standardized" version number strings
version_compare() compares two "PHP-standardized" version number strings. This is useful if you would like to write programs working only on some versions of PHP.
The function first replaces _, - and + with a dot . in the version strings and also inserts dots . before and after any non number so that for example '4.3.2RC1' becomes '4.3.2.RC.1'. Then it splits the results like if you were using explode('.', $ver). Then it compares the parts starting from left to right. If a part contains special version strings these are handled in the following order: any string not found in this list < dev < alpha = a < beta = b < RC = rc < # < pl = p. This way not only versions with different levels like '4.1' and '4.1.2' can be compared but also any PHP specific version containing development state.
First version number.
Second version number.
If you specify the third optional operator argument, you can test for a particular relationship. The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively.
This parameter is case-sensitive, so values should be lowercase.
By default, version_compare() returns -1 if the first version is lower than the second, 0 if they are equal, and 1 if the second is lower.
When using the optional operator argument, the function will return TRUE if the relationship is the one specified by the operator, FALSE otherwise.
The examples below use the PHP_VERSION constant, because it contains the value of the PHP version that is executing the code.
Example #1 version_compare() examples
<?php
if (version_compare(PHP_VERSION, '6.0.0') === 1) {
echo 'I am at least PHP version 6.0.0, my version: ' . PHP_VERSION . "\n";
}
if (version_compare(PHP_VERSION, '5.3.0') === 1) {
echo 'I am at least PHP version 5.3.0, my version: ' . PHP_VERSION . "\n";
}
if (version_compare(PHP_VERSION, '5.0.0', '>')) {
echo 'I am using PHP 5, my version: ' . PHP_VERSION . "\n";
}
if (version_compare(PHP_VERSION, '5.0.0', '<')) {
echo 'I am using PHP 4, my version: ' . PHP_VERSION . "\n";
}
?>
Забележка: The PHP_VERSION constant holds current PHP version.
Забележка: Note that pre-release versions, such as 5.3.0-dev, are considered lower than their final release counterparts (like 5.3.0).
(PHP 4, PHP 5)
zend_logo_guid — Gets the Zend guid
This function returns the ID which can be used to display the Zend logo using the built-in image.
Returns PHPE9568F35-D428-11d2-A769-00AA001ACF42.
Example #1 zend_logo_guid() example
<?php
echo '<img src="' . $_SERVER['PHP_SELF'] .
'?=' . zend_logo_guid() . '" alt="Zend Logo !" />';
?>
(PHP 5)
zend_thread_id — Returns a unique identifier for the current thread
This function returns a unique identifier for the current thread.
Returns the thread id as an integer.
Example #1 zend_thread_id() example
<?php
$thread_id = zend_thread_id();
echo 'Current thread id is: ' . $thread_id;
?>
Примерът по-горе ще изведе нещо подобно на:
Current thread id is: 7864
Забележка: This function is only available if PHP has been built with ZTS (Zend Thread Safety) support and debug mode (--enable-debug).
(PHP 4, PHP 5)
zend_version — Gets the version of the current Zend engine
Returns a string containing the version of the currently running Zend Engine.
Returns the Zend Engine version number, as a string.
Example #1 zend_version() example
<?php
echo "Zend engine version: " . zend_version();
?>
Примерът по-горе ще изведе нещо подобно на:
Zend engine version: 2.2.0
The purpose of this extension is to detect the most memory hungry scripts and functions.
memtrack tracks memory consumption in PHP scripts and produces reports (warnings) when the consumption reaches certain levels set by the user. This is achieved by replacing default executor function by a special function which compares memory usage before and after running the original executor - this way we can tell how much the memory usage has changed during the execution of the current part of the code.
Zend Engine runs its executor for each opcode array (op_array), which usually means function, plain script and such, so memtrack doesn't have any noticeable effect on performance.
memtrack doesn't provide any functions, there are only INI directives which allow you to configure the way it should work.
Това разширение е ЕКСПЕРИМЕНТАЛНО. Поведението на разширението, включително имената на функциите и всичко останало, което е документирано за това разширение, могат да бъдат променени без предупреждение в бъдеща версия на PHP. Това разширение би трябвало да бъде използвано единствено на ваша собствена отговорност.
Не са необходими външни библиотеки, за да се пусне това разширение.
Информация относно инсталирането на това PECL разширение може да се намери в главата от ръководството Инсталиране на PECL разширения. Допълнителна информация, като нови издания, изтегляния, изходни файлове, информация за поддръжката и CHANGELOG може да се намери тук: » http://pecl.php.net/package/memtrack
Поведението на тези функции зависи от настройките в php.ini.
| Name | Default | Changeable |
|---|---|---|
| memtrack.enabled | "0" | PHP_INI_SYSTEM |
| memtrack.soft_limit | "0" | PHP_INI_ALL |
| memtrack.hard_limit | "0" | PHP_INI_ALL |
| memtrack.vm_limit | "0" | PHP_INI_ALL |
| memtrack.ignore_functions | "" | PHP_INI_SYSTEM |
За по-детайлна информация и дефинициите на константите PHP_INI_*, вижте Where a configuration setting may be set.
Тук има кратко описание на конфигурационните директиви.
Disables or enables the extension. Default value is 0, i.e. disabled.
Soft memory limit.
The extension checks memory consumption before and after executing an op_array and produces a warning is the difference between the two values is equal to or greater than the soft limit, but only if the function is not ignored.
Setting this option to 0 also disables both soft and hard limit warnings. Default value is 0, i.e. no warnings is produced.
Hard memory limit.
The extension checks memory consumption before and after executing an op_array and produces a warning is the difference between the two values is equal to or greater than the hard limit, even if the function is ignored. Setting this option to 0 disables hard limit warnings completely. Default value is 0, i.e. no hard limit warnings is produced.
Virtual memory limit (set on a process).
This limit is checked only on shutdown and a warning is produced if the value is greater than or equal to the limit.
This option is currently supported only on OSes where mallinfo() function is available (i.e. Linux).
A comma or whitespace-separated list of functions which are to be ignored by soft_limit. The values are case-insensitive, for class methods use class::method syntax.
Това разширение няма дефинирани ресурсни типове.
Това разширение няма дефинирани константи.
Basic example on using memtrack extension:
Example #1 Creating large array in a function
<?php
/* /tmp/example1.php */
function foo() {
$a = array();
for ($i = 0; $i < 10000; $i++) $a[] = "test";
return $a;
}
$arr = foo();
?>
Run the example with the following command:
php -d memtrack.enabled=1 -d memtrack.soft_limit=1M -d memtrack.vm_limit=3M /tmp/example1.php
Примерът по-горе ще изведе нещо подобно на:
Warning: [memtrack] [pid 26177] user function foo() executed in /tmp/example1.php on line 10 allocated 4194304 bytes in /tmp/example1.php on line 0 Warning: [memtrack] [pid 26177] virtual memory usage on shutdown: 32911360 bytes in Unknown on line 0
The purpose of this extension is to allow overloading of object property access and method calls. Only one function is defined in this extension, overload() which takes the name of the class that should have this functionality enabled. The class named has to define appropriate methods if it wants to have this functionality: __get(), __set() and __call() respectively for getting/setting a property, or calling a method. This way overloading can be selective. Inside these handler functions the overloading is disabled so you can access object properties normally.
Това разширение е ЕКСПЕРИМЕНТАЛНО. Поведението на разширението, включително имената на функциите и всичко останало, което е документирано за това разширение, могат да бъдат променени без предупреждение в бъдеща версия на PHP. Това разширение би трябвало да бъде използвано единствено на ваша собствена отговорност.
This extension is not a part of PHP 5. PHP 5 supports __get(), __set() and __call() natively. See the Overloading in PHP 5 page for more information.
Не са необходими външни библиотеки, за да се пусне това разширение.
In order to use these functions, you must compile PHP with the --enable-overload option. Starting with PHP 4.3.0 this extension is enabled by default. You can disable overload support with --disable--overload.
Версията на PHP за Windows има вградена поддръжка за това разширение. За да използвате тези функции, не е необходимо да бъдат зареждани никакви допълнителни разширения.
Забележка: Builtin support for overload is available with PHP 4.3.0.
Това разширение няма дефинирани конфигурационни директиви в php.ini.
Това разширение няма дефинирани ресурсни типове.
Това разширение няма дефинирани константи.
Some simple examples on using the overload() function:
Example #1 Overloading a PHP class
<?php
class OO {
var $a = 111;
var $elem = array('b' => 9, 'c' => 42);
// Callback method for getting a property
function __get($prop_name, &$prop_value)
{
if (isset($this->elem[$prop_name])) {
$prop_value = $this->elem[$prop_name];
return true;
} else {
return false;
}
}
// Callback method for setting a property
function __set($prop_name, $prop_value)
{
$this->elem[$prop_name] = $prop_value;
return true;
}
}
// Here we overload the OO object
overload('OO');
$o = new OO;
echo "\$o->a: $o->a\n"; // print: $o->a: 111
echo "\$o->b: $o->b\n"; // print: $o->b: 9
echo "\$o->c: $o->c\n"; // print: $o->c: 42
echo "\$o->d: $o->d\n"; // print: $o->d:
// add a new item to the $elem array in OO
$o->x = 56;
// instantiate stdclass (it is built-in in PHP 4)
// $val is not overloaded!
$val = new stdclass;
$val->prop = 555;
// Set "a" to be an array with the $val object in it
// But __set() will put this in the $elem array
$o->a = array($val);
var_dump($o->a[0]->prop);
?>
(PHP 4 >= 4.3.0)
overload — Enable property and method call overloading for a class
The overload() function will enable property and method call overloading for a class identified by class_name .
The overloaded class name, as a string
Няма връщана стойност.
See an example in the introductory section of this part.
The Output Control functions allow you to control when output is sent from the script. This can be useful in several different situations, especially if you need to send headers to the browser after your script has began outputting data. The Output Control functions do not affect headers sent using header() or setcookie(), only functions such as echo() and data between blocks of PHP code.
Забележка: When upgrading from PHP 4.1.x (and 4.2.x) to 4.3.x due to a bug in earlier versions you must ensure that implict_flush is OFF in your php.ini, otherwise any output with ob_start() will not be hidden from output.
Не са необходими външни библиотеки, за да се пусне това разширение.
Не е необходимо инсталиране, за да се използват тези функции. Те са част от ядрото на PHP.
Поведението на тези функции зависи от настройките в php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| output_buffering | "0" | PHP_INI_PERDIR | |
| output_handler | NULL | PHP_INI_PERDIR | Available since PHP 4.0.4. |
| implicit_flush | "0" | PHP_INI_ALL | PHP_INI_PERDIR in PHP <= 4.2.3. |
За по-детайлна информация и дефинициите на константите PHP_INI_*, вижте Where a configuration setting may be set.
Тук има кратко описание на конфигурационните директиви.
You can enable output buffering for all files by setting this directive to 'On'. If you wish to limit the size of the buffer to a certain size - you can use a maximum number of bytes instead of 'On', as a value for this directive (e.g., output_buffering=4096). As of PHP 4.3.5, this directive is always Off in PHP-CLI.
You can redirect all of the output of your scripts to a function. For example, if you set output_handler to mb_output_handler(), character encoding will be transparently converted to the specified encoding. Setting any output handler automatically turns on output buffering.
Забележка: You cannot use both mb_output_handler() with ob_iconv_handler() and you cannot use both ob_gzhandler() and zlib.output_compression.
Забележка: Only built-in functions can be used with this directive. For user defined functions, use ob_start().
FALSE by default. Changing this to TRUE tells PHP to tell the output layer to flush itself automatically after every output block. This is equivalent to calling the PHP function flush() after each and every call to print() or echo() and each and every HTML block.
When using PHP within an web environment, turning this option on has serious performance implications and is generally recommended for debugging purposes only. This value defaults to TRUE when operating under the CLI SAPI.
See also ob_implicit_flush().
Това разширение няма дефинирани ресурсни типове.
Това разширение няма дефинирани константи.
Example #1 Output Control example
<?php
ob_start();
echo "Hello\n";
setcookie("cookiename", "cookiedata");
ob_end_flush();
?>
In the above example, the output from echo() would be stored in the output buffer until ob_end_flush() was called. In the mean time, the call to setcookie() successfully stored a cookie without causing an error. (You can not normally send headers to the browser after data has already been sent.)
(PHP 4, PHP 5)
flush — Flush the output buffer
Flushes the write buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This attempts to push current output all the way to the browser with a few caveats.
flush() may not be able to override the buffering scheme of your web server and it has no effect on any client-side buffering in the browser. It also doesn't affect PHP's userspace output buffering mechanism. This means you will have to call both ob_flush() and flush() to flush the ob output buffers if you are using those.
Several servers, especially on Win32, will still buffer the output from your script until it terminates before transmitting the results to the browser.
Server modules for Apache like mod_gzip may do buffering of their own that will cause flush() to not result in data being sent immediately to the client.
Even the browser may buffer its input before displaying it. Netscape, for example, buffers text until it receives an end-of-line or the beginning of a tag, and it won't render tables until the </table> tag of the outermost table is seen.
Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page.
Няма връщана стойност.
(PHP 4 >= 4.2.0, PHP 5)
ob_clean — Clean (erase) the output buffer
This function discards the contents of the output buffer.
This function does not destroy the output buffer like ob_end_clean() does.
Няма връщана стойност.
(PHP 4, PHP 5)
ob_end_clean — Clean (erase) the output buffer and turn off output buffering
This function discards the contents of the topmost output buffer and turns off this output buffering. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_clean() as the buffer contents are discarded when ob_end_clean() is called.
Връща TRUE при успех или FALSE при неуспех. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).
If the function fails it generates an E_NOTICE.
| Версия | Описание |
|---|---|
| 4.2.0 | The boolean return value was added. |
The following example shows an easy way to get rid of all output buffers:
Example #1 ob_end_clean() example
<?php
ob_start();
echo 'Text that won\'t get displayed.';
ob_end_clean();
?>
(PHP 4, PHP 5)
ob_end_flush — Flush (send) the output buffer and turn off output buffering
This function will send the contents of the topmost output buffer (if any) and turn this output buffer off. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_flush() as the buffer contents are discarded after ob_end_flush() is called.
Забележка: This function is similar to ob_get_flush(), except that ob_get_flush() returns the buffer as a string.
Връща TRUE при успех или FALSE при неуспех. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).
If the function fails it generates an E_NOTICE.
| Версия | Описание |
|---|---|
| 4.2.0 | The boolean return value was added. |
Example #1 ob_end_flush() example
The following example shows an easy way to flush and end all output buffers:
<?php
while (@ob_end_flush());
?>
(PHP 4 >= 4.2.0, PHP 5)
ob_flush — Flush (send) the output buffer
This function will send the contents of the output buffer (if any). If you want to further process the buffer's contents you have to call ob_get_contents() before ob_flush() as the buffer contents are discarded after ob_flush() is called.
This function does not destroy the output buffer like ob_end_flush() does.
Няма връщана стойност.
(PHP 4 >= 4.3.0, PHP 5)
ob_get_clean — Get current buffer contents and delete current output buffer
Gets the current buffer contents and delete current output buffer.
ob_get_clean() essentially executes both ob_get_contents() and ob_end_clean().
Returns the contents of the output buffer and end output buffering. If output buffering isn't active then FALSE is returned.
Example #1 A simple ob_get_clean() example
<?php
ob_start();
echo "Hello World";
$out = ob_get_clean();
$out = strtolower($out);
var_dump($out);
?>
Примерът по-горе ще изведе:
string(11) "hello world"
(PHP 4, PHP 5)
ob_get_contents — Return the contents of the output buffer
Gets the contents of the output buffer without clearing it.
This will return the contents of the output buffer or FALSE, if output buffering isn't active.
Example #1 A simple ob_get_contents() example
<?php
ob_start();
echo "Hello ";
$out1 = ob_get_contents();
echo "World";
$out2 = ob_get_contents();
ob_end_clean();
var_dump($out1, $out2);
?>
Примерът по-горе ще изведе:
string(6) "Hello " string(11) "Hello World"
(PHP 4 >= 4.3.0, PHP 5)
ob_get_flush — Flush the output buffer, return it as a string and turn off output buffering
ob_get_flush() flushes the output buffer, return it as a string and turns off output buffering.
Забележка: This function is similar to ob_end_flush(), except that this function returns the buffer as a string.
Returns the output buffer or FALSE if no buffering is active.
Example #1 ob_get_flush() example
<?php
//using output_buffering=On
print_r(ob_list_handlers());
//save buffer in a file
$buffer = ob_get_flush();
file_put_contents('buffer.txt', $buffer);
print_r(ob_list_handlers());
?>
Примерът по-горе ще изведе:
Array
(
[0] => default output handler
)
Array
(
)
(PHP 4 >= 4.0.2, PHP 5)
ob_get_length — Return the length of the output buffer
This will return the length of the contents in the output buffer.
Returns the length of the output buffer contents or FALSE if no buffering is active.
Example #1 A simple ob_get_length() example
<?php
ob_start();
echo "Hello ";
$len1 = ob_get_length();
echo "World";
$len2 = ob_get_length();
ob_end_clean();
echo $len1 . ", ." . $len2;
?>
Примерът по-горе ще изведе:
6, 11
(PHP 4 >= 4.2.0, PHP 5)
ob_get_level — Return the nesting level of the output buffering mechanism
Returns the nesting level of the output buffering mechanism.
Returns the level of nested output buffering handlers or zero if output buffering is not active.
(PHP 4 >= 4.2.0, PHP 5)
ob_get_status — Get status of output buffers
ob_get_status() returns status information on either the top level output buffer or all active output buffer levels if full_status is set to TRUE.
TRUE to return all active output buffer levels. If FALSE or not set, only the top level output buffer is returned.
If called without the full_status parameter or with full_status = FALSE a simple array with the following elements is returned:
Array
(
[level] => 2
[type] => 0
[status] => 0
[name] => URL-Rewriter
[del] => 1
)
If called with full_status = TRUE an array with one element for each active output buffer level is returned. The output level is used as key of the top level array and each array element itself is another array holding status information on one active output level.
Array
(
[0] => Array
(
[chunk_size] => 0
[size] => 40960
[block_size] => 10240
[type] => 1
[status] => 0
[name] => default output handler
[del] => 1
)
[1] => Array
(
[chunk_size] => 0
[size] => 40960
[block_size] => 10240
[type] => 0
[buffer_size] => 0
[status] => 0
[name] => URL-Rewriter
[del] => 1
)
)
The full output contains these additional elements:
(PHP 4 >= 4.0.4, PHP 5)
ob_gzhandler — ob_start callback function to gzip output buffer
ob_gzhandler() is intended to be used as a callback function for ob_start() to help facilitate sending gz-encoded data to web browsers that support compressed web pages. Before ob_gzhandler() actually sends compressed data, it determines what type of content encoding the browser will accept ("gzip", "deflate" or none at all) and will return its output accordingly. All browsers are supported since it's up to the browser to send the correct header saying that it accepts compressed web pages. If a browser doesn't support compressed pages this function returns FALSE.
| Версия | Описание |
|---|---|
| 4.0.5 | The mode parameter was added. |
Example #1 ob_gzhandler() example
<?php
ob_start("ob_gzhandler");
?>
<html>
<body>
<p>This should be a compressed page.</p>
</html>
<body>
Забележка: ob_gzhandler() requires the zlib extension.
Забележка: You cannot use both ob_gzhandler() and zlib.output_compression. Also note that using zlib.output_compression is preferred over ob_gzhandler().
(PHP 4, PHP 5)
ob_implicit_flush — Turn implicit flush on/off
ob_implicit_flush() will turn implicit flushing on or off. Implicit flushing will result in a flush operation after every output call, so that explicit calls to flush() will no longer be needed.
TRUE to turn implicit flushing on, FALSE otherwise. Defaults to TRUE.
Няма връщана стойност.
(PHP 4 >= 4.3.0, PHP 5)
ob_list_handlers — List all output handlers in use
Lists all output handlers in use.
This will return an array with the output handlers in use (if any). If output_buffering is enabled or an anonymous function was used with ob_start(), ob_list_handlers() will return "default output handler".
Example #1 ob_list_handlers() example
<?php
//using output_buffering=On
print_r(ob_list_handlers());
ob_end_flush();
ob_start("ob_gzhandler");
print_r(ob_list_handlers());
ob_end_flush();
// anonymous functions
ob_start(create_function('$string', 'return $string;'));
print_r(ob_list_handlers());
ob_end_flush();
?>
Примерът по-горе ще изведе:
Array
(
[0] => default output handler
)
Array
(
[0] => ob_gzhandler
)
Array
(
[0] => default output handler
)
(PHP 4, PHP 5)
ob_start — Turn on output buffering
This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.
The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.
Some web servers (e.g. Apache) change the working directory of a script when calling the callback function. You can change it back by e.g. chdir(dirname($_SERVER['SCRIPT_FILENAME'])) in the callback function.
Output buffers are stackable, that is, you may call ob_start() while another ob_start() is active. Just make sure that you call ob_end_flush() the appropriate number of times. If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order.
An optional output_callback function may be specified. This function takes a string as a parameter and should return a string. The function will be called when the output buffer is flushed (sent) or cleaned (with ob_flush(), ob_clean() or similar function) or when the output buffer is flushed to the browser at the end of the request. When output_callback is called, it will receive the contents of the output buffer as its parameter and is expected to return a new output buffer as a result, which will be sent to the browser. If the output_callback is not a callable function, this function will return FALSE.
If the callback function has two parameters, the second parameter is filled with a bit-field consisting of PHP_OUTPUT_HANDLER_START, PHP_OUTPUT_HANDLER_CONT and PHP_OUTPUT_HANDLER_END.
If output_callback returns FALSE original input is sent to the browser.
The output_callback parameter may be bypassed by passing a NULL value.
ob_end_clean(), ob_end_flush(), ob_clean(), ob_flush() and ob_start() may not be called from a callback function. If you call them from callback function, the behavior is undefined. If you would like to delete the contents of a buffer, return "" (a null string) from callback function. You can't even call functions using the output buffering functions like print_r($expression, true) or highlight_file($filename, true) from a callback function.
Забележка: In PHP 4.0.4, ob_gzhandler() was introduced to facilitate sending gz-encoded data to web browsers that support compressed web pages. ob_gzhandler() determines what type of content encoding the browser will accept and will return its output accordingly.
If the optional parameter chunk_size is passed, the buffer will be flushed after any output call which causes the buffer's length to equal or exceed chunk_size . Default value 0 means that the function is called only in the end, other special value 1 sets chunk_size to 4096.
If the optional parameter erase is set to FALSE, the buffer will not be deleted until the script finishes.
Връща TRUE при успех или FALSE при неуспех.
| Версия | Описание |
|---|---|
| 4.3.2 | This function was changed to return FALSE in case the passed output_callback can not be executed. |
| 4.2.0 | Added the erase parameter. |
Example #1 User defined callback function example
<?php
function callback($buffer)
{
// replace all the apples with oranges
return (str_replace("apples", "oranges", $buffer));
}
ob_start("callback");
?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php
ob_end_flush();
?>
Примерът по-горе ще изведе:
<html> <body> <p>It's like comparing oranges to oranges.</p> </body> </html>
(PHP 4 >= 4.3.0, PHP 5)
output_add_rewrite_var — Add URL rewriter values
This function adds another name/value pair to the URL rewrite mechanism. The name and value will be added to URLs (as GET parameter) and forms (as hidden input fields) the same way as the session ID when transparent URL rewriting is enabled with session.use_trans_sid. Please note that absolute URLs (http://example.com/..) aren't rewritten.
This function's behavior is controlled by the url_rewriter.tags php.ini parameter.
Забележка: Calling this function will implicitly start output buffering if it is not active already.
The variable name.
The variable value.
Връща TRUE при успех или FALSE при неуспех.
Example #1 output_add_rewrite_var() example
<?php
output_add_rewrite_var('var', 'value');
// some links
echo '<a href="file.php">link</a>
<a href="http://example.com">link2</a>';
// a form
echo '<form action="script.php" method="post">
<input type="text" name="var2" />
</form>';
print_r(ob_list_handlers());
?>
Примерът по-горе ще изведе:
<a href="file.php?var=value">link</a>
<a href="http://example.com">link2</a>
<form action="script.php" method="post">
<input type="hidden" name="var" value="value" />
<input type="text" name="var2" />
</form>
Array
(
[0] => URL-Rewriter
)
(PHP 4 >= 4.3.0, PHP 5)
output_reset_rewrite_vars — Reset URL rewriter values
This function resets the URL rewriter and removes all rewrite variables previously set by the output_add_rewrite_var() function or the session mechanism (if session.use_trans_sid was set on session_start()).
Връща TRUE при успех или FALSE при неуспех.
Example #1 output_reset_rewrite_vars() example
<?php
session_start();
output_add_rewrite_var('var', 'value');
echo '<a href="file.php">link</a>';
ob_flush();
output_reset_rewrite_vars();
echo '<a href="file.php">link</a>';
?>
Примерът по-горе ще изведе:
<a href="file.php?PHPSESSID=xxx&var=value">link</a> <a href="file.php">link</a>
See also header() and setcookie().
The runkit extension provides means to modify constants, user-defined functions, and user-defined classes. It also provides for custom superglobal variables and embeddable sub-interpreters via sandboxing.
This package is meant as a feature added replacement for the » classkit package. When compiled with the --enable-runkit=classkit option to ./configure, it will export classkit compatible function definitions and constants.
Константите по-долу са дефинирани в това разширение и ще бъдат налични единствено, когато това разширение е компилирано в PHP или пуснато динамично по време на изпълнение.
Modifying Constants, Functions, Classes, and Methods works with all releases of PHP 4 and PHP 5. No special requirements are necessary.
Custom Superglobals are only available in PHP 4.2.0 or later.
Sandboxing requires PHP 5.1.0 or later, or PHP 5.0.0 with a special TSRM patch applied. Regardless of which version of PHP is in use it must be compiled with the --enable-maintainer-zts option. See the README file in the runkit package for additional information.
Това » PECL разширение не е част от пакета на PHP.
Информация относно инсталирането на това PECL разширение може да се намери в главата от ръководството Инсталиране на PECL разширения. Допълнителна информация, като нови издания, изтегляния, изходни файлове, информация за поддръжката и CHANGELOG може да се намери тук: » http://pecl.php.net/package/runkit.
DLL файла на това разширение може да бъде изтеглен или от страницата за » изтегляне на PHP или от » http://pecl4win.php.net/
Поведението на тези функции зависи от настройките в php.ini.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| runkit.superglobal | "" | PHP_INI_PERDIR | |
| runkit.internal_override | "0" | PHP_INI_SYSTEM |
За по-детайлна информация и дефинициите на константите PHP_INI_*, вижте Where a configuration setting may be set.
Тук има кратко описание на конфигурационните директиви.
Example #1 Custom Superglobals with runkit.superglobal=_FOO,_BAR in php.ini
<?php
function show_values() {
echo "Foo is $_FOO\n";
echo "Bar is $_BAR\n";
echo "Baz is $_BAZ\n";
}
$_FOO = 'foo';
$_BAR = 'bar';
$_BAZ = 'baz';
/* Displays foo and bar, but not baz */
show_values();
?>
Това разширение няма дефинирани ресурсни типове.
(PECL runkit >= 0.7.0)
Runkit_Sandbox — Runkit Sandbox Class -- PHP Virtual Machine
Instantiating the Runkit_Sandbox class creates a new thread with its own scope and program stack. Using a set of options passed to the constructor, this environment may be restricted to a subset of what the primary interpreter can do and provide a safer environment for executing user supplied code.
Забележка: Поддръжката на Sandbox (необходима на runkit_lint(), runkit_lint_file() и класа Runkit_Sandbox) е достъпна само от PHP 5.1.0 или специално скърпени версии на PHP 5.0 и изисква безопасността на нишките да бъде включена. Вижте файла README, включен в пакета runkit за повече информация.
options is an associative array containing any combination of the special ini options listed below.
If the outer script which is instantiating the Runkit_Sandbox class is configured with safe_mode = off, then safe_mode may be turned on for the sandbox environment. This setting can not be used to disable safe_mode when it's already enabled in the outer script.
If the outer script which is instantiating the Runkit_Sandbox class is configured with safe_mode_gid = on, then safe_mode_gid may be turned off for the sandbox environment. This setting can not be used to enable safe_mode_gid when it's already disabled in the outer script.
If the outer script which is instantiating the Runkit_Sandbox class is configured with a safe_mode_include_dir, then a new safe_mode_include_dir may be set for sandbox environments below the currently defined value. safe_mode_include_dir may also be cleared to indicate that the bypass feature is disabled. If safe_mode_include_dir was blank in the outer script, but safe_mode was not enabled, then any arbitrary safe_mode_include_dir may be set while turning safe_mode on.
open_basedir may be set to any path below the current setting of open_basedir. If open_basedir is not set within the global scope, then it is assumed to be the root directory and may be set to any location.
Like safe_mode , this setting can only be made more restrictive, in this case by setting it to FALSE when it is previously set to TRUE
Comma separated list of functions to disable within the sandbox sub-interpreter. This list need not contain the names of the currently disabled functions, they will remain disabled whether listed here or not.
Comma separated list of classes to disable within the sandbox sub-interpreter. This list need not contain the names of the currently disabled classes, they will remain disabled whether listed here or not.
Comma separated list of variables to be treated as superglobals within the sandbox sub-interpreter. These variables will be used in addition to any variables defined internally or through the global runkit.superglobal setting.
Ini option runkit.internal_override may be disabled (but not re-enabled) within sandboxes.
Example #1 Instantiating a restricted sandbox
<?php
$options = array(
'safe_mode'=>true,
'open_basedir'=>'/var/www/users/jdoe/',
'allow_url_fopen'=>'false',
'disable_functions'=>'exec,shell_exec,passthru,system',
'disable_classes'=>'myAppClass');
$sandbox = new Runkit_Sandbox($options);
/* Non-protected ini settings may set normally */
$sandbox->ini_set('html_errors',true);
?>
All variables in the global scope of the sandbox environment are accessible as properties of the sandbox object. The first thing to note is that because of the way memory between these two threads is managed, object and resource variables can not currently be exchanged between interpreters. Additionally, all arrays are deep copied and any references will be lost. This also means that references between interpreters are not possible.
Example #2 Working with variables in a sandbox
<?php
$sandbox = new Runkit_Sandbox();
$sandbox->foo = 'bar';
$sandbox->eval('echo "$foo\n"; $bar = $foo . "baz";');
echo "{$sandbox->bar}\n";
if (isset($sandbox->foo)) unset($sandbox->foo);
$sandbox->eval('var_dump(isset($foo));');
?>
Примерът по-горе ще изведе:
bar barbaz bool(false)
Any function defined within the sandbox may be called as a method on the sandbox object. This also includes a few pseudo-function language constructs: eval(), include(), include_once(), require(), require_once(), echo(), print(), die(), and exit().
Example #3 Calling sandbox functions
<?php
$sandbox = new Runkit_Sandbox();
echo $sandbox->str_replace('a','f','abc');
?>
Примерът по-горе ще изведе:
fbc
When passing arguments to a sandbox function, the arguments are taken from the outer instance of PHP. If you wish to pass arguments from the sandbox's scope, be sure to access them as properties of the sandbox object as illustrated above.
Example #4 Passing arguments to sandbox functions
<?php
$sandbox = new Runkit_Sandbox();
$foo = 'bar';
$sandbox->foo = 'baz';
echo $sandbox->str_replace('a',$foo,'a');
echo $sandbox->str_replace('a',$sandbox->foo,'a');
?>
Примерът по-горе ще изведе:
bar baz
As of runkit version 0.5, certain Sandbox settings may be modified on the fly using ArrayAccess syntax. Some settings, such as active are read-only and meant to provide status information. Other settings, such as output_handler may be set and read much like a normal array offset. Future settings may be write-only, however no such settings currently exist.
| Setting | Type | Purpose | Default |
|---|---|---|---|
| active | Boolean (Read Only) | TRUE if the Sandbox is still in a usable state, FALSE if the request is in bailout due to a call to die(), exit(), or because of a fatal error condition. | TRUE (Initial) |
| output_handler | Callback | When set to a valid callback, all output generated by the Sandbox instance will be processed through the named function. Sandbox output handlers follow the same calling conventions as the system-wide output handler. | None |
| parent_access | Boolean | May the sandbox use instances of the Runkit_Sandbox_Parent class? Must be enabled for other Runkit_Sandbox_Parent related settings to work. | FALSE |
| parent_read | Boolean | May the sandbox read variables in its parent's context? | FALSE |
| parent_write | Boolean | May the sandbox modify variables in its parent's context? | FALSE |
| parent_eval | Boolean | May the sandbox evaluate arbitrary code in its parent's context? DANGEROUS | FALSE |
| parent_include | Boolean | May the sandbox include php code files in its parent's context? DANGEROUS | FALSE |
| parent_echo | Boolean | May the sandbox echo data in its parent's context effectively bypassing its own output_handler? | FALSE |
| parent_call | Boolean | May the sandbox call functions in its parent's context? | FALSE |
| parent_die | Boolean | May the sandbox kill its own parent? (And thus itself) | FALSE |
| parent_scope | Integer | What scope will parental property access look at? 0 == Global scope, 1 == Calling scope, 2 == Scope preceeding calling scope, 3 == The scope before that, etc..., etc... | 0 (Global) |
| parent_scope | String | When parent_scope is set to a string value, it refers to a named array variable in the global scope. If the named variable does not exist at the time of access it will be created as an empty array. If the variable exists but it not an array, a dummy array will be created containing a reference to the named global variable. |
(PECL runkit >= 0.7.0)
Runkit_Sandbox_Parent — Runkit Anti-Sandbox Class
Instantiating the Runkit_Sandbox_Parent class from within a sandbox environment created from the Runkit_Sandbox class provides some (controlled) means for a sandbox child to access its parent.
Забележка: Поддръжката на Sandbox (необходима на runkit_lint(), runkit_lint_file() и класа Runkit_Sandbox) е достъпна само от PHP 5.1.0 или специално скърпени версии на PHP 5.0 и изисква безопасността на нишките да бъде включена. Вижте файла README, включен в пакета runkit за повече информация.
In order for any of the Runkit_Sandbox_Parent features to function. Support must be enabled on a per-sandbox basis by enabling the parent_access flag from the parent's context.
Example #1 Working with variables in a sandbox
<?php
$sandbox = new Runkit_Sandbox();
$sandbox['parent_access'] = true;
?>
Just as with sandbox variable access, a sandbox parent's variables may be read from and written to as properties of the Runkit_Sandbox_Parent class. Read access to parental variables may be enabled with the parent_read setting (in addition to the base parent_access setting). Write access, in turn, is enabled through the parent_write setting.
Unlike sandbox child variable access, the variable scope is not limited to globals only. By setting the parent_scope setting to an appropriate integer value, other scopes in the active call stack may be inspected instead. A value of 0 (Default) will direct variable access at the global scope. 1 will point variable access at whatever variable scope was active at the time the current block of sandbox code was executed. Higher values progress back through the functions that called the functions that led to the sandbox executing code that tried to access its own parent's variables.
Example #2 Accessing parental variables
<?php
$php = new Runkit_Sandbox();
$php['parent_access'] = true;
$php['parent_read'] = true;
$test = "Global";
$php->eval('$PARENT = new Runkit_Sandbox_Parent;');
$php['parent_scope'] = 0;
one();
$php['parent_scope'] = 1;
one();
$php['parent_scope'] = 2;
one();
$php['parent_scope'] = 3;
one();
$php['parent_scope'] = 4;
one();
$php['parent_scope'] = 5;
one();
function one() {
$test = "one()";
two();
}
function two() {
$test = "two()";
three();
}
function three() {
$test = "three()";
$GLOBALS['php']->eval('var_dump($PARENT->test);');
}
?>
Примерът по-горе ще изведе:
string(6) "Global" string(7) "three()" string(5) "two()" string(5) "one()" string(6) "Global" string(6) "Global"
Just as with sandbox access, a sandbox may access its parents functions providing that the proper settings have been enabled. Enabling parent_call will allow the sandbox to call all functions available to the parent scope. Language constructs are each controlled by their own setting: print() and echo() are enabled with parent_echo. die() and exit() are enabled with parent_die. eval() is enabled with parent_eval while include(), include_once(), require(), and require_once() are enabled through parent_include.
(PECL runkit >= 0.7.0)
runkit_class_adopt — Convert a base class to an inherited class, add ancestral methods when appropriate
Name of class to be adopted
Parent class which child class is extending
Връща TRUE при успех или FALSE при неуспех.
Example #1 A runkit_class_adopt() example
<?php
class myParent {
function parentFunc() {
echo "Parent Function Output\n";
}
}
class myChild {
}
runkit_class_adopt('myChild','myParent');
myChild::parentFunc();
?>
Примерът по-горе ще изведе:
Parent Function Output
(PECL runkit >= 0.7.0)
runkit_class_emancipate — Convert an inherited class to a base class, removes any method whose scope is ancestral
Name of class to emancipate
Връща TRUE при успех или FALSE при неуспех.
Example #1 A runkit_class_emancipate() example
<?php
class myParent {
function parentFunc () {
echo "Parent Function Output\n";
}
}
class myChild extends myParent {
}
myChild::parentFunc();
runkit_class_emancipate('myChild');
myChild::parentFunc();
?>
Примерът по-горе ще изведе:
Parent Function Output Fatal error: Call to undefined function: parentFunc() in example.php on line 12
(PECL runkit >= 0.7.0)
runkit_constant_add — Similar to define(), but allows defining in class definitions as well
Name of constant to declare. Either a string to indicate a global constant, or classname::constname to indicate a class constant.
NULL, Bool, Long, Double, String, or Resource value to store in the new constant.
Връща TRUE при успех или FALSE при неуспех.
(PECL runkit >= 0.7.0)
runkit_constant_redefine — Redefine an already defined constant
Constant to redefine. Either string indicating global constant, or classname::constname indicating class constant.
New value to assign to constant.
Връща TRUE при успех или FALSE при неуспех.
(PECL runkit >= 0.7.0)
runkit_constant_remove — Remove/Delete an already defined constant
Name of constant to remove. Either a string indicating a global constant, or classname::constname indicating a class constant.
Връща TRUE при успех или FALSE при неуспех.
(PECL runkit >= 0.7.0)
runkit_function_add — Add a new function, similar to create_function()
Name of function to be created
Comma separated argument list
Code making up the function
Връща TRUE при успех или FALSE при неуспех.
Example #1 A runkit_function_add() example
<?php
runkit_function_add('testme','$a,$b','echo "The value of a is $a\n"; echo "The value of b is $b\n";');
testme(1,2);
?>
Примерът по-горе ще изведе:
The value of a is 1 The value of b is 2
(PECL runkit >= 0.7.0)
runkit_function_copy — Copy a function to a new function name
Name of existing function
Name of new function to copy definition to
Връща TRUE при успех или FALSE при неуспех.
Example #1 A runkit_function_copy() example
<?php
function original() {
echo "In a function\n";
}
runkit_function_copy('original','duplicate');
original();
duplicate();
?>
Примерът по-горе ще изведе:
In a function In a function
(PECL runkit >= 0.7.0)
runkit_function_redefine — Replace a function definition with a new implementation
Забележка: По подразбиране, само userspace функциите могат да бъдат отстранявани, преименувани или променяни. За да препокриете вътрешните функции, трябва да включите настройката runkit.internal_override във файла php.ini.
Name of function to redefine
New list of arguments to be accepted by function
New code implementation
Връща TRUE при успех или FALSE при неуспех.
Example #1 A runkit_function_redefine() example
<?php
function testme() {
echo "Original Testme Implementation\n";
}
testme();
runkit_function_redefine('testme','','echo "New Testme Implementation\n";');
testme();
?>
Примерът по-горе ще изведе:
Original Testme Implementation New Testme Implementation
(PECL runkit >= 0.7.0)
runkit_function_remove — Remove a function definition
Забележка: По подразбиране, само userspace функциите могат да бъдат отстранявани, преименувани или променяни. За да препокриете вътрешните функции, трябва да включите настройката runkit.internal_override във файла php.ini.
Name of function to be deleted
Връща TRUE при успех или FALSE при неуспех.
(PECL runkit >= 0.7.0)
runkit_function_rename — Change a function's name
Забележка: По подразбиране, само userspace функциите могат да бъдат отстранявани, преименувани или променяни. За да препокриете вътрешните функции, трябва да включите настройката runkit.internal_override във файла php.ini.
Current function name
New function name
Връща TRUE при успех или FALSE при неуспех.
(PECL runkit >= 0.7.0)
runkit_import — Process a PHP file importing function and class definitions, overwriting where appropriate
Similar to include() however any code residing outside of a function or class is simply ignored. Additionally, depending on the value of flags , any functions or classes which already exist in the currently running environment will be automatically overwritten by their new definitions.
Filename to import function and class definitions from
Bitwise OR of the RUNKIT_IMPORT_* family of constants.
Връща TRUE при успех или FALSE при неуспех.
(PECL runkit >= 0.7.0)
runkit_lint_file — Check the PHP syntax of the specified file
The runkit_lint_file() function performs a syntax (lint) check on the specified filename testing for scripting errors. This is similar to using php -l from the commandline.
Забележка: Поддръжката на Sandbox (необходима на runkit_lint(), runkit_lint_file() и класа Runkit_Sandbox) е достъпна само от PHP 5.1.0 или специално скърпени версии на PHP 5.0 и изисква безопасността на нишките да бъде включена. Вижте файла README, включен в пакета runkit за повече информация.
File containing PHP Code to be lint checked
Връща TRUE при успех или FALSE при неуспех.
(PECL runkit >= 0.7.0)
runkit_lint — Check the PHP syntax of the specified php code
The runkit_lint() function performs a syntax (lint) check on the specified php code testing for scripting errors. This is similar to using php -l from the command line except runkit_lint() accepts actual code rather than a filename.
Забележка: Поддръжката на Sandbox (необходима на runkit_lint(), runkit_lint_file() и класа Runkit_Sandbox) е достъпна само от PHP 5.1.0 или специално скърпени версии на PHP 5.0 и изисква безопасността на нишките да бъде включена. Вижте файла README, включен в пакета runkit за повече информация.
PHP Code to be lint checked
Връща TRUE при успех или FALSE при неуспех.
(PECL runkit >= 0.7.0)
runkit_method_add — Dynamically adds a new method to a given class
Тази функция е ЕКСПЕРИМЕНТАЛНА. Поведението на функцията, името й, както и съпътстващата документация, могат да бъдат променени без предупреждение в бъдеща версия на PHP. Тази функция би трябвало да бъде използвана единствено на ваша собствена отговорност.
The class to which this method will be added
The name of the method to add
Comma-delimited list of arguments for the newly-created method
The code to be evaluated when methodname is called
The type of method to create, can be RUNKIT_ACC_PUBLIC, RUNKIT_ACC_PROTECTED or RUNKIT_ACC_PRIVATE
Забележка: This parameter is only used as of PHP 5, because, prior to this, all methods were public.
Връща TRUE при успех или FALSE при неуспех.
Example #1 runkit_method_add() example
<?php
class Example {
function foo() {
echo "foo!\n";
}
}
// create an Example object
$e = new Example();
// Add a new public method
runkit_method_add(
'Example',
'add',
'$num1, $num2',
'return $num1 + $num2;',
RUNKIT_ACC_PUBLIC
);
// add 12 + 4
echo $e->add(12, 4);
?>
Примерът по-горе ще изведе:
16
(PECL runkit >= 0.7.0)
runkit_method_copy — Copies a method from class to another
Тази функция е ЕКСПЕРИМЕНТАЛНА. Поведението на функцията, името й, както и съпътстващата документация, могат да бъдат променени без предупреждение в бъдеща версия на PHP. Тази функция би трябвало да бъде използвана единствено на ваша собствена отговорност.
Destination class for copied method
Destination method name
Source class of the method to copy
Name of the method to copy from the source class. If this parameter is omitted, the value of dMethod is assumed.
Връща TRUE при успех или FALSE при неуспех.
Example #1 runkit_method_copy() example
<?php
class Foo {
function example() {
return "foo!\n";
}
}
class Bar {
// initially, no methods
}
// copy the example() method from the Foo class to the Bar class, as baz()
runkit_method_copy('Bar', 'baz', 'Foo', 'example');
// output copied function
echo Bar::baz();
?>
Примерът по-горе ще изведе:
foo!
(PECL runkit >= 0.7.0)
runkit_method_redefine — Dynamically changes the code of the given method
Забележка: Тази функция не може да се използва за да манипулира текущо стартирания (или заключен) метод.
Тази функция е ЕКСПЕРИМЕНТАЛНА. Поведението на функцията, името й, както и съпътстващата документация, могат да бъдат променени без предупреждение в бъдеща версия на PHP. Тази функция би трябвало да бъде използвана единствено на ваша собствена отговорност.
The class in which to redefine the method
The name of the method to redefine
Comma-delimited list of arguments for the redefined method
The new code to be evaluated when methodname is called
The redefined method can be RUNKIT_ACC_PUBLIC, RUNKIT_ACC_PROTECTED or RUNKIT_ACC_PRIVATE
Забележка: This parameter is only used as of PHP 5, because, prior to this, all methods were public.
Връща TRUE при успех или FALSE при неуспех.
Example #1 runkit_method_redefine() example
<?php
class Example {
function foo() {
return "foo!\n";
}
}
// create an Example object
$e = new Example();
// output Example::foo() (before redefine)
echo "Before: " . $e->foo();
// Redefine the 'foo' method
runkit_method_redefine(
'Example',
'foo',
'',
'return "bar!\n";',
RUNKIT_ACC_PUBLIC
);
// output Example::foo() (after redefine)
echo "After: " . $e->foo();
?>
Примерът по-горе ще изведе:
Before: foo! After: bar!
(PECL runkit >= 0.7.0)
runkit_method_remove — Dynamically removes the given method
Забележка: Тази функция не може да се използва за да манипулира текущо стартирания (или заключен) метод.
Тази функция е ЕКСПЕРИМЕНТАЛНА. Поведението на функцията, името й, както и съпътстващата документация, могат да бъдат променени без предупреждение в бъдеща версия на PHP. Тази функция би трябвало да бъде използвана единствено на ваша собствена отговорност.
The class in which to remove the method
The name of the method to remove
Връща TRUE при успех или FALSE при неуспех.
Example #1 runkit_method_remove() example
<?php
class Example {
function foo() {
return "foo!\n";
}
function bar() {
return "bar!\n";
}
}
// Remove the 'foo' method
runkit_method_remove(
'Example',
'foo'
);
echo implode(' ', get_class_methods('Example'));
?>
Примерът по-горе ще изведе:
bar
(PECL runkit >= 0.7.0)
runkit_method_rename — Dynamically changes the name of the given method
Забележка: Тази функция не може да се използва за да манипулира текущо стартирания (или заключен) метод.
Тази функция е ЕКСПЕРИМЕНТАЛНА. Поведението на функцията, името й, както и съпътстващата документация, могат да бъдат променени без предупреждение в бъдеща версия на PHP. Тази функция би трябвало да бъде използвана единствено на ваша собствена отговорност.
The class in which to rename the method
The name of the method to rename
The new name to give to the renamed method
Връща TRUE при успех или FALSE при неуспех.
Example #1 runkit_method_rename() example
<?php
class Example {
function foo() {
return "foo!\n";
}
}
// Rename the 'foo' method to 'bar'
runkit_method_rename(
'Example',
'foo',
'bar'
);
// output renamed function
echo Example::bar();
?>
Примерът по-горе ще изведе:
foo!
(PECL runkit >= 0.8.0)
runkit_return_value_used — Determines if the current functions return value will be used
Returns TRUE if the function's return value is used by the calling scope, otherwise FALSE
Example #1 runkit_return_value_used() example
<?php
function foo() {
var_dump(runkit_return_value_used());
}
foo();
$f = foo();
?>
Примерът по-горе ще изведе:
bool(false) bool(true)
(PECL runkit >= 0.7.0)
runkit_sandbox_output_handler — Specify a function to capture and/or process output from a runkit sandbox
Ordinarily, anything output (such as with echo() or print()) will be output as though it were printed from the parent's scope. Using runkit_sandbox_output_handler() however, output generated by the sandbox (including errors), can be captured by a function outside of the sandbox.
Забележка: Поддръжката на Sandbox (необходима на runkit_lint(), runkit_lint_file() и класа Runkit_Sandbox) е достъпна само от PHP 5.1.0 или специално скърпени версии на PHP 5.0 и изисква безопасността на нишките да бъде включена. Вижте файла README, включен в пакета runkit за повече информация.
Забележка: Deprecated
As of runkit version 0.5, this function is deprecated and is scheduled to be removed from the package prior to a 1.0 release. The output handler for a given Runkit_Sandbox instance may be read/set using the array offset syntax shown on the Runkit_Sandbox class definition page.
Object instance of Runkit_Sandbox class on which to set output handling.
Name of a function which expects one parameter. Output generated by sandbox will be passed to this callback. Anything returned by the callback will be displayed normally. If this parameter is not passed then output handling will not be changed. If a non-truth value is passed, output handling will be disabled and will revert to direct display.
Returns the name of the previously defined output handler callback, or FALSE if no handler was previously defined.
Example #1 Feeding output to a variable
<?php
function capture_output($str) {
$GLOBALS['sandbox_output'] .= $str;
return '';
}
$sandbox_output = '';
$php = new Runkit_Sandbox();
runkit_sandbox_output_handler($php, 'capture_output');
$php->echo("Hello\n");
$php->eval('var_dump("Excuse me");');
$php->die("I lost myself.");
unset($php);
echo "Sandbox Complete\n\n";
echo $sandbox_output;
?>
Примерът по-горе ще изведе:
Sandbox Complete Hello string(9) "Excuse me" I lost myself.
(PECL runkit >= 0.7.0)
runkit_superglobals — Return numerically indexed array of registered superglobals
Returns a numerically indexed array of the currently registered superglobals. i.e. _GET, _POST, _REQUEST, _COOKIE, _SESSION, _SERVER, _ENV, _FILES
The scream extension gives the possibility to disable the silencing error control operator so all errors are being reported. This feature is controlled by an ini setting.
PHP version 5.2.0 or greater.
Информация относно инсталирането на това PECL разширение може да се намери в главата от ръководството Инсталиране на PECL разширения. Допълнителна информация, като нови издания, изтегляния, изходни файлове, информация за поддръжката и CHANGELOG може да се намери тук: » http://pecl.php.net/package/scream
Поведението на тези функции зависи от настройките в php.ini.
| Име | По подразбиране | Модифицируемо | Changelog |
|---|---|---|---|
| scream.enabled | Off | PHP_INI_ALL |
За по-детайлна информация и дефинициите на константите PHP_INI_*, вижте Where a configuration setting may be set.
Тук има кратко описание на конфигурационните директиви.
Whether or not to enable scream.
Това разширение няма дефинирани ресурсни типове.
This example demonstrates how scream affects the behaviour of PHP's error handler.
Example #1 Enabling and disabling scream at runtime
<?php
// Make sure errors will be shown
ini_set('display_errors', true);
error_reporting(E_ALL);
// Disable scream - this is the default and produce an error
ini_set('scream.enabled', false);
echo "Opening http://example.com/not-existing-file\n";
@fopen('http://example.com/not-existing-file', 'r');
// Now enable scream and try again
ini_set('scream.enabled', true);
echo "Opening http://example.com/not-existing-file\n";
@fopen('http://example.com/another-not-existing-file', 'r');
?>
Примерът по-горе ще изведе нещо подобно на:
Opening http://example.com/not-existing-file Opening http://example.com/not-existing-file Warning: fopen(http://example.com/another-not-existing-file): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in example.php on line 14
Забележка: Usually one would set this in the php.ini configuration file instead of changing the code.
These functions let you read and manipulate ID3 tags. ID3 tags are used in MP3 files to store title of the song, as well as information about the artist, album, genre, year and track number.
Since version 0.2 it is also possible to extract text frames from ID3 v2.2+ tags.
Не са необходими външни библиотеки, за да се пусне това разширение.
id3 is part of PECL and can be installed using the PEAR installer. To compile PHP with id3 support, download the sourcecode, put it in php-src/ext/id3 and compile PHP using --enable-id3.
Това разширение няма дефинирани конфигурационни директиви в php.ini.
Това разширение няма дефинирани ресурсни типове.
Most of the id3 functions either let you specify or return a tag version. In order to specify the version please use on of these constants.
(PECL id3 >= 0.2)
id3_get_frame_long_name — Get the long name of an ID3v2 frame
id3_get_frame_long_name() returns the long name for an ID3v2 frame.
An ID3v2 frame
Returns the frame long name or FALSE on errors.
Example #1 id3_get_frame_long_name() example
<?php
$longName = id3_get_frame_long_name("TOLY");
echo $longName;
?>
Примерът по-горе ще изведе:
Original lyricist(s)/text writer(s)
(PECL id3 >= 0.2)
id3_get_frame_short_name — Get the short name of an ID3v2 frame
id3_get_frame_short_name() returns the short name for an ID3v2 frame.
An ID3v2 frame
Returns the frame short name or FALSE on errors.
The values returned by id3_get_frame_short_name() are used in the array returned by id3_get_tag().
Example #1 id3_get_frame_short_name() example
<?php
$shortName = id3_get_frame_short_name("TOLY");
echo $shortName;
?>
Примерът по-горе ще изведе:
originalLyricist
(PECL id3 >= 0.1)
id3_get_genre_id — Get the id for a genre
id3_get_genre_id() returns the id for a genre.
An integer ranging from 0 to 147
The genre id or FALSE on errors.
Example #1 id3_get_genre_id() example
<?php
$id = id3_get_genre_id("Alternative");
echo $id;
?>
Примерът по-горе ще изведе:
20
(PECL id3 >= 0.1)
id3_get_genre_list — Get all possible genre values
id3_get_genre_list() returns an array containing all possible genres that may be stored in an ID3 tag. This list has been created by Eric Kemp and later extended by WinAmp.
This function is useful to provide you users a list of genres from which they may choose one. When updating the ID3 tag you will always have to specify the genre as an integer ranging from 0 to 147.
Returns an array containing all possible genres that may be stored in an ID3 tag.
Example #1 id3_get_genre_list() example
<?php
$genres = id3_get_genre_list();
print_r($genres);
?>
Примерът по-горе ще изведе:
Array
(
[0] => Blues
[1] => Classic Rock
[2] => Country
[3] => Dance
[4] => Disco
[5] => Funk
[6] => Grunge
[7] => Hip-Hop
[8] => Jazz
[9] => Metal
[10] => New Age
[11] => Oldies
[12] => Other
[13] => Pop
[14] => R&B
[15] => Rap
[16] => Reggae
[17] => Rock
[18] => Techno
[19] => Industrial
[20] => Alternative
[21] => Ska
[22] => Death Metal
[23] => Pranks
[24] => Soundtrack
[25] => Euro-Techno
[26] => Ambient
[27] => Trip-Hop
[28] => Vocal
[29] => Jazz+Funk
[30] => Fusion
[31] => Trance
[32] => Classical
[33] => Instrumental
[34] => Acid
[35] => House
[36] => Game
[37] => Sound Clip
[38] => Gospel
[39] => Noise
[40] => Alternative Rock
[41] => Bass
[42] => Soul
[43] => Punk
[44] => Space
[45] => Meditative
[46] => Instrumental Pop
[47] => Instrumental Rock
[48] => Ethnic
[49] => Gothic
[50] => Darkwave
[51] => Techno-Industrial
[52] => Electronic
[53] => Pop-Folk
[54] => Eurodance
[55] => Dream
[56] => Southern Rock
[57] => Comedy
[58] => Cult
[59] => Gangsta
[60] => Top 40
[61] => Christian Rap
[62] => Pop/Funk
[63] => Jungle
[64] => Native US
[65] => Cabaret
[66] => New Wave
[67] => Psychadelic
[68] => Rave
[69] => Showtunes
[70] => Trailer
[71] => Lo-Fi
[72] => Tribal
[73] => Acid Punk
[74] => Acid Jazz
[75] => Polka
[76] => Retro
[77] => Musical
[78] => Rock & Roll
[79] => Hard Rock
[80] => Folk
[81] => Folk-Rock
[82] => National Folk
[83] => Swing
[84] => Fast Fusion
[85] => Bebob
[86] => Latin
[87] => Revival
[88] => Celtic
[89] => Bluegrass
[90] => Avantgarde
[91] => Gothic Rock
[92] => Progressive Rock
[93] => Psychedelic Rock
[94] => Symphonic Rock
[95] => Slow Rock
[96] => Big Band
[97] => Chorus
[98] => Easy Listening
[99] => Acoustic
[100] => Humour
[101] => Speech
[102] => Chanson
[103] => Opera
[104] => Chamber Music
[105] => Sonata
[106] => Symphony
[107] => Booty Bass
[108] => Primus
[109] => Porn Groove
[110] => Satire
[111] => Slow Jam
[112] => Club
[113] => Tango
[114] => Samba
[115] => Folklore
[116] => Ballad
[117] => Power Ballad
[118] => Rhytmic Soul
[119] => Freestyle
[120] => Duet
[121] => Punk Rock
[122] => Drum Solo
[123] => Acapella
[124] => Euro-House
[125] => Dance Hall
[126] => Goa
[127] => Drum & Bass
[128] => Club-House
[129] => Hardcore
[130] => Terror
[131] => Indie
[132] => BritPop
[133] => Negerpunk
[134] => Polsk Punk
[135] => Beat
[136] => Christian Gangsta
[137] => Heavy Metal
[138] => Black Metal
[139] => Crossover
[140] => Contemporary C
[141] => Christian Rock
[142] => Merengue
[143] => Salsa
[144] => Thrash Metal
[145] => Anime
[146] => JPop
[147] => SynthPop
)
(PECL id3 >= 0.1)
id3_get_genre_name — Get the name for a genre id
id3_get_genre_name() returns the name for a genre id.
An integer ranging from 0 to 147
Returns the name as a string.
Example #1 id3_get_genre_name() example
<?php
$genre = id3_get_genre_name(20);
echo $genre;
?>
Примерът по-горе ще изведе:
Alternative
(PECL id3 >= 0.1)
id3_get_tag — Get all information stored in an ID3 tag
id3_get_tag() is used to get all information stored in the id3 tag of the specified file.
The path to the MP3 file
Instead of a filename you may also pass a valid stream resource
Allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags
Since version 0.2 id3_get_tag() also supports ID3 tags of version 2.2, 2.3 and 2.4. To extract information from these tags, pass one of the constants ID3_V2_2, ID3_V2_3 or ID3_V2_4 as the second parameter. ID3 v2.x tags can contain a lot more information about the MP3 file than ID3 v1.x tags.
Returns an associative array with various keys like: title, artist, ..
The key genre will contain an integer between 0 and 147. You may use id3_get_genre_name() to convert it to a human readable string.
Example #1 id3_get_tag() example
<?php
$tag = id3_get_tag( "path/to/example.mp3" );
print_r($tag);
?>
Примерът по-горе ще изведе нещо подобно на:
Array
(
[title] => DN-38416
[artist] => Re:\Legion
[album] => Reflections
[year] => 2004
[genre] => 19
)
Example #2 id3_get_tag() example
<?php
$tag = id3_get_tag( "path/to/example2.mp3", ID3_V2_3 );
print_r($tag);
?>
Примерът по-горе ще изведе нещо подобно на:
Array
(
[copyright] => Dirty Mac
[originalArtist] => Dirty Mac
[composer] => Marcus Götze
[artist] => Dirty Mac
[title] => Little Big Man
[album] => Demo-Tape
[track] => 5/12
[genre] => (17)Rock
[year] => 2001
)
(PECL id3 >= 0.1)
id3_get_version — Get version of an ID3 tag
id3_get_version() retrieves the version(s) of the ID3 tag(s) in the MP3 file.
If a file contains an ID3 v1.1 tag, it always contains a 1.0 tag, as version 1.1 is just an extension of 1.0.
The path to the MP3 file
Instead of a filename you may also pass a valid stream resource
Returns the version number of the ID3 tag of the file. As a tag can contain ID3 v1.x and v2.x tags, the return value of this function should be bitwise compared with the predefined constants ID3_V1_0, ID3_V1_1 and ID3_V2.
Example #1 id3_get_version() example
<?php
$version = id3_get_version( "path/to/example.mp3" );
if ($version & ID3_V1_0) {
echo "Contains a 1.x tag\n";
}
if ($version & ID3_V1_1) {
echo "Contains a 1.1 tag\n";
}
if ($version & ID3_V2) {
echo "Contains a 2.x tag\n";
}
?>
Примерът по-горе ще изведе нещо подобно на:
Contains a 1.x tag Contains a 1.1 tag
(PECL id3 >= 0.1)
id3_remove_tag — Remove an existing ID3 tag
id3_remove_tag() is used to remove the information stored of an ID3 tag.
The path to the MP3 file
Instead of a filename you may also pass a valid stream resource
Allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags.
Връща TRUE при успех или FALSE при неуспех.
Example #1 id3_remove_tag() example
<?php
$result = id3_remove_tag( "path/to/example.mp3", ID3_V1_0 );
if ($result === true) {
echo "Tag succesfully removed\n";
}
?>
If the file is writable and contained a 1.0 tag, this will output:
Tag succesfully removed
Забележка: Currently id3_remove_tag() only supports version 1.0 and 1.1. If you choose to remove a 1.0 tag and the file contains a 1.1 tag, this tag will be removed, as v1.1 is only an extension of 1.0.
(PECL id3 >= 0.1)
id3_set_tag — Update information stored in an ID3 tag
id3_set_tag() is used to change the information stored of an ID3 tag. If no tag has been present, it will be added to the file.
The path to the MP3 file
Instead of a filename you may also pass a valid stream resource
An associative array of tag keys and values
The following keys may be used in the associative array:
| key | possible value | available in version |
|---|---|---|
| title | string with maximum of 30 characters | v1.0, v1.1 |
| artist | string with maximum of 30 characters | v1.0, v1.1 |
| album | string with maximum of 30 characters | v1.0, v1.1 |
| year | 4 digits | v1.0, v1.1 |
| genre | integer value between 0 and 147 | v1.0, v1.1 |
| comment | string with maximum of 30 characters (28 in v1.1) | v1.0, v1.1 |
| track | integer between 0 and 255 | v1.1 |
Allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags
Връща TRUE при успех или FALSE при неуспех.
Example #1 id3_set_tag() example
<?php
$data = array(
"title" => "Re:Start",
"artist" => "Re:\Legion",
"comment" => "A nice track"
);
$result = id3_set_tag( "path/to/example.mp3", $data, ID3_V1_0 );
if ($result === true) {
echo "Tag succesfully updated\n";
}
?>
If the file is writable, this will output:
Tag succesfully updated
Забележка: Currently id3_remove_tag() only supports version 1.0 and 1.1.
KTaglib is an object oriented binding to the taglib library from the KDE project used in projects like Amarok to read and write ID3 and Ogg tags. The library also provides access to audio information. The bindings are designed usually follow the underlying C++ API, but were changed whenever there is a more PHP-like way.
Забележка: At the moment ktaglib is able to read and write ID3v1 and ID3v2 tags.
If you want to build ktaglib you need at least taglib 1.5 installed. To obtain the taglib see the » taglib project page. Windows DLL's are build static against taglib, therefore there is no need to have taglib installed.
KTaglib support in PHP is not enabled by default. You will need to configure PHP --with-ktaglib[=DIR]
Забележка: KTaglib is part of PECL.
Константите по-долу са дефинирани в това разширение и ще бъдат налични единствено, когато това разширение е компилирано в PHP или пуснато динамично по време на изпълнение.
KTaglib uses class constants. Most of the constants are mappings to the according Taglib enums and constants.
(0.0.1)
KTaglib_MPEG_File::__construct — Opens a new file
Opens a new MPEG file.
The file to read
Example #1 Opens a new MP3 file and read the title
<?php
$mpeg = new KTaglib_MPEG_File('example.mp3');
echo $mpeg->getID3v1Tag()->getTitle();
?>
(0.0.1)
KTaglib_MPEG_File::getAudioProperties — Returns an object that provides access to the audio properties
Returns an object that provides access to the audio properties of the mpeg file.
Returns an KTaglib_MPEG_AudioProperties object or false.
(0.0.1)
KTaglib_MPEG_File::getID3v1Tag — Returns an object representing an ID3v1 tag
Returns an object that represents an ID3v1 tag, which can be used to get information about the ID3v1 tag.
Returns an KTaglib_MPEG_ID3v1Tag object or false if there is no ID3v1 tag.
(0.0.1)
KTaglib_MPEG_File::getID3v2Tag — Returns a ID3v2 object
Returns a ID3v2 object for the mpeg file. If no ID3v2 Tag is present, an KTaglib_TagNotFoundException is thrown.
Returns the KTaglib_ID3v2_Tag object of the MPEG file or false if there is no ID3v2 tag
Represents an MPEG file. MPEG files can have ID3v1, ID3v2 tags and audio properties.
(0.0.1)
KTaglib_MPEG_AudioProperties::getBitrate — Returns the bitrate of the MPEG file
Returns the bitrate of the MPEG file
Returns the bitrate as an integer
(0.0.1)
KTaglib_MPEG_AudioProperties::getChannels — Returns the amount of channels of a MPEG file
Returns the amount of channels of the MPEG file
Returns the channel count as an integer
(0.0.1)
KTaglib_MPEG_AudioProperties::getLayer — Returns the layer of a MPEG file
Returns the layer of the MPEG file (usually 3 for MP3).
Returns the layer as an integer
(0.0.1)
KTaglib_MPEG_AudioProperties::getLength — Returns the length of a MPEG file
Returns the length of the MPEG file
Returns the length as an integer
(0.0.1)
KTaglib_MPEG_AudioProperties::getSampleBitrate — Returns the sample bitrate of a MPEG file
Returns the sample bitrate of the MPEG file
Returns the sample bitrate as an integer
(0.0.1)
KTaglib_MPEG_AudioProperties::getVersion — Returns the version of a MPEG file
Returns the version of the MPEG file header. The possible versions are defined in Tag_MPEG_Header (Version1, Version2, Version2.5).
Returns the version
(0.0.1)
KTaglib_MPEG_AudioProperties::isCopyrighted — Returns the length of a MPEG file
Returns true if the MPEG file is copyrighted
Returns true if the MPEG file is copyrighted
(0.0.1)
KTaglib_MPEG_AudioProperties::isOriginal — Returns the length of a MPEG file
Returns true if the file is marked as the original file
Returns true if the file is marked as the original file
(0.0.1)
KTaglib_MPEG_AudioProperties::isProtectionEnabled — Returns the length of a MPEG file
Returns true if protection mechanism (like DRM) are enabled for this file
Returns true if protection mechanism (like DRM) are enabled for this file
Represents the audio properties of a MPEG file, like length, bitrate or samplerate.
(0.0.1)
KTaglib_Tag::getAlbum — Returns the title string from a ID3 tag
Returns the album string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.
Returns the album string
(0.0.1)
KTaglib_Tag::getArtist — Returns the artist string from a ID3 tag
Returns the artist string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.
Returns the artist string
(0.0.1)
KTaglib_Tag::getComment — Returns the comment from a ID3 tag
Returns the comment of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.
Returns the comment string
(0.0.1)
KTaglib_Tag::getGenre — Returns the genre from a ID3 tag
Returns the genre of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.
Returns the genre string
(0.0.1)
KTaglib_Tag::getTitle — Returns the title string from a ID3 tag
Returns the title string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.
Returns the title string
(0.0.1)
KTaglib_Tag::getTrack — Returns the track number from a ID3 tag
Returns the track number of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.
Returns the track number as an integer
(0.0.1)
KTaglib_Tag::getYear — Returns the year from a ID3 tag
Returns the year of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.
Returns the year as an integer
(0.0.1)
KTaglib_Tag::isEmpty — Returns true if the tag is empty
Returns true if the tag exists, but is empty. This method is implemented in ID3v1 and ID3v2 tags.
Returns true if the tag is empty, otherwise false.
Base class for ID3v1 or ID3v2 tags
(0.0.1)
KTaglib_ID3v2_Tag::addFrame — Add a frame to the ID3v2 tag
Adds a frame to the ID3v2 tag. The frame must be a valid KTagLib_ID3v2_Frame object. To save the tag, the save function needs to be invoked.
Returns true on success, otherwise false.
(0.0.1)
KTaglib_ID3v2_Tag::getFrameList — Returns an array of ID3v2 frames, associated with the ID3v2 tag
Returns an array of ID3v2 frames, associated with the ID3v2 tag.
Return an array of KTaglib_ID3v2_Frame objects
Represents and ID3v2 tag. It provides a list of ID3v2 frames and can be used to add and remove additional frames.
(0.0.1)
KTaglib_ID3v2_Frame::getSize — Returns the size of the frame in bytes
Returns the size of the frame in bytes. Please refer to id3.org to see what ID3v2 frames are and how they are defined.
Returns the size of the frame in bytes
(0.0.1)
KTaglib_ID3v2_Frame::__toString — Returns a string representation of the frame
Returns a string representation of the frame. This might be just the frame id, but might contain more information. Please see the ktaglib documentation for more information
Returns a string representation of the frame.
The base class for ID3v2 frames. ID3v2 tags are separated in various specialized frames. Some frames can exists multiple times.
(0.0.1)
KTaglib_ID3v2_AttachedPictureFrame::getDescription — Returns a description for the picture in a picture frame
Returns the attached description for a picture frame in an ID3v2.x frame.
Returns a description for the picture in a picture frame
(0.2.0)
KTaglib_ID3v2_AttachedPictureFrame::getMimeType — Returns the mime type of the picture
Returns the mime type of the image represented by the attached picture frame.
Please notice that this method might return different types. While ID3v2.2 have a mime type that doesn't start with "image/", ID3v2.3 and v2.4 usually start with "image/". Therefore the method might return "image/png" for IDv2.3 frames and just "PNG" for ID3v2.2 frames.
Notice that even the frame is an attached picture, the mime type might not be set and therefore an empty string might be returned.
Returns the mime type of the image represented by the attached picture frame.
(0.2.0)
KTaglib_ID3v2_AttachedPictureFrame::getType — Returns the type of the image
Returns the type of the image.
The ID3v2 specification allows an AttachedPictureFrame to set the type of an image. This can be e.g. FrontCover or FileIcon. Please refer to the KTagLib_ID3v2_AttachedPictureFrame class description for a list of available types.
Returns the integer representation of the type.
(0.0.1)
KTaglib_ID3v2_AttachedPictureFrame::savePicture — Saves the picture to a file
Saves the attached picture to the given filename.
Returns true on success, otherwise false
(0.2.0)
KTaglib_ID3v2_AttachedPictureFrame::setMimeType — Set's the mime type of the picture
Sets the mime type of the image. This should in most cases be "image/png" or "image/jpeg".
(0.0.1)
KTaglib_ID3v2_AttachedPictureFrame::setPicture — Sets the frame picture to the given image
Sets the picture to the give image. The image is loaded from the given filename. Please note that the picture is not saved unless you call the save method of the corresponding file object.
Returns true on success, otherwise false
(0.2.0)
KTaglib_ID3v2_AttachedPictureFrame::setType — Set the type of the image
Sets the type of the image. This can be e.g. FrontCover or FileIcon. Please refer to the KTaglib_ID3v2_AttachedPictureFrame class description for a list of available types and their constant mappings.
Represents an ID3v2 frame that can hold a picture.
The OGG/Vorbis file format, as defined by » http://www.vorbis.com/, is a scheme for compressing audio streams by multiple factors with a minimum of quality loss. This extension adds Ogg Vorbis support to PHP's URL Wrappers. When used in read mode, compressed OGG/Vorbis data is expanded to raw PCM audio in one of six PCM encoding formats listed below.
This extension requires PHP >= 4.3.0, » libogg >= 1.0, and » libvorbis >= 1.0.
Информация относно инсталирането на това PECL разширение може да се намери в главата от ръководството Инсталиране на PECL разширения. Допълнителна информация, като нови издания, изтегляния, изходни файлове, информация за поддръжката и CHANGELOG може да се намери тук: » http://pecl.php.net/package/oggvorbis
Това разширение няма дефинирани конфигурационни директиви в php.ini.
Това разширение няма дефинирани ресурсни типове.
Константите по-долу са дефинирани в това разширение и ще бъдат налични единствено, когато това разширение е компилирано в PHP или пуснато динамично по време на изпълнение.
| Constant | Definition |
|---|---|
| OGGVORBIS_PCM_U8 | Unsigned 8-bit PCM. |
| OGGVORBIS_PCM_S8 | Signed 8-bit PCM. |
| OGGVORBIS_PCM_U16_LE | Unsigned 16-bit PCM. Little Endian byte order. |
| OGGVORBIS_PCM_U16_BE | Unsigned 16-bit PCM. Big Endian byte order. |
| OGGVORBIS_PCM_S16_LE | Signed 16-bit PCM. Little Endian byte order. |
| OGGVORBIS_PCM_S16_BE | Signed 16-bit PCM. Big Endian byte order. |
| Option | Definition | Relevance | Default |
|---|---|---|---|
| pcm_mode | PCM byte encoding used. See constants below. | Read / Write | OGGVORBIS_PCM_S16_LE |
| rate | PCM Sampling rate. Measured in Hz. | Write only | 44100 |
| bitrate | Vorbis Average Bitrate Encoding / Variable Bitrate Encoding. Measured in bps (ABR) or Quality level (VBR: 0.0 to 1.0). 128000 ABR is rough equal to 0.4 VBR. | Write only | 128000 |
| channels | Number of PCM channels. 1 == Mono, 2 == Stereo. | Write only | 2 |
| serialno | Serial Number of stream within file. Must be unique within file. Because of the potential to select a duplicate serial number within a chained file, make efforts to manually assign unique numbers when encoding. | Write only | Random |
| comments | Associative array of file comments. Will be translated to strtoupper($name) . "=$value". Note: This context option is not available in oggvorbis-0.1 | Write only | array('ENCODER' => 'PHP/OggVorbis, http://pear.php.net/oggvorbis') |
Example #1 Reading an OGG/Vorbis file
<?php
dl("oggvorbis.so");
/* By default, ogg:// will decode to Signed 16-bit Little Endian */
$fp = fopen('ogg://myaudio.ogg', 'r');
/* Collect some information about the file. */
$metadata = stream_get_meta_data($fp);
/* Inspect the first song (usually the only song,
but OGG/Vorbis files may be chained) */
$songdata = $metadata['wrapper_data'][0];
echo "OGG/Vorbis file encoded by: {$songdata['vendor']}\n.";
echo " {$songdata['channels']} channels of {$songdata['rate']}Hz sampling encoded at {$songdata['bitrate_nominal']}bps.\n";
foreach($songdata['comments'] as $comment) {
echo " $comment\n";
}
while ($audio_data = fread($fp, 8192)) {
/* Do something with the PCM audio we're extracting from the OGG.
Copying to /dev/dsp is a good target on linux systems,
just remember to setup the device for your sampling mode first. */
}
fclose($fp);
?>
Example #2 Encode an audio file to OGG/Vorbis
<?php
dl('oggvorbis.so');
$context = stream_context_create(array('ogg'=>array(
'pcm_mode' => OGGVORBIS_PCM_S8, /* Signed 8bit audio */
'rate' => 44100, /* 44kHz CD quality */
'bitrate' => 0.5, /* Midquality VBR */
'channels' => 1, /* Mono */
'serialno' => 12345))); /* Unique within our stream */
/* Open file for appending. This will "chain" a second OGG stream at the end of the first. */
$ogg = fopen('ogg://mysong.ogg', 'a', false, $context);
$pcm = fopen('mysample.pcm', 'r');
/* Compress the raw PCM audio from mysample.pcm into mysong.ogg */
stream_copy_to_stream($pcm, $ogg);
fclose($pcm);
fclose($ogg);
?>
Platform independent audio bindings. Requires the » OpenAL library.
Не са необходими външни библиотеки, за да се пусне това разширение.
Това » PECL разширение не е част от пакета на PHP.
Информация относно инсталирането на това PECL разширение може да се намери в главата от ръководството Инсталиране на PECL разширения. Допълнителна информация, като нови издания, изтегляния, изходни файлове, информация за поддръжката и CHANGELOG може да се намери тук: » http://pecl.php.net/package/openal.
DLL файла на това разширение може да бъде изтеглен или от страницата за » изтегляне на PHP или от » http://pecl4win.php.net/
Това разширение няма дефинирани конфигурационни директиви в php.ini.
This extension defines four resource types: Open AL(Device) - Returned by openal_device_open(), Open AL(Context) - Returned by openal_context_create(), Open AL(Buffer) - Returned by openal_buffer_create(), and Open AL(Source) - Returned by openal_source_create().
Константите по-долу са дефинирани в това разширение и ще бъдат налични единствено, когато това разширение е компилирано в PHP или пуснато динамично по време на изпълнение.
(PECL openal >= 0.1.0)
openal_buffer_create — Generate OpenAL buffer
Returns an Open AL(Buffer) resource on success or FALSE on failure.
(PECL openal >= 0.1.0)
openal_buffer_data — Load a buffer with data
An Open AL(Buffer) resource (previously created by openal_buffer_create()).
Format of data , one of: AL_FORMAT_MONO8, AL_FORMAT_MONO16, AL_FORMAT_STEREO8 и AL_FORMAT_STEREO16
Block of binary audio data in the format and freq specified.
Frequency of data given in Hz.
Връща TRUE при успех или FALSE при неуспех.
(PECL openal >= 0.1.0)
openal_buffer_destroy — Destroys an OpenAL buffer
An Open AL(Buffer) resource (previously created by openal_buffer_create()).
Връща TRUE при успех или FALSE при неуспех.
(PECL openal >= 0.1.0)
openal_buffer_get — Retrieve an OpenAL buffer property
An Open AL(Buffer) resource (previously created by openal_buffer_create()).
Specific property, one of: AL_FREQUENCY, AL_BITS, AL_CHANNELS и AL_SIZE.
Returns an integer value appropriate to the property requested or FALSE on failure.
(PECL openal >= 0.1.0)
openal_buffer_loadwav — Load a .wav file into a buffer
An Open AL(Buffer) resource (previously created by openal_buffer_create()).
Path to .wav file on local file system.
Връща TRUE при успех или FALSE при неуспех.
(PECL openal >= 0.1.0)
openal_context_create — Create an audio processing context
An Open AL(Device) resource (previously created by openal_device_open()).
Returns an Open AL(Context) resource on success or FALSE on failure.
(PECL openal >= 0.1.0)
openal_context_current — Make the specified context current
An Open AL(Context) resource (previously created by openal_context_create()).
Връща TRUE при успех или FALSE при неуспех.
(PECL openal >= 0.1.0)
openal_context_destroy — Destroys a context
An Open AL(Context) resource (previously created by openal_context_create()).
Връща TRUE при успех или FALSE при неуспех.
(PECL openal >= 0.1.0)
openal_context_process — Process the specified context
An Open AL(Context) resource (previously created by openal_context_create()).
Връща TRUE при успех или FALSE при неуспех.
(PECL openal >= 0.1.0)
openal_context_suspend — Suspend the specified context
An Open AL(Context) resource (previously created by openal_context_create()).
Връща TRUE при успех или FALSE при неуспех.
(PECL openal >= 0.1.0)
openal_device_close — Close an OpenAL device
An Open AL(Device) resource (previously created by openal_device_open()) to be closed.
Връща TRUE при успех или FALSE при неуспех.
(PECL openal >= 0.1.0)
openal_device_open — Initialize the OpenAL audio layer
Open an audio device optionally specified by device_desc . If device_desc is not specified the first available audio device will be used.
Returns an Open AL(Device) resource on success or FALSE on failure.
(PECL openal >= 0.1.0)
openal_listener_get — Retrieve a listener property
Property to retrieve, one of: AL_GAIN (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)) и AL_ORIENTATION (array(float,float,float)).
Returns a float or array of floats (as appropriate), or FALSE on failure.
(PECL openal >= 0.1.0)
openal_listener_set — Set a listener property
Property to set, one of: AL_GAIN (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)) и AL_ORIENTATION (array(float,float,float)).
Value to set, either float, or an array of floats as appropriate.
Връща TRUE при успех или FALSE при неуспех.
(PECL openal >= 0.1.0)
openal_source_create — Generate a source resource
Returns an Open AL(Source) resource on success or FALSE on failure.
(PECL openal >= 0.1.0)
openal_source_destroy — Destroy a source resource
An Open AL(Source) resource (previously created by openal_source_create()).
Връща TRUE при успех или FALSE при неуспех.
(PECL openal >= 0.1.0)
openal_source_get — Retrieve an OpenAL source property
An Open AL(Source) resource (previously created by openal_source_create()).
Property to get, one of: AL_SOURCE_RELATIVE (int), AL_SOURCE_STATE (int), AL_PITCH (float), AL_GAIN (float), AL_MIN_GAIN (float), AL_MAX_GAIN (float), AL_MAX_DISTANCE (float), AL_ROLLOFF_FACTOR (float), AL_CONE_OUTER_GAIN (float), AL_CONE_INNER_ANGLE (float), AL_CONE_OUTER_ANGLE (float), AL_REFERENCE_DISTANCE (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)), AL_DIRECTION (array(float,float,float)).
Returns the type associated with the property being retrieved or FALSE on failure.
(PECL openal >= 0.1.0)
openal_source_pause — Pause the source
An Open AL(Source) resource (previously created by openal_source_create()).
Връща TRUE при успех или FALSE при неуспех.
(PECL openal >= 0.1.0)
openal_source_play — Start playing the source
An Open AL(Source) resource (previously created by openal_source_create()).
Връща TRUE при успех или FALSE при неуспех.
(PECL openal >= 0.1.0)
openal_source_rewind — Rewind the source
An Open AL(Source) resource (previously created by openal_source_create()).
Връща TRUE при успех или FALSE при неуспех.
(PECL openal >= 0.1.0)
openal_source_set — Set source property
An Open AL(Source) resource (previously created by openal_source_create()).
Property to set, one of: AL_BUFFER (OpenAL(Source)), AL_LOOPING (bool), AL_SOURCE_RELATIVE (int), AL_SOURCE_STATE (int), AL_PITCH (float), AL_GAIN (float), AL_MIN_GAIN (float), AL_MAX_GAIN (float), AL_MAX_DISTANCE (float), AL_ROLLOFF_FACTOR (float), AL_CONE_OUTER_GAIN (float), AL_CONE_INNER_ANGLE (float), AL_CONE_OUTER_ANGLE (float), AL_REFERENCE_DISTANCE (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)), AL_DIRECTION (array(float,float,float)).
Value to assign to specified property . Refer to the description of property for a description of the value(s) expected.
Връща TRUE при успех или FALSE при неуспех.
(PECL openal >= 0.1.0)
openal_source_stop — Stop playing the source
An Open AL(Source) resource (previously created by openal_source_create()).
Връща TRUE при успех или FALSE при неуспех.
(PECL openal >= 0.1.0)
openal_stream — Begin streaming on a source
An Open AL(Source) resource (previously created by openal_source_create()).
Format of data , one of: AL_FORMAT_MONO8, AL_FORMAT_MONO16, AL_FORMAT_STEREO8 и AL_FORMAT_STEREO16
Frequency of data to stream given in Hz.
Returns a stream resource on success, or FALSE on failure.
These package allows you to access Kerberos V administration servers. You can create, modify, and delete Kerberos V principals and policies.
More information about Kerberos can be found at » http://web.mit.edu/kerberos/www/.
Documentation for Kerberos and KADM5 can be found at » http://web.mit.edu/kerberos/www/krb5-1.2/krb5-1.2.8/doc/admin_toc.html.
Не са необходими външни библиотеки, за да се пусне това разширение.
These functions allow you to access Kerberos administration servers. In order to have these functions available, you must compile PHP with KADM5 support by using the --with-kadm5 configurable option. If you use this option without specifying the path to KADM5, PHP will use the built-in KADM5 client libraries. Users who run other applications that use KADM5 (for example, running PHP 4 and PHP 5 as concurrent apache modules, or auth-kadm5) should always specify the path to KADM5: --with-kadm5=/path/to/kadm5. This will force PHP to use the client libraries installed by KADM5, avoiding any conflicts.
Това разширение няма дефинирани конфигурационни директиви в php.ini.
This extension defines a KADM5 handle returned by kadm5_init_with_password().
The functions kadm5_create_principal(), kadm5_modify_principal(), and kadm5_modify_principal() allow to specify special attributes using a bitfield. The symbols are defined below:
| constant |
|---|
| KRB5_KDB_DISALLOW_POSTDATED |
| KRB5_KDB_DISALLOW_FORWARDABLE |
| KRB5_KDB_DISALLOW_TGT_BASED |
| KRB5_KDB_DISALLOW_RENEWABLE |
| KRB5_KDB_DISALLOW_PROXIABLE |
| KRB5_KDB_DISALLOW_DUP_SKEY |
| KRB5_KDB_DISALLOW_ALL_TIX |
| KRB5_KDB_REQUIRES_PRE_AUTH |
| KRB5_KDB_REQUIRES_HW_AUTH |
| KRB5_KDB_REQUIRES_PWCHANGE |
| KRB5_KDB_DISALLOW_SVR |
| KRB5_KDB_PWCHANGE_SERVER |
| KRB5_KDB_SUPPORT_DESMD5 |
| KRB5_KDB_NEW_PRINC |
The functions kadm5_create_principal(), kadm5_modify_principal(), and kadm5_get_principal() allow to specify or return principal's options as an associative array. The keys for the associative array are defined as string constants below:
| constant | funcdef | description |
|---|---|---|
| KADM5_PRINCIPAL | long | The expire time of the princial as a Kerberos timestamp. |
| KADM5_PRINC_EXPIRE_TIME | long | The expire time of the princial as a Kerberos timestamp. |
| KADM5_LAST_PW_CHANGE | long | The time this principal's password was last changed. |
| KADM5_PW_EXPIRATION | long | The expire time of the principal's current password, as a Kerberos timestamp. |
| KADM5_MAX_LIFE | long | The maximum lifetime of any Kerberos ticket issued to this principal. |
| KADM5_MAX_RLIFE | long | The maximum renewable lifetime of any Kerberos ticket issued to or for this principal. |
| KADM5_MOD_NAME | string | The name of the Kerberos principal that most recently modified this principal. |
| KADM5_MOD_TIME | long | The time this principal was last modified, as a Kerberos timestamp. |
| KADM5_KVNO | long | The version of the principal's current key. |
| KADM5_POLICY | string | The name of the policy controlling this principal. |
| KADM5_CLEARPOLICY | long | Standard procedure is to assign the 'default' policy to new principals. KADM5_CLEARPOLICY suppresses this behaviour. |
| KADM5_LAST_SUCCESS | long | The KDC time of the last successfull AS_REQ. |
| KADM5_LAST_FAILED | long | The KDC time of the last failed AS_REQ. |
| KADM5_FAIL_AUTH_COUNT | long | The number of consecutive failed AS_REQs. |
| KADM5_RANDKEY | long | Generates a random password for the principal. The parameter password will be ignored. |
| KADM5_ATTRIBUTES | long | A bitfield of attributes for use by the KDC. |
Константите по-долу са дефинирани в това разширение и ще бъдат налични единствено, когато това разширение е компилирано в PHP или пуснато динамично по време на изпълнение.
This simple example shows how to connect, query, print resulting principals and disconnect from a KADM5 database.
Example #1 KADM5 extension overview example
<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");
print "<h1>get_principals</h1>\n";
$principals = kadm5_get_principals($handle);
for( $i=0; $i<count($principals); $i++)
print "$principals[$i]<br>\n";
print "<h1>get_policies</h1>\n";
$policies = kadm5_get_policies($handle);
for( $i=0; $i<count($policies); $i++)
print "$policies[$i]<br>\n";
print "<h1>get_principal burbach@GONICUS.LOCAL</h1>\n";
$options = kadm5_get_principal($handle, "burbach@GONICUS.LOCAL" );
$keys = array_keys($options);
for( $i=0; $i<count($keys); $i++) {
$value = $options[$keys[$i]];
print "$keys[$i]: $value<br>\n";
}
$options = array(KADM5_PRINC_EXPIRE_TIME => 0);
kadm5_modify_principal($handle, "burbach@GONICUS.LOCAL", $options);
kadm5_destroy($handle);
?>
(PECL kadm5 >= 0.2.3)
kadm5_chpass_principal — Changes the principal's password
kadm5_chpass_principal() sets the new password password for the principal .
A KADM5 handle.
The principal.
The new password.
Връща TRUE при успех или FALSE при неуспех.
Example #1 Example of changing principal's password
<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");
kadm5_chpass_principal($handle, "burbach@GONICUS.LOCAL", "newpassword");
kadm5_destroy($handle);
?>
(PECL kadm5 >= 0.2.3)
kadm5_create_principal — Creates a kerberos principal with the given parameters
Creates a principal with the given password .
A KADM5 handle.
The principal.
If password is omitted or is NULL, a random key will be generated.
It is possible to specify several optional parameters within the array options . Allowed are the following options: KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES, KADM5_MAX_LIFE, KADM5_KVNO, KADM5_POLICY, KADM5_CLEARPOLICY, KADM5_MAX_RLIFE.
Връща TRUE при успех или FALSE при неуспех.
Example #1 Example of principal's creation
<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");
$attributes = KRB5_KDB_REQUIRES_PRE_AUTH | KRB5_KDB_DISALLOW_PROXIABLE;
$options = array(KADM5_PRINC_EXPIRE_TIME => 0,
KADM5_POLICY => "default",
KADM5_ATTRIBUTES => $attributes);
kadm5_create_principal($handle, "burbach@GONICUS.LOCAL", "password", $options);
kadm5_destroy($handle);
?>
(PECL kadm5 >= 0.2.3)
kadm5_delete_principal — Deletes a kerberos principal
Removes the principal from the Kerberos database.
A KADM5 handle.
The removed principal.
Връща TRUE при успех или FALSE при неуспех.
Example #1 kadm5_delete_principal() example
<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");
kadm5_delete_principal($handle, "burbach@GONICUS.LOCAL");
kadm5_destroy($handle);
?>
(PECL kadm5 >= 0.2.3)
kadm5_destroy — Closes the connection to the admin server and releases all related resources
Closes the connection to the admin server and releases all related resources.
A KADM5 handle.
Връща TRUE при успех или FALSE при неуспех.
(PECL kadm5 >= 0.2.3)
kadm5_flush — Flush all changes to the Kerberos database
Flush all changes to the Kerberos database, leaving the connection to the Kerberos admin server open.
A KADM5 handle.
Връща TRUE при успех или FALSE при неуспех.
(PECL kadm5 >= 0.2.3)
kadm5_get_policies — Gets all policies from the Kerberos database
Gets an array containing the policies's names.
A KADM5 handle.
Returns array of policies on success, or FALSE on failure.
Example #1 kadm5_get_policies() example
<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");
print "<h1>get_policies</h1>\n";
foreach (kadm5_get_policies($handle) as $policy) {
echo "$policy<br />\n";
}
kadm5_destroy($handle);
?>
(PECL kadm5 >= 0.2.3)
kadm5_get_principal — Gets the principal's entries from the Kerberos database
Gets the principal's entries from the Kerberos database.
A KADM5 handle.
The principal.
Returns array of options containing the following keys: KADM5_PRINCIPAL, KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES, KADM5_MAX_LIFE, KADM5_MOD_NAME, KADM5_MOD_TIME, KADM5_KVNO, KADM5_POLICY, KADM5_MAX_RLIFE, KADM5_LAST_SUCCESS, KADM5_LAST_FAILED, KADM5_FAIL_AUTH_COUNT on success, or FALSE on failure.
Example #1 kadm5_get_principal() example
<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");
print "<h1>get_principal burbach@GONICUS.LOCAL</h1>\n";
$options = kadm5_get_principal($handle, "burbach@GONICUS.LOCAL" );
foreach ($options as $key => $value) {
echo "$key: $value<br />\n";
}
kadm5_destroy($handle);
?>
(PECL kadm5 >= 0.2.3)
kadm5_get_principals — Gets all principals from the Kerberos database
kadm5_get_principals() returns an array containing the principals's names.
A KADM5 handle.
Returns array of principals on success, or FALSE on failure.
Example #1 kadm5_get_principals() example
<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");
print "<h1>get_principals</h1>\n";
foreach (kadm5_get_principals($handle) as $principal) {
echo "$principal<br />\n";
}
kadm5_destroy($handle);
?>
(PECL kadm5 >= 0.2.3)
kadm5_init_with_password — Opens a connection to the KADM5 library
Opens a connection with the KADM5 library using the principal and the given password to obtain initial credentials from the admin_server .
The server.
Defines the authentication domain for the connection.
The principal.
If password is omitted or is NULL, a random key will be generated.
Returns a KADM5 handle on success, or FALSE on failure.
Example #1 KADM5 initialization example
<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");
$attributes = KRB5_KDB_REQUIRES_PRE_AUTH | KRB5_KDB_DISALLOW_PROXIABLE;
$options = array(KADM5_PRINC_EXPIRE_TIME => 0,
KADM5_POLICY => "default",
KADM5_ATTRIBUTES => $attributes);
kadm5_create_principal($handle, "burbach@GONICUS.LOCAL", "password", $options);
kadm5_destroy($handle);
?>
Забележка: Connection should be closed after use with kadm5_destroy().
(PECL kadm5 >= 0.2.3)
kadm5_modify_principal — Modifies a kerberos principal with the given parameters
Modifies a principal according to the given options .
A KADM5 handle.
The principal.
It is possible to specify several optional parameters within the array options . Allowed are the following options: KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES, KADM5_MAX_LIFE, KADM5_KVNO, KADM5_POLICY, KADM5_CLEARPOLICY, KADM5_MAX_RLIFE. KADM5_FAIL_AUTH_COUNT.
Връща TRUE при успех или FALSE при неуспех.
Example #1 Example of modifying principal
<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");
$attributes = KRB5_KDB_REQUIRES_PRE_AUTH;
$options = array(KADM5_PRINC_EXPIRE_TIME => 3451234,
KADM5_POLICY => "gonicus",
KADM5_ATTRIBUTES => $attributes);
kadm5_modify_principal($handle, "burbach@GONICUS.LOCAL", $options);
kadm5_destroy($handle);
?>
This package is based on the libradius (Remote Authentication Dial In User Service) of FreeBSD. It allows clients to perform authentication and accounting by means of network requests to remote servers.
This PECL extension adds full support for Radius Authentication (» RFC 2865) and Radius Accounting (» RFC 2866). This package is available for Unix (tested on FreeBSD and Linux) and for Windows.
Забележка: An exact description for libradius can be found » here. A detailed description of the configuration file can be found » here.
Не са необходими външни библиотеки, за да се пусне това разширение.
Howto install the package?
or if you would like to have it as .so:
For Windows I recommend to use the php_radius.dll from » http://snaps.php.net/. PECL разширенията, които са премахнати от пакета на PHP могат да бъдат свалени от: » http://pecl4win.php.net/
Това разширение няма дефинирани конфигурационни директиви в php.ini.
Това разширение няма дефинирани ресурсни типове.
Константите по-долу са дефинирани в това разширение и ще бъдат налични единствено, когато това разширение е компилирано в PHP или пуснато динамично по време на изпълнение.
Type of Service, one of:
Framed Protocol, one of:
Compression, one of:
NAS port type, one of:
Accounting status type, one of:
Accounting authentic, one of:
Accounting terminate cause, one of:
Microsoft specific vendor attributes (» RFC 2548), one of:
Howto start?
Take also a look at the examples in this package.
The package contains an example php script. This script demonstrates howto authenticate with radius using PAP or CHAP (md5). If you authenticate with Microsoft Radius servers then its not possible to use CHAP (md5). If you would like to authenticate with Microsoft Servers you have to use MS-CHAPv1 or MS-CHAPv2, but its more complicated, because you need md4, sha1 and des to generate the right data. The enclosed examples demonstrate all authentication-methods, including MS-CHAPv1 and MS-CHAPv2. To get the MS-CHAP to work you need the mcrypt and the mhash extension, starting with version 1.2 of the package, the mcrypt extension is no longer needed.
(PECL radius >= 1.1.0)
radius_acct_open — Creates a Radius handle for accounting
Returns a handle on success, FALSE on error. This function only fails if insufficient memory is available.
Example #1 radius_acct_open() example
<?php
$res = radius_acct_open ()
or die ("Could not create handle");
print("Handle successfully created");
?>
(PECL radius >= 1.1.0)
radius_add_server — Adds a server
radius_add_server() may be called multiple times, and it may be used together with radius_config(). At most 10 servers may be specified. When multiple servers are given, they are tried in round-robin fashion until a valid response is received, or until each server's max_tries limit has been reached.
The hostname parameter specifies the server host, either as a fully qualified domain name or as a dotted-quad IP address in text form.
The port
specifies the UDP port to contact on
the server. If port is given as 0, the library looks up the
radius/udp
or
radacct/udp
service in the
network services database, and uses the port found there. If no entry
is found, the library uses the standard Radius ports, 1812 for
authentication and 1813 for accounting.
The shared secret for