Podręcznik PHP

Opracowany przez:
Mehdi Achour
Friedhelm Betz
Antony Dovgal
Nuno Lopes
Hannes Magnusson
Georg Richter
Damien Seguy
Jakub Vrana
2009-11-20
Pod redakcją: Philip Olson
Opracowany przez:
Tłumaczenie na język polski (kolejność alfabetyczna) :
Marcin Dąbrowski
Michał Garbowski
Jarosław Głowacki
Michał Grzechowiak
Michał Wilhelm Jany
Damian Jeżewski
Leszek Krupiński
Adam Major
Adrian Makowski
Paweł Paprota
Michał Pena
Michał Piotrowski
Sławomir Pucia
Jarek Tabor
Tomasz Wójtowicz

Copyright

Prawa autorskie do tego podręcznika © 1997 - 2009 należą do PHP Documentation Group. Materiał ten może być rozprowadzany tylko pod warunkami określonymi w Creative Commons Attribution 3.0 lub nowszych. Kopia Creative Commons Attribution 3.0 license jest dystrybuowana z tym podręcznikiem. Najnowsza wersja jest aktualnie dostępna pod adresem » http://creativecommons.org/licenses/by/3.0/.

W przypadku zainteresowania redystrybucją lub publikowaniem tego dokumentu w całości lub jego części, zmodyfikowanego lub niezmodyfikowanego, wszystkie pytania należy zadawać właścicielom praw autorskich do niego pod adresem » doc-license@lists.php.net. Adres ten jest podłączony do publicznie archiwizowanej listy dyskusyjnej.



Podręcznik PHP


Przedmowa

PHP, co jest skrótem od "PHP: Hypertext Preprocessor", jest powszechnie używanym językiem skryptowym ogólnego przeznaczenia, który jest szczególnie przystosowany do tworzenia aplikacji internetowych, także poprzez zagnieżdżenie wewnątrz języka HTML. Składnia, wywodząca się z języków C, Java i Perl, jest łatwa do nauczenia się. Głównym celem języka jest umożliwienie programistom szybkiego tworzenia stron internetowych, ale PHP umożliwia znacznie więcej.

Podręcznik ten składa się głównie z opisu funkcji, ale zawiera także opis języka, objaśnienie niektórych z głównych cech PHP, jak również kilka dodatkowych informacji.

Podręcznik można pobrać w kilku formatach spod adresu » http://www.php.net/download-docs.php. Więcej informacji na temat prac nad tym podręcznikiem można znaleźć w rozdziale 'O podręczniku'. Osobom zainteresowanym historią PHP polecamy odpowiedni dodatek.

Autorzy i współpracownicy

Wyróżniamy najbardziej aktywnych twórców na pierwszej stronie podręcznika, ale jest wielu innych współpracowników, którzy pomagają w pracach, lub włożyli w przeszłości wiele pracy przy tym projekcie. Jest wiele niewymienionych tutaj ludzi, którzy wnieśli wkład w rozwój tego podręcznika licznymi komentarzami. Cały czas te uwagi są one uwzględniane w odnośnikach, i za nie serdecznie dziękujemy. Wszystkie poniższe listy uporządkowane są w kolejności alfabetycznej.

Autorzy i edytorzy

Poniżsi współpracownicy powinni zostać wyróżnieni za wpływ jaki mieli (lub ciągle mają) w rozwój podręcznika: Bill Abt, Jouni Ahto, Alexander Aulbach, Daniel Beckham, Stig Bakken, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall, Simone Cortesi, Markus Fischer, Wez Furlong, Sara Golemon, Rui Hirokawa, Brad House, Pierre-Alain Joye, Etienne Kneuss, Moriyoshi Koizumi, Rasmus Lerdorf, Andrew Lindeman, Stanislav Malyshev, Rafael Martinez, Rick McGuire, Yasuo Ohgaki, Derick Rethans, Rob Richards, Sander Roobol, Egon Schmid, Thomas Schoefbeck, Sascha Schumann, Dan Scott, Masahiro Takagi, Michael Wallner, Lars Torben Wilson, Jim Winstead, Jeroen van Wolffelaar i Andrei Zmievski.

Poniżsi współpracownicy włożyli wiele pracy przy edycji podręcznika: Stig Bakken, Gabor Hojtsy, Hartmut Holzgraefe i Egon Schmid.

Opiekunowie notatek

Aktualnie najbardziej aktywni opiekunowie to: Daniel Brown, Nuno Lopes, Felipe Pena, Thiago Pojda i Maciek Sokolewicz.

Te osoby także pracowały nad zarządzaniem notatkami: Mehdi Achour, Daniel Beckham, Friedhelm Betz, Victor Boivie, Jesus M. Castagnetto, Nicolas Chaillan, Ron Chmara, Sean Coates, James Cox, Vincent Gevers, Sara Golemon, Zak Greant, Szabolcs Heilig, Oliver Hinckel, Hartmut Holzgraefe, Etienne Kneuss, Rasmus Lerdorf, Matthew Li, Andrew Lindeman, Aidan Lister, Hannes Magnusson, Maxim Maletsky, Bobby Matthis, James Moore, Philip Olson, Sebastian Picklum, Derick Rethans, Sander Roobol, Damien Seguy, Jason Sheets, Tom Sommer, Jani Taskinen, Yasuo Ohgaki, Jakub Vrana, Lars Torben Wilson, Jim Winstead, Jared Wyles i Jeroen van Wolffelaar.




Na początek


Introduction

Spis treści


What is PHP?

PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

Nice, but what does that mean? An example:

Przykład #1 An introductory example

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>Example</title>
    </head>
    <body>

        <?php
            
echo "Hi, I'm a PHP script!";
        
?>

    </body>
</html>

Instead of lots of commands to output HTML (as seen in C or Perl), PHP pages contain HTML with embedded code that does "something" (in this case, output "Hi, I'm a PHP script!"). The PHP code is enclosed in special start and end processing instructions <?php and ?> that allow you to jump into and out of "PHP mode."

What distinguishes PHP from something like client-side JavaScript is that the code is executed on the server, generating HTML which is then sent to the client. The client would receive the results of running that script, but would not know what the underlying code was. You can even configure your web server to process all your HTML files with PHP, and then there's really no way that users can tell what you have up your sleeve.

The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid reading the long list of PHP's features. You can jump in, in a short time, and start writing simple scripts in a few hours.

Although PHP's development is focused on server-side scripting, you can do much more with it. Read on, and see more in the What can PHP do? section, or go right to the introductory tutorial if you are only interested in web programming.



What can PHP do?

Anything. PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more.

There are three main areas where PHP scripts are used.

  • Server-side scripting. This is the most traditional and main target field for PHP. You need three things to make this work. The PHP parser (CGI or server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming. See the installation instructions section for more information.
  • Command line scripting. You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks. See the section about Command line usage of PHP for more information.
  • Writing desktop applications. PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such programs. You also have the ability to write cross-platform applications this way. PHP-GTK is an extension to PHP, not available in the main distribution. If you are interested in PHP-GTK, visit » its own website.

PHP can be used on all major operating systems, including Linux, many Unix variants (including HP-UX, Solaris and OpenBSD), Microsoft Windows, Mac OS X, RISC OS, and probably others. PHP has also support for most of the web servers today. This includes Apache, Microsoft Internet Information Server, Personal Web Server, Netscape and iPlanet servers, Oreilly Website Pro server, Caudium, Xitami, OmniHTTPd, and many others. For the majority of the servers, PHP has a module, for the others supporting the CGI standard, PHP can work as a CGI processor.

So with PHP, you have the freedom of choosing an operating system and a web server. Furthermore, you also have the choice of using procedural programming or object oriented programming, or a mixture of them. Although not every standard OOP feature is implemented in PHP 4, many code libraries and large applications (including the PEAR library) are written only using OOP code. PHP 5 fixes the OOP related weaknesses of PHP 4, and introduces a complete object model.

With PHP you are not limited to output HTML. PHP's abilities includes outputting images, PDF files and even Flash movies (using libswf and Ming) generated on the fly. You can also output easily any text, such as XHTML and any other XML file. PHP can autogenerate these files, and save them in the file system, instead of printing it out, forming a server-side cache for your dynamic content.

One of the strongest and most significant features in PHP is its support for a wide range of databases. Writing a database-enabled web page is incredibly simple. The following databases are currently supported:

  • Adabas D
  • dBase
  • Empress
  • FilePro (read-only)
  • Hyperwave
  • IBM DB2
  • Informix
  • Ingres
  • InterBase
  • FrontBase
  • mSQL
  • Direct MS-SQL
  • MySQL
  • ODBC
  • Oracle (OCI7 and OCI8)
  • Ovrimos
  • PostgreSQL
  • SQLite
  • Solid
  • Sybase
  • Velocis
  • Unix dbm

We also have a database abstraction extension (named PDO) allowing you to transparently use any database supported by that extension. Additionally PHP supports ODBC, the Open Database Connection standard, so you can connect to any other database supporting this world standard.

PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (on Windows) and countless others. You can also open raw network sockets and interact using any other protocol. PHP has support for the WDDX complex data exchange between virtually all Web programming languages. Talking about interconnection, PHP has support for instantiation of Java objects and using them transparently as PHP objects. You can also use our CORBA extension to access remote objects.

PHP has extremely useful text processing features, from the POSIX Extended or Perl regular expressions to parsing XML documents. For parsing and accessing XML documents, PHP 4 supports the SAX and DOM standards, and you can also use the XSLT extension to transform XML documents. PHP 5 standardizes all the XML extensions on the solid base of libxml2 and extends the feature set adding SimpleXML and XMLReader support.

At last but not least, we have many other interesting extensions, the mnoGoSearch search engine functions, the IRC Gateway functions, many compression utilities (gzip, bz2, zip), calendar conversion, translation...

As you can see this page is not enough to list all the features and benefits PHP can offer. Read on in the sections about installing PHP, and see the function reference part for explanation of the extensions mentioned here.




Here we would like to show the very basics of PHP in a short, simple tutorial. This text only deals with dynamic web page creation with PHP, though PHP is not only capable of creating web pages. See the section titled What can PHP do for more information.

PHP-enabled web pages are treated just like regular HTML pages and you can create and edit them the same way you normally create regular HTML pages.


What do I need?

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.



Your first PHP-enabled page

Create a file named hello.php and put it in your web server's root directory (DOCUMENT_ROOT) with the following content:

Przykład #1 Our first PHP script: hello.php

<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
 <?php echo '<p>Hello World</p>'?> 
 </body>
</html>

Use your browser to access the file with your web server's URL, ending with the /hello.php file reference. When developing locally this URL will be something like http://localhost/hello.php or http://127.0.0.1/hello.php but this depends on the web server's configuration. If everything is configured correctly, this file will be parsed by PHP and the following output will be sent to your browser:

<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
 <p>Hello World</p>
 </body>
</html>

This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display: Hello World using the PHP echo() statement. Note that the file does not need to be executable or special in any way. The server finds out that this file needs to be interpreted by PHP because you used the ".php" extension, which the server is configured to pass on to PHP. Think of this as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things.

If you tried this example and it did not output anything, it prompted for download, or you see the whole file as text, chances are that the server you are on does not have PHP enabled, or is not configured properly. Ask your administrator to enable it for you using the Installation chapter of the manual. If you are developing locally, also read the installation chapter to make sure everything is configured properly. Make sure that you access the file via http with the server providing you the output. If you just call up the file from your file system, then it will not be parsed by PHP. If the problems persist anyway, do not hesitate to use one of the many » PHP support options.

The point of the example is to show the special PHP tag format. In this example we used <?php to indicate the start of a PHP tag. Then we put the PHP statement and left PHP mode by adding the closing tag, ?>. You may jump in and out of PHP mode in an HTML file like this anywhere you want. For more details, read the manual section on the basic PHP syntax.

Informacja: A Note on Line Feeds
Line feeds have little meaning in HTML, however it is still a good idea to make your HTML look nice and clean by putting line feeds in. A linefeed that follows immediately after a closing ?> will be removed by PHP. This can be extremely useful when you are putting in many blocks of PHP or include files containing PHP that aren't supposed to output anything. At the same time it can be a bit confusing. You can put a space after the closing ?> to force a space and a line feed to be output, or you can put an explicit line feed in the last echo/print from within your PHP block.

Informacja: A Note on Text Editors
There are many text editors and Integrated Development Environments (IDEs) that you can use to create, edit and manage PHP files. A partial list of these tools is maintained at » PHP Editors List. If you wish to recommend an editor, please visit the above page and ask the page maintainer to add the editor to the list. Having an editor with syntax highlighting can be helpful.

Informacja: A Note on Word Processors
Word processors such as StarOffice Writer, Microsoft Word and Abiword are not optimal for editing PHP files. If you wish to use one for this test script, you must ensure that you save the file as plain text or PHP will not be able to read and execute the script.

Informacja: A Note on Windows Notepad
If you are writing your PHP scripts using Windows Notepad, you will need to ensure that your files are saved with the .php extension. (Notepad adds a .txt extension to files automatically unless you take one of the following steps to prevent it.) When you save the file and are prompted to provide a name for the file, place the filename in quotes (i.e. "hello.php"). Alternatively, you can click on the 'Text Documents' drop-down menu in the 'Save' dialog box and change the setting to "All Files". You can then enter your filename without quotes.

Now that you have successfully created a working PHP script, it is time to create the most famous PHP script! Make a call to the phpinfo() function and you will see a lot of useful information about your system and setup such as available predefined variables, loaded PHP modules, and configuration settings. Take some time and review this important information.

Przykład #2 Get system information from PHP

<?php phpinfo(); ?>



Something Useful

Let us do something more useful now. We are going to check what sort of browser the visitor is using. For that, we check the user agent string the browser sends as part of the HTTP request. This information is stored in a variable. Variables always start with a dollar-sign in PHP. The variable we are interested in right now is $_SERVER['HTTP_USER_AGENT'].

Informacja: $_SERVER is a special reserved PHP variable that contains all web server information. It is known as a superglobal. See the related manual page on superglobals for more information. These special variables were introduced in PHP » 4.1.0. Before this time, we used the older $HTTP_*_VARS arrays instead, such as $HTTP_SERVER_VARS. Although deprecated, these older variables still exist. (See also the note on old code.)

To display this variable, you can simply do:

Przykład #1 Printing a variable (Array element)

<?php
echo $_SERVER['HTTP_USER_AGENT'];
?>

A sample output of this script may be:


Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)

There are many types of variables available in PHP. In the above example we printed an Array element. Arrays can be very useful.

$_SERVER is just one variable that PHP automatically makes available to you. A list can be seen in the Reserved Variables section of the manual or you can get a complete list of them by looking at the output of the phpinfo() function used in the example in the previous section.

You can put multiple PHP statements inside a PHP tag and create little blocks of code that do more than just a single echo. For example, if you want to check for Internet Explorer you can do this:

Przykład #2 Example using control structures and functions

<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
    echo 
'You are using Internet Explorer.<br />';
}
?>

A sample output of this script may be:

You are using Internet Explorer.<br />

Here we introduce a couple of new concepts. We have an if statement. If you are familiar with the basic syntax used by the C language, this should look logical to you. Otherwise, you should probably pick up an introductory PHP book and read the first couple of chapters, or read the Language Reference part of the manual.

The second concept we introduced was the strpos() function call. strpos() is a function built into PHP which searches a string for another string. In this case we are looking for 'MSIE' (so-called needle) inside $_SERVER['HTTP_USER_AGENT'] (so-called haystack). If the needle is found inside the haystack, the function returns the position of the needle relative to the start of the haystack. Otherwise, it returns FALSE. If it does not return FALSE, the if expression evaluates to TRUE and the code within its {braces} is executed. Otherwise, the code is not run. Feel free to create similar examples, with if, else, and other functions such as strtoupper() and strlen(). Each related manual page contains examples too. If you are unsure how to use functions, you will want to read both the manual page on how to read a function definition and the section about PHP functions.

We can take this a step further and show how you can jump in and out of PHP mode even in the middle of a PHP block:

Przykład #3 Mixing both HTML and PHP modes

<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
?>
<h3>strpos() must have returned non-false</h3>
<p>You are using Internet Explorer</p>
<?php
} else {
?>
<h3>strpos() must have returned false</h3>
<p>You are not using Internet Explorer</p>
<?php
}
?>

A sample output of this script may be:

<h3>strpos() must have returned non-false</h3>
<p>You are using Internet Explorer</p>

Instead of using a PHP echo statement to output something, we jumped out of PHP mode and just sent straight HTML. The important and powerful point to note here is that the logical flow of the script remains intact. Only one of the HTML blocks will end up getting sent to the viewer depending on the result of strpos(). In other words, it depends on whether the string MSIE was found or not.



Dealing with Forms

One of the most powerful features of PHP is the way it handles HTML forms. The basic concept that is important to understand is that any form element will automatically be available to your PHP scripts. Please read the manual section on Variables from external sources for more information and examples on using forms with PHP. Here is an example HTML form:

Przykład #1 A simple HTML form

<form action="action.php" method="post">
 <p>Your name: <input type="text" name="name" /></p>
 <p>Your age: <input type="text" name="age" /></p>
 <p><input type="submit" /></p>
</form>

There is nothing special about this form. It is a straight HTML form with no special tags of any kind. When the user fills in this form and hits the submit button, the action.php page is called. In this file you would write something like this:

Przykład #2 Printing data from our form

Hi <?php echo htmlspecialchars($_POST['name']); ?>.
You are <?php echo (int)$_POST['age']; ?> years old.

A sample output of this script may be:

Hi Joe. You are 22 years old.

Apart from the htmlspecialchars() and (int) parts, it should be obvious what this does. htmlspecialchars() makes sure any characters that are special in html are properly encoded so people can't inject HTML tags or Javascript into your page. For the age field, since we know it is a number, we can just convert it to an integer which will automatically get rid of any stray characters. You can also have PHP do this for you automatically by using the filter extension. The $_POST['name'] and $_POST['age'] variables are automatically set for you by PHP. Earlier we used the $_SERVER superglobal; above we just introduced the $_POST superglobal which contains all POST data. Notice how the method of our form is POST. If we used the method GET then our form information would live in the $_GET superglobal instead. You may also use the $_REQUEST superglobal, if you do not care about the source of your request data. It contains the merged information of GET, POST and COOKIE data. Also see the import_request_variables() function.

You can also deal with XForms input in PHP, although you will find yourself comfortable with the well supported HTML forms for quite some time. While working with XForms is not for beginners, you might be interested in them. We also have a short introduction to handling data received from XForms in our features section.



Using old code with new versions of PHP

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:

  • The deprecation of the old $HTTP_*_VARS arrays (which need to be indicated as global when used inside a function or method). The following superglobal arrays were introduced in PHP » 4.1.0. They are: $_GET, $_POST, $_COOKIE, $_SERVER, $_FILES, $_ENV, $_REQUEST, and $_SESSION. The older $HTTP_*_VARS arrays, such as $HTTP_POST_VARS, also exist. Od PHP 5.0.0, długie tablice zmiennych predefiniowanych mogą być wyłączone dyrektywą konfiguracji register_long_arrays.
  • External variables are no longer registered in the global scope by default. In other words, as of PHP » 4.2.0 the PHP directive register_globals is off by default in php.ini. The preferred method of accessing these values is via the superglobal arrays mentioned above. Older scripts, books, and tutorials may rely on this directive being on. If it were on, for example, one could use $id from the URL http://www.example.com/foo.php?id=42. Whether on or off, $_GET['id'] is available.

For more details on these changes, see the section on predefined variables and links therein.



What's next?

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/





Instalacja i konfiguracja


Ogólnie o instalacji

Przed instalacją musisz wiedzieć do czego potrzebne ci jest PHP. PHP jest używane głównie w trzech polach, tak jak to zostało opisane w rozdziale Co potrafi PHP?

  • skrypty po stronie serwera
  • skrypty wywoływane z linii poleceń
  • aplikacje po stronie klienta

Dla pierwszej pozycji w najbardziej popularnej postaci potrzebne są trzy rzeczy: samo PHP, serwer WWW i przeglądarka internetowa. Najprawdopodobniej posiadasz już przeglądarkę, i zależnie od systemu operacyjnego także serwer (np. Apache na systemach Linux lub IIS na systemach Windows). Możesz także wynająć przestrzeń na serwerze komercyjnym. Tym sposobem nie musisz niczego własnoręcznie konfigurować, a jedynie pisać skrypty, umieszczać je na serwerze i oglądać wyniki w oknie przeglądarki.

Własnoręcznie konfigurując serwer i PHP masz dwie możliwości połączenia PHP z serwerem. Dla wielu serwerów PHP posiada bezpośredni interfejs modułu (zwany także SAPI). Do tych serwerów należą Apache, Microsoft Internet Information Server, Netscape i iPlanet. Przez wiele innych serwerów jest obsługiwane przez ISAPI, interfejs modułów Microsoft (na przykład OmniHTTPd). Jeśli PHP nie ma obsługi modułowej dla twojego serwera, możesz używać go jako procesor CGI lub FastCGI. Oznacza to, że możesz skonfigurować twój serwer tak, aby korzystał z pliku wykonywalnego PHP (php.exe na systemach Windows) do przetwarzania wszystkich plików PHP dostępnych na serwerze.

Jeśli jesteś zainteresowany używaniem PHP do pisania skryptów wywoływanych z linii poleceń (np. pisania skryptów do automatycznego generowania off-line obrazów dla Ciebie lub przetwarzania plików tekstowych zależnie od przekazanych argumentów), potrzebujesz pliku wykonywalnego PHP. Aby uzyskać więcej informacji przeczytaj rozdział Pisanie aplikacji PHP wywoływanych z linii poleceń. W tym przypadku nie potrzebujesz ani serwera ani przeglądarki.

W PHP możesz pisać także aplikacje z interfejsem użytkownika używając rozszerzenia PHP-GTK. Jest to podejście zupełnie inne niż tworzenie stron internetowych, ponieważ nie wysyłasz żadnego wyjścia HTMLowego, ale obsługujesz okienka i obiekty w nich zawarte. Aby uzyskać więcej informacji o PHP-GTK, odwiedź » stronę poświęconą temu rozszerzeniu. PHP-GTK nie jest zawarte w oficjalnej dystrybucji PHP.

Od tego miejsca rozdział dotyczy konfiguracji PHP z serwerami WWW pracującymi pod kontrolą systemów Unix i Windows w postaci modułów serwera lub binariów CGI. W następnych sekcjach znajdziesz informacje o wywoływaniu PHP z linii poleceń.

Kod źródlowy oraz dystrybucje binarne dla Windows, można znaleźć na stronie » http://www.php.net/downloads.php. Zalecane jest korzystanie z jednego z najbliższego » serweru lustrzanego do pobierania dystrybucji PHP.



Installation on Unix systems

Spis treści

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:

  • Basic Unix skills (being able to operate "make" and a C compiler)
  • An ANSI C compiler
  • flex: Version 2.5.4
  • bison: Version 1.28 (preferred), 1.35, or 1.75
  • A web server
  • Any module specific components (such as GD, PDF libs, etc.)

The initial PHP setup and configuration process is controlled by the use of the 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.


Apache 1.3.x on Unix systems

This section contains notes and hints specific to Apache installs of PHP on Unix platforms. We also have instructions and notes for Apache 2 on a separate page.

You can select arguments to add to the configure on line 10 below from the list of core configure options and from extension specific options described at the respective places in the manual. The version numbers have been omitted here, to ensure the instructions are not incorrect. You will need to replace the 'xxx' here with the correct values from your files.

Przykład #1 Installation Instructions (Apache Shared Module Version) for PHP

1.  gunzip apache_xxx.tar.gz
2.  tar -xvf apache_xxx.tar
3.  gunzip php-xxx.tar.gz
4.  tar -xvf php-xxx.tar
5.  cd apache_xxx
6.  ./configure --prefix=/www --enable-module=so
7.  make
8.  make install
9.  cd ../php-xxx

10. Now, configure your PHP.  This is where you customize your PHP
    with various options, like which extensions will be enabled.  Do a
    ./configure --help for a list of available options.  In our example
    we'll do a simple configure with Apache 1 and MySQL support.  Your
    path to apxs may differ from our example.

      ./configure --with-mysql --with-apxs=/www/bin/apxs

11. make
12. make install

    If you decide to change your configure options after installation,
    you only need to repeat the last three steps. You only need to 
    restart apache for the new module to take effect. A recompile of
    Apache is not needed.
  
    Note that unless told otherwise, 'make install' will also install PEAR,
    various PHP tools such as phpize, install the PHP CLI, and more.

13. Setup your php.ini file:

      cp php.ini-development /usr/local/lib/php.ini

    You may edit your .ini file to set PHP options.  If you prefer your
    php.ini in another location, use --with-config-file-path=/some/path in
    step 10. 
    
    If you instead choose php.ini-production, be certain to read the list
    of changes within, as they affect how PHP behaves.

14. Edit your httpd.conf to load the PHP module.  The path on the right hand
    side of the LoadModule statement must point to the path of the PHP
    module on your system.  The make install from above may have already
    added this for you, but be sure to check.
        
    For PHP 4:
            
      LoadModule php4_module libexec/libphp4.so

    For PHP 5:
                      
      LoadModule php5_module libexec/libphp5.so
      
15. And in the AddModule section of httpd.conf, somewhere under the
    ClearModuleList, add this:
    
    For PHP 4:
    
      AddModule mod_php4.c
      
    For PHP 5:
    
      AddModule mod_php5.c

16. Tell Apache to parse certain extensions as PHP.  For example,
    let's have Apache parse the .php extension as PHP.  You could
    have any extension(s) parse as PHP by simply adding more, with
    each separated by a space.  We'll add .phtml to demonstrate.

      AddType application/x-httpd-php .php .phtml

    It's also common to setup the .phps extension to show highlighted PHP
    source, this can be done with:
    
      AddType application/x-httpd-php-source .phps

17. Use your normal procedure for starting the Apache server. (You must
    stop and restart the server, not just cause the server to reload by
    using a HUP or USR1 signal.)

Alternatively, to install PHP as a static object:

Przykład #2 Installation Instructions (Static Module Installation for Apache) for PHP

1.  gunzip -c apache_1.3.x.tar.gz | tar xf -
2.  cd apache_1.3.x
3.  ./configure
4.  cd ..

5.  gunzip -c php-5.x.y.tar.gz | tar xf -
6.  cd php-5.x.y
7.  ./configure --with-mysql --with-apache=../apache_1.3.x
8.  make
9.  make install

10. cd ../apache_1.3.x

11. ./configure --prefix=/www --activate-module=src/modules/php5/libphp5.a
    (The above line is correct! Yes, we know libphp5.a does not exist at this
    stage. It isn't supposed to. It will be created.)

12. make
    (you should now have an httpd binary which you can copy to your Apache bin dir if
    it is your first install then you need to "make install" as well)

13. cd ../php-5.x.y
14. cp php.ini-development /usr/local/lib/php.ini

15. You can edit /usr/local/lib/php.ini file to set PHP options.
    Edit your httpd.conf or srm.conf file and add:
    AddType application/x-httpd-php .php

Informacja: Replace php-5 by php-4 and php5 by php4 in PHP 4.

Depending on your Apache install and Unix variant, there are many possible ways to stop and restart the server. Below are some typical lines used in restarting the server, for different apache/unix installations. You should replace /path/to/ with the path to these applications on your systems.

Przykład #3 Example commands for restarting Apache

1. Several Linux and SysV variants:
/etc/rc.d/init.d/httpd restart

2. Using apachectl scripts:
/path/to/apachectl stop
/path/to/apachectl start

3. httpdctl and httpsdctl (Using OpenSSL), similar to apachectl:
/path/to/httpsdctl stop
/path/to/httpsdctl start

4. Using mod_ssl, or another SSL server, you may want to manually
stop and start:
/path/to/apachectl stop
/path/to/apachectl startssl

The locations of the apachectl and http(s)dctl binaries often vary. If your system has locate or whereis or which commands, these can assist you in finding your server control programs.

Different examples of compiling PHP for apache are as follows:

./configure --with-apxs --with-pgsql

This will create a libphp5.so (or libphp4.so in PHP 4) shared library that is loaded into Apache using a LoadModule line in Apache's httpd.conf file. The PostgreSQL support is embedded into this library.

./configure --with-apxs --with-pgsql=shared

This will create a libphp4.so shared library for Apache, but it will also create a pgsql.so shared library that is loaded into PHP either by using the extension directive in php.ini file or by loading it explicitly in a script using the dl() function.

./configure --with-apache=/path/to/apache_source --with-pgsql

This will create a libmodphp5.a library, a mod_php5.c and some accompanying files and copy this into the src/modules/php5 directory in the Apache source tree. Then you compile Apache using --activate-module=src/modules/php5/libphp5.a and the Apache build system will create libphp5.a and link it statically into the httpd binary (replace php5 by php4 in PHP 4). The PostgreSQL support is included directly into this httpd binary, so the final result here is a single httpd binary that includes all of Apache and all of PHP.

./configure --with-apache=/path/to/apache_source --with-pgsql=shared

Same as before, except instead of including PostgreSQL support directly into the final httpd you will get a pgsql.so shared library that you can load into PHP from either the php.ini file or directly using dl().

When choosing to build PHP in different ways, you should consider the advantages and drawbacks of each method. Building as a shared object will mean that you can compile apache separately, and don't have to recompile everything as you add to, or change, PHP. Building PHP into apache (static method) means that PHP will load and run faster. For more information, see the Apache » web page on DSO support.

Informacja: Apache's default httpd.conf currently ships with a section that looks like this:

User nobody
Group "#-1"

Unless you change that to "Group nogroup" or something like that ("Group daemon" is also very common) PHP will not be able to open files.

Informacja: Make sure you specify the installed version of apxs when using --with-apxs=/path/to/apxs. You must NOT use the apxs version that is in the apache sources but the one that is actually installed on your system.



Apache 2.x on Unix systems

This section contains notes and hints specific to Apache 2.x installs of PHP on Unix systems.

Ostrzeżenie

Nie zalecamy korzystania z wątkowanego MPM na produkcyjnych serwerach Apache2. Zamiast niego wskazane jest używanie preforkowanego MPM, lub używanie Apache1. Wyjaśnienie powodów można znaleźć w odpowiednim punkcie FAQ, dotyczącym używania Apache2 z wątkowanym MPM

The » Apache Documentation is the most authoritative source of information on the Apache 2.x server. More information about installation options for Apache may be found there.

Informacja: PHP and Apache 2.0.x compatibility notes
The following versions of PHP are known to work with the most recent version of Apache 2.0.x:

These versions of PHP are compatible to Apache 2.0.40 and later.
Apache 2.0 SAPI-support started with PHP 4.2.0. PHP 4.2.3 works with Apache 2.0.39, don't use any other version of Apache with PHP 4.2.3. However, the recommended setup is to use PHP 4.3.0 or later with the most recent version of Apache2.
All mentioned versions of PHP will work still with Apache 1.3.x.

The most receive version of Apache HTTP Server may be obtained from » Apache download site, and a fitting PHP version from the above mentioned places. This quick guide covers only the basics to get started with Apache 2.x and PHP. For more information read the » Apache Documentation. The version numbers have been omitted here, to ensure the instructions are not incorrect. In the examples below, 'NN' should be replaced with the specific version of Apache being used.

There are currently two versions of Apache 2.x - there's 2.0 and 2.2. While there are various reasons for choosing each, 2.2 is the current latest version, and the one that is recommended, if that option is available to you. However, the instructions here will work for either 2.0 or 2.2.

Przykład #1 Installation Instructions (Apache 2 Shared Module Version)

1.  gzip -d httpd-2_x_NN.tar.gz
2.  tar xvf httpd-2_x_NN.tar
3.  gunzip php-NN.tar.gz
4.  tar -xvf php-NN.tar
5.  cd httpd-2_x_NN
6.  ./configure --enable-so
7.  make
8.  make install

    Now you have Apache 2.x.NN available under /usr/local/apache2,
    configured with loadable module support and the standard MPM prefork.
    To test the installation use your normal procedure for starting
    the Apache server, e.g.:
    /usr/local/apache2/bin/apachectl start
    and stop the server to go on with the configuration for PHP:
    /usr/local/apache2/bin/apachectl stop.

9.  cd ../php-NN

10. Now, configure your PHP.  This is where you customize your PHP
    with various options, like which extensions will be enabled.  Do a
    ./configure --help for a list of available options.  In our example
    we'll do a simple configure with Apache 2 and MySQL support.  Your
    path to apxs may differ, in fact, the binary may even be named apxs2 on
    your system. 
    
      ./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql

11. make
12. make install

    If you decide to change your configure options after installation,
    you only need to repeat the last three steps. You only need to
    restart apache for the new module to take effect. A recompile of
    Apache is not needed.
                
    Note that unless told otherwise, 'make install' will also install PEAR,
    various PHP tools such as phpize, install the PHP CLI, and more.
    
13. Setup your php.ini 
    
    cp php.ini-development /usr/local/lib/php.ini
          
    You may edit your .ini file to set PHP options.  If you prefer having
    php.ini in another location, use --with-config-file-path=/some/path in
    step 10.
    
    If you instead choose php.ini-production, be certain to read the list
    of changes within, as they affect how PHP behaves.

14. Edit your httpd.conf to load the PHP module.  The path on the right hand
    side of the LoadModule statement must point to the path of the PHP
    module on your system.  The make install from above may have already
    added this for you, but be sure to check.

      LoadModule php5_module modules/libphp5.so
 
15. Tell Apache to parse certain extensions as PHP.  For example, let's have
    Apache parse .php files as PHP.  Instead of only using the Apache AddType
    directive, we want to avoid potentially dangerous uploads and created
    files such as exploit.php.jpg from being executed as PHP.  Using this
    example, you could have any extension(s) parse as PHP by simply adding
    them.  We'll add .phtml to demonstrate.
            
      <FilesMatch \.php$>
          SetHandler application/x-httpd-php
      </FilesMatch>

    Or, if we wanted to allow .php, .php2, .php3, .php4, .php5, .php6, and
    .phtml files to be executed as PHP, but nothing else, we'd use this:

      <FilesMatch "\.ph(p[2-6]?|tml)$">
          SetHandler application/x-httpd-php
      </FilesMatch>
    
    And to allow .phps files to be handled by the php source filter, and
    displayed as syntax-highlighted source code, use this:

      <FilesMatch "\.phps$">
          SetHandler application/x-httpd-php-source
      </FilesMatch>

    mod_rewrite may be used To allow any arbitrary .php file to be displayed 
    as syntax-highlighted source code, without having to rename or copy it 
    to a .phps file:

      RewriteEngine On
      RewriteRule (.*\.php)s$ $1 [H=application/x-httpd-php-source]

    The php source filter should not be enabled on production systems, where
    it may expose confidential or otherwise sensitive information embedded in
    source code.

16. Use your normal procedure for starting the Apache server, e.g.:
   
      /usr/local/apache2/bin/apachectl start

          - OR -

      service httpd restart
   

Following the steps above you will have a running Apache2 web server with support for PHP as a SAPI module. Of course there are many more configuration options available Apache and PHP. For more information type ./configure --help in the corresponding source tree.

Apache may be built multithreaded by selecting the worker MPM, rather than the standard prefork MPM, when Apache is built. This is done by adding the following option to the argument passed to ./configure, in step 6 above:


--with-mpm=worker

This should not be undertaken without being aware of the consequences of this decision, and having at least a fair understanding of the implications. The Apache documentation regarding » MPM-Modules discusses MPMs in a great deal more detail.

Informacja: The Apache MultiViews FAQ discusses using multiviews with PHP.

Informacja: To build a multithreaded version of Apache, the target system must support threads. In this case, PHP should also be built with experimental Zend Thread Safety (ZTS). Under this configuration, not all extensions will be available. The recommended setup is to build Apache with the default prefork MPM-Module.



Lighttpd 1.4 on Unix systems

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).

Letting Lighttpd spawn php processes

To configure Lighttpd to connect to php and spawn fastcgi processes, edit lighttpd.conf. Sockets are preferred to connect to fastcgi processes on the local system.

Przykład #1 Partial lighttpd.conf

server.modules += ( "mod_fastcgi" )

fastcgi.server = ( ".php" =>
  ((
    "socket" => "/tmp/php.socket",
    "bin-path" => "/usr/local/bin/php-cgi",
    "bin-environment" => (
      "PHP_FCGI_CHILDREN" => "16",
      "PHP_FCGI_MAX_REQUESTS" => "10000"
    ),
    "min-procs" => 1,
    "max-procs" => 1,
    "idle-timeout" => 20
  ))
)

The bin-path directive allows lighttpd to spawn fastcgi processes dynamically. PHP will spawn children according to the PHP_FCGI_CHILDREN environment variable. The "bin-environment" directive sets the environment for the spawned processes. PHP will kill a child process after the number of requests specified by PHP_FCGI_MAX_REQUESTS is reached. The directives "min-procs" and "max-procs" should generally be avoided with PHP. PHP manages its own children and opcode caches like APC will only share among children managed by PHP. If "min-procs" is set to something greater than 1, the total number of php responders will be multiplied PHP_FCGI_CHILDREN (2 min-procs * 16 children gives 32 responders).

Spawning with spawn-fcgi

Lighttpd provides a program called spawn-fcgi to ease the process of spawning fastcgi processes easier.

Spawning php-cgi

It is possible to spawn processes without spawn-fcgi, though a bit of heavy-lifting is required. Setting the PHP_FCGI_CHILDREN environment var controls how many children PHP will spawn to handle incoming requests. Setting PHP_FCGI_MAX_REQUESTS will determine how long (in requests) each child will live. Here's a simple bash script to help spawn php responders.

Przykład #2 Spawning FastCGI Responders

#!/bin/sh

# Location of the php-cgi binary
PHP=/usr/local/bin/php-cgi

# PID File location
PHP_PID=/tmp/php.pid

# Binding to an address
#FCGI_BIND_ADDRESS=10.0.1.1:10000
# Binding to a domain socket
FCGI_BIND_ADDRESS=/tmp/php.sock

PHP_FCGI_CHILDREN=16
PHP_FCGI_MAX_REQUESTS=10000

env -i PHP_FCGI_CHILDREN=$PHP_FCGI_CHILDREN \
       PHP_FCGI_MAX_REQUESTS=$PHP_FCGI_MAX_REQUESTS \
       $PHP -b $FCGI_BIND_ADDRESS &

echo $! > "$PHP_PID"

Connecting to remote FCGI instances

Fastcgi instances can be spawned on multiple remote machines in order to scale applications.

Przykład #3 Connecting to remote php-fastcgi instances

fastcgi.server = ( ".php" =>
   (( "host" => "10.0.0.2", "port" => 1030 ),
    ( "host" => "10.0.0.3", "port" => 1030 ))
)


Caudium

PHP can be built as a Pike module for the » Caudium webserver. Follow the simple instructions below to install PHP for Caudium.

Przykład #1 Caudium Installation Instructions

1.  Make sure you have Caudium installed prior to attempting to
    install PHP 4. For PHP 4 to work correctly, you will need Pike
    7.0.268 or newer. For the sake of this example we assume that
    Caudium is installed in /opt/caudium/server/.
2.  Change directory to php-x.y.z (where x.y.z is the version number).
3.  ./configure --with-caudium=/opt/caudium/server
4.  make
5.  make install
6.  Restart Caudium if it's currently running.
7.  Log into the graphical configuration interface and go to the
    virtual server where you want to add PHP 4 support.
8.  Click Add Module and locate and then add the PHP 4 Script Support module.
9.  If the documentation says that the 'PHP 4 interpreter isn't
    available', make sure that you restarted the server. If you did
    check /opt/caudium/logs/debug/default.1 for any errors related to
    PHP4.so. Also make sure that 
    caudium/server/lib/[pike-version]/PHP4.so
    is present.
10. Configure the PHP Script Support module if needed.

You can of course compile your Caudium module with support for the various extensions available in PHP 4. See the reference pages for extension specific configure options.

Informacja: When compiling PHP 4 with MySQL support you must make sure that the normal MySQL client code is used. Otherwise there might be conflicts if your Pike already has MySQL support. You do this by specifying a MySQL install directory the --with-mysql option.



fhttpd related notes

To build PHP as an fhttpd module, answer "yes" to "Build as an fhttpd module?" (the --with-fhttpd=DIR option to configure) and specify the fhttpd source base directory. The default directory is /usr/local/src/fhttpd. If you are running fhttpd, building PHP as a module will give better performance, more control and remote execution capability.

Informacja: Support for fhttpd is no longer available as of PHP 4.3.0.



Sun, iPlanet and Netscape servers on Sun Solaris

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.

  1. Install the following packages from » http://www.sunfreeware.com/ or another download site:

    • autoconf-2.13
    • automake-1.4
    • bison-1_25-sol26-sparc-local
    • flex-2_5_4a-sol26-sparc-local
    • gcc-2_95_2-sol26-sparc-local
    • gzip-1.2.4-sol26-sparc-local
    • m4-1_4-sol26-sparc-local
    • make-3_76_1-sol26-sparc-local
    • mysql-3.23.24-beta (if you want mysql support)
    • perl-5_005_03-sol26-sparc-local
    • tar-1.13 (GNU tar)

  2. Make sure your path includes the proper directories PATH=.:/usr/local/bin:/usr/sbin:/usr/bin:/usr/ccs/bin and make it available to your system export PATH .
  3. gunzip php-x.x.x.tar.gz (if you have a .gz dist, otherwise go to 4).
  4. tar xvf php-x.x.x.tar
  5. Change to your extracted PHP directory: cd ../php-x.x.x
  6. 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

  7. Run make followed by make install.

After performing the base install and reading the appropriate readme file, you may need to perform some additional configuration steps.

Configuration Instructions for Sun/iPlanet/Netscape

Firstly you may need to add some paths to the LD_LIBRARY_PATH environment for the server to find all the shared libs. This can best done in the start script for your 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/.

  1. Add the following line to mime.types (you can do that by the administration server):

    type=magnus-internal/x-httpd-php exts=php
    

  2. 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.

  3. 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"

  4. 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.

  5. 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>
    

  6. To use PHP Authentication on a single directory, add the following:

    <Object ppath="d:\path\to\authenticated\dir\*">
    AuthTrans fn=php4_auth_trans
    </Object>
    

Informacja: The stacksize that PHP uses depends on the configuration of the web server. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").

CGI environment and recommended modifications in php.ini

Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the web server itself) and this space has only one environment. If you want to get CGI variables like PATH_INFO, HTTP_HOST etc. it is not the correct way to try this in the old PHP way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running web server without any valid CGI variables!

Informacja: Why are there (invalid) CGI variables in the environment?
Answer: This is because you started the web server process from the admin server which runs the startup script of the web server, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started web server has some CGI environment variables in it. You can test this by starting the web server not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.

Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):

variables_order = "GPCS"
register_globals = On

Special use for error pages or self-made directory listings (PHP >= 4.3.3)

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'].

Note about nsapi_virtual() and subrequests (PHP >= 4.3.3)

The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the web server and insert the result in the web page. This function uses some undocumented features from the NSAPI library. On Unix the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.

Informacja: But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!



CGI and command line setups

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.

Ostrzeżenie

Używając instalacji CGI, serwer jest podatny na wiele potencjalnych ataków. Sposoby obrony przed nimi zostały opisane w rozdziale o bezpieczeństwie instalacji CGI.

As of PHP 4.3.0, some important additions have happened to PHP. A new SAPI named CLI also exists and it has the same name as the CGI binary. What is installed at {PREFIX}/bin/php depends on your configure line and this is described in detail in the manual section named Using PHP from the command line. For further details please read that section of the manual.

Testing

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.

Using Variables

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'.



HP-UX specific installation notes

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



OpenBSD installation notes

This section contains notes and hints specific to installing PHP on » OpenBSD 3.6.

Using Binary Packages

Using binary packages to install PHP on OpenBSD is the recommended and simplest method. The core package has been separated from the various modules, and each can be installed and removed independently from the others. The files you need can be found on your OpenBSD CD or on the FTP site.

The main package you need to install is php4-core-4.3.8.tgz, which contains the basic engine (plus gettext and iconv). Next, take a look at the module packages, such as php4-mysql-4.3.8.tgz or php4-imap-4.3.8.tgz. You need to use the phpxs command to activate and deactivate these modules in your php.ini.

Przykład #1 OpenBSD Package Install Example

# pkg_add php4-core-4.3.8.tgz
# /usr/local/sbin/phpxs -s
# cp /usr/local/share/doc/php4/php.ini-recommended /var/www/conf/php.ini
  (add in mysql)
# pkg_add php4-mysql-4.3.8.tgz
# /usr/local/sbin/phpxs -a mysql
  (add in imap)
# pkg_add php4-imap-4.3.8.tgz
# /usr/local/sbin/phpxs -a imap
  (remove mysql as a test)
# pkg_delete php4-mysql-4.3.8
# /usr/local/sbin/phpxs -r mysql
  (install the PEAR libraries)
# pkg_add php4-pear-4.3.8.tgz

Read the » packages(7) manual page for more information about binary packages on OpenBSD.

Using Ports

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.

Common Problems

  • The default install of Apache runs inside a » chroot(2) jail, which will restrict PHP scripts to accessing files under /var/www. You will therefore need to create a /var/www/tmp directory for PHP session files to be stored, or use an alternative session backend. In addition, database sockets need to be placed inside the jail or listen on the localhost interface. If you use network functions, some files from /etc such as /etc/resolv.conf and /etc/services will need to be moved into /var/www/etc. The OpenBSD PEAR package automatically installs into the correct chroot directories, so no special modification is needed there. More information on the OpenBSD Apache is available in the » OpenBSD FAQ.
  • The OpenBSD 3.6 package for the » gd extension requires XFree86 to be installed. If you do not wish to use some of the font features that require X11, install the php4-gd-4.3.8-no_x11.tgz package instead.

Older Releases

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).



Solaris specific installation tips

This section contains notes and hints specific to installing PHP on Solaris systems.

Required software

Solaris installs often lack C compilers and their related tools. Read this FAQ for information on why using GNU versions for some of these tools is necessary. The required software is as follows:

  • gcc (recommended, other C compilers may work)
  • make
  • flex
  • bison
  • m4
  • autoconf
  • automake
  • perl
  • gzip
  • tar
  • GNU sed

In addition, you will need to install (and possibly compile) any additional software specific to your configuration, such as Oracle or MySQL.

Using Packages

You can simplify the Solaris install process by using pkgadd to install most of your needed components.



Debian GNU/Linux installation notes

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.

Using APT

First, note that other related packages may be desired like libapache2-mod-php5 to integrate with Apache 2, and php-pear for PEAR.

Second, before installing a package, it's wise to ensure the package list is up to date. Typically, this is done by running the command apt-get update.

Przykład #1 Debian Install Example with Apache 2

# apt-get install php5-common libapache2-mod-php5 php5-cli

APT will automatically install the PHP 5 module for Apache 2 and all of its dependencies, and then activate it. Apache should be restarted in order for the changes take place. For example:

Przykład #2 Stopping and starting Apache once PHP is installed

# /etc/init.d/apache2 stop
# /etc/init.d/apache2 start

Better control of configuration

In the last section, PHP was installed with only core modules. It's very likely that additional modules will be desired, such as MySQL, cURL, GD, etc. These may also be installed via the apt-get command.

Przykład #3 Methods for listing additional PHP 5 packages

# apt-cache search php5
# aptitude search php5
# aptitude search php5 |grep -i mysql

The examples will show a lot of packages including several PHP specific ones like php5-cgi, php5-cli and php5-dev. Determine which are needed and install them like any other with either apt-get or aptitude. And because Debian performs dependency checks, it'll prompt for those so for example to install MySQL and cURL:

Przykład #4 Install PHP with MySQL, cURL

# apt-get install php5-mysql php5-curl

APT will automatically add the appropriate lines to the different php.ini related files like /etc/php5/apache2/php.ini, /etc/php5/conf.d/pdo.ini, etc. and depending on the extension will add entries similar to extension=foo.so. However, restarting the web server (like Apache) is required before these changes take affect.

Common Problems

  • If the PHP scripts are not parsing via the web server, then it's likely that PHP was not added to the web server's configuration file, which on Debian may be /etc/apache2/apache2.conf or similar. See the Debian manual for further details.
  • If an extension was seemingly installed yet the functions are undefined, be sure that the appropriate ini file is being loaded and/or the web server was restarted after installation.
  • There are two basic commands for installing packages on Debian (and other linux variants): apt-get and aptitude. However, explaining the subtle differences between these commands goes beyond the scope of this manual.



Installation on Mac OS X

Spis treści

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.


Using Packages

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:



Using the bundled PHP

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:

  1. Locate and open the Apache configuration file. By default, the location is as follows: /private/etc/apache2/httpd.conf Using Finder or Spotlight to find this file may prove difficult as by default it's private and owned by the root user.

    Informacja: One way to open this is by using a Unix based text editor in the Terminal, for example nano, and because the file is owned by root we'll use the sudo command to open it (as root) so for example type the following into the Terminal Application (after, it will prompt for a password): sudo nano /private/etc/apache2/httpd.conf Noteworthy nano commands: ^w (search), ^o (save), and ^x (exit) where ^ represents the Ctrl key.

    Informacja: Versions of Mac OS X prior to 10.5 were bundled with older versions of PHP and Apache. As such, the Apache configuration file on legacy machines may be /etc/httpd/httpd.conf.

  2. 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
    
    Notice the location/path. When building PHP in the future, the above files should be replaced or commented out.

  3. Be sure the desired extensions will parse as PHP (examples: .php .html and .inc)

    Due to the following statement already existing in httpd.conf (as of Mac Panther), once PHP is enabled the .php files will automatically parse as PHP.

    <IfModule mod_php5.c>
        # If php is turned on, we respect .php and .phps files.
        AddType application/x-httpd-php .php
        AddType application/x-httpd-php-source .phps
    
        # Since most users will want index.php to work we
        # also automatically enable index.php
        <IfModule mod_dir.c>
            DirectoryIndex index.html index.php
        </IfModule>
    </IfModule>
    

    Informacja: Before OS X 10.5 (Leopard), PHP 4 was bundled instead of PHP 5 in which case the above instructions will differ slightly by changing 5's to 4's.

  4. Be sure the DirectoryIndex loads the desired default index file This is also set in httpd.conf. Typically index.php and index.html are used. By default index.php is enabled because it's also in the PHP check shown above. Adjust accordingly.
  5. Set the php.ini location or use the default A typical default location on Mac OS X is /usr/local/php/php.ini and a call to phpinfo() will reveal this information. If a php.ini is not used, PHP will use all default values. See also the related FAQ on finding php.ini.
  6. Locate or set the DocumentRoot This is the root directory for all the web files. Files in this directory are served from the web server so the PHP files will parse as PHP before outputting them to the browser. A typical default path is /Library/WebServer/Documents but this can be set to anything in httpd.conf. Alternatively, the default DocumentRoot for individual users is /Users/yourusername/Sites
  7. Create a phpinfo() file

    The phpinfo() function will display information about PHP. Consider creating a file in the DocumentRoot with the following PHP code:

    <?php phpinfo(); ?>

  8. Restart Apache, and load the PHP file created above To restart, either execute sudo apachectl graceful in the shell or stop/start the "Personal Web Server" option in the OS X System Preferences. By default, loading local files in the browser will have an URL like so: http://localhost/info.php Or using the DocumentRoot in the user directory is another option and would end up looking like: http://localhost/~yourusername/info.php

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.



Compiling for OS X Server

Mac OS X Server install

  1. Get the latest distributions of Apache and PHP.
  2. 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

  3. If you want the compiler to do some optimization, you may also want to add this line:

    setenv OPTIM=-O2

  4. 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.

  5. Type make and make install. This will add a directory to your Apache source directory under src/modules/php4.
  6. 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.

  7. Copy and rename the php.ini-development file to your bin directory from your PHP 4 source directory: cp php.ini-development /usr/local/bin/php.ini or (if your don't have a local directory) cp php.ini-development /usr/bin/php.ini .



Installing for Apache on MacOS X Client

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.

Ostrzeżenie

Be sure you know what you're doing before advancing beyond this point! You can cause irreparable harm to your Apache installation otherwise.

Informacja: These instructions will only work with the original Apache web server as shipped by Apple. If you re-built or upgraded your Apache, you will have to build your own PHP module.

To install:

  1. For Apache 1.3, download: http://www2.entropy.ch/download/entropy-php-5.2.4-1.tar.gz
  2. For Apache 2, download: wget http://www2.entropy.ch/download/entropy-php-5.2.4-1-apache2.tar.gz
  3. Unpack the compressed .tar.gz file, but DO NOT USE StuffIt Expander. Instead, use Apple's BOMArchiveHelper or the command line.
  4. Double-click the installer package and follow the directions of the installer application.

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.




Installation on Windows systems

Spis treści

This section applies to Windows 98/Me and Windows NT/2000/XP/2003. PHP will not work on 16 bit platforms such as Windows 3.1 and sometimes we refer to the supported Windows platforms as Win32. Windows 95 is no longer supported as of PHP 4.3.0.

Informacja: Windows 98/ME/NT4 is no longer supported as of PHP 5.3.0.

Informacja: Windows 95 is no longer supported as of PHP 4.3.0.

There are two main ways to install PHP for Windows: either manually or by using the installer.

If you have Microsoft Visual Studio, you can also build PHP from the original source code.

Once you have PHP installed on your Windows system, you may also want to load various extensions for added functionality.

Ostrzeżenie

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.


Windows Installer (PHP 5.1.0 and earlier)

The Windows PHP installer is available from the downloads page at » http://www.php.net/downloads.php. This installs the CGI version of PHP and for IIS, PWS, and Xitami, it configures the web server as well. The installer does not include any extra external PHP extensions (php_*.dll) as you'll only find those in the Windows Zip Package and PECL downloads.

Informacja: While the Windows installer is an easy way to make PHP work, it is restricted in many aspects as, for example, the automatic setup of extensions is not supported. Use of the installer isn't the preferred method for installing PHP.

First, install your selected HTTP (web) server on your system, and make sure that it works.

Run the executable installer and follow the instructions provided by the installation wizard. Two types of installation are supported - standard, which provides sensible defaults for all the settings it can, and advanced, which asks questions as it goes along.

The installation wizard gathers enough information to set up the php.ini file, and configure certain web servers to use PHP. One of the web servers the PHP installer does not configure for is Apache, so you'll need to configure it manually.

Once the installation has completed, the installer will inform you if you need to restart your system, restart the server, or just start using PHP.

Ostrzeżenie

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.



Windows Installer (PHP 5.2 and later)

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.

Normal Install

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 ).

Ostrzeżenie

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.

Silent Install

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 use the same syntax to specify the Apache Configuration Directory (APACHEDIR), the Sambar Server directory (SAMBARDIR), and the Xitami Server directory (XITAMIDIR).

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

Upgrading PHP with the Install

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.



Manual Installation Steps

This section contains instructions for manually installing and configuring PHP on Microsoft Windows. For the instructions on how to use PHP installer to setup and configure PHP and a web server on Windows refer to Windows Installer (PHP 5.2 and later).

Selecting and downloading the PHP distribution package

Download the PHP zip binary distribution from » PHP for Windows: Binaries and Sources. There are several different versions of the zip package - chose the version that is suitable for the web server being used:

  • If PHP is used with IIS then choose PHP 5.3 VC9 Non Thread Safe or PHP 5.2 VC6 Non Thread Safe;

  • If PHP is used with Apache 1 or Apache 2 then choose PHP 5.3 VC6 or PHP 5.2 VC6.

Informacja: VC9 Versions are compiled with the Visual Studio 2008 compiler and have improvements in performance and stability. The VC9 versions require you to have the » Microsoft 2008 C++ Runtime (x86) or the » Microsoft 2008 C++ Runtime (x64) installed.

The PHP package structure and content

Unpack the content of the zip archive into a directory of your choice, for example C:\PHP\. The directory and file structure extracted from the zip will look as below:

Przykład #1 PHP 5 package structure


c:\php
   |
   +--dev
   |  |
   |  |-php5ts.lib                 -- php5.lib in non thread safe version
   |
   +--ext                          -- extension DLLs for PHP
   |  |
   |  |-php_bz2.dll
   |  |
   |  |-php_cpdf.dll
   |  |
   |  |-...
   |
   +--extras                       -- empty 
   |
   +--pear                         -- initial copy of PEAR
   |
   |
   |-go-pear.bat                   -- PEAR setup script
   |
   |-...
   |
   |-php-cgi.exe                   -- CGI executable
   |
   |-php-win.exe                   -- executes scripts without an opened command prompt
   |
   |-php.exe                       -- Command line PHP executable (CLI)
   |
   |-...
   |
   |-php.ini-development           -- default php.ini settings
   |
   |-php.ini-production            -- recommended php.ini settings
   |
   |-php5apache2_2.dll             -- does not exist in non thread safe version
   |
   |-php5apache2_2_filter.dll      -- does not exist in non thread safe version
   |
   |-...
   |
   |-php5ts.dll                    -- core PHP DLL ( php5.dll in non thread safe version)
   | 
   |-...

Below is the list of the modules and executables included in the PHP zip distribution:

  • go-pear.bat - the PEAR setup script. Refer to » Installation (PEAR) for more details.

  • php-cgi.exe - CGI executable that can be used when running PHP on IIS via CGI or FastCGI.

  • php-win.exe - the PHP executable for executing PHP scripts without using a command line window (for example PHP applications that use Windows GUI).

  • php.exe - the PHP executable for executing PHP scripts within a command line interface (CLI).

  • php5apache2_2.dll - Apache 2.2.X module.

  • php5apache2_2_filter.dll - Apache 2.2.X filter.

Changing the php.ini file

After the php package content has been extracted, copy the php.ini-production into php.ini in the same folder. If necessary, it is also possible to place the php.ini into any other location of your choice but that will require additional configuration steps as described in PHP Configuration.

The php.ini file tells PHP how to configure itself, and how to work with the environment that it runs in. Here are a number of settings for the php.ini file that help PHP work better with Windows. Some of these are optional. There are many other directives that may be relevant to your environment - refer to the list of php.ini directives for more information.

Required directives:

  • extension_dir = <path to extension directory> - The extension_dir needs to point to the directory where PHP extensions files are stored. The path can be absolute (i.e. "C:\PHP\ext") or relative (i.e. ".\ext"). Extensions that are listed lower in the php.ini file need to be located in the extension_dir.

  • extension = xxxxx.dll - For each extension you wish to enable, you need a corresponding "extension=" directive that tells PHP which extensions in the extension_dir to load at startup time.

  • log_errors = On - PHP has an error logging facility that can be used to send errors to a file, or to a service (i.e. syslog) and works in conjunction with the error_log directive below. When running under IIS, the log_errors should be enabled, with a valid error_log.

  • error_log = <path to the error log file> - The error_log needs to specify the absolute, or relative path to the file where PHP errors should be logged. This file needs to be writable for the web server. The most common places for this file are in various TEMP directories, for example "C:\inetpub\temp\php-errors.log".

  • cgi.force_redirect = 0 - This directive is required for running under IIS. It is a directory security facility required by many other web servers. However, enabling it under IIS will cause the PHP engine to fail on Windows.

  • cgi.fix_pathinfo = 1 - This lets PHP access real path info following the CGI Spec. The IIS FastCGI implementation needs this set.

  • fastcgi.impersonate = 1 - FastCGI under IIS supports the ability to impersonate security tokens of the calling client. This allows IIS to define the security context that the request runs under.

  • fastcgi.logging = 0 - FastCGI logging should be disabled on IIS. If it is left enabled, then any messages of any class are treated by FastCGI as error conditions which will cause IIS to generate an HTTP 500 exception.

Optional directives

  • max_execution_time = ## - This directive tells PHP the maximum amount of time that it can spend executing any given script. The default for this is 30 seconds. Increase the value of this directive if PHP application take long time to execute.

  • memory_limit = ###M - The amount of memory available for the PHP process, in Megabytes. The default is 128, which is fine for most PHP applications. Some of the more complex ones might need more.

  • display_errors = Off - This directive tells PHP whether to include any error messages in the stream that it returns to the Web server. If this is set to "On", then PHP will send whichever classes of errors that you define with the error_reporting directive back to web server as part of the error stream. For security reasons it is recommended to set it to "Off" on production servers in order not to reveal any security sensitive information that is often included in the error messages.

  • open_basedir = <paths to directories, separated by semicolon>, e.g. openbasedir="C:\inetpub\wwwroot;C:\inetpub\temp". This directive specified the directory paths where PHP is allowed to perform file system operations. Any file operation outside of the specified paths will result in an error. This directive is especially useful for locking down the PHP installation in shared hosting environments to prevent PHP scripts from accessing any files outside of the web site's root directory.

  • upload_max_filesize = ###M and post_max_size = ###M - The maximum allowed size of an uploaded file and post data respectively. The values of these directives should be increased if PHP applications need to perform large uploads, such as for example photos or video files.

PHP is now setup on your system. The next step is to choose a web server, and enable it to run PHP. Choose a web server from the table of contents.

In addition to running PHP via a web server, PHP can run from the command line just like a .BAT script. See Command Line PHP on Microsoft Windows for further details.



ActiveScript

This section contains notes specific to the ActiveScript installation.

ActiveScript is a Windows only SAPI that enables you to use PHP script in any ActiveScript compliant host, like Windows Script Host, ASP/ASP.NET, Windows Script Components or Microsoft Scriptlet control.

As of PHP 5.0.1, ActiveScript has been moved to the » PECL repository. DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Informacja: You should read the manual installation steps first!

After installing PHP, you should download the ActiveScript DLL (php5activescript.dll) and place it in the main PHP folder (e.g. C:\php).

After having all the files needed, you must register the DLL on your system. To achieve this, open a Command Prompt window (located in the Start Menu). Then go to your PHP directory by typing something like cd C:\php. To register the DLL just type regsvr32 php5activescript.dll.

To test if ActiveScript is working, create a new file, named test.wsf (the extension is very important) and type:

<job id="test">
 
 <script language="PHPScript">
  $WScript->Echo("Hello World!");
 </script>
 
</job>

Save and double-click on the file. If you receive a little window saying "Hello World!" you're done.

Informacja: In PHP 4, the engine was named 'ActivePHP', so if you are using PHP 4, you should replace 'PHPScript' with 'ActivePHP' in the above example.

Informacja: ActiveScript doesn't use the default php.ini file. Instead, it will look only in the same directory as the .exe that caused it to load. You should create php-activescript.ini and place it in that folder, if you wish to load extensions, etc.



Microsoft IIS

This section contains PHP installation instructions specific to Microsoft Internet Information Services (IIS).



Microsoft IIS 5.1 and IIS 6.0

This section contains instructions for manually setting up Internet Information Services (IIS) 5.1 and IIS 6.0 to work with PHP on Microsoft Windows XP and Windows Server 2003. For instructions on setting up IIS 7.0 and later versions on Windows Vista, Windows Server 2008, Windows 7 and Windows Server 2008 R2 refer to Microsoft IIS 7.0 and later.

Configuring IIS to process PHP requests

Download and install PHP in accordance to the instructions described in manual installation steps

Informacja: Non-thread-safe build of PHP is recommended when using IIS. The non-thread-safe builds are available at » PHP for Windows: Binaries and Sources Releases.

Configure the CGI- and FastCGI-specific settings in php.ini file as shown below:

Przykład #1 CGI and FastCGI settings in php.ini

fastcgi.impersonate = 1
fastcgi.logging = 0
cgi.fix_pathinfo=1
cgi.force_redirect = 0

Download and install the » Microsoft FastCGI Extension for IIS 5.1 and 6.0. The extension is available for 32-bit and 64-bit platforms - select the right download package for your platform.

Configure the FastCGI extension to handle PHP-specific requests by running the command shown below. Replace the value of the "-path" parameter with the absolute file path to the php-cgi.exe file.

Przykład #2 Configuring FastCGI extension to handle PHP requests

cscript %windir%\system32\inetsrv\fcgiconfig.js -add -section:"PHP" ^
-extension:php -path:"C:\PHP\php-cgi.exe"

This command will create an IIS script mapping for *.php file extension, which will result in all URLs that end with .php being handled by FastCGI extension. Also, it will configure FastCGI extension to use the executable php-cgi.exe to process the PHP requests.

Informacja: At this point the required installation and configuration steps are completed. The remaining instructions below are optional but highly recommended for achieving optimal functionality and performance of PHP on IIS.

Impersonation and file system access

It is recommended to enable FastCGI impersonation in PHP when using IIS. This is controlled by the fastcgi.impersonate directive in php.ini file. When impersonation is enabled, PHP will perform all the file system operations on behalf of the user account that has been determined by IIS authentication. This ensures that even if the same PHP process is shared across different IIS web sites, the PHP scripts in those web sites will not be able to access each others' files as long as different user accounts are used for IIS authentication on each web site.

For example IIS 5.1 and IIS 6.0, in its default configuration, has anonymous authentication enabled with built-in user account IUSR_<MACHINE_NAME> used as a default identity. This means that in order for IIS to execute PHP scripts, it is necessary to grant IUSR_<MACHINE_NAME> account read permission on those scripts. If PHP applications need to perform write operations on certain files or write files into some folders then IUSR_<MACHINE_NAME> account should have write permission to those.

To determine which user account is used by IIS anonymous authentication, follow these steps:

  1. In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";

  2. Expand the list of web sites under the "Web Sites" node in the tree view, right-click on a web site that is being used and select "Properties";

  3. Click the "Directory Security" tab;

  4. Take note of a "User name:" field in the "Authentication Methods" dialog

To modify the permissions settings on files and folders, use the Windows Explorer user interface or icacls command.

Przykład #3 Configuring file access permissions

icacls C:\inetpub\wwwroot\upload /grant IUSR:(OI)(CI)(M)

Set index.php as a default document in IIS

The IIS default documents are used for HTTP requests that do not specify a document name. With PHP applications, index.php usually acts as a default document. To add index.php to the list of IIS default documents, follow these steps:

  1. In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";

  2. Right-click on the "Web Sites" node in the tree view and select "Properties";

  3. Click the "Documents" tab;

  4. Click the "Add..." button and enter "index.php" for the "Default content page:".

FastCGI and PHP Recycling configuration

Configure IIS FastCGI extension settings for recycling of PHP processes by using the commands shown below. The FastCGI setting instanceMaxRequests controls how many requests will be processed by a single php-cgi.exe process before FastCGI extension shuts it down. The PHP environment variable PHP_FCGI_MAX_REQUESTS controls how many requests a single php-cgi.exe process will handle before it recycles itself. Make sure that the value specified for FastCGI InstanceMaxRequests setting is less than or equal to the value specified for PHP_FCGI_MAX_REQUESTS.

Przykład #4 Configuring FastCGI and PHP recycling

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-InstanceMaxRequests:10000

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-EnvironmentVars:PHP_FCGI_MAX_REQUESTS:10000

Configuring FastCGI timeout settings

Increase the timeout settings for FastCGI extension if there are applications that have long running PHP scripts. The two settings that control timeouts are ActivityTimeout and RequestTimeout. Refer to » Configuring FastCGI Extension for IIS 6.0 for more information about those settings.

Przykład #5 Configuring FastCGI timeout settings

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-ActivityTimeout:90

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-RequestTimeout:90

Changing the Location of php.ini file

PHP searches for php.ini file in several locations and it is possible to change the default locations of php.ini file by using PHPRC environment variable. To instruct PHP to load the configuration file from a custom location run the command shown below. The absolute path to the directory with php.ini file should be specified as a value of PHPRC environment variable.

Przykład #6 Changing the location of php.ini file

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-EnvironmentVars:PHPRC:"C:\Some\Directory\"



Microsoft IIS 7.0 and later

This section contains instructions for manually setting up Internet Information Services (IIS) 7.0 and later to work with PHP on Microsoft Windows Vista SP1, Windows 7, Windows Server 2008 and Windows Server 2008 R2. For instructions on setting up IIS 5.1 and IIS 6.0 on Windows XP and Windows Server 2003 refer to Microsoft IIS 5.1 and IIS 6.0.

Enabling FastCGI support in IIS

FastCGI module is disabled in default installation of IIS. The steps to enable it differ based on the version of Windows being used.

To enable FastCGI support on Windows Vista SP1 and Windows 7:

  1. In the Windows Start Menu choose "Run:", type "optionalfeatures.exe" and click "Ok";

  2. In the "Windows Features" dialog expand "Internet Information Services", "World Wide Web Services", "Application Development Features" and then enable the "CGI" checkbox;

  3. Click OK and wait until the installation is complete.

To enable FastCGI support on Windows Server 2008 and Windows Server 2008 R2:

  1. In the Windows Start Menu choose "Run:", type "CompMgmtLauncher" and click "Ok";

  2. If the "Web Server (IIS)" role is not present under the "Roles" node, then add it by clicking "Add Roles";

  3. If the "Web Server (IIS)" role is present, then click "Add Role Services" and then enable the "CGI" checkbox under "Application Development" group;

  4. Click "Next" and then "Install" and wait for the installation to complete.

Configuring IIS to process PHP requests

Download and install PHP in accordance to the instructions described in manual installation steps

Informacja: Non-thread-safe build of PHP is recommended when using IIS. The non-thread-safe builds are available at » PHP for Windows: Binaries and Sources Releases.

Configure the CGI- and FastCGI-specific settings in php.ini file as shown below:

Przykład #1 CGI and FastCGI settings in php.ini

fastcgi.impersonate = 1
fastcgi.logging = 0
cgi.fix_pathinfo=1
cgi.force_redirect = 0

Configure IIS handler mapping for PHP by using either IIS Manager user interface or a command line tool.

Using IIS Manager user interface to create a handler mapping for PHP

Follow these steps to create an IIS handler mapping for PHP in IIS Manager user interface:

  1. In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";

  2. In the IIS Manager user interface select the server node in the "Connections" tree view;

  3. In the "Features View" page open the "Handler Mappings" feature;

  4. In the "Actions" pane click "Add Module Mapping...";

  5. In the "Add Module Mapping" dialog enter the following:

    • Request path: *.php
    • Module: FastCgiModule
    • Executable: C:\[Path to PHP installation]\php-cgi.exe
    • Name: PHP_via_FastCGI

  6. Click "Request Restrictions" button and then configure the mapping to invoke handler only if request is mapped to a file or a folder;

  7. Click OK on all the dialogs to save the configuration.

Using command line tool to create a handler mapping for PHP

Use the command shown below to create an IIS FastCGI process pool which will use php-cgi.exe executable for processing PHP requests. Replace the value of the fullPath parameter with the absolute file path to the php-cgi.exe file.

Przykład #2 Creating IIS FastCGI process pool

%windir%\system32\inetsrv\appcmd set config /section:system.webServer/fastCGI ^
/+[fullPath='c:\PHP\php-cgi.exe']

Configure IIS to handle PHP specific requests by running the command shown below. Replace the value of the scriptProcessor parameter with the absolute file path to the php-cgi.exe file.

Przykład #3 Creating handler mapping for PHP requests

%windir%\system32\inetsrv\appcmd set config /section:system.webServer/handlers ^
/+[name='PHP_via_FastCGI', path='*.php',verb='*',modules='FastCgiModule',^
scriptProcessor='c:\PHP\php-cgi.exe',resourceType='Either']

This command creates an IIS handler mapping for *.php file extension, which will result in all URLs that end with .php being handled by FastCGI module.

Informacja: At this point the required installation and configuration steps are completed. The remaining instructions below are optional but highly recommended for achieving optimal functionality and performance of PHP on IIS.

Impersonation and file system access

It is recommended to enable FastCGI impersonation in PHP when using IIS. This is controlled by the fastcgi.impersonate directive in php.ini file. When impersonation is enabled, PHP will perform all the file system operations on behalf of the user account that has been determined by IIS authentication. This ensures that even if the same PHP process is shared across different IIS web sites, the PHP scripts in those web sites will not be able to access each other's files as long as different user accounts are used for IIS authentication on each web site.

For example IIS 7, in its default configuration, has anonymous authentication enabled with built-in user account IUSR used as a default identity. This means that in order for IIS to execute PHP scripts, it is necessary to grant IUSR account read permission on those scripts. If PHP applications need to perform write operations on certain files or write files into some folders then IUSR account should have write permission to those.

To determine what user account is used as an anonymous identity in IIS 7 use the following command. Replace the "Default Web Site" with the name of IIS web site that you use. In the output XML configuration element look for the userName attribute.

Przykład #4 Determining the account used as IIS anonymous identity

%windir%\system32\inetsrv\appcmd.exe list config "Default Web Site" ^
/section:anonymousAuthentication

<system.webServer>
  <security>
    <authentication>
      <anonymousAuthentication enabled="true" userName="IUSR" />
    </authentication>
   </security>
</system.webServer>

Informacja: If userName attribute is not present in the anonymousAuthentication element, or is set to an empty string, then it means that the application pool identity is used as an anonymous identity for that web site.

To modify the permissions settings on files and folders, use the Windows Explorer user interface or icacls command.

Przykład #5 Configuring file access permissions

icacls C:\inetpub\wwwroot\upload /grant IUSR:(OI)(CI)(M)

Set index.php as a default document in IIS

The IIS default documents are used for HTTP requests that do not specify a document name. With PHP applications, index.php usually acts as a default document. To add index.php to the list of IIS default documents, use this command:

Przykład #6 Set index.php as a default document in IIS

%windir%\system32\inetsrv\appcmd.exe set config ^
-section:system.webServer/defaultDocument /+"files.[value='index.php']" ^
/commit:apphost

FastCGI and PHP Recycling configuration

Configure IIS FastCGI settings for recycling of PHP processes by using the commands shown below. The FastCGI setting instanceMaxRequests controls how many requests will be processed by a single php-cgi.exe process before IIS shuts it down. The PHP environment variable PHP_FCGI_MAX_REQUESTS controls how many requests a single php-cgi.exe process will handle before it recycles itself. Make sure that the value specified for FastCGI InstanceMaxRequests setting is less than or equal to the value specified for PHP_FCGI_MAX_REQUESTS.

Przykład #7 Configuring FastCGI and PHP recycling

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/[fullPath='c:\php\php-cgi.exe'].instanceMaxRequests:10000

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/+"[fullPath='C:\{php_folder}\php-cgi.exe'].environmentVariables.^
[name='PHP_FCGI_MAX_REQUESTS',value='10000']"

Configuring FastCGI timeout settings

Increase the timeout settings for FastCGI if it is expected to have long running PHP scripts. The two settings that control timeouts are activityTimeout and requestTimeout. Use the commands below to change the timeout settings. Make sure to replace the value in the fullPath parameter to contain the absolute path to the php-cgi.exe file.

Przykład #8 Configuring FastCGI and PHP recycling

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/[fullPath='C:\php\php-cgi.exe',arguments=''].activityTimeout:"90"  /commit:apphost

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/[fullPath='C:\php\php-cgi.exe',arguments=''].requestTimeout:"90"  /commit:apphost

Changing the Location of php.ini file

PHP searches for php.ini file in several locations and it is possible to change the default locations of php.ini file by using PHPRC environment variable. To instruct PHP to load the configuration file from a custom location run the command shown below. The absolute path to the directory with php.ini file should be specified as a value of PHPRC environment variable.

Przykład #9 Changing the location of php.ini file

appcmd.exe set config  -section:system.webServer/fastCgi ^
/+"[fullPath='C:\php\php.exe',arguments=''].environmentVariables.^
[name='PHPRC',value='C:\Some\Directory\']" /commit:apphost



Apache 1.3.x on Microsoft Windows

This section contains notes and hints specific to Apache 1.3.x installs of PHP on Microsoft Windows systems. There are also instructions and notes for Apache 2 on a separate page.

Informacja: Please read the manual installation steps first!

There are two ways to set up PHP to work with Apache 1.3.x on Windows. One is to use the CGI binary (php.exe for PHP 4 and php-cgi.exe for PHP 5), the other is to use the Apache Module DLL. In either case you need to edit your httpd.conf to configure Apache to work with PHP, and then restart the server.

It is worth noting here that now the SAPI module has been made more stable under Windows, we recommend it's use above the CGI binary, since it is more transparent and secure.

Although there can be a few variations of configuring PHP under Apache, these are simple enough to be used by the newcomer. Please consult the Apache Documentation for further configuration directives.

After changing the configuration file, remember to restart the server, for example, NET STOP APACHE followed by NET START APACHE, if you run Apache as a Windows Service, or use your regular shortcuts.

Informacja: Nalezy pamiętać, że podając ścieżki w plikach konfiguracyjnych Apache w systemie Windows, wszystkie znaki backslash takie jak na przykład w ścieżce c:\directory\file.ext muszą być zamienione na znaki slash, na przykład c:/directory/file.ext. Zamykające znaki slash mogą być także niezbędne dla katalogów.

Installing as an Apache module

You should add the following lines to your Apache httpd.conf file:

Przykład #1 PHP as an Apache 1.3.x module

This assumes PHP is installed to c:\php. Adjust the path if this is not the case.

For PHP 4:

# Add to the end of the LoadModule section
# Don't forget to copy this file from the sapi directory!
LoadModule php4_module "C:/php/php4apache.dll"

# Add to the end of the AddModule section
AddModule mod_php4.c

For PHP 5:

# Add to the end of the LoadModule section
LoadModule php5_module "C:/php/php5apache.dll"

# Add to the end of the AddModule section
AddModule mod_php5.c

For both:

# Add this line inside the <IfModule mod_mime.c> conditional brace
AddType application/x-httpd-php .php

# For syntax highlighted .phps files, also add
AddType application/x-httpd-php-source .phps

Installing as a CGI binary

If you unzipped the PHP package to C:\php\ as described in the Manual Installation Steps section, you need to insert these lines to your Apache configuration file to set up the CGI binary:

Przykład #2 PHP and Apache 1.3.x as CGI

ScriptAlias /php/ "c:/php/"
AddType application/x-httpd-php .php

# For PHP 4
Action application/x-httpd-php "/php/php.exe"

# For PHP 5
Action application/x-httpd-php "/php/php-cgi.exe"

# specify the directory where php.ini is
SetEnv PHPRC C:/php

Note that the second line in the list above can be found in the actual versions of httpd.conf, but it is commented out. Remember also to substitute the c:/php/ for your actual path to PHP.

Ostrzeżenie

Używając instalacji CGI, serwer jest podatny na wiele potencjalnych ataków. Sposoby obrony przed nimi zostały opisane w rozdziale o bezpieczeństwie instalacji CGI.

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'); ?>.



Apache 2.0.x on Microsoft Windows

This section contains notes and hints specific to Apache 2.0.x installs of PHP on Microsoft Windows systems. We also have instructions and notes for Apache 1.3.x users on a separate page.

Informacja: You should read the manual installation steps first!

Informacja: Apache 2.2.x Support
Users of Apache 2.2.x may use the documentation below except the appropriate DLL file is named php5apache2_2.dll and it only exists as of PHP 5.2.0. See also » http://snaps.php.net/

Ostrzeżenie

Nie zalecamy korzystania z wątkowanego MPM na produkcyjnych serwerach Apache2. Zamiast niego wskazane jest używanie preforkowanego MPM, lub używanie Apache1. Wyjaśnienie powodów można znaleźć w odpowiednim punkcie FAQ, dotyczącym używania Apache2 z wątkowanym MPM

You are highly encouraged to take a look at the » Apache Documentation to get a basic understanding of the Apache 2.0.x Server. Also consider to read the » Windows specific notes for Apache 2.0.x before reading on here.

Informacja: PHP and Apache 2.0.x compatibility notes
The following versions of PHP are known to work with the most recent version of Apache 2.0.x:

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.

Ostrzeżenie

Apache 2.0.x is designed to run on Windows NT 4.0, Windows 2000 or Windows XP. At this time, support for Windows 9x is incomplete. Apache 2.0.x is not expected to work on those platforms at this time.

Download the most recent version of » Apache 2.0.x and a fitting PHP version. Follow the Manual Installation Steps and come back to go on with the integration of PHP and Apache.

There are two ways to set up PHP to work with Apache 2.0.x on Windows. One is to use the CGI binary the other is to use the Apache module DLL. In either case you need to edit your httpd.conf to configure Apache to work with PHP and then restart the server.

Informacja: Nalezy pamiętać, że podając ścieżki w plikach konfiguracyjnych Apache w systemie Windows, wszystkie znaki backslash takie jak na przykład w ścieżce c:\directory\file.ext muszą być zamienione na znaki slash, na przykład c:/directory/file.ext. Zamykające znaki slash mogą być także niezbędne dla katalogów.

Installing as a CGI binary

You need to insert these three lines to your Apache httpd.conf configuration file to set up the CGI binary:

Przykład #1 PHP and Apache 2.0 as CGI

ScriptAlias /php/ "c:/php/"
AddType application/x-httpd-php .php

# For PHP 4
Action application/x-httpd-php "/php/php.exe"

# For PHP 5
Action application/x-httpd-php "/php/php-cgi.exe"

Ostrzeżenie

Używając instalacji CGI, serwer jest podatny na wiele potencjalnych ataków. Sposoby obrony przed nimi zostały opisane w rozdziale o bezpieczeństwie instalacji CGI.

Installing as an Apache module

You need to insert these two lines to your Apache httpd.conf configuration file to set up the PHP module for Apache 2.0:

Przykład #2 PHP and Apache 2.0 as Module

# For PHP 4 do something like this:
LoadModule php4_module "c:/php/php4apache2.dll"
# Don't forget to copy the php4apache2.dll file from the sapi directory!
AddType application/x-httpd-php .php

# For PHP 5 do something like this:
LoadModule php5_module "c:/php/php5apache2.dll"
AddType application/x-httpd-php .php

# configure the path to php.ini
PHPIniDir "C:/php"

Informacja: Remember to substitute your actual path to PHP for the c:/php/ in the above examples. Take care to use either php4apache2.dll or php5apache2.dll in your LoadModule directive and not php4apache.dll or php5apache.dll as the latter ones are designed to run with Apache 1.3.x.

Informacja: If you want to use content negotiation, read related FAQ.

Ostrzeżenie

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.



Sun, iPlanet and Netscape servers on Microsoft Windows

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.

CGI setup on Sun, iPlanet and Netscape servers

To install PHP as a CGI handler, do the following:

  • Copy php4ts.dll to your systemroot (the directory where you installed Windows)
  • Make a file association from the command line. Type the following two lines:

    assoc .php=PHPScript
    ftype PHPScript=c:\php\php.exe %1 %*

  • In the Netscape Enterprise Administration Server create a dummy shellcgi directory and remove it just after (this step creates 5 important lines in obj.conf and allow the web server to handle shellcgi scripts).
  • In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/shellcgi, File Suffix:php).
  • Do it for each web server instance you want PHP to run

More details about setting up PHP as a CGI executable can be found here: » http://benoit.noss.free.fr/php/install-php.html

NSAPI setup on Sun, iPlanet and Netscape servers

To install PHP with NSAPI, do the following:

  • Copy php4ts.dll to your systemroot (the directory where you installed Windows)
  • Make a file association from the command line. Type the following two lines:

    assoc .php=PHPScript
    ftype PHPScript=c:\php\php.exe %1 %*

  • In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/x-httpd-php, File Suffix: php).
  • 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.

  • Restart your web service and apply changes
  • Do it for each web server instance you want PHP to run

Informacja: More details about setting up PHP as an NSAPI filter can be found here: » http://benoit.noss.free.fr/php/install-php4.html

Informacja: The stacksize that PHP uses depends on the configuration of the web server. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").

CGI environment and recommended modifications in php.ini

Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the web server itself) and this space has only one environment. If you want to get CGI variables like PATH_INFO, HTTP_HOST etc. it is not the correct way to try this in the old PHP way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running web server without any valid CGI variables!

Informacja: Why are there (invalid) CGI variables in the environment?
Answer: This is because you started the web server process from the admin server which runs the startup script of the web server, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started web server has some CGI environment variables in it. You can test this by starting the web server not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.

Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):

variables_order = "GPCS"
register_globals = On

Special use for error pages or self-made directory listings (PHP >= 4.3.3)

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'].

Note about nsapi_virtual() and subrequests (PHP >= 4.3.3)

The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the web server and insert the result in the web page. The problem is, that this function uses some undocumented features from the NSAPI library.

Under Unix this is not a problem, because the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.

Under Windows limitations in the DLL handling need the use of a automatic detection of the most recent ns-httpdXX.dll file. This is tested for servers till version 6.1. If a newer version of the Sun server is used, the detection fails and nsapi_virtual() is disabled.

If this is the case, try the following: Add the following parameter to php4_init in magnus.conf/obj.conf:

Init fn=php4_init ... server_lib="ns-httpdXX.dll"

where XX is the correct DLL version number. To get it, look in the server-root for the correct DLL name. The DLL with the biggest filesize is the right one.

You can check the status by using the phpinfo() function.

Informacja: But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!



OmniHTTPd Server

This section contains notes and hints specific to » OmniHTTPd on Windows.

Informacja: You should read the manual installation steps first!

Ostrzeżenie

Używając instalacji CGI, serwer jest podatny na wiele potencjalnych ataków. Sposoby obrony przed nimi zostały opisane w rozdziale o bezpieczeństwie instalacji CGI.

You need to complete the following steps to make PHP work with OmniHTTPd. This is a CGI executable setup. SAPI is supported by OmniHTTPd, but some tests have shown that it is not so stable to use PHP as an ISAPI module.

Informacja: Important for CGI users
Read the faq on cgi.force_redirect for important details. This directive needs to be set to 0.

  1. Install OmniHTTPd server.

  2. Right click on the blue OmniHTTPd icon in the system tray and select Properties

  3. Click on Web Server Global Settings

  4. 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.

  5. On the Mime tab, enter: virtual = wwwserver/stdcgi | actual = .php, and use the Add button.

  6. Click OK

Repeat steps 2 - 6 for each extension you want to associate with PHP.

Informacja: Some OmniHTTPd packages come with built in PHP support. You can choose at setup time to do a custom setup, and uncheck the PHP component. We recommend you to use the latest PHP binaries. Some OmniHTTPd servers come with PHP 4 beta distributions, so you should choose not to set up the built in support, but install your own. If the server is already on your machine, use the Replace button in Step 4 and 5 to set the new, correct information.



Sambar Server on Microsoft Windows

This section contains notes and hints specific to the » Sambar Server for Windows.

Informacja: You should read the manual installation steps first!

This list describes how to set up the ISAPI module to work with the Sambar server on Windows.

  • Find the file called mappings.ini (in the config directory) in the Sambar install directory.

  • Open mappings.ini and add the following line under [ISAPI]:

    Przykład #1 ISAPI configuration of Sambar

    #for PHP 4
    *.php = c:\php\php4isapi.dll
    
    #for PHP 5
    *.php = c:\php\php5isapi.dll
    

    (This line assumes that PHP was installed in c:\php.)

  • Now restart the Sambar server for the changes to take effect.

Informacja: If you intend to use PHP to communicate with resources which are held on a different computer on your network, then you will need to alter the account used by the Sambar Server Service. The default account used for the Sambar Server Service is LocalSystem which will not have access to remote resources. The account can be amended by using the Services option from within the Windows Control Panel Administation Tools.



Xitami on Microsoft Windows

This section contains notes and hints specific to » Xitami on Windows.

Informacja: You should read the manual installation steps first!

This list describes how to set up the PHP CGI binary to work with Xitami on Windows.

Informacja: Important for CGI users
Read the faq on cgi.force_redirect for important details. This directive needs to be set to 0. If you want to use $_SERVER['PHP_SELF'] you have to enable the cgi.fix_pathinfo directive.

Ostrzeżenie

Używając instalacji CGI, serwer jest podatny na wiele potencjalnych ataków. Sposoby obrony przed nimi zostały opisane w rozdziale o bezpieczeństwie instalacji CGI.

  • 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.



Building from source

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:



Installation of extensions on Windows

After installing PHP and a web server on Windows, you will probably want to install some extensions for added functionality. You can choose which extensions you would like to load when PHP starts by modifying your php.ini. You can also load a module dynamically in your script using dl().

The DLLs for PHP extensions are prefixed with php_.

Many extensions are built into the Windows version of PHP. This means additional DLL files, and the extension directive, are not used to load these extensions. The Windows PHP Extensions table lists extensions that require, or used to require, additional PHP DLL files. Here's a list of built in extensions:

In PHP 4 (updated PHP 4.3.11): BCMath, Caledar, COM, Ctype, FTP, MySQL, ODBC, Overload, PCRE, Session, Tokenizer, WDDX, XML i Zlib

In PHP 5 (updated PHP 5.0.4), the following changes exist. Built in: DOM, LibXML, Iconv, SimpleXML, SPL i SQLite. And the following are no longer built in: MySQL and Overload.

The default location PHP searches for extensions is C:\php4\extensions in PHP 4 and C:\php5 in PHP 5. To change this setting to reflect your setup of PHP edit your php.ini file:

  • You will need to change the extension_dir setting to point to the directory where your extensions lives, or where you have placed your php_*.dll files. For example:

    extension_dir = C:\php\extensions

  • Enable the extension(s) in php.ini you want to use by uncommenting the extension=php_*.dll lines in php.ini. This is done by deleting the leading ; from the extension you want to load.

    Przykład #1 Enable Bzip2 extension for PHP-Windows

    // change the following line from ...
    ;extension=php_bz2.dll
    
    // ... to
    extension=php_bz2.dll

  • Some of the extensions need extra DLLs to work. Couple of them can be found in the distribution package, in the C:\php\dlls\ folder in PHP 4 or in the main folder in PHP 5, but some, for example Oracle (php_oci8.dll) require DLLs which are not bundled with the distribution package. If you are installing PHP 4, copy the bundled DLLs from C:\php\dlls folder to the main C:\php folder. Don't forget to include C:\php in the system PATH (this process is explained in a separate FAQ entry).

  • Some of these DLLs are not bundled with the PHP distribution. See each extensions documentation page for details. Also, read the manual section titled Installation of PECL extensions for details on PECL. An increasingly large number of PHP extensions are found in PECL, and these extensions require a separate download.

Informacja: If you are running a server module version of PHP remember to restart your web server to reflect your changes to php.ini.

The following table describes some of the extensions available and required additional dlls.

PHP Extensions
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



Command Line PHP on Microsoft Windows

This section contains notes and hints specific to getting PHP running from the command line for Windows.

Informacja: You should read the manual installation steps first!

Getting PHP to run from the command line can be performed without making any changes to Windows.

C:\PHP5\php.exe -f "C:\PHP Scripts\script.php" -- -arg1 -arg2 -arg3

But there are some easy steps that can be followed to make this simpler. Some of these steps should already have been taken, but are repeated here to be able to provide a complete step-by-step sequence.

  • Add the location of the PHP executable (php.exe, php-win.exe or php-cli.exe depending upon your PHP version and display preferences) to the PATH environment variable. Read more about how to add your PHP directory to PATH in the corresponding FAQ entry.

  • Add the .PHP extension to the PATHEXT environment variable. This can be done at the same time as amending the PATH environment variable. Follow the same steps as described in the FAQ but amend the PATHEXT environment variable rather than the PATH environment variable.

    Informacja: The position in which you place the .PHP will determine which script or program is executed when there are matching filenames. For example, placing .PHP before .BAT will cause your script to run, rather than the batch file, if there is a batch file with the same name.

  • Associate the .PHP extension with a file type. This is done by running the following command:

    assoc .php=phpfile
    

  • Associate the phpfile file type with the appropriate PHP executable. This is done by running the following command:

    ftype phpfile="C:\PHP5\php.exe" -f "%1" -- %~2
    

Following these steps will allow PHP scripts to be run from any directory without the need to type the PHP executable or the .PHP extension and all parameters will be supplied to the script for processing.

The example below details some of the registry changes that can be made manually.

Przykład #1 Registry changes

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.php]
@="phpfile"
"Content Type"="application/php"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile]
@="PHP Script"
"EditFlags"=dword:00000000
"BrowserFlags"=dword:00000008
"AlwaysShowExt"=""

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\DefaultIcon]
@="C:\\PHP5\\php-win.exe0"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell]
@="Open"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open]
@="&Open"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open\command]
@="\"C:\\PHP5\\php.exe\" -f \"%1\" -- %~2"

With these changes the same command can be written as:

"C:\PHP Scripts\script" -arg1 -arg2 -arg3
or, if your "C:\PHP Scripts" path is in the PATH environment variable:
script -arg1 -arg2 -arg3

Informacja: There is a small problem if you intend to use this technique and use your PHP scripts as commandline filter, like the example below:

dir | "C:\PHP Scripts\script" -arg1 -arg2 -arg3
or
dir | script -arg1 -arg2 -arg3
You may find that the script simply hangs and nothing is output. To get this operational, you need to make another registry change.
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer]
"InheritConsoleHandles"=dword:00000001
Further information regarding this issue can be found in this » Microsoft Knowledgebase Article : 321788.




Installation of PECL extensions

Spis treści


Introduction to PECL Installations

» 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.



Downloading PECL extensions

There are several options for downloading PECL extensions, such as:

  • The pecl install extname command downloads the extensions code automatically, so in this case there is no need for a separate download.
  • » http://pecl.php.net/ The PECL web site contains information about the different extensions that are offered by the PHP Development Team. The information available here includes: ChangeLog, release notes, requirements and other similar details.
  • pecl download extname PECL extensions that have releases listed on the PECL web site are available for download and installation using the » pecl command. Specific revisions may also be specified.
  • SVN Most PECL extensions also reside in SVN. A web-based view may be seen at » http://svn.php.net/viewvc/pecl/. To download straight from SVN, the following sequence of commands may be used:


    $ svn checkout http://svn.php.net/repository/pecl/extname/trunk extname

  • Windows downloads At this time the PHP project does not compile Windows binaries for PECL extensions. However, to compile PHP under Windows see the chapter titled building PHP for Windows.


Installing a PHP extension on Windows

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.

Where to find an 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.

Which extension to download?

Many times, you will find several versions of each DLL:

  • Different version numbers (at least the first two numbers should match)
  • Different thread safety settings
  • Different processor architecture (x86, x64, ...)
  • Different debugging settings
  • etc.

You should keep in mind that your extension settings should match all the settings of the PHP executable you are using. The following PHP script will tell you all about your PHP settings:

Przykład #1 phpinfo() call

<?php
phpinfo
();
?>

Or from the command line, run:

drive:\\path\to\php\executable\php.exe -i

Loading an extension

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.

Resolving problems

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.



Compiling shared PECL extensions with the pecl command

PECL makes it easy to create shared PHP extensions. Using the » pecl command, do the following:


$ pecl install extname

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:


$ pecl install extname-beta

You may also install a specific version using this variant:


$ pecl install extname-0.1

Informacja: After enabling the extension in php.ini, restarting the web service is required for the changes to be picked up.



Compiling shared PECL extensions with phpize

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.



Compiling PECL extensions statically into PHP

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:


/your/phpsrcdir/ext/extname

From here, force PHP to rebuild the configure script, and then build PHP as normal:


$ cd /your/phpsrcdir
$ rm configure
$ ./buildconf --force
$ ./configure --help
$ ./configure --with-extname --enable-someotherext --with-foobar
$ make
$ make install

Informacja: To run the 'buildconf' script you need autoconf 2.13 and automake 1.4+ (newer versions of autoconf may work, but are not supported).

Whether --enable-extname or --with-extname is used depends on the extension. Typically an extension that does not require external libraries uses --enable. To be sure, run the following after buildconf:


$ ./configure --help | grep extname




Problemy?

Spis treści


Przeczytaj FAQ

Niektóre problemy występują częściej niż inne. Tej najczęściej spotykane są wypisane w FAQ PHP, częsci tego podręcznika.



Inne problemy

Jeśli w dalszym ciągu nie wiesz co zrobić, być może ktoś z listy dyskusyjnej poświęconej instalacji PHP będzie mógł ci pomóc. Powinienej sprawdzić najpierw archiwum, bo być może ktoś już odpowiedział na twoje pytanie. Archiwa znajdują się w dziale 'Wspracie' na stronie » http://www.php.net/support.php. Aby zapisać się na listę dyskusyjną dotyczącą instalacji PHP, wyślij pusty list na adres » php-install-subscribe@lists.php.net. Adresem listy dyskusyjnej jest » php-install@lists.php.net.

Jeśli chcesz uzyskać pomoc na liście dyskusyjnej, postaraj się być precyzyjny i podaj niezbędne szczegóły dotyczące Twojego środowiska (system operacyjny, wersja PHP, serwer WWW, czy PHP działa jako CGI czy jako moduł, tryb bezpieczny, itp.), i kod, aby inni mogli odtworzyć i sprawdzić Twój problem.



Raporty o błędach

Jeśli uważasz, że znalazłeś błąd w PHP, zgłoś go. Programiści PHP prawdopodobnie nie wiedzą i nim, więc jeśli go nie zgłosisz, to najprawdopodobniej nie będzie usunięty. Możesz zgłaszać błędy korzystając z systemu zgłaszania błędów znajdującego się pod adresem » http://bugs.php.net/. Nie wysyłaj raportów o błędach na listy dyskusyjne lub bezpośrednio do developerów. System śledzenia błędów ma także opcję zgłaszania pomysłów na nowe możliwości.

Przeczytaj dokument » Jak wysyłać raporty o błędach przed wysłaniem jakiegokolwiek raportu o błędzie!




Runtime Configuration

Spis treści


The configuration file

The configuration file (php.ini) is read when PHP starts up. For the server module versions of PHP, this happens only once when the web server is started. For the CGI and CLI version, it happens on every invocation.

php.ini is searched in these locations (in order):

  • SAPI module specific location (PHPIniDir directive in Apache 2, -c command line option in CGI and CLI, php_ini parameter in NSAPI, PHP_INI_PATH environment variable in THTTPD)

  • The PHPRC environment variable. Before PHP 5.2.0 this was checked after the registry key mentioned below.

  • As of PHP 5.2.0, the location of the php.ini file can be set for different versions of PHP. The following registry keys are examined in order: [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y.z], [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y] and [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x], where x, y and z mean the PHP major, minor and release versions. If there is a value for IniFilePath in these keys, then the first one found will be used as the location of the php.ini (Windows only).

  • [HKEY_LOCAL_MACHINE\SOFTWARE\PHP], value of IniFilePath (Windows only).

  • Current working directory (except CLI)

  • The web server's directory (for SAPI modules), or directory of PHP (otherwise in Windows)

  • Windows directory (C:\windows or C:\winnt) (for Windows), or --with-config-file-path compile time option

If php-SAPI.ini exists (where SAPI is used SAPI, so the filename is e.g. php-cli.ini or php-apache.ini), it's used instead of php.ini. SAPI name can be determined by php_sapi_name().

Informacja: The Apache web server changes the directory to root at startup causing PHP to attempt to read php.ini from the root filesystem if it exists.

The php.ini directives handled by extensions are documented respectively on the pages of the extensions themselves. The list of the core directives is available in the appendix. Probably not all PHP directives are documented in the manual though. For a complete list of directives available in your PHP version, please read your well commented php.ini file. Alternatively, you may find the » the latest php.ini from SVN helpful too.

Przykład #1 php.ini example

; any text on a line after an unquoted semicolon (;) is ignored
[php] ; section markers (text within square brackets) are also ignored
; Boolean values can be set to either:
;    true, on, yes
; or false, off, no, none
register_globals = off
track_errors = yes

; you can enclose strings in double-quotes
include_path = ".:/usr/local/lib/php"

; backslashes are treated the same as any other character
include_path = ".;c:\php\lib"

Since PHP 5.1.0, it is possible to refer to existing .ini variables from within .ini files. Example: open_basedir = ${open_basedir} ":/new/dir".



.user.ini files

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).



Where a configuration setting may be set

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().

Definition of PHP_INI_* modes
Mode Value Meaning
PHP_INI_USER 1 Entry can be set in user scripts (like with ini_set()) or in the Windows registry
PHP_INI_PERDIR 6 Entry can be set in php.ini, .htaccess or httpd.conf
PHP_INI_SYSTEM 4 Entry can be set in php.ini or httpd.conf
PHP_INI_ALL 7 Entry can be set anywhere



How to change configuration settings

Running PHP as an Apache module

When using PHP as an Apache module, you can also change the configuration settings using directives in Apache configuration files (e.g. httpd.conf) and .htaccess files. You will need "AllowOverride Options" or "AllowOverride All" privileges to do so.

There are several Apache directives that allow you to change the PHP configuration from within the Apache configuration files. For a listing of which directives are PHP_INI_ALL, PHP_INI_PERDIR, or PHP_INI_SYSTEM, have a look at the List of php.ini directives appendix.

php_value name value

Sets the value of the specified directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives. To clear a previously set value use none as the value.

Informacja: Don't use php_value to set boolean values. php_flag (see below) should be used instead.

php_flag name on|off

Used to set a boolean configuration directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives.

php_admin_value name value

Sets the value of the specified directive. This can not be used in .htaccess files. Any directive type set with php_admin_value can not be overridden by .htaccess or ini_set(). To clear a previously set value use none as the value.

php_admin_flag name on|off

Used to set a boolean configuration directive. This can not be used in .htaccess files. Any directive type set with php_admin_flag can not be overridden by .htaccess.

Przykład #1 Apache configuration example

<IfModule mod_php5.c>
  php_value include_path ".:/usr/local/lib/php"
  php_admin_flag safe_mode on
</IfModule>
<IfModule mod_php4.c>
  php_value include_path ".:/usr/local/lib/php"
  php_admin_flag safe_mode on
</IfModule>

Uwaga

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

Changing PHP configuration via the Windows registry

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.

Other interfaces to PHP

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().





Opis języka


Podstawowa składnia

Spis treści


Wyskakiwanie z HTMLa

Kiedy PHP przetwarza plik, szuka otwierających i zamykających znaczników (tagów), które mówią PHP o rozpoczęciu i zakończeniu interpretowania kodu pomiędzy nimi. Przetwarzanie w taki sposób pozwala zagnieżdzać php w dowolnym rodzaju dokumentów, ponieważ wszystko poza parą znaczników, otwierającym i zamykającym jest ignorowane przez parser PHP. Najczęściej zobaczysz php zagnieżdzone w dokumentach HTML, tak jak w tym przykładzie.

<p>To zostanie zignorowane.</p>
<?php echo 'Kiedy to zostanie przetworzone.'?>
<p>To również zostanie zignorowane.</p>

Możesz także użyć bardziej zaawansowanej struktury:

Przykład #1 Zaawansowane wyskakiwanie

<?php
if ($wyrazenie) { 
    
?>
    <strong>To jest prawda.</strong>
    <?php 
} else { 
    
?>
    <strong>To jest fałsz.</strong>
    <?php 
}
?>

To działa jak się spodziewano, ponieważ kiedy PHP natrafi na zamykający znacznik ?>, poprostu zaczyna wyświetlać cokolwiek znajdzie (z wyjątkiem bezpośrednio następującej nowej linii - zobacz oddzielanie instrukcji ) dopóki nie natrafi na kolejny otwierający znacznik. Podany przykład jest oczywiście przekombinowany, ale do wyświetlania dużych bloków tekstu, wychodzenie z trybu przetwarzania PHP jest zasadniczo bardziej efektywne niż wysyłanie całego tekstu przez funkcje echo() lub print().

Mamy cztery różne pary otwierających i zamykających znaczników, które mogą być użyte w php. Dwie z nich, <?php ?> i <script language="php"> </script> są zawsze dostępne. Dwie następne to krótkie znaczniki i znaczniki w stylu ASP, mogą być włączane i wyłączane w pliku konfiguracyjnym php.ini. Część osób postrzega krótkie znaczniki i znaczniki w stylu ASP jako wygodne, jednakże są one mniej przenośne, i zasadniczo nie polecane.

Informacja: Zauważ również, że jeśli zagnieżdzasz PHP w XML lub XHTML musisz stosować znaczniki <?php ?> aby pozostać w zgodzie ze standardami.

Przykład #2 Znaczniki otwierające i zamykające PHP

1.  <?php echo 'jeśli chcesz obsługiwać dokumenty XHTML lub XML, zrób to tak'?>

2.  <script language="php">
        
echo 'niektóre edytory (jak FrontPage) nie lubią
              instrukcji przetwarzania'
;
    
</script>

3.  <? echo 'to jest najprostsza instrukcja przetwarzania SGML'?>
    <?= wyrazenie ?> To jest skrót dla "<? echo wyrazenie ?>"

4.  <% echo 'Możesz opcjonalnie użyć znaczników w stylu ASP'; %>
    <%= $zmienna; # To jest skrót dla "<% echo . . ." %>

Z pokazanych znaczników, pierwszy i drugi przykład są zawsze dostępne, pierwszy przykład jest najbardziej powszechny i rekomendowany.

Krótkie znaczniki (trzeci przykład) są dostepne jedynie, kiedy są włączone za pomocą dyrektywy konfiguracyjnej short_open_tag w php.ini lub jeśli php zostało skonfigurowane z opcją --enable-short-tags.

Znaczniki w stylu ASP (czwarty przykład) są dostępne jedynie gdy zostaną włączone poprzez dyrektywę konfiguracyjną asp_tags w php.ini

Informacja: Powinieneś unikać używania krótkich znaczników, kiedy rozwijasz aplikacje lub biblioteki, które są nastawione na rozpowszechnianie lub pracujesz na serwerach PHP, nad którymi nie masz kontroli, ponieważ krótkie znaczniki mogą nie być obsługiwane na docelowym serwerze. Dla przenośnego, rozpowszechnialnego kodu, miej pewność, aby nie użyć krotkich znaczników.



Oddzielanie instrukcji

Podobnie jak C i Perl, PHP wymaga aby instrukcje były zakończone średnikiem, na końcu każdego wyrażenia. Zamykający znacznik bloku kodu PHP automatycznie implikuje średnik; nie musisz mieć średnika zamykającego ostatnią linię z bloku PHP. Zamykający znacznik dla bloku będzie zawierać bezpośrednio następującą nową linie jeśli taka istnieje.

<?php
    
echo 'To jest test';
?>

<?php echo 'To jest test' ?>

<?php echo 'Pomineliśmy ostatni zamykający znacznik';

Informacja: Zamykający znacznik bloku PHP na końcu pliku jest opcjonalny, i w niektórych przypadkach pominięcie jego jest pomocne kiedy używamy include() lub require(), tak więc niechciane białe znaki nie będą znajdować się na końcu pliku, i ciągle będzie możliwe dodanie nagłówków do odpowiedzi. To jest także poręczne jeśli używasz buferowania wyjścia, i nie chciałbyś zobaczyć dodanych niechcianych białych znaków na końcu cześci generowanej przez includowany plik.



Komentarze

PHP obsługuje komentarze w stylu 'C', 'C++' i powłoki Unix (styl Perl\'a). Na przykład:

<?php
    
echo 'To jest test'// To jest jednoliniowy komentarz w stylu c++
    /* To jest wieloliniowy komentarz
       jeszcze inna linia komentarza */
    
echo 'To jest jeszcze jeden test';
    echo 
'Ostatni test'# To jest jednoliniowy komentarz w stylu powłoki
?>

"Jednolinijkowy" styl komentarzy obowiązuje jedynie do konca linii lub bieżącego bloku kodu PHP, cokolwiek wystąpi pierwsze. Co oznacza, że kod HTML za // ... ?> lub # ... ?> ZOSTANIE wyświetlony: ?> przerywa tryb PHP i wraca do trybu HTML, i // lub # nie może wpłynąć na to. Jeśli, dyrektywa konfiguracyjna asp_tags jest włączona, to działa tak samo z // %> i # %>. Jednakże, znacznik </script> nie przerywa trybu PHP w jednolinijkowym komentarzu.

<h1>To jest <?php # echo 'prosty';?> przykład.</h1>
<p>Nagłowek powyżej będzie mówił 'To jest  przykład'.</p>

Komentarze w stylu 'C' kończą się na pierwszym napotkanym */. Upewnij się, że nie zagnieżdzasz komentarzy w stylu 'C'. Łatwo jest popełnić pomyłkę jeśli próbujesz odkomentować duży blok kodu.

<?php
 
/* 
    echo 'To jest test'; /* Ten komentarz będzie przyczyną problemów */
 
*/
?>




Types

Spis treści


Introduction

PHP supports eight primitive types.

Four scalar types:

Two compound types:

And finally two special types:

This manual also introduces some pseudo-types for readability reasons:

And the pseudo-variable $... .

Some references to the type "double" may remain in the manual. Consider double the same as float; the two names exist only for historic reasons.

The type of a variable is not usually set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used.

Informacja: To check the type and value of an expression, use the var_dump() function. To get a human-readable representation of a type for debugging, use the gettype() function. To check for a certain type, do not use gettype(), but rather the is_type functions. Some examples:

<?php
$a_bool 
TRUE;   // a boolean
$a_str  "foo";  // a string
$a_str2 'foo';  // a string
$an_int 12;     // an integer

echo gettype($a_bool); // prints out:  boolean
echo gettype($a_str);  // prints out:  string

// If this is an integer, increment it by four
if (is_int($an_int)) {
    
$an_int += 4;
}

// If $bool is a string, print it out
// (does not print out anything)
if (is_string($a_bool)) {
    echo 
"String: $a_bool";
}
?>

To forcibly convert a variable to a certain type, either cast the variable or use the settype() function on it.

Note that a variable may be evaluated with different values in certain situations, depending on what type it is at the time. For more information, see the section on Type Juggling. The type comparison tables may also be useful, as they show examples of various type-related comparisons.



Booleans

This is the simplest type. A boolean expresses a truth value. It can be either TRUE or FALSE.

Informacja: The boolean type was introduced in PHP 4.

Syntax

To specify a boolean literal, use the keywords TRUE or FALSE. Both are case-insensitive.

<?php
$foo 
True// assign the value TRUE to $foo
?>

Typically, some kind of operator which returns a boolean value, and the value is passed on to a control structure.

<?php
// == is an operator which test
// equality and returns a boolean
if ($action == "show_version") {
    echo 
"The version is 1.23";
}

// this is not necessary...
if ($show_separators == TRUE) {
    echo 
"<hr>\n";
}

// ...because instead, this can be used:
if ($show_separators) {
    echo 
"<hr>\n";
}
?>

Converting to boolean

To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unncecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.

See also Type Juggling.

When converting to boolean, the following values are considered FALSE:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

Every other value is considered TRUE (including any resource).

Ostrzeżenie

-1 is considered TRUE, like any other non-zero (whether negative or positive) number!

<?php
var_dump
((bool) "");        // bool(false)
var_dump((bool) 1);         // bool(true)
var_dump((bool) -2);        // bool(true)
var_dump((bool) "foo");     // bool(true)
var_dump((bool) 2.3e5);     // bool(true)
var_dump((bool) array(12)); // bool(true)
var_dump((bool) array());   // bool(false)
var_dump((bool) "false");   // bool(true)
?>


Integers

An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}.

See also:

Syntax

Integers can be specified in decimal (base 10), hexadecimal (base 16), or octal (base 8) notation, optionally preceded by a sign (- or +).

To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x.

Przykład #1 Integer literals

<?php
$a 
1234// decimal number
$a = -123// a negative number
$a 0123// octal number (equivalent to 83 decimal)
$a 0x1A// hexadecimal number (equivalent to 26 decimal)
?>

Formally, the structure for integer literals is:

decimal     : [1-9][0-9]*
            | 0

hexadecimal : 0[xX][0-9a-fA-F]+

octal       : 0[0-7]+

integer     : [+-]?decimal
            | [+-]?hexadecimal
            | [+-]?octal

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bits platforms usually have the maximum value of about 9E18. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

Ostrzeżenie

If an invalid digit is given in an octal integer (i.e. 8 or 9), the rest of the number is ignored.

Przykład #2 Octal weirdness

<?php
var_dump
(01090); // 010 octal = 8 decimal
?>

Integer overflow

If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.

<?php
$large_number 
=  2147483647;
var_dump($large_number);
// output: int(2147483647)

$large_number =  2147483648;
var_dump($large_number);
// output: float(2147483648)

// it's true also for hexadecimal specified integers between 2^31 and 2^32-1:
var_dump0xffffffff );
// output: float(4294967295)

// this doesn't go for hexadecimal specified integers above 2^32-1:
var_dump0x100000000 );
// output: int(2147483647)

$million 1000000;
$large_number =  50000 $million;
var_dump($large_number);
// output: float(50000000000)
?>
Ostrzeżenie

Unfortunately, there was a bug in PHP which caused this to not always work correctly when negative numbers were involved. For example, the result of -50000 * $million is -429496728. However, when both operands were positive, there was no problem.

This was fixed in PHP 4.1.0.

There is no integer division operator in PHP. 1/2 yields the float 0.5. The value can be casted to an integer to round it downwards, or the round() function provides finer control over rounding.

<?php
var_dump
(25/7);         // float(3.5714285714286) 
var_dump((int) (25/7)); // int(3)
var_dump(round(25/7));  // float(4) 
?>

Converting to integer

To explicitly convert a value to integer, use either the (int) or (integer) casts. However, in most cases the cast is not needed, since a value will be automatically converted if an operator, function or control structure requires an integer argument. A value can also be converted to integer with the intval() function.

See also: type-juggling.

From booleans

FALSE will yield 0 (zero), and TRUE will yield 1 (one).

From floating point numbers

When converting from float to integer, the number will be rounded towards zero.

If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31), the result is undefined, since the float doesn't have enough precision to give an exact integer result. No warning, not even a notice will be issued when this happens!

Ostrzeżenie

Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results.

<?php
echo (int) ( (0.1+0.7) * 10 ); // echoes 7!
?>

See also the warning about float precision.

From strings

See String conversion to numbers

From other types

Uwaga

The behaviour of converting to integer is undefined for other types. Do not rely on any observed behaviour, as it can change without notice.



Floating point numbers

Floating point numbers (also known as "floats", "doubles", or "real numbers") can be specified using any of the following syntaxes:

<?php
$a 
1.234
$b 1.2e3
$c 7E-10;
?>

Formally:

LNUM          [0-9]+
DNUM          ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM})

The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64 bit IEEE format).

Ostrzeżenie

Floating point precision

It is typical that simple decimal fractions like 0.1 or 0.7 cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9.

This is due to the fact that it is impossible to express some fractions in decimal notation with a finite number of digits. For instance, 1/3 in decimal form becomes 0.3.

So never trust floating number results to the last digit, and never compare floating point numbers for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

Converting to float

For information on converting strings to float, see String conversion to numbers. For values of other types, the conversion is performed by converting the value to integer first and then to float. See Converting to integer for more information. As of PHP 5, a notice is thrown if an object is converted to float.



Strings

A string is series of characters. Before PHP 6, a character is the same as a byte. That is, there are exactly 256 different characters possible. This also implies that PHP has no native support of Unicode. See utf8_encode() and utf8_decode() for some basic Unicode functionality.

Informacja: It is no problem for a string to become very large. PHP imposes no boundary on the size of a string; the only limit is the available memory of the computer on which PHP is running.

Syntax

A string literal can be specified in four different ways:

Single quoted

The simplest way to specify a string is to enclose it in single quotes (the character ').

To specify a literal single quote, escape it with a backslash (\). To specify a literal backslash before a single quote, or at the end of the string, double it (\\). Note that attempting to escape any other character will print the backslash too.

Informacja: Unlike the two other syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

<?php
echo 'this is a simple string';

echo 
'You can also have embedded newlines in 
strings this way as it is
okay to do'
;

// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';

// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';

// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';

// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';

// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>

Double quoted

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

Escaped characters
Sequence Meaning
\n linefeed (LF or 0x0A (10) in ASCII)
\r carriage return (CR or 0x0D (13) in ASCII)
\t horizontal tab (HT or 0x09 (9) in ASCII)
\v vertical tab (VT or 0x0B (11) in ASCII) (since PHP 5.2.5)
\f form feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
\\ backslash
\$ dollar sign
\" double-quote
\[0-7]{1,3} the sequence of characters matching the regular expression is a character in octal notation
\x[0-9A-Fa-f]{1,2} the sequence of characters matching the regular expression is a character in hexadecimal notation

As in single quoted strings, escaping any other character will result in the backslash being printed too. Before PHP 5.1.1, the backslash in \{$var} had not been printed.

The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.

Heredoc

A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.

The closing identifier must begin in the first column of the line. Also, the identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.

Ostrzeżenie

It is very important to note that the line with the closing identifier must contain no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter (possibly followed by a semicolon) must also be followed by a newline.

If this rule is broken and the closing identifier is not "clean", it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line.

Heredocs can not be used for initializing class properties. Since PHP 5.3, this limitation is valid only for heredocs containing variables.

Przykład #1 Invalid example

<?php
class foo {
    public 
$bar = <<<EOT
bar
EOT;
}
?>

Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.

Przykład #2 Heredoc string quoting example

<?php
$str 
= <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

/* More complex example, with variables. */
class foo
{
    var 
$foo;
    var 
$bar;

    function 
foo()
    {
        
$this->foo 'Foo';
        
$this->bar = array('Bar1''Bar2''Bar3');
    }
}

$foo = new foo();
$name 'MyName';

echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some 
{$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>

Powyższy przykład wyświetli:

My name is "MyName". I am printing some Foo.
Now, I am printing some Bar2.
This should print a capital 'A': A

It is also possible to use the Heredoc syntax to pass data to function arguments:

Przykład #3 Heredoc in arguments example

<?php
var_dump
(array(<<<EOD
foobar!
EOD
));
?>

As of PHP 5.3.0, its possible to initialize static variables and class properties/constants using the Heredoc syntax:

Przykład #4 Using Heredoc to initialize static values

<?php
// Static variables
function foo()
{
    static 
$bar = <<<LABEL
Nothing in here...
LABEL;
}

// Class properties/constants
class foo
{
    const 
BAR = <<<FOOBAR
Constant example
FOOBAR;

    public 
$baz = <<<FOOBAR
Property example
FOOBAR;
}
?>

PHP 5.3.0 also introduces the possibility for Heredoc's to use double quotes in declarings:

Przykład #5 Using double quotes in Heredoc

<?php
echo <<<"FOOBAR"
Hello World!
FOOBAR;
?>

Informacja: Heredoc support was added in PHP 4.

Nowdoc

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML <![CDATA[ ]]> construct, in that it declares a block of text which is not for parsing.

A nowdoc is identified with the same <<< seqeuence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.

Przykład #6 Nowdoc string quoting example

<?php
$str 
= <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;

/* More complex example, with variables. */
class foo
{
    public 
$foo;
    public 
$bar;

    function 
foo()
    {
        
$this->foo 'Foo';
        
$this->bar = array('Bar1''Bar2''Bar3');
    }
}

$foo = new foo();
$name 'MyName';

echo <<<'EOT'
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41
EOT;
?>

Powyższy przykład wyświetli:

My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41

Informacja: Unlike heredocs, nowdocs can be used in any static data context. The typical example is initializing class properties or constants:

Przykład #7 Static data example

<?php
class foo {
    public 
$bar = <<<'EOT'
bar
EOT;
}
?>

Informacja: Nowdoc support was added in PHP 5.3.0.

Variable parsing

When a string is specified in double quotes or with heredoc, variables are parsed within it.

There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort.

The complex syntax was introduced in PHP 4, and can be recognised by the curly braces surrounding the expression.

Simple syntax

If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name.

<?php
$beer 
'Heineken';
echo 
"$beer's taste is great"// works; "'" is an invalid character for variable names
echo "He drank some $beers";   // won't work; 's' is a valid character for variable names but the variable is "$beer"
echo "He drank some ${beer}s"// works
echo "He drank some {$beer}s"// works
?>

Similarly, an array index or an object property can be parsed. With array indices, the closing square bracket (]) marks the end of the index. The same rules apply to object properties as to simple variables.

<?php
// These examples are specific to using arrays inside of strings.
// When outside of a string, always quote array string keys and do not use
// {braces}.

// Show all errors
error_reporting(E_ALL);

$fruits = array('strawberry' => 'red''banana' => 'yellow');

// Works, but note that this works differently outside a string
echo "A banana is $fruits[banana].";

// Works
echo "A banana is {$fruits['banana']}.";

// Works, but PHP looks for a constant named banana first, as described below.
echo "A banana is {$fruits[banana]}.";

// Won't work, use braces.  This results in a parse error.
echo "A banana is $fruits['banana'].";

// Works
echo "A banana is " $fruits['banana'] . ".";

// Works
echo "This square is $square->width meters broad.";

// Won't work. For a solution, see the complex syntax.
echo "This square is $square->width00 centimeters broad.";
?>

For anything more complex, you should use the complex syntax.

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

In fact, any value in the namespace can be included in a string with this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

<?php
// Show all errors
error_reporting(E_ALL);

$great 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";
echo 
"This is ${great}";

// Works
echo "This square is {$square->width}00 centimeters broad."

// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong  outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}"

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " $arr['foo'][3];

echo 
"This works too: {$obj->values[3]->name}";

echo 
"This is the value of the var named $name{${$name}}";

echo 
"This is the value of the var named by the return value of getName(): {${getName()}}";

echo 
"This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";
?>

It is also possible to access class properties using variables within strings using this syntax.

<?php
class foo {
    var 
$bar 'I am bar.';
}

$foo = new foo();
$bar 'bar';
$baz = array('foo''bar''baz''quux');
echo 
"{$foo->$bar}\n";
echo 
"{$foo->$baz[1]}\n";
?>

Powyższy przykład wyświetli:


I am bar.
I am bar.

Informacja: Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.

<?php
// Show all errors.
error_reporting(E_ALL);

class 
beers {
    const 
softdrink 'rootbeer';
    public static 
$ale 'ipa';
}

$rootbeer 'A & W';
$ipa 'Alexander Keith\'s';

// This works; outputs: I'd like an A & W
echo "I'd like an {${beers::softdrink}}\n";

// This works too; outputs: I'd like an Alexander Keith's
echo "I'd like an {${beers::$ale}}\n";
?>

String access and modification by character

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose.

Informacja: Strings may also be accessed using braces, as in $str{42}, for the same purpose. However, this syntax is deprecated as of PHP 5.3.0. Use square brackets instead, such as $str[42].

Ostrzeżenie

Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer. Illegal offset type emits E_NOTICE. Negative offset emits E_NOTICE in write but reads empty string. Only the first character of an assigned string is used. Assigning empty string assigns NUL byte.

Przykład #8 Some string examples

<?php
// Get the first character of a string
$str 'This is a test.';
$first $str[0];

// Get the third character of a string
$third $str[2];

// Get the last character of a string.
$str 'This is still a test.';
$last $str[strlen($str)-1]; 

// Modify the last character of a string
$str 'Look at the sea';
$str[strlen($str)-1] = 'e';

?>

Informacja: Accessing variables of other types using [] or {} silently returns NULL.

Useful functions and operators

Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. See String operators for more information.

There are a number of useful functions for string manipulation.

See the string functions section for general functions, and the regular expression functions or the Perl-compatible regular expression functions for advanced find & replace functionality.

There are also functions for URL strings, and functions to encrypt/decrypt strings (mcrypt and mhash).

Finally, see also the character type functions.

Converting to string

A value can be converted to a string using the (string) cast or the strval() function. String conversion is automatically done in the scope of an expression where a string is needed. This happens when using the echo() or print() functions, or when a variable is compared to a string. The sections on Types and Type Juggling will make the following clearer. See also the settype() function.

A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

An integer or float is converted to a string representing the number textually (including the exponent part for floats). Floating point numbers can be converted using exponential notation (4.1E+6).

Informacja: The decimal point character is defined in the script's locale (category LC_NUMERIC). See the setlocale() function.

Arrays are always converted to the string "Array"; because of this, echo() and print() can not by themselves show the contents of an array. To view a single element, use a construction such as echo $arr['foo']. See below for tips on viewing the entire contents.

Objects in PHP 4 are always converted to the string "Object". To print the values of object properties for debugging reasons, read the paragraphs below. To get an object's class name, use the get_class() function. As of PHP 5, the __toString method is used when applicable.

Resources are always converted to strings with the structure "Resource id #1", where 1 is the unique number assigned to the resource by PHP at runtime. Do not rely upon this structure; it is subject to change. To get a resource's type, use the get_resource_type() function.

NULL is always converted to an empty string.

As stated above, directly converting an array, object, or resource to a string does not provide any useful information about the value beyond its type. See the functions print_r() and var_dump() for more effective means of inspecting the contents of these types.

Most PHP values can also be converted to strings for permanent storage. This method is called serialization, and is performed by the serialize() function. If the PHP engine was built with WDDX support, PHP values can also be serialized as well-formed XML text.

String conversion to numbers

When a string is evaluated in a numeric context, the resulting value and type are determined as follows.

If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

<?php
$foo 
"10.5";                // $foo is float (11.5)
$foo "-1.3e3";              // $foo is float (-1299)
$foo "bob-1.3e3";           // $foo is integer (1)
$foo "bob3";                // $foo is integer (1)
$foo "10 Small Pigs";       // $foo is integer (11)
$foo "10.2 Little Piggies"// $foo is float (14.2)
$foo "10.0 pigs " 1;          // $foo is float (11)
$foo "10.0 pigs " 1.0;        // $foo is float (11)     
?>

For more information on this conversion, see the Unix manual page for strtod(3).

To test any of the examples in this section, cut and paste the examples and insert the following line to see what's going on:

<?php
echo "\$foo==$foo; type is " gettype ($foo) . "<br />\n";
?>

Do not expect to get the code of one character by converting it to integer, as is done in C. Use the ord() and chr() functions to convert between ASCII codes and characters.



Arrays

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

Explanation of those data structures is beyond the scope of this manual, but at least one example is provided for each of them. For more information, look towards the considerable literature that exists about this broad topic.

Syntax

Specifying with array()

An array can be created by the array() language construct. It takes as parameters any number of comma-separated key => value pairs.

array(  key =>  value
     , ...
     )
// key may only be an integer or string
// value may be any value of any type
<?php
$arr 
= array("foo" => "bar"12 => true);

echo 
$arr["foo"]; // bar
echo $arr[12];    // 1
?>

A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.

A value can be any PHP type.

Informacja: Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an E_NOTICE-level error message will be issued, and the result will be NULL.

<?php
$arr 
= array("somearray" => array(=> 513 => 9"a" => 42));

echo 
$arr["somearray"][6];    // 5
echo $arr["somearray"][13];   // 9
echo $arr["somearray"]["a"];  // 42
?>

If a key is not specified for a value, the maximum of the integer indices is taken and the new key will be that value plus 1. If a key that already has an assigned value is specified, that value will be overwritten.

<?php
// This array is the same as ...
array(=> 433256"b" => 12);

// ...this array
array(=> 43=> 32=> 56"b" => 12);
?>
Ostrzeżenie

Before PHP 4.3.0, appending to an array in which the current maximum key was negative would create a new key as described above. Since PHP 4.3.0, the new key will be 0.

Using TRUE as key will evaluate to integer 1 as a key. Using FALSE as key will evaluate to integer 0 as a key. Using NULL as a key will evaluate to the empty string. Using the empty string as a key will create (or overwrite) a key with the empty string and its value; it is not the same as using empty brackets.

Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.

Creating/modifying with square bracket syntax

An existing array can be modified by explicitly setting values in it.

This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]).

$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type

If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the unset() function on it.

<?php
$arr 
= array(=> 112 => 2);

$arr[] = 56;    // This is the same as $arr[13] = 56;
                // at this point of the script

$arr["x"] = 42// This adds a new element to
                // the array with key "x"
                
unset($arr[5]); // This removes the element from the array

unset($arr);    // This deletes the whole array
?>

Informacja: As mentioned above, if no key is specified, the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1. If no integer indices exist yet, the key will be 0 (zero).
Note that the maximum integer key used for this need not currently exist in the array. It need only have existed in the array at some time since the last time the array was re-indexed. The following example illustrates:

<?php
// Create a simple array.
$array = array(12345);
print_r($array);

// Now delete every item, but leave the array itself intact:
foreach ($array as $i => $value) {
    unset(
$array[$i]);
}
print_r($array);

// Append an item (note that the new key is 5, instead of 0).
$array[] = 6;
print_r($array);

// Re-index:
$array array_values($array);
$array[] = 7;
print_r($array);
?>

Powyższy przykład wyświetli:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Array
(
)
Array
(
    [5] => 6
)
Array
(
    [0] => 6
    [1] => 7
)

Useful functions

There are quite a few useful functions for working with arrays. See the array functions section.

Informacja: The unset() function allows removing keys from an array. Be aware that the array will not be reindexed. If a true "remove and shift" behavior is desired, the array can be reindexed using the array_values() function.

<?php
$a 
= array(=> 'one'=> 'two'=> 'three');
unset(
$a[2]);
/* will produce an array that would have been defined as
   $a = array(1 => 'one', 3 => 'three');
   and NOT
   $a = array(1 => 'one', 2 =>'three');
*/

$b array_values($a);
// Now $b is array(0 => 'one', 1 =>'three')
?>

The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array.

Array do's and don'ts

Why is $foo[bar] wrong?

Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while $foo[bar] is not. But why? It is common to encounter this kind of syntax in old scripts:

<?php
$foo
[bar] = 'enemy';
echo 
$foo[bar];
// etc
?>

This is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in future define constants which, unfortunately for such code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.

Informacja: This does not mean to always quote the key. Do not quote keys which are constants or variables, as this will prevent PHP from interpreting them.

<?php
error_reporting
(E_ALL);
ini_set('display_errors'true);
ini_set('html_errors'false);
// Simple array:
$array = array(12);
$count count($array);
for (
$i 0$i $count$i++) {
    echo 
"\nChecking $i: \n";
    echo 
"Bad: " $array['$i'] . "\n";
    echo 
"Good: " $array[$i] . "\n";
    echo 
"Bad: {$array['$i']}\n";
    echo 
"Good: {$array[$i]}\n";
}
?>

Powyższy przykład wyświetli:

Checking 0: 
Notice: Undefined index:  $i in /path/to/script.html on line 9
Bad: 
Good: 1
Notice: Undefined index:  $i in /path/to/script.html on line 11
Bad: 
Good: 1

Checking 1: 
Notice: Undefined index:  $i in /path/to/script.html on line 9
Bad: 
Good: 2
Notice: Undefined index:  $i in /path/to/script.html on line 11
Bad: 
Good: 2

More examples to demonstrate this behaviour:

<?php
// Show all errors
error_reporting(E_ALL);

$arr = array('fruit' => 'apple''veggie' => 'carrot');

// Correct
print $arr['fruit'];  // apple
print $arr['veggie']; // carrot

// Incorrect.  This works but also throws a PHP error of level E_NOTICE because
// of an undefined constant named fruit
// 
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit];    // apple

// This defines a constant to demonstrate what's going on.  The value 'veggie'
// is assigned to a constant named fruit.
define('fruit''veggie');

// Notice the difference now
print $arr['fruit'];  // apple
print $arr[fruit];    // carrot

// The following is okay, as it's inside a string. Constants are not looked for
// within strings, so no E_NOTICE occurs here
print "Hello $arr[fruit]";      // Hello apple

// With one exception: braces surrounding arrays within strings allows constants
// to be interpreted
print "Hello {$arr[fruit]}";    // Hello carrot
print "Hello {$arr['fruit']}";  // Hello apple

// This will not work, and will result in a parse error, such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using superglobals in strings as well
print "Hello $arr['fruit']";
print 
"Hello $_GET['foo']";

// Concatenation is another option
print "Hello " $arr['fruit']; // Hello apple
?>

When error_reporting is set to show E_NOTICE level errors (by setting it to E_ALL, for example), such uses will become immediately visible. By default, error_reporting is set not to show notices.

As stated in the syntax section, what's inside the square brackets ('[' and ']') must be an expression. This means that code like this works:

<?php
echo $arr[somefunc($bar)];
?>

This is an example of using a function return value as the array index. PHP also knows about constants:

<?php
$error_descriptions
[E_ERROR]   = "A fatal error has occured";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE]  = "This is just an informal notice";
?>

Note that E_ERROR is also a valid identifier, just like bar in the first example. But the last example is in fact the same as writing:

<?php
$error_descriptions
[1] = "A fatal error has occured";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";
?>

because E_ERROR equals 1, etc.

So why is it bad then?

At some point in the future, the PHP team might want to add another constant or keyword, or a constant in other code may interfere. For example, it is already wrong to use the words empty and default this way, since they are reserved keywords.

Informacja: To reiterate, inside a double-quoted string, it's valid to not surround array indexes with quotes so "$foo[bar]" is valid. See the above examples for details on why as well as the section on variable parsing in strings.

Converting to array

For any of the types: integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue).

If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behaviour:

<?php

class {
    private 
$A// This will become '\0A\0A'
}

class 
extends {
    private 
$A// This will become '\0B\0A'
    
public $AA// This will become 'AA'
}

var_dump((array) new B());
?>

The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'.

Converting NULL to an array results in an empty array.

Comparing

It is possible to compare arrays with the array_diff() function and with array operators.

Examples

The array type in PHP is very versatile. Here are some examples:

<?php
// This:
$a = array( 'color' => 'red',
            
'taste' => 'sweet',
            
'shape' => 'round',
            
'name'  => 'apple',
            
4        // key will be 0
          
);

$b = array('a''b''c');

// . . .is completely equivalent with this:
$a = array();
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name']  = 'apple';
$a[]        = 4;        // key will be 0

$b = array();
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';

// After the above code is executed, $a will be the array
// array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round', 
// 'name' => 'apple', 0 => 4), and $b will be the array 
// array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c').
?>

Przykład #1 Using array()

<?php
// Array as (property-)map
$map = array( 'version'    => 4,
              
'OS'         => 'Linux',
              
'lang'       => 'english',
              
'short_tags' => true
            
);
            
// strictly numerical keys
$array = array( 7,
                
8,
                
0,
                
156,
                -
10
              
);
// this is the same as array(0 => 7, 1 => 8, ...)

$switching = array(         10// key = 0
                    
5    =>  6,
                    
3    =>  7
                    
'a'  =>  4,
                            
11// key = 6 (maximum of integer-indices was 5)
                    
'8'  =>  2// key = 8 (integer!)
                    
'02' => 77// key = '02'
                    
0    => 12  // the value 10 will be overwritten by 12
                  
);
                  
// empty array
$empty = array();         
?>

Przykład #2 Collection

<?php
$colors 
= array('red''blue''green''yellow');

foreach (
$colors as $color) {
    echo 
"Do you like $color?\n";
}

?>

Powyższy przykład wyświetli:

Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?

Changing the values of the array directly is possible since PHP 5 by passing them by reference. Before that, a workaround is necessary:

Przykład #3 Collection

<?php
// PHP 5
foreach ($colors as &$color) {
    
$color strtoupper($color);
}
unset(
$color); /* ensure that following writes to
$color will not modify the last array element */

// Workaround for older versions
foreach ($colors as $key => $color) {
    
$colors[$key] = strtoupper($color);
}

print_r($colors);
?>

Powyższy przykład wyświetli:

Array
(
    [0] => RED
    [1] => BLUE
    [2] => GREEN
    [3] => YELLOW
)

This example creates a one-based array.

Przykład #4 One-based index

<?php
$firstquarter  
= array(=> 'January''February''March');
print_r($firstquarter);
?>

Powyższy przykład wyświetli:

Array 
(
    [1] => 'January'
    [2] => 'February'
    [3] => 'March'
)

Przykład #5 Filling an array

<?php
// fill an array with all items from a directory
$handle opendir('.');
while (
false !== ($file readdir($handle))) {
    
$files[] = $file;
}
closedir($handle); 
?>

Arrays are ordered. The order can be changed using various sorting functions. See the array functions section for more information. The count() function can be used to count the number of items in an array.

Przykład #6 Sorting an array

<?php
sort
($files);
print_r($files);
?>

Because the value of an array can be anything, it can also be another array. This enables the creation of recursive and multi-dimensional arrays.

Przykład #7 Recursive and multi-dimensional arrays

<?php
$fruits 
= array ( "fruits"  => array ( "a" => "orange",
                                       
"b" => "banana",
                                       
"c" => "apple"
                                     
),
                  
"numbers" => array ( 1,
                                       
2,
                                       
3,
                                       
4,
                                       
5,
                                       
6
                                     
),
                  
"holes"   => array (      "first",
                                       
=> "second",
                                            
"third"
                                     
)
                );

// Some examples to address values in the array above 
echo $fruits["holes"][5];    // prints "second"
echo $fruits["fruits"]["a"]; // prints "orange"
unset($fruits["holes"][0]);  // remove "first"

// Create a new multi-dimensional array
$juices["apple"]["green"] = "good"
?>

Array assignment always involves value copying. Use the reference operator to copy an array by reference.

<?php
$arr1 
= array(23);
$arr2 $arr1;
$arr2[] = 4// $arr2 is changed,
             // $arr1 is still array(2, 3)
             
$arr3 = &$arr1;
$arr3[] = 4// now $arr1 and $arr3 are the same
?>


Objects

Object Initialization

To create a new object, use the new statement to instantiate a class:

<?php
class foo
{
    function 
do_foo()
    {
        echo 
"Doing foo."
    }
}

$bar = new foo;
$bar->do_foo();
?>

For a full discussion, see the Classes and Objects chapter.

Converting to object

If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. If the value was NULL, the new instance will be empty. Arrays convert to an object with properties named by keys, and corresponding values. For any other value, a member variable named scalar will contain the value.

<?php
$obj 
= (object) 'ciao';
echo 
$obj->scalar;  // outputs 'ciao'
?>


Resources

A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. See the appendix for a listing of all these functions and the corresponding resource types.

Informacja: The resource type was introduced in PHP 4

See also the get_resource_type() function.

Converting to resource

As resource variables hold special handlers to opened files, database connections, image canvas areas and the like, converting to a resource makes no sense.

Freeing resources

Thanks to the reference-counting system introduced with PHP 4's Zend Engine, a resource with no more references to it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the memory manually.

Informacja: Persistent database links are an exception to this rule. They are not destroyed by the garbage collector. See the persistent connections section for more information.



NULL

The special NULL value represents a variable with no value. NULL is the only possible value of type NULL.

Informacja: The null type was introduced in PHP 4.

A variable is considered to be null if:

  • it has been assigned the constant NULL.

  • it has not been set to any value yet.

  • it has been unset().

Syntax

There is only one value of type null, and that is the case-insensitive keyword NULL.

<?php
$var 
NULL;       
?>

See also the functions is_null() and unset().

Casting to NULL

Casting a variable to null will remove the variable and unset its value.



Pseudo-types and variables used in this documentation

mixed

mixed indicates that a parameter may accept multiple (but not necessarily all) types.

gettype() for example will accept all PHP types, while str_replace() will accept strings and arrays.

number

number indicates that a parameter can be either integer or float.

callback

Some functions like call_user_func() or usort() accept user-defined callback functions as a parameter. Callback functions can not only be simple functions, but also object methods, including static class methods.

A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs such as: array(), echo(), empty(), eval(), exit(), isset(), list(), print() or unset().

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.

Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object at index 0.

Apart from common user-defined function, create_function() can also be used to create an anonymous callback function. As of PHP 5.3.0 it is possible to also pass a closure to a callback parameter.

Przykład #1 Callback function examples

<?php 

// An example callback function
function my_callback_function() {
    echo 
'hello world!';
}

// An example callback method
class MyClass {
    static function 
myCallbackMethod() {
        echo 
'Hello World!';
    }
}

// Type 1: Simple callback
call_user_func('my_callback_function'); 

// Type 2: Static class method call
call_user_func(array('MyClass''myCallbackMethod')); 

// Type 3: Object method call
$obj = new MyClass();
call_user_func(array($obj'myCallbackMethod'));

// Type 4: Static class method call (As of PHP 5.2.3)
call_user_func('MyClass::myCallbackMethod');

// Type 5: Relative static class method call (As of PHP 5.3.0)
class {
    public static function 
who() {
        echo 
"A\n";
    }
}

class 
extends {
    public static function 
who() {
        echo 
"B\n";
    }
}

call_user_func(array('B''parent::who')); // A
?>

Przykład #2 Callback example using a Closure

<?php
// Our closure
$double = function($a) {
    return 
$a 2;
};

// This is our range of numbers
$numbers range(15);

// Use the closure as a callback here to 
// double the size of each element in our 
// range
$new_numbers array_map($double$numbers);

print 
implode(' '$new_numbers);
?>

Powyższy przykład wyświetli:

2 4 6 8 10

Informacja: In PHP4, it was necessary to use a reference to create a callback that points to the actual object, and not a copy of it. For more details, see References Explained.

void

void as a return type means that the return value is useless. void in a parameter list means that the function doesn't accept any parameters.

...

$... in function prototypes means and so on. This variable name is used when a function can take an endless number of arguments.



Type Juggling

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.

An example of PHP's automatic type conversion is the addition operator '+'. If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does not change the types of the operands themselves; the only change is in how the operands are evaluated and what the type of the expression itself is.

<?php
$foo 
"0";  // $foo is string (ASCII 48)
$foo += 2;   // $foo is now an integer (2)
$foo $foo 1.3;  // $foo is now a float (3.3)
$foo "10 Little Piggies"// $foo is integer (15)
$foo "10 Small Pigs";     // $foo is integer (15)
?>

If the last two examples above seem odd, see String conversion to numbers.

To force a variable to be evaluated as a certain type, see the section on Type casting. To change the type of a variable, see the settype() function.

To test any of the examples in this section, use the var_dump() function.

Informacja: The behaviour of an automatic conversion to array is currently undefined.
Also, because PHP supports indexing into strings via offsets using the same syntax as array indexing, the following example holds true for all PHP versions:

<?php
$a    
'car'// $a is a string
$a[0] = 'b';   // $a is still a string
echo $a;       // bar
?>

See the section titled String access by character for more information.

Type Casting

Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.

<?php
$foo 
10;   // $foo is an integer
$bar = (boolean) $foo;   // $bar is a boolean
?>

The casts allowed are:

  • (int), (integer) - cast to integer
  • (bool), (boolean) - cast to boolean
  • (float), (double), (real) - cast to float
  • (string) - cast to string
  • (binary) - cast to binary string (PHP 6)
  • (array) - cast to array
  • (object) - cast to object
  • (unset) - cast to NULL (PHP 5)

(binary) casting and b prefix forward support was added in PHP 5.2.1

Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent:

<?php
$foo 
= (int) $bar;
$foo = ( int ) $bar;
?>

Casting literal strings and variables to binary strings:

<?php
$binary 
= (binary) $string;
$binary b"binary string";
?>

Informacja: Instead of casting a variable to a string, it is also possible to enclose the variable in double quotes.

<?php
$foo 
10;            // $foo is an integer
$str "$foo";        // $str is a string
$fst = (string) $foo// $fst is also a string

// This prints out that "they are the same"
if ($fst === $str) {
    echo 
"they are the same";
}
?>

It may not be obvious exactly what will happen when casting between certain types. For more information, see these sections:




Zmienne

Spis treści


Podstawy

Każdą zmienną w PHP zapisuje się, poprzedzając jej nazwę znakiem dolara "$". Wielkość liter w nazwie zmiennej jest rozróżniana.

Nazw zmiennych dotyczą te same reguły, co innych rodzajów nazw w PHP. Poprawna nazwa zmiennej zaczyna się od litery lub znaku podkreślenia "_", po których może wystąpić dowolna ilość liter, cyfr lub znaków podkreślenia. Jako wyrażenie regularne, można to zapisać tak: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

Informacja: W naszym rozumieniu, litery to znaki a-z, A-Z i bajty od 127 do 255 (0x7f-0xff).

Informacja: $this to specialna zmienna, której nie można definiować.

Wskazówka

Zobacz także Userland Naming Guide.

Aby uzyskać więcej informacji na temat funkcji powiązanych ze zmiennymi, zobacz Funkcje Obsługi Zmiennych.

<?php
$zmienna 
'Pan';
$Zmienna 'Jan';
echo 
"$zmienna$Zmienna";  // wyświetla "Pan, Jan"

$7dni 'tydzień';          // niepoprawna nazwa - zaczyna się od cyfry
$_7dni 'tydzień';         // poprawna nazwa - zaczyna się znakiem podkreślenia
$jaźń 'osobowość';        // poprawna nazwa - "ń" i "ź" należą do ASCII 127-255
?>

Domyślnie, zmienne zawsze są zawsze przypisywane przez wartość. Innymi słowy, jeśli przypiszesz do zmiennej jakieś wyrażenie, wartość tego wyrażenia zostanie skopiowana do zmiennej. Oznacza to, że po przypisaniu wartości jednej zmiennej do drugiej, późniejsza zmiana wartości jednej z nich nie spowoduje zmiany wartości drugiej. Więcej informacji na ten temat w rozdziale Wyrażenia.

PHP oferuje jeszcze jeden sposób przypisywania wartości do zmiennych: przypisanie przez referencję. Oznacza to, że nowa zmienna tylko odnosi się (innymi słowy, "staje się aliasem" lub "wskazuje na") do pierwotnej zmiennej. Zmiany wykonane na nowej zmiennej oddziałują także na pierwotną zmienną i vice versa.

Aby przypisać przez referencję, postaw znak ampersand (&) przed nazwą zmiennej przypisywanej (zmiennej od której pobierasz wartość). Na przykład poniższy kod wyświetla "To jest PHP" dwa razy:

<?php
$foo 
"PHP";               // Przypisz wartość "PHP" do $foo.
$bar = &$foo;               // Przypisz referencyjnie $foo do $bar.
$bar "To jest $bar";      // Zmień $bar...
echo $bar;
echo 
$foo;                  // $foo też się zmieniło.
?>

Należy pamiętać, że tylko wyrażenia posiadające nazwę mogą być przypisane przez referencję.

<?php
$foo 
25;
$bar = &$foo;      // Przypisanie poprawne.
$bar = &(24 7);  // Przypisanie niepoprawne - do nienazwanego wyrażenia.

function test()
{
   return 
25;
}

$bar = &test();    // Niepoprawne.
?>

W PHP nie jest konieczne inicjowanie zmiennych, jednak jest to bardzo dobry nawyk. Niezainicjowane zmienne mają domyślne wartości dla ich typu, zależnie od kontekstu, w jaki zmienne te zostały użyte - zmienne logiczne typu boolean domyślnie przyjmują wartość FALSE, zmiennym całkowitym typu integer domyślnie nadawane jest zero, łańcuchom tekstowym (np. użytym wewnątrz echo()) nadany jest łańcuch pusty, natomiast tablice zostają pustymi tablicami.

Przykład #1 Domyślne wartości niezainicjowanych zmiennych

<?php
// Zmienna bez nadanej wartości ORAZ bez odwołań do niej (brak kontekstu, w jakim została użyta); zwróci NULL
var_dump($zmienna_bez_kontekstu_uzycia);

// Używanie zmiennej logicznej typu boolean; zwróci 'false' (Zobacz informacje o operatorach trójparametrowych, by poznać tę składnię)
echo($nieinicjowana_zmiena_bool "true\n" "false\n");

// Używanie łańcuchów; zwróci 'string(3) "abc"'
$nieinicjowany_lancuch .= 'abc';
var_dump($nieinicjowany_lancuch);

// Używanie zmiennych całkowitych; zwróci 'int(25)'
$nieinicjowana_zmienna_int += 25// 0 + 25 => 25
var_dump($nieinicjowana_zmienna_int);

// Używanie zmiennych typu float/double; zwróci 'float(1.25)'
$nieinicjowana_zmienna_float += 1.25;
var_dump($nieinicjowana_zmienna_float);

// Używanie tablicy; zwróci array(1) {  [3]=> string(3) "def" }
$nieinicjowana_tablica[3] = "def"// array() + array(3 => "def") => array(3 => "def")
var_dump($nieinicjowana_tablica);

// Używanie obiektu; stworzy nowy obiekt stdClass (zobacz http://www.php.net/manual/pl/reserved.classes.php)
// Zwróci: object(stdClass)#1 (1) {  ["foo"]=>  string(3) "bar" }
$nieinicjowany_obiekt->foo 'bar';
var_dump($nieinicjowany_obiekt);
?>

Poleganie na domyślnej wartości niezainicjowanej zmiennej jest problematyczne, w razie zawarcia jednego pliku wewnątrz innego, posiadającego tak samo nazwane zmienne. Jest to również poważne zagrożenie dla bezpieczeństwa przy włączonej opcji register_globals. Ostrzeżenie klasy E_NOTICE pojawi się podczas pracy z niezainicjowanymi zmiennymi, jednak w przypadku przypisywania elentów do niezainicjowanych tablic - już nie. Funkcja isset() może zostać użyta w celu wykrycia, czy zmienna została już zainicjowana.



Zmienne Predefiniowane

PHP udostępnia dla każdego pracującego skryptu dużą ilość predefiniowanych zmiennych. Jednakże wiele spośród tych zmiennych nie może być w pełni objaśnionych, gdyż są zależne od rodzaju serwera, jego wersji, ustawień i innych czynników. Niektóre z tych zmiennych nie będą dostępne dla skryptów PHP uruchomionych z Linii Poleceń. Lista tych zmiennych znajduje się w rozdziale Predefiniowane Zmienne.

Ostrzeżenie

W PHP 4.2.0 i późniejszych, domyślne ustawienie dla instrukcji PHP register_globals jest wyłączone. Jest to bardzo istotna zmiana w PHP. Mając opcję register_globals wyłączoną wpływamy na ustawienie zmiennych predefiniowanych, dostępnych globalnie. Na przykład, aby poznać wartość DOCUMENT_ROOT użyjesz $_SERVER['DOCUMENT_ROOT'] zamiast $DOCUMENT_ROOT, lub $_GET['id'] z adresu URL http://www.example.com/test.php?id=3 zamiast $id, albo $_ENV['HOME'] a nie $HOME.

Aby uzyskać informacje powiązane z tą zmianą, przeczytaj część o konfiguracji register_globals, rozdziału o bezpieczeństwie Używanie Register Globals , oraz w informacjach o wydaniu (ang. Release Announcements) PHP » 4.1.0 jak i » 4.2.0

Używanie dostępnych zmiennych predefiniowanych, jak tablice superglobalne, jest zalecane.

Począwszy od wersji 4.1.0, PHP udostępnia dodatkowo zestaw predefiniowanych tablic, które zawierają zmienne serwera, zmienne środowiskowe oraz zmienne użytkownika. Tablice te są dość specyficzne, gdyż są one automatycznie globalne, tzn. automatycznie dostępne w każdym miejscu. Dlatego nazywa się je "superglobalami". (W PHP nie ma mechanizmu pozwalającego użytkownikowi na definiowanie własnych superglobali.) Superglobale PHP wymienione są poniżej; jednakże wykaz ich zawartości i głębsze omówienie prefiniowanych zmiennych PHP oraz ich natury znajduje się w rozdziale predefiniowane zmienne. Zauważ także, że starsze zmienne predefiniowane ($HTTP_*_VARS) wciąż funkcjonują. Od PHP 5.0.0, długie tablice zmiennych predefiniowanych mogą być wyłączone dyrektywą konfiguracji register_long_arrays.

Informacja: Zmienne zmienne
Zmienne superglobale nie mogą być użyte jako zmienne zmienne wewnątrz funkcji, ani jako metody klasy.

Informacja: Nawet pomimo tego, że zmienne superglobalne i HTTP_*_VARS mogą istnieć w tym samym czasie; nie są one tożsame, czyli zmiana jednej nie zmieni drugiej.

Jeśli pewne zmienne w variables_order nie są ustawione, to ich odpowiedniki zmiennych predefiniowanych PHP również są puste.



Zasięg zmiennych

Zasięg zmiennej zależy od miejsca, w jakim ją zdefiniowano. Najczęściej zmienne PHP widoczne są tylko w jednym zasięgu. Taki zasięg obejmuje również pliki dołączone funkcjami include i require. Na przykład:

<?php
$a 
1;
include 
'b.inc';
?>

Tutaj zmienna $a będzie dostępna także wewnątrz dołączonego funkcją include pliku b.inc w skrypcie. Jednakże wewnątrz funkcji zdefiniowanych samodzielnie zmienne mają zasięg lokalny. Każda zmienna użyta wewnątrz funkcji jest domyślnie ograniczona do zasięgu lokalnego funkcji. Na przykład:

<?php
$a 
1/* zasięg globalny */ 

function test()

    echo 
$a/* odwołanie do zmiennej o zasięgu lokalnym */ 


test();
?>

Ten skrypt nie wyświetli niczego, ponieważ instrukcja echo odwołuje się do zmiennej lokalnej $a, której jak dotąd nie została przypisana żadna wartość. Można tu zauważyć różnicę w stosunku do języka C, gdzie zmienne globalne są zawsze dostępne wewnątrz definicji funkcji, o ile nie zostały nadpisane przez lokalną definicję zmiennej. Może to spowodować problem, że ktoś może nieodwracalnie zmienić wartość zmiennej globalnej. W PHP zmienne globalne muszą być jawnie określone jako globalne wewnątrz funkcji, w której mają być użyte, do czego używamy słowa kluczowego global.

polecenie global

Najpierw, przykład użycia global:

Przykład #1 Używanie polecenia global

<?php
$a 
1;
$b 2;

function 
Suma()
{
    global 
$a$b;

    
$b $a $b;
}

Suma();
echo 
$b;
?>

Powyższy skrypt wyświetli wynik "3". Przez zadeklarowanie wewnątrz funkcji globalności zmiennych $a i $b, wszystkie odwołania do tych zmiennych będą odnosiły się do ich globalnych wersji. Nie ma żadnych ograniczeń w ilości zmiennych globalnych, na których chcemy operować wewnątrz funkcji.

Drugim sposobem uzyskania dostępu do zmiennych globalnych wewnątrz funkcji jest użycie specjalnej, zdefiniowanej przez PHP tablicy $GLOBALS. Powyższy przykład można zatem przepisać tak:

Przykład #2 Używanie $GLOBALS zamiast polecenia global

<?php
$a 
1;
$b 2;

function 
Suma()
{
    
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}

Suma();
echo 
$b;
?>

Tablica $GLOBALS jest asocjacyjną tablicą, w której nazwa zmiennej jest kluczem, a zawartość zmiennej wartością komórki tablicy. Zauważ, że $GLOBALS jest dostępna z każdego miejsca, ponieważ $GLOBALS jest tablicą superglobalną. Poniżej przykład demonstrujący moc superglobali:

Przykład #3 Przykład demonstrujący superglobale i zasięg zmiennych

<?php
function test_global()
{
    
// Większość predefiniowanych zmiennych nie jest "super i wymaga
    // 'global', by być dostępnymi w zasięgu lokalnym funkcji.
    
global $HTTP_POST_VARS;
    
    echo 
$HTTP_POST_VARS['name'];
    
    
// Superglobale są dostępne z każdego miejsca 
    // i nie wymagają 'global'. Superglobale udostępniono
    // wraz z PHP 4.1.0, a HTTP_POST_VARS jest 
    // uważane za przestarzałe.
    
echo $_POST['name'];
}
?>

Używanie zmiennych statycznych

Jeszcze jedną ważną rzeczą, związaną z zasięgiem zmiennych jest zmienna statyczna (ang. static variable). Zmienna statyczna może mieć wyłącznie zasięg lokalny, ale nie traci swojej wartości, kiedy program opuści ten zasięg lokalny, w którym dana zmienna statyczna się znajduje. Rozważmy poniższy przykład:

Przykład #4 Przykład ukazujący przydatność zmiennych statycznych

<?php
function test()
{
    
$a 0;
    echo 
$a;
    
$a++;
}
?>

Ta funkcja jest bezużyteczna, gdyż przy każdym jej wywołaniu zmienna $a otrzymuje wartość 0, w związku z czym funkcja stale wyświetla "0". Występująca potem inkrementacja $a++ nie ma żadnego znaczenia, gdyż funkcja się kończy i zmienna $a znika. Aby powyższa funkcja miała jakiś sens, należy zapobiec gubieniu wartości $a, do czego używamy słowa kluczowego static:

Przykład #5 Przykład użycia zmiennych statycznych

<?php
function Test()
{
    static 
$a 0;
    echo 
$a;
    
$a++;
}
?>

Teraz, $a jest inicjowana tylko pry pierwszym wywołaniu funkcji a, przy każdym wywołaniu funkcji test(), zostanie wyświetlona wartość zmiennej $a, po czym ta zmienna zostanie inkrementowana.

Zmienne statyczne pozwalają też na wykorzystanie funkcji rekurencyjnych, czyli takich, które wywołują same siebie. Funkcje rekurencyjne należy pisać ostrożnie, gdyż łatwo jest wywołać nieskończoną rekurencję. Musisz być pewny, że masz odpowiednie mechanizmy do zatrzymania rekurencji w jakimś momencie. Poniższa, prosta funkcja rekurencyjnie liczy do 10, używając zmiennej statycznej $licznik, aby wiedzieć, kiedy się zatrzymać:

Przykład #6 Zmienne statyczne w funkcjach rekurencyjnych

<?php
function test()
{
    static 
$licznik 0;

    
$licznik++;
    echo 
$licznik;
    if (
$licznik 10) {
        
test();
    }
    
$licznik--;
}
?>

Informacja: Zmienne statyczne mogą być deklarowane, tak jak w powyższym przykładzie. Próba przypisania wartości do tego typu zmiennych, poprzez wynik jakiegoś wyrażenia, spowoduje błąd składni (ang. Parse error).

Przykład #7 Deklaracja zmiennych statycznych

<?php
function foo(){
    static 
$int 0;          // prawidłowo
    
static $int 1+2;        // błąd  (w rzeczywistości to jest wyrażenie)
    
static $int sqrt(121);  // błąd  (to również jest wyrażenie)

    
$int++;
    echo 
$int;
}
?>


Referencje do zmiennych statycznych i globalnych

Silnik Zend 1 (ang. Zend Engine 1) napędzający PHP4, implementuje modyfikatory statyczny oraz globalny dla zmiennych, pod względem referencji. Na przykład, w rzeczywistości globalna zmienna wprowadzona wewnątrz zasięgu funkcji z wyrażeniem global na dziś dzień tworzy referencję do zmiennej globalnej. Takie zachowanie może prowadzić do nieoczekiwanych sytuacji, czego dowodzi poniższy przykład:

<?php
function test_global_ref() {
    global 
$obj;
    
$obj = &new stdclass;
}

function 
test_global_noref() {
    global 
$obj;
    
$obj = new stdclass;
}

test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>

Wykonanie tego przykładu da następujące wyniki:


NULL
object(stdClass)(0) {
}

Podobna sytuacja dotyczy deklaracji static. Referencje nie są magazynowane statycznie:

<?php
function &get_instance_ref() {
    static 
$obj;

    echo 
'Obiekt statyczny: ';
    
var_dump($obj);
    if (!isset(
$obj)) {
        
// Przypisanie referencji do zmiennej statycznej.
    
$obj = &new stdclass;
    }
    
$obj->property++;
    return 
$obj;
}

function &
get_instance_noref() {
    static 
$obj;

    echo 
'Obiekt statyczny: ';
    
var_dump($obj);
    if (!isset(
$obj)) {
        
// Przypisanie do obiektu zmiennej statycznej
        
$obj = new stdclass;
    }
    
$obj->property++;
    return 
$obj;
}

$obj1 get_instance_ref();
$still_obj1 get_instance_ref();
echo 
"\n";
$obj2 get_instance_noref();
$still_obj2 get_instance_noref();
?>

Wykonanie tego przykładu da następujące wyniki:


Obiekt statyczny: NULL
Obiekt statyczny: NULL

Obiekt statyczny: NULL
Obiekt statyczny: object(stdClass)(1) {
["property"]=>
int(1)
}

Ten przykład pokazuje, że podczas przypisywania referencji do zmiennej statycznej, nie następuje zapamiętanie, gdy wywołasz funkcję &get_instance_ref() po raz drugi.



Zmienne zmienne

W niektórych przypadkach jest wygodne, by móc użyć zmiennej o zmiennej nazwie. To znaczy zmiennej, której nazwa może być zmieniana dynamicznie. Zwykła zmienna jest ustawiana wyrażeniem jak poniżej:

<?php
$a 
"witaj";
?>

Zmienna zmienna pobiera wartość jednej zmiennej i traktuje ją jako nazwę innej. W powyższym przykładzie, witaj, może stać się nazwą zmiennej, dzięki użyciu dwóch znaków dolara, tzn.

<?php
$$a "świecie";
?>

W tym momencie dwie zmienne zostały zdefiniowane i umieszczone w drzewie symbolicznym PHP: $a zawierająca "witaj" i $witaj zawierająca "świecie". Zatem poniższy zapis:

<?php
echo "$a ${$a}";
?>

znaczy to samo, co:

<?php
echo "$a $witaj";
?>

tzn. obydwa wyświetlą: witaj świecie.

Aby używać zmiennych zmiennych jako tablic, trzeba wyjaśnić pewną niejasność. Mianowicie, jeśli napiszesz $$a[1], parser musi wiedzieć, czy chesz użyć $a[1] jako nazwy zmiennej, czy $$a jako nazwy tablicy, której rekord [1] cię interesuje. W tym przypadku należy zastosować odrębną składnię: ${$a[1]} dla pierwszego przypadku a ${$a}[1] dla drugiego.

Ostrzeżenie

Zauważ, że zmienne zmienne nie mogą być używane z Tablicami superglobalnymi PHP, wewnątrz funkcji, czy metod klas. Zmienna $this jest także specjalną zmienną, dla której referencje dynamiczne nie są dozwolone.



Zmienne ze źródeł zewnętrznych

Formularze HTML (GET i POST)

Kiedy do skryptu PHP zostanie wysłany formularz, informacja z niego jest automatycznie dostępna w skrypcie. Istnieje wiele sposobów na uzyskanie tych informacji, dla przykładu:

Przykład #1 Prosty formularz HTML

<form action="foo.php" method="post">
    Imie:  <input type="text" name="imie" /><br />
    Email: <input type="text" name="email" /><br />
    <input type="submit" name="submit" value="Wyslij!" />
</form>

W zależności od twoich szczególnych ustawień i osobistych upodobań, istnieje wiele sposobów dostępu do danych z twoich formularzy HTML. Oto kilka przykładów:

Przykład #2 Dostęp do informacji z prostego formularza HTML (wysłanego metodą POST)

<?php
// Możliwe od PHP 4.1.0
      
   echo $_POST['imie'];
   echo $_REQUEST['imie'];

   import_request_variables('p', 'p_');
   echo $p_imie;

// Niedostępne od PHP 6. Od PHP 5.0.0, te długie predefiniowane
// zmienne mogą być niedostępne z włączoną opcją register_long_arrays.

   echo $HTTP_POST_VARS['imie'];

// Dostępne, jeśli opcja register_globals jest włączona - "on". Począwszy od
// PHP 4.2.0 domyślna wartość opcji register_globals to off.
// Nie jest zalecane poleganie na tej metodzie.

   echo $imie;
?>

Przesyłanie danych z formularza metodą GET jest podobne, z takim wyjątkiem, że użyjesz zmienną predefiniowaną odpowiednią dla tej metody, zamiast poprzedniej. GET także odnosi się do tzw. QUERY_STRING (informacje w adresie URL, po znaku '?'). Tak więc, dla przykładu, http://www.example.com/test.php?id=3 zawiera dane dla metody GET, dostępne poprzez $_GET['id']. Zobacz także $_REQUEST oraz import_request_variables().

Informacja: Tablice superglobalne, takie jak $_POST i $_GET, zostały udostępnione w PHP 4.1.0

Jak widać, przed PHP 4.2.0 domyślną wartością opcji register_globals było on. Społeczność PHP jest całkowiie przekonana, by nie polegać na tej opcji; i rzeczywiście najlepiej jest nadać jej wartość off, oraz przystosować do tego kod.

Informacja: Dyrektywa konfiguracyjna magic_quotes_gpc oddziałuje na zmienne z Get, Post i Cookie. Jeśli jest włączona, tekst (It's "PHP!") automagicznie zmieni się w (It\'s \"PHP!\"). Jest to potrzebne przy wpisywaniu danych do baz danych. Zobacz także addslashes(), stripslashes() i magic_quotes_sybase.

PHP obsługuje także tablice w kontekście zmiennych z formularzy (zajrzyj do FAQ). Można na przykład pogrupować razem powiązane zmienne lub użyć tej możliwości do pobrania wartości z pola wyboru (select). Na przykład, wyślijmy formularz z pliku metodą POST do samego siebie i wyświetlmy te dane:

Przykład #3 Bardziej złożone zmienne w formularzach

<?php
if ($_POST) {
    echo 
'<pre>';
    echo 
htmlspecialchars(print_r($_POSTtrue));
    echo 
'</pre>';
}
?>
<form action="" method="post">
    Nazwisko: <input type="text" name="personal[nazwisko]"><br />
    Email: <input type="text" name="personal[email]"><br />
    Piwo: <br />
    <select multiple name="piwo[]">
        <option value="zywiec">Żywiec</option>
        <option value="tyskie">Tyskie</option>
        <option value="lech">Lech</option>
    </select><br />
    <input type="submit" value="Wyślij mnie!" />
</form>

Nazwy zmiennych dla SUBMIT w postaci obrazka

Przy tworzeniu formularza, można użyć obrazka, zamiast standardowego przycisku Wyślij, za pomocą takiego znacznika:

<input type="image" src="obrazek.gif" name="sub" />

Kiedy użytkownik kliknie gdzieś na obrazku, formularz, którego to dotyczy, zostanie wysłany do serwera z dwiema dodatkowymi zmiennymi, sub_x i sub_y. Zawierają one współrzędne miejsca kliknięcia na obrazek. Można przy tym zauważyć, że na razie w nazwach zmiennych znajduje się kropka zamiast podkreślnika, ale PHP konwertuje kropkę na podkreślnik automatycznie.

Ciasteczka HTTP

PHP bez problemu obsługuje ciasteczka HTTP, takie jak zdefiniowano w » Specyfikacji Netscape'a. Ciasteczka są mechanizmem przechowywania informacji w przeglądarce klienta w celu śledzenia lub identyfikowania stałych bywalców strony. Ciasteczka ustawia się za pomocą funkcji setcookie(). Ciasteczka są częścią nagłówka HTTP, więc funkcja SetCookie musi być wywołana zanim jakakolwiek inna informacja zostanie wysłana do przeglądarki. Takie samo ograniczenie dotyczy funkcji header(). Dane z ciasteczek są wówczas dostępne w odpowiednich tablicach danych cookies, takich jak $_COOKIE, $HTTP_COOKIE_VARS jak również $_REQUEST. Zobacz także stronę dotyczącą funkcji setcookie() aby poznać więcej informacji i przykładów.

Jeśli chcesz przypisać wiele wartości do jednego ciasteczka, możesz po prostu złączyć je w tablicę. Na przykład:

<?php
  setcookie
("MojeCiasteczko[foo]"'Test 1'time()+3600);
  
setcookie("MojeCiasteczko[bar]"'Test 2'time()+3600);
?>

Spowoduje to stworzenie dwóch oddzielnych ciasteczek, mimo, iż MojeCiasteczko będzie teraz pojedynczą tablicą w twoim skrypcie. Jeśli chcesz ustawić tylko jedno ciasteczko z wieloma wartościami, rozważ możliwość użycia przedtem funkcji serialize() lub explode() na wartości.

Pamiętaj, że wysłane ciasteczko zastąpi wcześniejsze ciasteczko o tej nazwie, o ile ścieżka lub domena nie są różne. Na przykład dla koszyka do zakupów możesz potrzebować licznika a jego wartość stale przekazywać dalej, tzn.

Przykład #4 Przykład użycia funkcji setcookie()

<?php
if (isset($_COOKIE['ile'])) {
    
$ile $_COOKIE['ile'] + 1;
} else {
    
$ile 1;
}
setcookie('ile'$iletime()+3600);
setcookie("Cart[$ile]"$pozycjatime()+3600);
?>

Kropki w nazwach odbieranych zmiennych

PHP normalnie nie zmienia nazw zmiennych podczas przekazywania ich do skryptu. Jednakże należy pamiętać, że kropka "." nie jest poprawnym znakiem w nazwie zmiennej PHP. Dlaczego? Proszę spojrzeć na to:

<?php
$varname
.ext;  /* niepoprawna nazwa zmiennej */
?>

To co widzi parser, to zmienna o nazwie $varname, po której pojawia się operator konkatenacji, a następnie pusty łańcuch (czyli taki, który nie jest żadnym słowem kluczowym, ani zarezerwowanym) "ext". Oczywiście, nie daje to żadnego sensownego wyniku.

Warto zatem wiedzieć, że PHP automatycznie zastąpi podkreślnikiem "_" każdą kropkę w nazwie każdej odebranej zmiennej.

Określanie typów zmiennych

Ponieważ PHP samodzielnie określa typy zmiennych i konwertuje je (zasadniczo) jak potrzeba, nie zawsze jest jasne, jakiego typu jest dana zmienna w danym momencie. PHP zawiera kilka funkcji do określania typów zmiennych, takich jak: gettype(), is_array(), is_float(), is_int(), is_object() i is_string(). Zobacz także rozdział o Typach.




Stałe

Spis treści

Stałe są to nazwy, identyfikujące proste wartości. Jak sama nazwa wskazuje, nie mogą się one zmieniać w trakcie wykonywania skryptu (wyjątkiem są magiczne stałe, które własciwie nie sa stałymi). W nazwach stałych domyślnie rozróżniana jest wielkość liter. Zgodnie z ogólnie przyjętą konwencją, nazwy stałych zawsze pisane sa wielkimi literami.

Nazwy stałych obowiązują identyczne zasady, jak w przypadku wszystkich innych etykiet. Poprawna nazwa stałej zaczyna się od litery lub podkreślnika, po których następuje dowolna ilość liter, cyfr i podkreślników. Jako wyrażenie regularne, określone zostałoby to następująco: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Wskazówka

Zobacz także Userland Naming Guide.

Przykład #1 Poprawne i niepoprawne nazwy stałych

<?php

// Poprawne nazwy stałych
define("FOO",     "something");
define("FOO2",    "something else");
define("FOO_BAR""something more");

// Niepoprawne nazwy stałych
define("2FOO",    "something");

// Pomimo tego, że poniższy zapis jest poprawny, powinno się go unikać:
// PHP może kiedyś zawierać magiczną stałą,
// która zepsuje Twój skrypt
define("__FOO__""something"); 

?>

Informacja: Dla naszych celów, literami są a-z, A-Z, oraz znaki ASCII z przedziału od 127 do 255 (0x7f-0xff).

Podobnie jak superglobals, zasięg stałych jest globalny. Można sie odwoływać do nich w każdym miejscu pliku, nie przejmując sie zasięgiem. Więcej informacji na ten temat znajdziesz w rozdziale pt. zasięg zmiennych.


Składnia

Możesz zdefiniować stałą, używając funkcji define(). Raz zdefiniowana stała nie może byc zmieniona ani usunięta.

Stałe mogą zawierać jedynie dane skalarne (boolean, integer, float oraz string) Stałe nie mogą być typu resource.

Wartość stałej otrzymujemy, używając jej nazwy. W przeciwieństwie do zmiennych, nazw stałych nie poprzedzamy znakiem $. Możesz także użyć funkcji constant() do odczytania wartości stałej, jeśli chcesz wygenerować jej nazwę dynamicznie. Aby uzyskać listę wszystkich zdefiniowanych stałych, użyj get_defined_constants().

Informacja: Stałe i zmienne globalne operują w różnych przestrzeniach nazw. Oznacza to, że na przykład TRUE i $TRUE oznaczają co innego.

Jeśli używasz niezdefiniowanej stałej, PHP traktuje to, jak gdybyś chciał użyć nazwy stałej jako wartości typu string (STAŁA a "STAŁA"). Błąd typu E_NOTICE zostanie wywołany, kiedy to się stanie. Przeczytaj także, dlaczego $foo[bar] jest niepoprawne (jeśli nie zdefiniujesz bar jako stałej). Chcąc sprawdzić, czy dana stała istnieje, użyj funkcji defined().

Oto różnice pomiędzy stałymi i zmiennymi:

  • Nazwy stałych nie są poprzedzone znakiem dolara ($);
  • Stałe mogą zostać zdefiniowane jedynie przy użyciu funkcji define() a nie poprzez zwykłe przypisanie;
  • Stałe mogą być definiowane i używane wszędzie, niezależnie od zasięgu zmiennych;
  • Stałe nie mogą być zmieniane ani usuwane jeśli raz zostały ustawione ; oraz
  • Stałe mogą zawierać jedynie wartości skalarne.

Przykład #1 Definiowanie stałych

<?php
define
("CONSTANT""Hello world.");
echo 
CONSTANT// wypisuje "Hello world."
echo Constant// wypisuje "Constant" i wywoułuje ostrzeżenie.
?>

Zobacz także Stałe Klas.



Magiczne stałe

PHP zapewnia szeroki zakres predefiniowanych stałych każdemu skryptowi, który jest uruchamiany. Wiele z tych stałych jest jednak dostępnych dzieki różnym rozszerzeniom i można z nich korzystać jedynie, kiedy te rozszerzenia sa dostępne przez dynamiczne załadowanie, badź też zostały wkompilowane.

Istnieje siedem magicznych stałych, które zmieniają sie w zależności od tego, gdzie są użyte. Na przykład, wartość __LINE__ zależy od linii, w której ta stała została użyta. Nazwy tych magicznych stałych są niezależne od wielkości liter:

Kilka "magicznych" stałych PHP
Nazwa Opis
__LINE__ Aktualna linia pliku.
__FILE__ Pełna scieżka i nazwa pliku. Jeśli użyta wewnątrz dołączonego pliku, jego nazwa jest zwracana. Od PHP 4.0.2, __FILE__zawsze zawiera bezwzględną scieżkę z rozwiązanymi dowiązaniami symbolicznymi, podczas kiedy w starszych wersjach czasem zawierała scieżkę względną.
__DIR__ Nazwa katalogu pliku. Jeśli użyta wewnątrz dołączonego pliku, zwraca nazwę jego katalogu. Odpowiada dirname(__FILE__). Zwracana nazwa nie zawiera końcowego ukośnika, chyba że jest to katalog root. (Dodano w PHP 5.3.0.)
__FUNCTION__ Nazwa funkcji. (Dodano w PHP 4.3.0) W PHP 5 ta stała zwraca nazwę funkcji tak jak ją zadeklarowano (z uwzględnieniem wielkości liter), podczas kiedy w PHP 4 zwracana wartość zawiera jedynie małe litery.
__CLASS__ Nazwa klasy. (Dodano w PHP 4.3.0) W PHP 5 ta stała zwraca nazwę klasy tak jak ją zadeklarowano (z uwzględnieniem wielkości liter), podczas kiedy w PHP 4 zwracana wartość zawiera jedynie małe litery.
__METHOD__ Nazwa metody. (Dodano w PHP 5.0.0) Nazwa metody zwracana jest tak jak ją zadeklarowano (z uwzględnieniem wielkości liter).
__NAMESPACE__ Nazwa aktualnej przestrzeni nazw (z uwzględnieniem wielkości liter). Ta stała definiowana jest w czasie kompilacji (Dodano w PHP 5.3.0).

Zobacz także get_class(), get_object_vars(), file_exists() i function_exists().




Wyrażenia

Wyrażenia są naważniejszymi elementami składowymi PHP. W PHP prawie wszystko co napiszesz jest wyrażeniem. Najprostszą i najdokładniejszą definicją wyrażenia jest "wszystko co ma wartość".

Najbardziej podstawową formą wyrażeń są stałe i zmienna. Jeśli napiszesz "$a = 5" przypisujesz '5' do '$a'. '5' ma oczywiście wartość 5, lub innymi słowy '5' jest wyrażeniem o wartości 5 (w tym przypadku, '5' jest stałą liczbą całkowitą).

Po tym przypisaniu możesz się spodziwać, że wartością $a jest także 5, więc jeśli napiszesz "$b = $a" możesz się spodziewać, że będzie to równoznaczne z napisaniem "$b = 5". Innymi słowy, $a jest wyrażeniem o wartości 5. Jeśli wszystko działa prawidłowo, wszystko będzie się dziać tak jak napisano wyżej.

Trochę bardziej złożonymi przykładami wyrażeń są funkcje. Przyjrzyj się poniższej funkcji:

<?php
function foo ()
{
    return 
5;
}
?>

Zakładając, że zapoznałeś się z koncepcją funkcji (jeśli nie, przejrzyj najpierw rozdział o funkcjach), możesz założyć, że napisanie $c = foo() jest równoznaczne z napisaniem $c = 5, i masz racię. Funkcje są wyrażeniami o wartości którą zwracają. Ponieważ foo() zwraca 5, wartością wyrażenia 'foo()' jest 5. Zazwyczaj funkcje nie zwracają statycznej wartości, ale coś obliczają.

Oczywiście wartości w PHP nie muszą być liczbami całkowitymi, i bardzo często nie są nimi. PHP obsługuje 3 skalarne warotści danych: wartości całkowite (integer), wartości rzeczywiste (float i ciągi znaków (string) (wartości skalarne to takie, których nie możesz 'rozbić' na mniejsze kawałki, w przeciwieństwie do np. tablic). PHP obsługuje także dwa złożone (nieskalarne) typy danych: tablice i obiekty. Każdą z tych wartości można przypisać do zmiennych lub może być zwrócona przez funkcję.

PHP rozwija wyrażenia prawdopodobnie znacznie bardziej, niż wiele innych języków programowania. PHP jest językiem wyrażeń, co oznacza że prawie wszystko w nim jest wyrażeniem. Przyjrzyj się przykładowi, który już analizowaliśmy, '$a = 5'. Łatwo jest zauważyć, że są tu dwie wartości. Wartość stałej całkowitej '5', a także wartość $a, która zostanie zamieniona na 5. Ale tak naprawdę jest tu jeszcze jedna wartość, którą jest wartość operacji przypisania. Przypisanie przyjmuje wartość przypisywanej wartości, w tym przypadku 5. W praktyce oznacza to, że '$a = 5', niezależnie co to robi, jest wyrażeniem o wartości 5. Wynika z tego, że napisanie '$b = ($a = 5)' jest równoznaczne napisaniu '$a = 5; $b = 5;' (średnik oznacza koniec instrukcji). Ponieważ przypisania są przetwarzane od prawej do lewej, możesz także napisać '$b = $a = 5'.

Kolejnym dobrym przykładem korzystania z wyrażeń jest pre- i postinkrementacja, a także dekrementacja. Użytkownicy PHP i wielu innych języków mogą być już zaznajomieni z notacją zmienna++ i zmienna--. Są to operatory inkrementacji i dekrementacji. W PHP/FI 2 instrukcja '$a++' nie ma wartości (nie jest wyrażeniem), więc nie możesz jej przypisać lub użyć w jakikolwiek sposób. PHP rozszerza możliwości inkrementacji/dekrementacji robiąc także z nich wyrażenia, podobnie jak w C. W PHP, tak jak w C, sa dwa typy inkrementacji: preinkrementacja i postinkrementacja. I pre- i postinkrementacja zwiększają wartość zmiannej, więc efekt w stosunku do zmiennej jest taki sam. Różnica jest w wartości wyrażenia inkrementacji. Preinkrementacja, która jest oznaczana jako '++$zmienna', zwraca zwiększoną wartość (PHP zwiększa zmienną przed odczytaniem wartości, dlatego nazywa się to 'pre-inkrementacją'). Postinkrementacja, która jest oznaczana jako '$zmienna++', zwraca orginalną wartość $zmienna przed zwiększeniem jej wartości (PHP zwiększa wartość po odczytaniu jej wartości, stąd nazwa 'post-inkrementacja').

Popularnym typem wyrażeń są porównania. Wyrażenia te zwracają wartość FALSE lub TRUE. PHP obsługuje > (większy), >= (większy lub równy), == (równy), != (nie równy), < (mniejszy) i <= (mniejszy lub równy). Język obsługuje także zbiór operatorów ścisłego porównania: === (równy i tego samego typu) i !== (nie równy lub różnego typu). Wyrażenia te są powszechnie używane przy sprawdzaniu warunków, jak na przykład instrukcje if.

Ostatnim przykładem, którym będziemy się tu zajmować są połączone wyrażenia operacji i przypisania. Już wiesz, że jeśli chcesz zwiększyć wartość zmiennej $a o 1, możesz po prostu napisać '$a++' lub '++$a'. Ale co jeśli chcesz dodać do niej więcej niż jeden, na przykład 3? Mógłbyś napisać wielokrotnie '$a++', ale nie jest to sposób ani efektywny ani wygodny. Częściej spotykane jest używanie instrukcji '$a = $a + 3'. '$a + 4' zwraca wartość zmiennej $a plus 3, która jest przypisywana z powrotem do $a, co oznacza zwiększenie wartości zmiennej $a o 3. W PHP, tak jak kilku innych językach jak na przykład C, możesz napisać to krócej, co z czasem stanie się także bardziej przejrzyste i łatwiejsze do zrozumienia. Dodanie 4 do bieżącej wartości $a może być zapisane jako '$a += 4'. Oznacza to dokładnie "weź wartość $a, dodaj do niej 3 i przypisz ją z powrotem do $a". Oprócz bycia krótszą i bardziej przejrzystą, instrukcja ta jest także szybsza w wykonaniu. Wartość '$a += 5', tak jak wartość zwykłego przypisania, jest przypisywaną wartością. Zauważ, że NIE jest to 4, ale połączona warotść $a i 4 (jest to wartość która jest przypisywana do $a). Dowolne dwuoperandowe operatory mogą być użyte w trybie operacji-przypisania, na przykład '$a -= 5' (odejmij 5 od wartości $a), '$b *= 7' (pomnóż wartość $b przez 7), itp.

Jest jeszcze jedno wyrażenie, które może się wydać dziwne jeśli nie widziałeś go w innych językac, trójoperandowy operator warunkowy:

<?php
$pierwsze 
$drugie $trzecie
?>

Jeśli wartością pierwszego podwyrażenia jest TRUE (rózna od zera), to zwracany jest drugie podwyrażanie, i jest to wynik wyrażenia warunkowego. W przeciwnym wypadku, zwracana jest wartość trzeciego podwyrażenia.

Poniższy przykład powinien pomóc w lepszym zrozumieniu pre- i postinkrementacji i ogólnie koncepcji wyrażeń:

<?php
function double($i)
{
    return 
$i*2;
}
$b $a 5;        /* przypisz wartość pięc do zmiennej $a i $b */
$c $a++;          /* postinkrementuj, przypisz początkową wartość
                       $a (5) do $c */
$e $d = ++$b;     /* preinkrementuj, przypisz zwiększoną wartość
                       $b (6) to $d i $e */

/* w tym momencie i $d i $e są równe 6 */

$f double($d++);  /* przypisz podwojoną wartość $d przed
                       inkrementacji, 2*6 = 12 do $f */
$g double(++$e);  /* przypisz podwojoną wartość $e po
                       inkrementacji, 2*7 = 14 do $g */
$h $g += 10;      /* na początku $g jest zwiększane o 10 i przyjmuje 
                       wartość 24; wartość przypisania (24) jest później
                       przypisywana do $h, które przyjmuje wartość 24. */
?>

Na początku rozdziału powiedzieliśmy, że będziemy opisywać różne typy instrukcji, i tak jak obiecywaliśmy, wyrażenia mogą być instrukcjami. Jednakże nie każde wyrażenie jest instrukcją. Niektóre wyrażenia mogą być instrukcjami. Ten przypadek ma postać 'wyrażenie' ';', czyli wyrażenie a po nim średnik. W '$b=$a=5;', $a=5 jest poprawnym wyrażeniem, ale nie jest instrukcją. Jednakże '$b=$a=$b;' jest poprawną intrukcją.

Ostatnią rzeczą wartą uwagi jest wartość prawdy wyrażeń. W wielu przypadkach, głównie przy sprawdzaniu warunkow i w pętlach, nie interesuje cię wartość wyrażenia, ale tylko czy oznacza TRUE czy FALSE. Stałe TRUE i FALSE (niezależne od wielkości znaków) są dwiema możliwymi wartościami logicznymi. Kiedy to konieczne, wyrażenie jest automatycznie konwertowane na typ boolean. Zobacz rozdział o rzutowaniu typów jeśli interesują cię szczegóły jak to jest przeprowadzane.

PHP dostarcza pełnej i potężnej implementacji wyrażeń i całkowita ich dokumentacja przekracza ramy tego podręcznika. Powyższe przykłady powinny dać ci ogólne pojęcie czym są wyrażenia i jak możesz konstruować przydatne wyrażenia. Przez resztę podręcznika będziemy pisać expr aby oznaczyć dowolne poprawne wyrażenie PHP.



Operators

Spis treści

An operator is something that you feed with one or more values (or expressions, in programming jargon) which yields another value (so that the construction itself becomes an expression). So you can think of functions or constructions that return a value (like print) as operators and those that return nothing (like echo) as any other thing.

There are three types of operators. Firstly there is the unary operator which operates on only one value, for example ! (the negation operator) or ++ (the increment operator). The second group are termed binary operators; this group contains most of the operators that PHP supports, and a list follows below in the section Operator Precedence.

The third group is the ternary operator: ?:. It should be used to select between two expressions depending on a third one, rather than to select two sentences or paths of execution. Surrounding ternary expressions with parentheses is a very good idea.


Operator Precedence

The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18. If operator precedence is equal, left to right associativity is used.

The following table lists the precedence of operators with the highest-precedence operators listed at the top of the table. Operators on the same line have equal precedence, in which case their associativity decides which order to evaluate them in.

Operator Precedence
Associativity Operators Additional Information
non-associative clone new clone and new
left [ array()
non-associative ++ -- increment/decrement
right ~ - (int) (float) (string) (array) (object) (bool) @ types
non-associative instanceof types
right ! logical
left * / % arithmetic
left + - . arithmetic i string
left << >> bitwise
non-associative < <= > >= <> comparison
non-associative == != === !== comparison
left & bitwise i references
left ^ bitwise
left | bitwise
left && logical
left || logical
left ? : ternary
right = += -= *= /= .= %= &= |= ^= <<= >>= assignment
left and logical
left xor logical
left or logical
left , many uses

Left associativity means that the expression is evaluated from left to right, right associativity means the opposite.

Przykład #1 Associativity

<?php
$a 
5// (3 * 3) % 5 = 4
$a true true 2// (true ? 0 : true) ? 1 : 2 = 2

$a 1;
$b 2;
$a $b += 3// $a = ($b += 3) -> $a = 5, $b = 5
?>

Use parentheses to increase readability of the code.

Informacja: Although = has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is put into $a.



Arithmetic Operators

Remember basic arithmetic from school? These work just like those.

Arithmetic Operators
Example Name Result
-$a Negation Opposite of $a.
$a + $b Addition Sum of $a and $b.
$a - $b Subtraction Difference of $a and $b.
$a * $b Multiplication Product of $a and $b.
$a / $b Division Quotient of $a and $b.
$a % $b Modulus Remainder of $a divided by $b.

The division operator ("/") returns a float value unless the two operands are integers (or strings that get converted to integers) and the numbers are evenly divisible, in which case an integer value will be returned.

Operands of modulus are converted to integers (by stripping the decimal part) before processing.

Informacja: Remainder $a % $b is negative for negative $a.

See also the manual page on Math functions.



Assignment Operators

The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the rights (that is, "gets set to").

The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3. This allows you to do some tricky things:

<?php

$a 
= ($b 4) + 5// $a is equal to 9 now, and $b has been set to 4.

?>

In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic, array union and string operators that allow you to use a value in an expression and then set its value to the result of that expression. For example:

<?php

$a 
3;
$a += 5// sets $a to 8, as if we had said: $a = $a + 5;
$b "Hello ";
$b .= "There!"// sets $b to "Hello There!", just like $b = $b . "There!";

?>

Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. This may also have relevance if you need to copy something like a large array inside a tight loop. Assignment by reference is also supported, using the $var = &$othervar; syntax. 'Assignment by reference' means that both variables end up pointing at the same data, and nothing is copied anywhere. To learn more about references, please read References explained. As of PHP 5, objects are assigned by reference unless explicitly told otherwise with the new clone keyword.



Bitwise Operators

Bitwise operators allow evaluation and manipulation of specific bits within an integer.

Bitwise Operators
Example Name Result
$a & $b And Bits that are set in both $a and $b are set.
$a | $b Or (inclusive or) Bits that are set in either $a or $b are set.
$a ^ $b Xor (exclusive or) Bits that are set in $a or $b but not both are set.
~ $a Not Bits that are set in $a are not set, and vice versa.
$a << $b Shift left Shift the bits of $a $b steps to the left (each step means "multiply by two")
$a >> $b Shift right Shift the bits of $a $b steps to the right (each step means "divide by two")

Bit shifting in PHP is arithmetic. Bits shifted off either end are discarded. Left shifts have zeros shifted in on the right while the sign bit is shifted out on the left, meaning the sign of an operand is not preserved. Right shifts have copies of the sign bit shifted in on the left, meaning the sign of an operand is preserved.

Use parentheses to ensure the desired precedence. For example, $a & $b == true evaluates the equivalency then the bitwise and; while ($a & $b) == true evaluates the bitwise and then the equivalency.

Be aware of data type conversions. If both the left-hand and right-hand parameters are strings, the bitwise operator will operate on the characters' ASCII values.

PHP's error_reporting ini setting uses bitwise values,
providing a real-world demonstration of turning
bits off. To show all errors, except for notices,
the php.ini file instructions say to use:
E_ALL & ~E_NOTICE

      

This works by starting with E_ALL:
00000000000000000111011111111111
Then taking the value of E_NOTICE...
00000000000000000000000000001000
... and inverting it via ~:
11111111111111111111111111110111
Finally, it uses AND (&) to find the bits turned
on in both values:
00000000000000000111011111110111
      

Another way to accomplish that is using XOR (^)
to find bits that are on in only one value or the other:
E_ALL ^ E_NOTICE

      

error_reporting can also be used to demonstrate turning bits on.
The way to show just errors and recoverable errors is:
E_ERROR | E_RECOVERABLE_ERROR

      

This process combines E_ERROR
00000000000000000000000000000001
and
00000000000000000001000000000000
using the OR (|) operator
to get the bits turned on in either value:
00000000000000000001000000000001
      

Przykład #1 Bitwise AND, OR and XOR operations on integers

<?php
/*
 * Ignore the top section,
 * it is just formatting to make output clearer.
 */

$format '(%1$2d = %1$04b) = (%2$2d = %2$04b)'
        
' %3$s (%4$2d = %4$04b)' "\n";

echo <<<EOH
 ---------     ---------  -- ---------
 result        value      op test
 ---------     ---------  -- ---------
EOH;


/*
 * Here are the examples.
 */

$values = array(01248);
$test 4;

echo 
"\n Bitwise AND \n";
foreach (
$values as $value) {
    
$result $value $test;
    
printf($format$result$value'&'$test);
}

echo 
"\n Bitwise Inclusive OR \n";
foreach (
$values as $value) {
    
$result $value $test;
    
printf($format$result$value'|'$test);
}

echo 
"\n Bitwise Exclusive OR (XOR) \n";
foreach (
$values as $value) {
    
$result $value $test;
    
printf($format$result$value'^'$test);
}
?>

Powyższy przykład wyświetli:

 ---------     ---------  -- ---------
 result        value      op test
 ---------     ---------  -- ---------
 Bitwise AND
( 0 = 0000) = ( 0 = 0000) & ( 5 = 0101)
( 1 = 0001) = ( 1 = 0001) & ( 5 = 0101)
( 0 = 0000) = ( 2 = 0010) & ( 5 = 0101)
( 4 = 0100) = ( 4 = 0100) & ( 5 = 0101)
( 0 = 0000) = ( 8 = 1000) & ( 5 = 0101)

 Bitwise Inclusive OR
( 5 = 0101) = ( 0 = 0000) | ( 5 = 0101)
( 5 = 0101) = ( 1 = 0001) | ( 5 = 0101)
( 7 = 0111) = ( 2 = 0010) | ( 5 = 0101)
( 5 = 0101) = ( 4 = 0100) | ( 5 = 0101)
(13 = 1101) = ( 8 = 1000) | ( 5 = 0101)

 Bitwise Exclusive OR (XOR)
( 5 = 0101) = ( 0 = 0000) ^ ( 5 = 0101)
( 4 = 0100) = ( 1 = 0001) ^ ( 5 = 0101)
( 7 = 0111) = ( 2 = 0010) ^ ( 5 = 0101)
( 1 = 0001) = ( 4 = 0100) ^ ( 5 = 0101)
(13 = 1101) = ( 8 = 1000) ^ ( 5 = 0101)

Przykład #2 Bitwise XOR operations on strings

<?php
echo 12 9// Outputs '5'

echo "12" "9"// Outputs the Backspace character (ascii 8)
                 // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8

echo "hallo" "hello"// Outputs the ascii values #0 #4 #0 #0 #0
                        // 'a' ^ 'e' = #4

echo "3"// Outputs 1
              // 2 ^ ((int)"3") == 1

echo "2" 3// Outputs 1
              // ((int)"2") ^ 3 == 1
?>

Przykład #3 Bit shifting on integers

<?php
/*
 * Here are the examples.
 */

echo "\n--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---\n";

$val 4;
$places 1;
$res $val >> $places;
p($res$val'>>'$places'copy of sign bit shifted into left side');

$val 4;
$places 2;
$res $val >> $places;
p($res$val'>>'$places);

$val 4;
$places 3;
$res $val >> $places;
p($res$val'>>'$places'bits shift out right side');

$val 4;
$places 4;
$res $val >> $places;
p($res$val'>>'$places'same result as above; can not shift beyond 0');


echo 
"\n--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---\n";

$val = -4;
$places 1;
$res $val >> $places;
p($res$val'>>'$places'copy of sign bit shifted into left side');

$val = -4;
$places 2;
$res $val >> $places;
p($res$val'>>'$places'bits shift out right side');

$val = -4;
$places 3;
$res $val >> $places;
p($res$val'>>'$places'same result as above; can not shift beyond -1');


echo 
"\n--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---\n";

$val 4;
$places 1;
$res $val << $places;
p($res$val'<<'$places'zeros fill in right side');

$val 4;
$places = (PHP_INT_SIZE 8) - 4;
$res $val << $places;
p($res$val'<<'$places);

$val 4;
$places = (PHP_INT_SIZE 8) - 3;
$res $val << $places;
p($res$val'<<'$places'sign bits get shifted out');

$val 4;
$places = (PHP_INT_SIZE 8) - 2;
$res $val << $places;
p($res$val'<<'$places'bits shift out left side');


echo 
"\n--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---\n";

$val = -4;
$places 1;
$res $val << $places;
p($res$val'<<'$places'zeros fill in right side');

$val = -4;
$places = (PHP_INT_SIZE 8) - 3;
$res $val << $places;
p($res$val'<<'$places);

$val = -4;
$places = (PHP_INT_SIZE 8) - 2;
$res $val << $places;
p($res$val'<<'$places'bits shift out left side, including sign bit');


/*
 * Ignore this bottom section,
 * it is just formatting to make output clearer.
 */

function p($res$val$op$places$note '') {
    
$format '%0' . (PHP_INT_SIZE 8) . "b\n";

    
printf("Expression: %d = %d %s %d\n"$res$val$op$places);

    echo 
" Decimal:\n";
    
printf("  val=%d\n"$val);
    
printf("  res=%d\n"$res);

    echo 
" Binary:\n";
    
printf('  val=' $format$val);
    
printf('  res=' $format$res);

    if (
$note) {
        echo 
" NOTE: $note\n";
    }

    echo 
"\n";
}
?>

Wyświetla następujący przykład na systemach 32 bitowych:


--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---
Expression: 2 = 4 >> 1
 Decimal:
  val=4
  res=2
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000010
 NOTE: copy of sign bit shifted into left side

Expression: 1 = 4 >> 2
 Decimal:
  val=4
  res=1
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000001

Expression: 0 = 4 >> 3
 Decimal:
  val=4
  res=0
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000000
 NOTE: bits shift out right side

Expression: 0 = 4 >> 4
 Decimal:
  val=4
  res=0
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000000
 NOTE: same result as above; can not shift beyond 0


--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---
Expression: -2 = -4 >> 1
 Decimal:
  val=-4
  res=-2
 Binary:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111110
 NOTE: copy of sign bit shifted into left side

Expression: -1 = -4 >> 2
 Decimal:
  val=-4
  res=-1
 Binary:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111111
 NOTE: bits shift out right side

Expression: -1 = -4 >> 3
 Decimal:
  val=-4
  res=-1
 Binary:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111111
 NOTE: same result as above; can not shift beyond -1


--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---
Expression: 8 = 4 << 1
 Decimal:
  val=4
  res=8
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000001000
 NOTE: zeros fill in right side

Expression: 1073741824 = 4 << 28
 Decimal:
  val=4
  res=1073741824
 Binary:
  val=00000000000000000000000000000100
  res=01000000000000000000000000000000

Expression: -2147483648 = 4 << 29
 Decimal:
  val=4
  res=-2147483648
 Binary:
  val=00000000000000000000000000000100
  res=10000000000000000000000000000000
 NOTE: sign bits get shifted out

Expression: 0 = 4 << 30
 Decimal:
  val=4
  res=0
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000000
 NOTE: bits shift out left side


--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---
Expression: -8 = -4 << 1
 Decimal:
  val=-4
  res=-8
 Binary:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111000
 NOTE: zeros fill in right side

Expression: -2147483648 = -4 << 29
 Decimal:
  val=-4
  res=-2147483648
 Binary:
  val=11111111111111111111111111111100
  res=10000000000000000000000000000000

Expression: 0 = -4 << 30
 Decimal:
  val=-4
  res=0
 Binary:
  val=11111111111111111111111111111100
  res=00000000000000000000000000000000
 NOTE: bits shift out left side, including sign bit

Wyświetla następujący przykład na systemach 64 bitowych:


--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---
Expression: 2 = 4 >> 1
 Decimal:
  val=4
  res=2
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000010
 NOTE: copy of sign bit shifted into left side

Expression: 1 = 4 >> 2
 Decimal:
  val=4
  res=1
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000001

Expression: 0 = 4 >> 3
 Decimal:
  val=4
  res=0
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTE: bits shift out right side

Expression: 0 = 4 >> 4
 Decimal:
  val=4
  res=0
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTE: same result as above; can not shift beyond 0


--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---
Expression: -2 = -4 >> 1
 Decimal:
  val=-4
  res=-2
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111110
 NOTE: copy of sign bit shifted into left side

Expression: -1 = -4 >> 2
 Decimal:
  val=-4
  res=-1
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111111
 NOTE: bits shift out right side

Expression: -1 = -4 >> 3
 Decimal:
  val=-4
  res=-1
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111111
 NOTE: same result as above; can not shift beyond -1


--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---
Expression: 8 = 4 << 1
 Decimal:
  val=4
  res=8
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000001000
 NOTE: zeros fill in right side

Expression: 4611686018427387904 = 4 << 60
 Decimal:
  val=4
  res=4611686018427387904
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0100000000000000000000000000000000000000000000000000000000000000

Expression: -9223372036854775808 = 4 << 61
 Decimal:
  val=4
  res=-9223372036854775808
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=1000000000000000000000000000000000000000000000000000000000000000
 NOTE: sign bits get shifted out

Expression: 0 = 4 << 62
 Decimal:
  val=4
  res=0
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTE: bits shift out left side


--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---
Expression: -8 = -4 << 1
 Decimal:
  val=-4
  res=-8
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111000
 NOTE: zeros fill in right side

Expression: -9223372036854775808 = -4 << 61
 Decimal:
  val=-4
  res=-9223372036854775808
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1000000000000000000000000000000000000000000000000000000000000000

Expression: 0 = -4 << 62
 Decimal:
  val=-4
  res=0
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTE: bits shift out left side, including sign bit

Ostrzeżenie

Don't right shift for more than 32 bits on 32 bits systems. Don't left shift in case it results to number longer than 32 bits. Use functions from the gmp extension for bitwise manipulation on numbers beyond PHP_INT_MAX.

See also pack(), unpack(), gmp_and(), gmp_or(), gmp_xor(), gmp_testbit(), gmp_clrbit()



Comparison Operators

Comparison operators, as their name implies, allow you to compare two values. You may also be interested in viewing the type comparison tables, as they show examples of various type related comparisons.

Comparison Operators
Example Name Result
$a == $b Equal TRUE if $a is equal to $b.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)
$a != $b Not equal TRUE if $a is not equal to $b.
$a <> $b Not equal TRUE if $a is not equal to $b.
$a !== $b Not identical TRUE if $a is not equal to $b, or they are not of the same type. (introduced in PHP 4)
$a < $b Less than TRUE if $a is strictly less than $b.
$a > $b Greater than TRUE if $a is strictly greater than $b.
$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.
$a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b.

If you compare an integer with a string, the string is converted to a number. If you compare two numerical strings, they are compared as integers. These rules also apply to the switch statement.

<?php
var_dump
(== "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("1" == "1e0"); // 1 == 1 -> true

switch ("a") {
case 
0:
    echo 
"0";
    break;
case 
"a"// never reached because "a" is already matched with 0
    
echo "a";
    break;
}
?>

For various types, comparison is done according to the following table (in order).

Comparison with Various Types
Type of Operand 1 Type of Operand 2 Result
null or string string Convert NULL to "", numerical or lexical comparison
bool or null anything Convert to bool, FALSE < TRUE
object object Built-in classes can define its own comparison, different classes are uncomparable, same class - compare properties the same way as arrays (PHP 4), PHP 5 has its own explanation
string, resource or number string, resource or number Translate strings and resources to numbers, usual math
array array Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are uncomparable, otherwise - compare value by value (see following example)
array anything array is always greater
object anything object is always greater

Przykład #1 Transcription of standard array comparison

<?php
// Arrays are compared like this with standard comparison operators
function standard_array_compare($op1$op2)
{
    if (
count($op1) < count($op2)) {
        return -
1// $op1 < $op2
    
} elseif (count($op1) > count($op2)) {
        return 
1// $op1 > $op2
    
}
    foreach (
$op1 as $key => $val) {
        if (!
array_key_exists($key$op2)) {
            return 
null// uncomparable
        
} elseif ($val $op2[$key]) {
            return -
1;
        } elseif (
$val $op2[$key]) {
            return 
1;
        }
    }
    return 
0// $op1 == $op2
}
?>

See also strcasecmp(), strcmp(), Array operators, and the manual section on Types.

Ternary Operator

Another conditional operator is the "?:" (or ternary) operator.

Przykład #2 Assigning a default value

<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' $_POST['action'];

// The above is identical to this if/else statement
if (empty($_POST['action'])) {
    
$action 'default';
} else {
    
$action $_POST['action'];
}

?>

The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

Informacja: Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.

Informacja: It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious:

Przykład #3 Non-obvious Ternary Behaviour

<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');

// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right

// the following is a more obvious version of the same code as above
echo ((true 'true' 'false') ? 't' 'f');

// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>




Error Control Operators

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

If the track_errors feature is enabled, any error message generated by the expression will be saved in the variable $php_errormsg. This variable will be overwritten on each error, so check early if you want to use it.

<?php
/* Intentional file error */
$my_file = @file ('non_existent_file') or
    die (
"Failed opening file: error was '$php_errormsg'");

// this works for any expression, not just functions:
$value = @$cache[$key];
// will not issue a notice if the index $key doesn't exist.

?>

Informacja: The @-operator works only on expressions. A simple rule of thumb is: if you can take the value of something, you can prepend the @ operator to it. For instance, you can prepend it to variables, function and include() calls, constants, and so forth. You cannot prepend it to function or class definitions, or conditional structures such as if and foreach, and so forth.

See also error_reporting() and the manual section for Error Handling and Logging functions.

Ostrzeżenie

Currently the "@" error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use "@" to suppress errors from a certain function and either it isn't available or has been mistyped, the script will die right there with no indication as to why.



Execution Operators

PHP supports one execution operator: backticks (``). Note that these are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned (i.e., it won't simply be dumped to output; it can be assigned to a variable). Use of the backtick operator is identical to shell_exec().

<?php
$output 
= `ls -al`;
echo 
"<pre>$output</pre>";
?>

Informacja: The backtick operator is disabled when tryb bezpieczny is enabled or shell_exec() is disabled.

See also the manual section on Program Execution functions, popen() proc_open(), and Using PHP from the commandline.



Incrementing/Decrementing Operators

PHP supports C-style pre- and post-increment and decrement operators.

Informacja: The increment/decrement operators do not affect boolean values. Decrementing NULL values has no effect too, but incrementing them results in 1.

Increment/decrement Operators
Example Name Effect
++$a Pre-increment Increments $a by one, then returns $a.
$a++ Post-increment Returns $a, then increments $a by one.
--$a Pre-decrement Decrements $a by one, then returns $a.
$a-- Post-decrement Returns $a, then decrements $a by one.

Here's a simple example script:

<?php
echo "<h3>Postincrement</h3>";
$a 5;
echo 
"Should be 5: " $a++ . "<br />\n";
echo 
"Should be 6: " $a "<br />\n";

echo 
"<h3>Preincrement</h3>";
$a 5;
echo 
"Should be 6: " . ++$a "<br />\n";
echo 
"Should be 6: " $a "<br />\n";

echo 
"<h3>Postdecrement</h3>";
$a 5;
echo 
"Should be 5: " $a-- . "<br />\n";
echo 
"Should be 4: " $a "<br />\n";

echo 
"<h3>Predecrement</h3>";
$a 5;
echo 
"Should be 4: " . --$a "<br />\n";
echo 
"Should be 4: " $a "<br />\n";
?>

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in Perl 'Z'+1 turns into 'AA', while in C 'Z'+1 turns into '[' ( ord('Z') == 90, ord('[') == 91 ). Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.

Przykład #1 Arithmetic Operations on Character Variables

<?php
$i 
'W';
for (
$n=0$n<6$n++) {
    echo ++
$i "\n";
}
?>

Powyższy przykład wyświetli:

X
Y
Z
AA
AB
AC

Incrementing or decrementing booleans has no effect.



Logical Operators

Logical Operators
Example Name Result
$a and $b And TRUE if both $a and $b are TRUE.
$a or $b Or TRUE if either $a or $b is TRUE.
$a xor $b Xor TRUE if either $a or $b is TRUE, but not both.
! $a Not TRUE if $a is not TRUE.
$a && $b And TRUE if both $a and $b are TRUE.
$a || $b Or TRUE if either $a or $b is TRUE.

The reason for the two different variations of "and" and "or" operators is that they operate at different precedences. (See Operator Precedence.)

Przykład #1 Logical operators illustrated

<?php

// --------------------
// foo() will never get called as those operators are short-circuit

$a = (false && foo());
$b = (true  || foo());
$c = (false and foo());
$d = (true  or  foo());

// --------------------
// "||" has a greater precedence than "or"

// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e false || true;

// The constant false is assigned to $f and then true is ignored
// Acts like: (($e = false) or true)
$f false or true;

var_dump($e$f);

// --------------------
// "&&" has a greater precedence than "and"

// The result of the expression (true && false) is assigned to $g
// Acts like: ($g = (true && false))
$g true && false;

// The constant true is assigned to $h and then false is ignored
// Acts like: (($h = true) and false)
$h true and false;

var_dump($g$h);
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
bool(false)
bool(false)
bool(true)


String Operators

There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends the argument on the right side to the argument on the left side. Please read Assignment Operators for more information.

<?php
$a 
"Hello ";
$b $a "World!"// now $b contains "Hello World!"

$a "Hello ";
$a .= "World!";     // now $a contains "Hello World!"
?>

See also the manual sections on the String type and String functions.



Array Operators

Array Operators
Example Name Result
$a + $b Union Union of $a and $b.
$a == $b Equality TRUE if $a and $b have the same key/value pairs.
$a === $b Identity TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
$a != $b Inequality TRUE if $a is not equal to $b.
$a <> $b Inequality TRUE if $a is not equal to $b.
$a !== $b Non-identity TRUE if $a is not identical to $b.

The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.

<?php
$a 
= array("a" => "apple""b" => "banana");
$b = array("a" => "pear""b" => "strawberry""c" => "cherry");

$c $a $b// Union of $a and $b
echo "Union of \$a and \$b: \n";
var_dump($c);

$c $b $a// Union of $b and $a
echo "Union of \$b and \$a: \n";
var_dump($c);
?>

When executed, this script will print the following:

Union of $a and $b:
array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(6) "cherry"
}
Union of $b and $a:
array(3) {
  ["a"]=>
  string(4) "pear"
  ["b"]=>
  string(10) "strawberry"
  ["c"]=>
  string(6) "cherry"
}

Elements of arrays are equal for the comparison if they have the same key and value.

Przykład #1 Comparing arrays

<?php
$a 
= array("apple""banana");
$b = array(=> "banana""0" => "apple");

var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>

See also the manual sections on the Array type and Array functions.



Type Operators

instanceof is used to determine whether a PHP variable is an instantiated object of a certain class:

Przykład #1 Using instanceof with classes

<?php
class MyClass
{
}

class 
NotMyClass
{
}
$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof NotMyClass);
?>

Powyższy przykład wyświetli:

bool(true)
bool(false)

instanceof can also be used to determine whether a variable is an instantiated object of a class that inherits from a parent class:

Przykład #2 Using instanceof with inherited classes

<?php
class ParentClass
{
}

class 
MyClass extends ParentClass
{
}

$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof ParentClass);
?>

Powyższy przykład wyświetli:

bool(true)
bool(true)

To check if an object is not an instanceof a class, the logical not operator can be used.

Przykład #3 Using instanceof to check if object is not an instanceof a class

<?php
class MyClass
{
}

$a = new MyClass;
var_dump(!($a instanceof stdClass));
?>

Powyższy przykład wyświetli:

bool(true)

Lastly, instanceof can also be used to determine whether a variable is an instantiated object of a class that implements an interface:

Przykład #4 Using instanceof for class

<?php
interface MyInterface
{
}

class 
MyClass implements MyInterface
{
}

$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof MyInterface);
?>

Powyższy przykład wyświetli:

bool(true)
bool(true)

Although instanceof is usually used with a literal classname, it can also be used with another object or a string variable:

Przykład #5 Using instanceof with other variables

<?php
interface MyInterface
{
}

class 
MyClass implements MyInterface
{
}

$a = new MyClass;
$b = new MyClass;
$c 'MyClass';
$d 'NotMyClass';

var_dump($a instanceof $b); // $b is an object of class MyClass
var_dump($a instanceof $c); // $c is a string 'MyClass'
var_dump($a instanceof $d); // $d is a string 'NotMyClass'
?>

Powyższy przykład wyświetli:

bool(true)
bool(true)
bool(false)

There are a few pitfalls to be aware of. Before PHP version 5.1.0, instanceof would call __autoload() if the class name did not exist. In addition, if the class was not loaded, a fatal error would occur. This can be worked around by using a dynamic class reference, or a string variable containing the class name:

Przykład #6 Avoiding classname lookups and fatal errors with instanceof in PHP 5.0

<?php
$d 
'NotMyClass';
var_dump($a instanceof $d); // no fatal error here
?>

Powyższy przykład wyświetli:

bool(false)

The instanceof operator was introduced in PHP 5. Before this time is_a() was used but is_a() has since been deprecated in favor of instanceof. Note that as of PHP 5.3.0, is_a() is no longer deprecated.

See also get_class() and is_a().




Control Structures

Spis treści


Introduction

Any PHP script is built out of a series of statements. A statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well. The various statement types are described in this chapter.



if

The if construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an if structure that is similar to that of C:

if (expr)
  statement

As described in the section about expressions, expression is evaluated to its Boolean value. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it. More information about what values evaluate to FALSE can be found in the 'Converting to boolean' section.

The following example would display a is bigger than b if $a is bigger than $b:

<?php
if ($a $b)
  echo 
"a is bigger than b";
?>

Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group. For example, this code would display a is bigger than b if $a is bigger than $b, and would then assign the value of $a into $b:

<?php
if ($a $b) {
  echo 
"a is bigger than b";
  
$b $a;
}
?>

If statements can be nested infinitely within other if statements, which provides you with complete flexibility for conditional execution of the various parts of your program.



else

Often you'd want to execute a statement if a certain condition is met, and a different statement if the condition is not met. This is what else is for. else extends an if statement to execute a statement in case the expression in the if statement evaluates to FALSE. For example, the following code would display a is greater than b if $a is greater than $b, and a is NOT greater than b otherwise:

<?php
if ($a $b) {
  echo 
"a is greater than b";
} else {
  echo 
"a is NOT greater than b";
}
?>

The else statement is only executed if the if expression evaluated to FALSE, and if there were any elseif expressions - only if they evaluated to FALSE as well (see elseif).



elseif/else if

elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE. For example, the following code would display a is bigger than b, a equal to b or a is smaller than b:

<?php
if ($a $b) {
    echo 
"a is bigger than b";
} elseif (
$a == $b) {
    echo 
"a is equal to b";
} else {
    echo 
"a is smaller than b";
}
?>

There may be several elseifs within the same if statement. The first elseif expression (if any) that evaluates to TRUE would be executed. In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different (if you're familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior.

The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE.

Informacja: Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define your if/elseif conditions, you must not separate else if into two words, or PHP will fail with a parse error.

<?php

/* Incorrect Method: */
if($a $b):
    echo 
$a." is greater than ".$b;
else if(
$a == $b): // Will not compile.
    
echo "The above line causes a parse error.";
endif;


/* Correct Method: */
if($a $b):
    echo 
$a." is greater than ".$b;
elseif(
$a == $b): // Note the combination of the words.
    
echo $a." equals ".$b;
else:
    echo 
$a." is neither greater than or equal to ".$b;
endif;

?>



Alternative syntax for control structures

PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.

<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>

In the above example, the HTML block "A is equal to 5" is nested within an if statement written in the alternative syntax. The HTML block would be displayed only if $a is equal to 5.

The alternative syntax applies to else and elseif as well. The following is an if structure with elseif and else in the alternative format:

<?php
if ($a == 5):
    echo 
"a equals 5";
    echo 
"...";
elseif (
$a == 6):
    echo 
"a equals 6";
    echo 
"!!!";
else:
    echo 
"a is neither 5 nor 6";
endif;
?>

See also while, for, and if for further examples.



while

while loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is:

while (expr)
    statement

The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once.

Like with the if statement, you can group multiple statements within the same while loop by surrounding a group of statements with curly braces, or by using the alternate syntax:

while (expr):
    statement
    ...
endwhile;

The following examples are identical, and both print the numbers 1 through 10:

<?php
/* example 1 */

$i 1;
while (
$i <= 10) {
    echo 
$i++;  /* the printed value would be
                   $i before the increment
                   (post-increment) */
}

/* example 2 */

$i 1;
while (
$i <= 10):
    echo 
$i;
    
$i++;
endwhile;
?>



do-while

do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning. The main difference from regular while loops is that the first iteration of a do-while loop is guaranteed to run (the truth expression is only checked at the end of the iteration), whereas it may not necessarily run with a regular while loop (the truth expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the beginning, the loop execution would end immediately).

There is just one syntax for do-while loops:

<?php
$i 
0;
do {
    echo 
$i;
} while (
$i 0);
?>

The above loop would run one time exactly, since after the first iteration, when truth expression is checked, it evaluates to FALSE ($i is not bigger than 0) and the loop execution ends.

Advanced C users may be familiar with a different usage of the do-while loop, to allow stopping execution in the middle of code blocks, by encapsulating them with do-while (0), and using the break statement. The following code fragment demonstrates this:

<?php
do {
    if (
$i 5) {
        echo 
"i is not big enough";
        break;
    }
    
$i *= $factor;
    if (
$i $minimum_limit) {
        break;
    }
   echo 
"i is ok";

    
/* process i */

} while (0);
?>

Don't worry if you don't understand this right away or at all. You can code scripts and even powerful scripts without using this 'feature'. Since PHP 5.3.0, it is possible to use goto operator instead of this hack.



for

for loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is:

for (expr1; expr2; expr3)
    statement

The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.

In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.

At the end of each iteration, expr3 is evaluated (executed).

Each of the expressions can be empty or contain multiple expressions separated by commas. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional break statement instead of using the for truth expression.

Consider the following examples. All of them display the numbers 1 through 10:

<?php
/* example 1 */

for ($i 1$i <= 10$i++) {
    echo 
$i;
}

/* example 2 */

for ($i 1; ; $i++) {
    if (
$i 10) {
        break;
    }
    echo 
$i;
}

/* example 3 */

$i 1;
for (; ; ) {
    if (
$i 10) {
        break;
    }
    echo 
$i;
    
$i++;
}

/* example 4 */

for ($i 1$j 0$i <= 10$j += $i, print $i$i++);
?>

Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in for loops comes in handy in many occasions.

PHP also supports the alternate "colon syntax" for for loops.

for (expr1; expr2; expr3):
    statement
    ...
endfor;

Its a common thing to many users to iterate though arrays like in the example below.

<?php
/*
* This is an array with some data we want to modify
* when running through the for loop.
*/
$people = Array(
        Array(
'name' => 'Kalle''salt' => 856412),
        Array(
'name' => 'Pierre''salt' => 215863)
        );

for(
$i 0$i sizeof($people); ++$i)
{
    
$people[$i]['salt'] = rand(000000999999);
}
?>

The problem lies in the second for expression. This code can be slow because it has to calculate the size of the array on each iteration. Since the size never change, it can be optimized easily using an intermediate variable to store the size and use in the loop instead of sizeof. The example below illustrates this:

<?php
$people 
= Array(
        Array(
'name' => 'Kalle''salt' => 856412),
        Array(
'name' => 'Pierre''salt' => 215863)
        );

for(
$i 0$size sizeof($people); $i $size; ++$i)
{
    
$people[$i]['salt'] = rand(000000999999);
}
?>



foreach

PHP 4 introduced a foreach construct, much like Perl and some other languages. This simply gives an easy way to iterate over arrays. foreach works only on arrays, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes; the second is a minor but useful extension of the first:

foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement

The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element).

The second form does the same thing, except that the current element's key will be assigned to the variable $key on each loop.

As of PHP 5, it is possible to iterate objects too.

Informacja: When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.

Informacja: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.

As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.

<?php
$arr 
= array(1234);
foreach (
$arr as &$value) {
    
$value $value 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>

This is possible only if iterated array can be referenced (i.e. is variable), that means the following code won't work:

<?php
foreach (array(1234) as &$value) {
    
$value $value 2;
}

?>

Ostrzeżenie

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

Informacja: foreach does not support the ability to suppress error messages using '@'.

You may have noticed that the following are functionally identical:

<?php
$arr 
= array("one""two""three");
reset($arr);
while (list(, 
$value) = each($arr)) {
    echo 
"Value: $value<br />\n";
}

foreach (
$arr as $value) {
    echo 
"Value: $value<br />\n";
}
?>

The following are also functionally identical:

<?php
$arr 
= array("one""two""three");
reset($arr);
while (list(
$key$value) = each($arr)) {
    echo 
"Key: $key; Value: $value<br />\n";
}

foreach (
$arr as $key => $value) {
    echo 
"Key: $key; Value: $value<br />\n";
}
?>

Some more examples to demonstrate usages:

<?php
/* foreach example 1: value only */

$a = array(12317);

foreach (
$a as $v) {
    echo 
"Current value of \$a: $v.\n";
}

/* foreach example 2: value (with its manual access notation printed for illustration) */

$a = array(12317);

$i 0/* for illustrative purposes only */

foreach ($a as $v) {
    echo 
"\$a[$i] => $v.\n";
    
$i++;
}

/* foreach example 3: key and value */

$a = array(
    
"one" => 1,
    
"two" => 2,
    
"three" => 3,
    
"seventeen" => 17
);

foreach (
$a as $k => $v) {
    echo 
"\$a[$k] => $v.\n";
}

/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach (
$a as $v1) {
    foreach (
$v1 as $v2) {
        echo 
"$v2\n";
    }
}

/* foreach example 5: dynamic arrays */

foreach (array(12345) as $v) {
    echo 
"$v\n";
}
?>



break

break ends execution of the current for, foreach, while, do-while or switch structure.

break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.

<?php
$arr 
= array('one''two''three''four''stop''five');
while (list(, 
$val) = each($arr)) {
    if (
$val == 'stop') {
        break;    
/* You could also write 'break 1;' here. */
    
}
    echo 
"$val<br />\n";
}

/* Using the optional argument. */

$i 0;
while (++
$i) {
    switch (
$i) {
    case 
5:
        echo 
"At 5<br />\n";
        break 
1;  /* Exit only the switch. */
    
case 10:
        echo 
"At 10; quitting<br />\n";
        break 
2;  /* Exit the switch and the while. */
    
default:
        break;
    }
}
?>



continue

continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

Informacja: Note that in PHP the switch statement is considered a looping structure for the purposes of continue.

continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.

<?php
while (list($key$value) = each($arr)) {
    if (!(
$key 2)) { // skip odd members
        
continue;
    }
    
do_something_odd($value);
}

$i 0;
while (
$i++ < 5) {
    echo 
"Outer<br />\n";
    while (
1) {
        echo 
"&nbsp;&nbsp;Middle<br />\n";
        while (
1) {
            echo 
"&nbsp;&nbsp;Inner<br />\n";
            continue 
3;
        }
        echo 
"This never gets output.<br />\n";
    }
    echo 
"Neither does this.<br />\n";
}
?>

Omitting the semicolon after continue can lead to confusion. Here's an example of what you shouldn't do.

<?php
for ($i 0$i 5; ++$i) {
    if (
$i == 2)
        continue
    print 
"$i\n";
}
?>

One can expect the result to be :

0
1
3
4

but this script will output :

2

because the return value of the print() call is int(1), and it will look like the optional numeric argument mentioned above.



switch

The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.

Informacja: Note that unlike some other languages, the continue statement applies to switch and acts similar to break. If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2.

Informacja: Note that switch/case does loose comparision.

The following two examples are two different ways to write the same thing, one using a series of if and elseif statements, and the other using the switch statement:

Przykład #1 switch structure

<?php
if ($i == 0) {
    echo 
"i equals 0";
} elseif (
$i == 1) {
    echo 
"i equals 1";
} elseif (
$i == 2) {
    echo 
"i equals 2";
}

switch (
$i) {
    case 
0:
        echo 
"i equals 0";
        break;
    case 
1:
        echo 
"i equals 1";
        break;
    case 
2:
        echo 
"i equals 2";
        break;
}
?>

Przykład #2 switch structure allows usage of strings

<?php
switch ($i) {
    case 
"apple":
        echo 
"i is apple";
        break;
    case 
"bar":
        echo 
"i is bar";
        break;
    case 
"cake":
        echo 
"i is cake";
        break;
}
?>

It is important to understand how the switch statement is executed in order to avoid mistakes. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example:

<?php
switch ($i) {
    case 
0:
        echo 
"i equals 0";
    case 
1:
        echo 
"i equals 1";
    case 
2:
        echo 
"i equals 2";
}
?>

Here, if $i is equal to 0, PHP would execute all of the echo statements! If $i is equal to 1, PHP would execute the last two echo statements. You would get the expected behavior ('i equals 2' would be displayed) only if $i is equal to 2. Thus, it is important not to forget break statements (even though you may want to avoid supplying them on purpose under certain circumstances).

In a switch statement, the condition is evaluated only once and the result is compared to each case statement. In an elseif statement, the condition is evaluated again. If your condition is more complicated than a simple compare and/or is in a tight loop, a switch may be faster.

The statement list for a case can also be empty, which simply passes control into the statement list for the next case.

<?php
switch ($i) {
case 
0:
case 
1:
case 
2:
    echo 
"i is less than 3 but not negative";
    break;
case 
3:
    echo 
"i is 3";
}
?>

A special case is the default case. This case matches anything that wasn't matched by the other cases. For example:

<?php
switch ($i) {
    case 
0:
        echo 
"i equals 0";
        break;
    case 
1:
        echo 
"i equals 1";
        break;
    case 
2:
        echo 
"i equals 2";
        break;
    default:
       echo 
"i is not equal to 0, 1 or 2";
}
?>

The case expression may be any expression that evaluates to a simple type, that is, integer or floating-point numbers and strings. Arrays or objects cannot be used here unless they are dereferenced to a simple type.

The alternative syntax for control structures is supported with switches. For more information, see Alternative syntax for control structures.

<?php
switch ($i):
    case 
0:
        echo 
"i equals 0";
        break;
    case 
1:
        echo 
"i equals 1";
        break;
    case 
2:
        echo 
"i equals 2";
        break;
    default:
        echo 
"i is not equal to 0, 1 or 2";
endswitch;
?>

Its possible to use a semicolon instead of a colon after a case like:

<?php
switch($beer)
{
    case 
'tuborg';
    case 
'carlsberg';
    case 
'heineken';
        echo 
'Good choice';
    break;
    default;
        echo 
'Please make a new selection...';
    break;
}
?>



declare

The declare construct is used to set execution directives for a block of code. The syntax of declare is similar to the syntax of other flow control constructs:

declare (directive)
    statement

The directive section allows the behavior of the declare block to be set. Currently only two directives are recognized: the ticks directive (See below for more information on the ticks directive) and the encoding directive (See below for more information on the encoding directive).

Informacja: The encoding directive was added in PHP 5.3.0

The statement part of the declare block will be executed - how it is executed and what side effects occur during execution may depend on the directive set in the directive block.

The declare construct can also be used in the global scope, affecting all code following it (however if the file with declare was included then it does not affect the parent file).

<?php
// these are the same:

// you can use this:
declare(ticks=1) {
    
// entire script here
}

// or you can use this:
declare(ticks=1);
// entire script here
?>

Ticks

A tick is an event that occurs for every N low-level tickable statements executed by the parser within the declare block. The value for N is specified using ticks=N within the declare blocks's directive section.

Not all statements are tickable. Typically, condition expressions and argument expressions are not tickable.

The event(s) that occur on each tick are specified using the register_tick_function(). See the example below for more details. Note that more than one event can occur for each tick.

Przykład #1 Tick usage example

<?php

declare(ticks=1);

// A function called on each tick event
function tick_handler()
{
     echo 
"tick_handler() called\n";
}

register_tick_function('tick_handler');

$a 1;

if (
$a 0) {
      
$a += 2;
      print(
$a);
}

?>

Przykład #2 Ticks usage example

<?php

function tick_handler()
{
  echo 
"tick_handler() called\n";
}

$a 1;
tick_handler();

if (
$a 0) {
      
$a += 2;
      
tick_handler();
      print(
$a);
      
tick_handler();
}
tick_handler();

?>

See also register_tick_function() and unregister_tick_function().

Encoding

A script's encoding can be specified per-script using the encoding directive.

Przykład #3 Declaring an encoding for the script.

<?php
declare(encoding='ISO-8859-1');
// code here
?>

Uwaga

When combined with namespaces, the only legal syntax for declare is declare(encoding='...'); where ... is the encoding value. declare(encoding='...') {} will result in a parse error when combined with namespaces.

The encoding declare value is ignored in PHP 5.3 unless php is compiled with --enable-zend-multibyte. In PHP 6.0, the encoding directive will be used to inform the scanner what encoding the file is created in. Legal values are encoding names such as UTF-8.



return

If called from within a function, the return() statement immediately ends execution of the current function, and returns its argument as the value of the function call. return() will also end the execution of an eval() statement or script file.

If called from the global scope, then execution of the current script file is ended. If the current script file was include()ed or require()ed, then control is passed back to the calling file. Furthermore, if the current script file was include()ed, then the value given to return() will be returned as the value of the include() call. If return() is called from within the main script file, then script execution ends. If the current script file was named by the auto_prepend_file or auto_append_file configuration options in php.ini, then that script file's execution is ended.

For more information, see Returning values.

Informacja: Note that since return() is a language construct and not a function, the parentheses surrounding its arguments are not required. It is common to leave them out, and you actually should do so as PHP has less work to do in this case.

Informacja: If no parameter is supplied, then the parentheses must be omitted and NULL will be returned. Calling return() with parentheses but with no arguments will result in a parse error.

Informacja: You should never use parentheses around your return variable when returning by reference, as this will not work. You can only return variables by reference, not the result of a statement. If you use return ($a); then you're not returning a variable, but the result of the expression ($a) (which is, of course, the value of $a).



require()

require() is identical to include() except upon failure it will also produce a fatal E_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.

See the include() documentation for how this works.



include()

The include() statement includes and evaluates the specified file.

The documentation below also applies to require().

Files are included based on the file path given or, if none is given, the include_path specified. The include() construct will emit a warning if it cannot find a file; this is different behavior from require(), which will emit a fatal error.

If a path is defined (full or relative), the include_path will be ignored altogether. For example, if a filename begins with ../, the parser will look in the parent directory to find the requested file.

For more information on how PHP handles including files and the include path, see the documentation for include_path.

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

Przykład #1 Basic include() example

vars.php
<?php

$color 
'green';
$fruit 'apple';

?>

test.php
<?php

echo "A $color $fruit"// A

include 'vars.php';

echo 
"A $color $fruit"// A green apple

?>

If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function. An exception to this rule are magic constants which are evaluated by the parser before the include occurs.

Przykład #2 Including within functions

<?php

function foo()
{
    global 
$color;

    include 
'vars.php';

    echo 
"A $color $fruit";
}

/* vars.php is in the scope of foo() so     *
* $fruit is NOT available outside of this  *
* scope.  $color is because we declared it *
* as global.                               */

foo();                    // A green apple
echo "A $color $fruit";   // A green

?>

When a file is included, parsing drops out of PHP mode and into HTML mode at the beginning of the target file, and resumes again at the end. For this reason, any code inside the target file which should be executed as PHP code must be enclosed within valid PHP start and end tags.

If "URL fopen wrappers" are enabled in PHP (which they are in the default configuration), you can specify the file to be included using a URL (via HTTP or other supported wrapper - see List of Supported Protocols/Wrappers for a list of protocols) instead of a local pathname. If the target server interprets the target file as PHP code, variables may be passed to the included file using a URL request string as used with HTTP GET. This is not strictly speaking the same thing as including the file and having it inherit the parent file's variable scope; the script is actually being run on the remote server and the result is then being included into the local script.

Ostrzeżenie

PHP w wersji starszej niż 4.3.0, pracujące pod kontrolą systemów Windows, nie obsługują dostępu do zdalnych plików w tej funkcji, nawet jeśli opcja allow_url_fopen jest włączona.

Przykład #3 include() through HTTP

<?php

/* This example assumes that www.example.com is configured to parse .php
* files and not .txt files. Also, 'Works' here means that the variables
* $foo and $bar are available within the included file. */

// Won't work; file.txt wasn't handled by www.example.com as PHP
include 'http://www.example.com/file.txt?foo=1&bar=2';

// Won't work; looks for a file named 'file.php?foo=1&bar=2' on the
// local filesystem.
include 'file.php?foo=1&bar=2';

// Works.
include 'http://www.example.com/file.php?foo=1&bar=2';

$foo 1;
$bar 2;
include 
'file.txt';  // Works.
include 'file.php';  // Works.

?>

Ostrzeżenie

Security warning

Remote file may be processed at the remote server (depending on the file extension and the fact if the remote server runs PHP or not) but it still has to produce a valid PHP script because it will be processed at the local server. If the file from the remote server should be processed there and outputted only, readfile() is much better function to use. Otherwise, special care should be taken to secure the remote script to produce a valid and desired code.

See also Remote files, fopen() and file() for related information.

Handling Returns: It is possible to execute a return() statement inside an included file in order to terminate processing in that file and return to the script which called it. Also, it's possible to return values from included files. You can take the value of the include call as you would a normal function. This is not, however, possible when including remote files unless the output of the remote file has valid PHP start and end tags (as with any local file). You can declare the needed variables within those tags and they will be introduced at whichever point the file was included.

Because include() is a special language construct, parentheses are not needed around its argument. Take care when comparing return value.

Przykład #4 Comparing return value of include

<?php
// won't work, evaluated as include(('vars.php') == 'OK'), i.e. include('')
if (include('vars.php') == 'OK') {
    echo 
'OK';
}

// works
if ((include 'vars.php') == 'OK') {
    echo 
'OK';
}
?>

Przykład #5 include() and the return() statement

return.php
<?php

$var 
'PHP';

return 
$var;

?>

noreturn.php
<?php

$var 
'PHP';

?>

testreturns.php
<?php

$foo 
= include 'return.php';

echo 
$foo// prints 'PHP'

$bar = include 'noreturn.php';

echo 
$bar// prints 1

?>

$bar is the value 1 because the include was successful. Notice the difference between the above examples. The first uses return() within the included file while the other does not. If the file can't be included, FALSE is returned and E_WARNING is issued.

If there are functions defined in the included file, they can be used in the main file independent if they are before return() or after. If the file is included twice, PHP 5 issues fatal error because functions were already declared, while PHP 4 doesn't complain about functions defined after return(). It is recommended to use include_once() instead of checking if the file was already included and conditionally return inside the included file.

Another way to "include" a PHP file into a variable is to capture the output by using the Output Control Functions with include(). For example:

Przykład #6 Using output buffering to include a PHP file into a string

<?php
$string 
get_include_contents('somefile.php');

function 
get_include_contents($filename) {
    if (
is_file($filename)) {
        
ob_start();
        include 
$filename;
        
$contents ob_get_contents();
        
ob_end_clean();
        return 
$contents;
    }
    return 
false;
}

?>

In order to automatically include files within scripts, see also the auto_prepend_file and auto_append_file configuration options in php.ini.

Informacja: Ponieważ jest to element składni języka a nie funkcja, nie może być on wywoływany używając zmiennych funkcji

See also require(), require_once(), include_once(), get_included_files(), readfile(), virtual(), and include_path.



require_once()

The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.

See the include_once() documentation for information about the _once behaviour, and how it differs from its non _once siblings.



include_once()

The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.

include_once() may be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, so in this case it may help avoid problems such as function redefinitions, variable value reassignments, etc.

See the include() documentation for information about how this function works.

Informacja: With PHP 4, _once functionality differs with case-insensitive operating systems (like Windows) so for example:

Przykład #1 include_once() with a case insensitive OS in PHP 4

<?php
include_once "a.php"// this will include a.php
include_once "A.php"// this will include a.php again! (PHP 4 only)
?>


This behaviour changed in PHP 5, so for example with Windows the path is normalized first so that C:\PROGRA~1\A.php is realized the same as C:\Program Files\a.php and the file is included just once.



goto

The goto operator can be used to jump to another section in the program. The target point is specified by a label followed by a colon, and the instruction is given as goto followed by the desired target label. This is not a full unrestricted goto. The target label must be within the same file and context, meaning that you cannot jump out of a function or method, nor can you jump into one. You also cannot jump into any sort of loop or switch structure. You may jump out of these, and a common use is to use a goto in place of a multi-level break.

Przykład #1 goto example

<?php
goto a;
echo 
'Foo';
 
a:
echo 
'Bar';
?>

Powyższy przykład wyświetli:

Bar

Przykład #2 goto loop example

<?php
for($i=0,$j=50$i<100$i++) {
  while(
$j--) {
    if(
$j==17) goto end
  }  
}
echo 
"i = $i";
end:
echo 
'j hit 17';
?>

Powyższy przykład wyświetli:

j hit 17

Przykład #3 This will not work

<?php
goto loop;
for(
$i=0,$j=50$i<100$i++) {
  while(
$j--) {
    
loop:
  }
}
echo 
"$i = $i";
?>

Powyższy przykład wyświetli:

Fatal error: 'goto' into loop or switch statement is disallowed in
script on line 2

Informacja: The goto operator is available as of PHP 5.3.

Image courtesy of » xkcd




Funkcje

Spis treści


Funkcje definiowane przez użytkownika

Funkcja może być definiowana przy użyciu następującej składni:

Przykład #1 Pseudokod demonstrujący użycie funkcji

<?php
function foo($arg_1$arg_2/* ..., */ $arg_n)
{
    echo 
"Przykładowa funkcja.\n";
    return 
$retval;
}
?>

Każdy poprawny kod może być użyty wewnątrz funkcji, łącznie z definicjami innych funkcji i klas.

Nazwy funkcji obowiązują identyczne zasady, jak w przypadku wszystkich innych etykiet w PHP. Poprawna nazwa funkcji zaczyna się od litery lub podkreślnika, po których następuje dowolna ilość liter, cyfr i podkreślników. Jako wyrażenie regularne, określone zostałoby to następująco: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.

Wskazówka

Zobacz także Userland Naming Guide.

Funkcje nie muszą być zdefiniowane przed odniesieniem się do nich, oprócz sytuacji, w których funkcja jest zdefiniowana warunkowo jak w dwóch poniższych przykładach.

Kiedy funkcja jest zdefiniowana warunkowo, jak w dwóch poniższych przykładach, jej definicja musi być przetworzona przed jej wywołaniem.

Przykład #2 Funkcje zdefiniowane warunkowo

<?php

$makefoo 
true;

/* Nie możemy tu wywołać foo() 
   ponieważ jeszcze nie istnieje,
   ale możemy wywołać bar() */

bar();

if (
$makefoo) {
  function 
foo()
  {
    echo 
"Nie istnieję, dopóki nie zostanę wykonana.\n";
  }
}

/* Teraz możemy bezpiecznie wywołać foo()
   ponieważ $makefoo ma wartość logiczną 1 */

if ($makefoofoo();

function 
bar() 
{
  echo 
"Istnieję od początku działania skryptu.\n";
}

?>

Przykład #3 Funkcje wewnątrz funkcji

<?php
function foo() 
{
  function 
bar() 
  {
    echo 
"Nie istnieję, dopóki foo() nie jest wywołana.\n";
  }
}

/* Nie możemy tu wywołać bar() 
   ponieważ jeszcze nie istnieje. */

foo();

/* Teraz możemy wywołać bar(),
   wykonanie foo() spodowało
   że jest to już możliwe. */

bar();

?>

Wszystkie funkcje i klasy w PHP mają globalny zasięg - mogą być wykonane poza funkcją, nawet jeśli były zdefiniowane wewnątrz niej, i odwrotnie.

PHP nie umożliwia przeładowywania funkcji, nie jest też możliwe usunięcie jej definicji lub redefiniowanie poprzednio określonych funkcji.

Informacja: Nazwy funkcji nie rozróżniają wielkości liter, ale dobrym zwyczajem jest wywoływanie ich w formie, w której zostały zdefiniowane.

Zarówno przyjmowanie różnej ilości argumentów jak i wartości domyślne argumentów są obsługiwane w funkcjach. Zobacz także opisy funkcji func_num_args(), func_get_arg(), i func_get_args() aby uzyskać więcej informacji.

W PHP jest możliwe wykonywanie rekurencyjnych funkcji. Unikaj jednak wywoływania rekurencyjnych funkcji/metod które osiągają poziom rekurencji większy niż 100-200, ponieważ może to spowodować przepełnienie stosu i zakończenie wykonywania skryptu.

Przykład #4 Funkcje rekurencyjne

<?php
function recursion($a)
{
    if (
$a 20) {
        echo 
"$a\n";
        
recursion($a 1);
    }
}
?>



Argumenty funkcji

Dane mogą być przekazywane do funkcji przez listę argumentów, która jest listą oddzielonych przecinkami wyrażeń.

PHP obsługuje podawanie argumentów jako wartości (domyślnie), przez referencję, oraz domyślne wartości argumentów. Różna ilość argumentów także jest obsługiwana, zobacz opisy funkcji func_num_args(), func_get_arg(), i func_get_args() aby dowiedzieć się więcej.

Przykład #1 Tablica jako argument funkcji

<?php
function takes_array($input)
{
    echo 
"$input[0] + $input[1] = "$input[0]+$input[1];
}
?>

Podawanie argumentów jako referencji

Domyślnie, argumenty funkcji podawane są jako wartości (kiedy wartość argumentu wewnątrz funkcji się zmienia, nie wpływa to na wartość zmiennej poza funkcją). Aby pozwolić funkcji na modyfikację jej jej argumentów, muszą one być podane przez referencję.

Aby argument zawsze był podawany przez referencję, poprzedź nazwę argumentu znakiem (&) w definicji funkcji:

Przykład #2 Podawanie parametrów funkcji przez referencję

<?php
function add_some_extra(&$string)
{
    
$string .= 'i coś ekstra.';
}
$str 'To jest ciąg znaków, ';
add_some_extra($str);
echo 
$str;    // wypisuje 'To jest ciąg znaków, i coś ekstra.'
?>

Domyślne wartości argumentów

Można zdefiniować domyślne wartości skalarne argumentów w stylu C++ następująco:

Przykład #3 Użycie domyślnych wartości argumentów w funkcji

<?php
function makecoffee($type "cappuccino")
{
    return 
"Robię kubek $type.\n";
}
echo 
makecoffee();
echo 
makecoffee(null);
echo 
makecoffee("espresso");
?>

Wynikiem powyższego kodu jest:


Robię kubek cappuccino.
Robię kubek .
Robię kubek espresso.

PHP pozwala również na użycie tablic(array) i specjalnego typu NULL jako domyślnych wartości, na przykład:

Przykład #4 Użycie nie-skalarnych typów jako domyślnych wartości

<?php
function makecoffee($types = array("cappuccino"), $coffeeMaker NULL)
{
    
$device is_null($coffeeMaker) ? "rąk" $coffeeMaker;
    return 
"Robię kubek ".join(", "$types)." za pomocą $device.\n";
}
echo 
makecoffee();
echo 
makecoffee(array("cappuccino""lavazza"), "teapot");
?>

Domyślna wartość musi być stałym wyrażeniem, a nie na przykład zmienną, członkiem klasy czy wywołaniem funkcji.

Zauważ, że przy użyciu domyślnych wartości, powinne one być zdefiniowane po prawej stronie nie-domyślnych argumentów; W przeciwnym wypadku, nie zadziała to jak powinno. Na przykład:

Przykład #5 Niepoprawne użycie domyślnych wartości argumentów

<?php
function makeyogurt($type "acidophilus"$flavour)
{
    return 
"Making a bowl of $type $flavour.\n";
}
 
echo 
makeyogurt("raspberry");   // nie zadziała tak, jak oczekujemy
?>

Wynik powyższego skryptu to:


Warning: Missing argument 2 in call to makeyogurt() in
/usr/local/etc/httpd/htdocs/phptest/functest.html on line 41
Making a bowl of raspberry .

Porównaj go teraz z:

Przykład #6 Poprawne użycie domyślnych wartości argumentów

<?php
function makeyogurt($flavour$type "jogurtu")
{
    return 
"Robię miskę $type $flavour.\n";
}
 
echo 
makeyogurt("malinowego");   // działa zgodnie z naszymi oczekiwaniami
?>

Wynikiem działania powyższego przykładu jest:


Robię miskę malinowego jogurtu.

Informacja: Od PHP 5 domyślne wartości argumentów mogą być podawane przez referencję.

Podawanie różnej ilości argumentów

Od PHP 4 możliwe jest użycie różnej ilości argumentów dla funkcji definiowanych przez użytkownika. Jest to dosyć proste przy użyciu funkcji func_num_args(), func_get_arg() i func_get_args().

Nie wymaga to żadnej specjalnej składni, listy argumentów w dalszym ciągu podawane są przy definiowaniu funkcji i zachowują się normalnie.



Zwracanie wartości

Wartości zwracane są przy użyciu opcjonalnego wyrażenia return. Wszystkie typy mogą być zwracane, łącznie z tablicami i obiektami. Powoduje to natychmiastowe zakończenie wykonywania funkcji i wznowienie wykonywania skryptu od linijki w której funkcja została wywołana. Zobacz return() aby uzyskać więcej informacji.

Przykład #1 Użycie return()

<?php
function square($num)
{
    return 
$num $num;
}
echo 
square(4);   // wypisuje '16'.
?>

Funkcjia nie może zwracać wielu wartości, ale podobny efekt może zostać osiągnięty poprzez zwracanie tablicy.

Przykład #2 Zwracanie tablicy

<?php
function small_numbers()
{
    return array (
012);
}
list (
$zero$one$two) = small_numbers();
?>

Aby zwrócić referencję, użyj operatora & zarówno w deklaracji funkcji jak i podczas przypisywania zwracanej wartości zmiennej:

Przykład #3 Zwracanie referencji

<?php
function &returns_reference()
{
    return 
$someref;
}

$newref =& returns_reference();
?>

Aby uzyskać więcej informacji o referencjach, przejdź do Wyjaśnienie Referencji.



Funkcje zmiennych

PHP obsługuje opcję funkcji zmiennych. Oznacza to, że jeśli do nazwy zmiennej dodane są nawiasy, PHP postara się znaleźć funkcję o nazwie takiej jak wartość zmiennej i spróbuje ją wykonać. Między innymi, może to służyć do zaimplementowania tzw. callbacks, tablic funkcji, a także wielu innych rzeczy.

Funkcje zmiennych nie zadziałają z takimi elementami języka jak echo(), print(), unset(), isset(), empty(), include(), require() i podobnymi. Używaj okrężnych funkcji aby skorzystać z któregoś z powyższych elementów języka jako funkcji zmiennych.

Przykład #1 Przykład funkcji zmiennych

<?php
function foo() {
    echo 
"W foo()<br />\n";
}

function 
bar($arg '')
{
    echo 
"W bar(); argumentem było '$arg'.<br />\n";
}

// To jest funkcja okrężna dla "echo"
function echoit($string)
{
    echo 
$string;
}

$func 'foo';
$func();        // Wywołuje foo()

$func 'bar';
$func('test');  // Wywołuje bar()

$func 'echoit';
$func('test');  // Wywołuje echoit()
?>

Jako funkcje zmiennych mogą być także wywoływane metody obiektów.

Przykład #2 Przykład metod zmiennych

<?php
class Foo
{
    function 
Zmienna()
    {
        
$name 'Bar';
        
$this->$name(); // Wywołuje metodę Bar()
    
}
    
    function 
Bar()
    {
        echo 
"To jest Bar";
    }
}

$foo = new Foo();
$funcname "Zmienna";
$foo->$funcname();  // Wywołuje $foo->Zmienna()

?>

Zobacz także call_user_func(), zmienne zmienne oraz function_exists().



Wewnętrzne (wbudowane) funkcje

PHP zapewnia wiele wbudowanych funkcji i konstrukcji. Istnieją także funkcje wymagające wkompilowania specyficznych rozszerzeń PHP, w przeciwnym wypadku wywołanie ich skutkuje błędami "undefined function". Na przykładd, aby użyć funkcji obrazków takich jak imagecreatetruecolor(), PHP musi być skompilowane z obsługą GD. Aby użyć mysql_connect(), PHP musi być skompilowane z obsługą MySQL. Jest wiele funkcji wbudowanych w rdzeń każdej wersji PHP, takich jak funkcje typu string oraz zmiennych. Wywołanie to phpinfo() lub get_loaded_extensions() pokaże, które rozszerzenia PHP są załadowane. Zauważ, że wiele rozszerzeń jest domyślnie załadowanych i podręcznik PHP jest podzielony według rozszerzeń. Zobacz rozdziały o konfiguracji, instalacji, a także te dotyczące poszczególnych rozszerzeń, aby dowiedzieć się jak uruchomić PHP.

Czytanie i rozumienie prototypów funkcji wyjaśnione jest w rozdziale podręcznika zatytułowanym jak czytać definicje funkcji. Ważne jest zrozumienie, czy funkcja zwraca konkretną wartość czy operuje bezpośrednio na podanej zmiennej. Na przykład, str_replace() zwróci zmodyfikowany obiekt typu string, podczas gdy usort() pracuje bezpośrednio na podanej zmiennej. Każda funkcja posiada swoją stronę w podręczniku PHP, która podaje informacje takie jak parametry funkcji, jej zachowanie, wartości zwracane po poprawnym wykonaniu i w przypadku błędu, a także dane dotyczące jej dostępności. Znanie tych ważnych (chociaż często drobnych) różnic jest kluczowe podczas pisania kodu w PHP.

Informacja: Jeśli parametry podane funkcji nie są takie, jak spodziewane, na przykład tablica(array) podawana jest w miejscu, gdzie oczekiwana jest zmienna typu string, wartość zwracana przez funkcję nie jest zdefiniowana. W takim wypadku funkcja prawdopodobnie zwróci NULL ale jest to jedynie konwencja a nie zasada, na której można się opierać.

Zobacz także function_exists(), the function reference, get_extension_funcs() i dl().

» Anonymous Functions




Classes and Objects

Spis treści


Introduction

Starting with PHP 5, the object model was rewritten to allow for better performance and more features. This was a major change from PHP 4. PHP 5 has a full object model.

Among the features in PHP 5 are the inclusions of visibility, abstract and final classes and methods, additional magic methods, interfaces, cloning and typehinting.

PHP treats objects in the same way as references or handles, meaning that each variable contains an object reference rather than a copy of the entire object. See Objects and References

Wskazówka

Zobacz także Userland Naming Guide.



The Basics

class

Every class definition begins with the keyword class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the class's properties and methods.

The class name can be any valid label which is a not a PHP reserved word. A valid class name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.

A class may contain its own constants, variables (called "properties"), and functions (called "methods").

Przykład #1 Simple Class definition

<?php
class SimpleClass
{
    
// property declaration
    
public $var 'a default value';

    
// method declaration
    
public function displayVar() {
        echo 
$this->var;
    }
}
?>

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

Przykład #2 Some examples of the $this pseudo-variable

<?php
class A
{
    function 
foo()
    {
        if (isset(
$this)) {
            echo 
'$this is defined (';
            echo 
get_class($this);
            echo 
")\n";
        } else {
            echo 
"\$this is not defined.\n";
        }
    }
}

class 
B
{
    function 
bar()
    {
        
// Note: the next line will issue a warning if E_STRICT is enabled.
        
A::foo();
    }
}

$a = new A();
$a->foo();

// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
$b = new B();
$b->bar();

// Note: the next line will issue a warning if E_STRICT is enabled.
B::bar();
?>

Powyższy przykład wyświetli:

$this is defined (A)
$this is not defined.
$this is defined (B)
$this is not defined.

new

To create an instance of a class, a new object must be created and assigned to a variable. An object will always be assigned when creating a new object unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).

Przykład #3 Creating an instance

<?php
$instance 
= new SimpleClass();

// This can also be done with a variable:
$className 'Foo';
$instance = new $className(); // Foo()
?>

In the class context, it is possible to create a new object by new self and new parent.

When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A copy of an already created object can be made by cloning it.

Przykład #4 Object Assignment

<?php
$assigned   
=  $instance;
$reference  =& $instance;

$instance->var '$assigned will have this value';

$instance null// $instance and $reference become null

var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>

Powyższy przykład wyświetli:

NULL
NULL
object(SimpleClass)#1 (1) {
   ["var"]=>
     string(30) "$assigned will have this value"
}

extends

A class can inherit the methods and properties of another class by using the keyword extends in the class declaration. It is not possible to extend multiple classes; a class can only inherit from one base class.

The inherited methods and properties can be overridden by redeclaring them with the same name defined in the parent class. However, if the parent class has defined a method as final, that method may not be overridden. It is possible to access the overridden methods or static properties by referencing them with parent::.

Przykład #5 Simple Class Inheritance

<?php
class ExtendClass extends SimpleClass
{
    
// Redefine the parent method
    
function displayVar()
    {
        echo 
"Extending class\n";
        
parent::displayVar();
    }
}

$extended = new ExtendClass();
$extended->displayVar();
?>

Powyższy przykład wyświetli:

Extending class
a default value


Properties

Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

See Visibility for more information on the meanings of public, protected, and private.

Informacja: In order to maintain backward compatibility with PHP 4, PHP 5 will still accept the use of the keyword var in property declarations instead of (or in addition to) public, protected, or private. However, var is no longer required. In versions of PHP from 5.0 to 5.1.3, the use of var was considered deprecated and would issue an E_STRICT warning, but since PHP 5.1.3 it is no longer deprecated and does not issue the warning.
If you declare a property using var instead of one of public, protected, or private, then PHP 5 will treat the property as if it had been declared as public.

Within class methods the properties, constants, and methods may be accessed by using the form $this->property (where property is the name of the property) unless the access is to a static property within the context of a static class method, in which case it is accessed using the form self::$property. See Static Keyword for more information.

The pseudo-variable $this is available inside any class method when that method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

Przykład #1 property declarations

<?php
class SimpleClass
{
   
// invalid property declarations:
   
public $var1 'hello ' 'world';
   public 
$var2 = <<<EOD
hello world
EOD;
   public 
$var3 1+2;
   public 
$var4 self::myStaticMethod();
   public 
$var5 $myVar;

   
// valid property declarations:
   
public $var6 myConstant;
   public 
$var7 = array(truefalse);

   
// This is allowed only in PHP 5.3.0 and later.
   
public $var8 = <<<'EOD'
hello world
EOD;
}
?>

Informacja: There are some nice functions to handle classes and objects. You might want to take a look at the Class/Object Functions.

Unlike heredocs, nowdocs can be used in any static data context, including property declarations.

Przykład #2 Example of using a nowdoc to initialize a property

<?php
class foo {
   
// As of PHP 5.3.0
   
public $bar = <<<'EOT'
bar
EOT;
}
?>

Informacja: Nowdoc support was added in PHP 5.3.0.



Class Constants

It is possible to define constant values on a per-class basis remaining the same and unchangeable. Constants differ from normal variables in that you don't use the $ symbol to declare or use them.

The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.

Its also possible for interfaces to have constants. Look at the interface documentation for examples.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

Przykład #1 Defining and using a constant

<?php
class MyClass
{
    const 
constant 'constant value';

    function 
showConstant() {
        echo  
self::constant "\n";
    }
}

echo 
MyClass::constant "\n";

$classname "MyClass";
echo 
$classname::constant "\n"// As of PHP 5.3.0

$class = new MyClass();
$class->showConstant();

echo 
$class::constant."\n"// As of PHP 5.3.0
?>

Przykład #2 Static data example

<?php
class foo {
    
// As of PHP 5.3.0
    
const bar = <<<'EOT'
bar
EOT;
}
?>

Unlike heredocs, nowdocs can be used in any static data context.

Informacja: Nowdoc support was added in PHP 5.3.0.



Autoloading Classes

Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).

In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class/interface which hasn't been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.

Informacja: Exceptions thrown in __autoload function cannot be caught in the catch block and results in a fatal error.

Informacja: Autoloading is not available if using PHP in CLI interactive mode.

Informacja: If the class name is used e.g. in call_user_func() then it can contain some dangerous characters such as ../. It is recommended to not use the user-input in such functions or at least verify the input in __autoload().

Przykład #1 Autoload example

This example attempts to load the classes MyClass1 and MyClass2 from the files MyClass1.php and MyClass2.php respectively.

<?php
function __autoload($class_name) {
    require_once 
$class_name '.php';
}

$obj  = new MyClass1();
$obj2 = new MyClass2(); 
?>

Przykład #2 Autoload other example

This example attempts to load the interface ITest.

<?php

function __autoload($name) {
    
var_dump($name);
}

class 
Foo implements ITest {
}

/*
string(5) "ITest"

Fatal error: Interface 'ITest' not found in ...
*/
?>



Constructors and Destructors

Constructor

void __construct ([ mixed $args [, $... ]] )

PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.

Informacja: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.

Przykład #1 using new unified constructors

<?php
class BaseClass {
   function 
__construct() {
       print 
"In BaseClass constructor\n";
   }
}

class 
SubClass extends BaseClass {
   function 
__construct() {
       
parent::__construct();
       print 
"In SubClass constructor\n";
   }
}

$obj = new BaseClass();
$obj = new SubClass();
?>

For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.

Destructor

void __destruct ( void )

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence.

Przykład #2 Destructor Example

<?php
class MyDestructableClass {
   function 
__construct() {
       print 
"In constructor\n";
       
$this->name "MyDestructableClass";
   }

   function 
__destruct() {
       print 
"Destroying " $this->name "\n";
   }
}

$obj = new MyDestructableClass();
?>

Like constructors, parent destructors will not be called implicitly by the engine. In order to run a parent destructor, one would have to explicitly call parent::__destruct() in the destructor body.

Informacja: Destructors called during the script shutdown have HTTP headers already sent. The working directory in the script shutdown phase can be different with some SAPIs (e.g. Apache).

Informacja: Attempting to throw an exception from a destructor (called in the time of script termination) causes a fatal error.



Visibility

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

Property Visibility

Class properties must be defined as public, private, or protected. If declared using var without an explicit visibility keyword, the property will be defined as public.

Przykład #1 Property declaration

<?php
/**
 * Define MyClass
 */
class MyClass
{
    public 
$public 'Public';
    protected 
$protected 'Protected';
    private 
$private 'Private';

    function 
printHello()
    {
        echo 
$this->public;
        echo 
$this->protected;
        echo 
$this->private;
    }
}

$obj = new MyClass();
echo 
$obj->public// Works
echo $obj->protected// Fatal Error
echo $obj->private// Fatal Error
$obj->printHello(); // Shows Public, Protected and Private


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    
// We can redeclare the public and protected method, but not private
    
protected $protected 'Protected2';

    function 
printHello()
    {
        echo 
$this->public;
        echo 
$this->protected;
        echo 
$this->private;
    }
}

$obj2 = new MyClass2();
echo 
$obj2->public// Works
echo $obj2->private// Undefined
echo $obj2->protected// Fatal Error
$obj2->printHello(); // Shows Public, Protected2, Undefined

?>

Informacja: The PHP 4 method of declaring a variable with the var keyword is still supported for compatibility reasons (as a synonym for the public keyword). In PHP 5 before 5.1.3, its usage would generate an E_STRICT warning.

Method Visibility

Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public.

Przykład #2 Method Declaration

<?php
/**
 * Define MyClass
 */
class MyClass
{
    
// Declare a public constructor
    
public function __construct() { }

    
// Declare a public method
    
public function MyPublic() { }

    
// Declare a protected method
    
protected function MyProtected() { }

    
// Declare a private method
    
private function MyPrivate() { }

    
// This is public
    
function Foo()
    {
        
$this->MyPublic();
        
$this->MyProtected();
        
$this->MyPrivate();
    }
}

$myclass = new MyClass;
$myclass->MyPublic(); // Works
$myclass->MyProtected(); // Fatal Error
$myclass->MyPrivate(); // Fatal Error
$myclass->Foo(); // Public, Protected and Private work


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    
// This is public
    
function Foo2()
    {
        
$this->MyPublic();
        
$this->MyProtected();
        
$this->MyPrivate(); // Fatal Error
    
}
}

$myclass2 = new MyClass2;
$myclass2->MyPublic(); // Works
$myclass2->Foo2(); // Public and Protected work, not Private

class Bar 
{
    public function 
test() {
        
$this->testPrivate();
        
$this->testPublic();
    }

    public function 
testPublic() {
        echo 
"Bar::testPublic\n";
    }
    
    private function 
testPrivate() {
        echo 
"Bar::testPrivate\n";
    }
}

class 
Foo extends Bar 
{
    public function 
testPublic() {
        echo 
"Foo::testPublic\n";
    }
    
    private function 
testPrivate() {
        echo 
"Foo::testPrivate\n";
    }
}

$myFoo = new foo();
$myFoo->test(); // Bar::testPrivate 
                // Foo::testPublic
?>



Object Inheritance

Inheritance is a well-esablished programming principle, and PHP makes use of this principle in its object model. This principle will affect the way many classes and objects relate to one another.

For example, when you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.

This is useful for defining and abstracting functionality, and permits the implementation of additional functionality in similar objects without the need to reimplement all of the shared functionality.

Przykład #1 Inheritance Example

<?php

class foo
{
    public function 
printItem($string)
    {
        echo 
'Foo: ' $string PHP_EOL;
    }
    
    public function 
printPHP()
    {
        echo 
'PHP is great.' PHP_EOL;
    }
}

class 
bar extends foo
{
    public function 
printItem($string)
    {
        echo 
'Bar: ' $string PHP_EOL;
    }
}

$foo = new foo();
$bar = new bar();
$foo->printItem('baz'); // Output: 'Foo: baz'
$foo->printPHP();       // Output: 'PHP is great' 
$bar->printItem('baz'); // Output: 'Bar: baz'
$bar->printPHP();       // Output: 'PHP is great'

?>


Scope Resolution Operator (::)

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.

When referencing these items from outside the class definition, use the name of the class.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

Paamayim Nekudotayim would, at first, seem like a strange choice for naming a double-colon. However, while writing the Zend Engine 0.5 (which powers PHP 3), that's what the Zend team decided to call it. It actually does mean double-colon - in Hebrew!

Przykład #1 :: from outside the class definition

<?php
class MyClass {
    const 
CONST_VALUE 'A constant value';
}

$classname 'MyClass';
echo 
$classname::CONST_VALUE// As of PHP 5.3.0

echo MyClass::CONST_VALUE;
?>

Two special keywords self and parent are used to access properties or methods from inside the class definition.

Przykład #2 :: from inside the class definition

<?php
class OtherClass extends MyClass
{
    public static 
$my_static 'static var';

    public static function 
doubleColon() {
        echo 
parent::CONST_VALUE "\n";
        echo 
self::$my_static "\n";
    }
}

$classname 'OtherClass';
echo 
$classname::doubleColon(); // As of PHP 5.3.0

OtherClass::doubleColon();
?>

When an extending class overrides the parents definition of a method, PHP will not call the parent's method. It's up to the extended class on whether or not the parent's method is called. This also applies to Constructors and Destructors, Overloading, and Magic method definitions.

Przykład #3 Calling a parent's method

<?php
class MyClass
{
    protected function 
myFunc() {
        echo 
"MyClass::myFunc()\n";
    }
}

class 
OtherClass extends MyClass
{
    
// Override parent's definition
    
public function myFunc()
    {
        
// But still call the parent function
        
parent::myFunc();
        echo 
"OtherClass::myFunc()\n";
    }
}

$class = new OtherClass();
$class->myFunc();
?>


Static Keyword

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can).

For compatibility with PHP 4, if no visibility declaration is used, then the property or method will be treated as if it was declared as public.

Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.

Static properties cannot be accessed through the object using the arrow operator ->.

Calling non-static methods statically generates an E_STRICT level warning.

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

Przykład #1 Static property example

<?php
class Foo
{
    public static 
$my_static 'foo';

    public function 
staticValue() {
        return 
self::$my_static;
    }
}

class 
Bar extends Foo
{
    public function 
fooStatic() {
        return 
parent::$my_static;
    }
}


print 
Foo::$my_static "\n";

$foo = new Foo();
print 
$foo->staticValue() . "\n";
print 
$foo->my_static "\n";      // Undefined "Property" my_static 

print $foo::$my_static "\n";
$classname 'Foo';
print 
$classname::$my_static "\n"// As of PHP 5.3.0

print Bar::$my_static "\n";
$bar = new Bar();
print 
$bar->fooStatic() . "\n";
?>

Przykład #2 Static method example

<?php
class Foo {
    public static function 
aStaticMethod() {
        
// ...
    
}
}

Foo::aStaticMethod();
$classname 'Foo';
$classname::aStaticMethod(); // As of PHP 5.3.0
?>


Class Abstraction

PHP 5 introduces abstract classes and methods. It is not allowed to create an instance of a class that has been defined as abstract. Any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature they cannot define the implementation.

When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.

Przykład #1 Abstract class example

<?php
abstract class AbstractClass
{
    
// Force Extending class to define this method
    
abstract protected function getValue();
    abstract protected function 
prefixValue($prefix);

    
// Common method
    
public function printOut() {
        print 
$this->getValue() . "\n";
    }
}

class 
ConcreteClass1 extends AbstractClass
{
    protected function 
getValue() {
        return 
"ConcreteClass1";
    }

    public function 
prefixValue($prefix) {
        return 
"{$prefix}ConcreteClass1";
    }
}

class 
ConcreteClass2 extends AbstractClass
{
    public function 
getValue() {
        return 
"ConcreteClass2";
    }

    public function 
prefixValue($prefix) {
        return 
"{$prefix}ConcreteClass2";
    }
}

$class1 = new ConcreteClass1;
$class1->printOut();
echo 
$class1->prefixValue('FOO_') ."\n";

$class2 = new ConcreteClass2;
$class2->printOut();
echo 
$class2->prefixValue('FOO_') ."\n";
?>

Powyższy przykład wyświetli:

ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2

Old code that has no user-defined classes or functions named 'abstract' should run without modifications.



Object Interfaces

Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.

Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.

All methods declared in an interface must be public, this is the nature of an interface.

implements

To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.

Informacja: A class cannot implement two interfaces that share function names, since it would cause ambiguity.

Informacja: Interfaces can be extended like classes using the extends operator.

Informacja: The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error.

Constants

Its possible for interfaces to have constants. Interface constants works exactly like class constants. They cannot be overridden by a class/interface that inherits it.

Przykłady

Przykład #1 Interface example

<?php

// Declare the interface 'iTemplate'
interface iTemplate
{
    public function 
setVariable($name$var);
    public function 
getHtml($template);
}

// Implement the interface
// This will work
class Template implements iTemplate
{
    private 
$vars = array();
  
    public function 
setVariable($name$var)
    {
        
$this->vars[$name] = $var;
    }
  
    public function 
getHtml($template)
    {
        foreach(
$this->vars as $name => $value) {
            
$template str_replace('{' $name '}'$value$template);
        }
 
        return 
$template;
    }
}

// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
    private 
$vars = array();
  
    public function 
setVariable($name$var)
    {
        
$this->vars[$name] = $var;
    }
}
?>

Przykład #2 Extendable Interfaces

<?php
interface a
{
    public function 
foo();
}

interface 
extends a
{
    public function 
baz(Baz $baz);
}

// This will work
class implements b
{
    public function 
foo()
    {
    }

    public function 
baz(Baz $baz)
    {
    }
}

// This will not work and result in a fatal error
class implements b
{
    public function 
foo()
    {
    }

    public function 
baz(Foo $foo)
    {
    }
}
?>

Przykład #3 Multiple interface inheritance

<?php
interface a
{
    public function 
foo();
}

interface 
b
{
    public function 
bar();
}

interface 
extends ab
{
    public function 
baz();
}

class 
implements c
{
    public function 
foo()
    {
    }

    public function 
bar()
    {
    }

    public function 
baz()
    {
    }
}
?>

Przykład #4 Interfaces with constants

<?php
interface a
{
    const 
'Interface constant';
}

// Prints: Interface constant
echo a::b;


// This will however not work because its not allowed to 
// override constants. This is the same concept as with 
// class constants
class implements a
{
    const 
'Class constant';
}
?>

An interface, together with type-hinting, provides a good way to make sure that a particular object contains particular methods. See instanceof operator and type hinting.



Overloading

Overloading in PHP provides means to dynamically "create" properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types.

The overloading methods are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope. The rest of this section will use the terms "inaccessible properties" and "inaccessible methods" to refer to this combination of declaration and visibility.

All overloading methods must be defined as public.

Informacja: None of the arguments of these magic methods can be passed by reference.

Informacja: PHP's interpretation of "overloading" is different than most object oriented languages. Overloading traditionally provides the ability to have multiple methods with the same name but different quantities and types of arguments.

Rejestr zmian

Wersja Opis
5.3.0 Added __callStatic(). Added warning to enforce public visibility and non-static declaration.
5.1.0 Added __isset() and __unset().

Property overloading

void __set ( string $name , mixed $value )
mixed __get ( string $name )
bool __isset ( string $name )
void __unset ( string $name )

__set() is run when writing data to inaccessible properties.

__get() is utilized for reading data from inaccessible properties.

__isset() is triggered by calling isset() or empty() on inaccessible properties.

__unset() is invoked when unset() is used on inaccessible properties.

The $name argument is the name of the property being interacted with. The __set() method's $value argument specifies the value the $name'ed property should be set to.

Property overloading only works in object context. These magic methods will not be triggered in static context. Therefore these methods can not be declared static.

Informacja: The return value of __set() is ignored because of the way PHP processes the assignment operator. Similarly, __get() is never called when chaining assignemnts together like this:

 $a = $obj->b = 8; 

Przykład #1 Overloading properties via the __get(), __set(), __isset() and __unset() methods

<?php
class PropertyTest {
    
/**  Location for overloaded data.  */
    
private $data = array();

    
/**  Overloading not used on declared properties.  */
    
public $declared 1;

    
/**  Overloading only used on this when accessed outside the class.  */
    
private $hidden 2;

    public function 
__set($name$value) {
        echo 
"Setting '$name' to '$value'\n";
        
$this->data[$name] = $value;
    }

    public function 
__get($name) {
        echo 
"Getting '$name'\n";
        if (
array_key_exists($name$this->data)) {
            return 
$this->data[$name];
        }

        
$trace debug_backtrace();
        
trigger_error(
            
'Undefined property via __get(): ' $name .
            
' in ' $trace[0]['file'] .
            
' on line ' $trace[0]['line'],
            
E_USER_NOTICE);
        return 
null;
    }

    
/**  As of PHP 5.1.0  */
    
public function __isset($name) {
        echo 
"Is '$name' set?\n";
        return isset(
$this->data[$name]);
    }

    
/**  As of PHP 5.1.0  */
    
public function __unset($name) {
        echo 
"Unsetting '$name'\n";
        unset(
$this->data[$name]);
    }

    
/**  Not a magic method, just here for example.  */
    
public function getHidden() {
        return 
$this->hidden;
    }
}


echo 
"<pre>\n";

$obj = new PropertyTest;

$obj->1;
echo 
$obj->"\n\n";

var_dump(isset($obj->a));
unset(
$obj->a);
var_dump(isset($obj->a));
echo 
"\n";

echo 
$obj->declared "\n\n";

echo 
"Let's experiment with the private property named 'hidden':\n";
echo 
"Privates are visible inside the class, so __get() not used...\n";
echo 
$obj->getHidden() . "\n";
echo 
"Privates not visible outside of class, so __get() is used...\n";
echo 
$obj->hidden "\n";
?>

Powyższy przykład wyświetli:

Setting 'a' to '1'
Getting 'a'
1

Is 'a' set?
bool(true)
Unsetting 'a'
Is 'a' set?
bool(false)

1

Let's experiment with the private property named 'hidden':
Privates are visible inside the class, so __get() not used...
2
Privates not visible outside of class, so __get() is used...
Getting 'hidden'


Notice:  Undefined property via __get(): hidden in <file> on line 70 in <file> on line 29

Method overloading

mixed __call ( string $name , array $arguments )
mixed __callStatic ( string $name , array $arguments )

__call() is triggered when invoking inaccessible methods in an object context.

__callStatic() is triggered when invoking inaccessible methods in a static context.

The $name argument is the name of the method being called. The $arguments argument is an enumerated array containing the parameters passed to the $name'ed method.

Przykład #2 Overloading methods via the __call() and __callStatic() methods

<?php
class MethodTest {
    public function 
__call($name$arguments) {
        
// Note: value of $name is case sensitive.
        
echo "Calling object method '$name' "
             
implode(', '$arguments). "\n";
    }

    
/**  As of PHP 5.3.0  */
    
public static function __callStatic($name$arguments) {
        
// Note: value of $name is case sensitive.
        
echo "Calling static method '$name' "
             
implode(', '$arguments). "\n";
    }
}

$obj = new MethodTest;
$obj->runTest('in object context');

MethodTest::runTest('in static context');  // As of PHP 5.3.0
?>

Powyższy przykład wyświetli:

Calling object method 'runTest' in object context
Calling static method 'runTest' in static context


Object Iteration

PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example a foreach statement. By default, all visible properties will be used for the iteration.

Przykład #1 Simple Object Iteration

<?php
class MyClass
{
    public 
$var1 'value 1';
    public 
$var2 'value 2';
    public 
$var3 'value 3';

    protected 
$protected 'protected var';
    private   
$private   'private var';

    function 
iterateVisible() {
       echo 
"MyClass::iterateVisible:\n";
       foreach(
$this as $key => $value) {
           print 
"$key => $value\n";
       }
    }
}

$class = new MyClass();

foreach(
$class as $key => $value) {
    print 
"$key => $value\n";
}
echo 
"\n";


$class->iterateVisible();

?>

Powyższy przykład wyświetli:

var1 => value 1
var2 => value 2
var3 => value 3

MyClass::iterateVisible:
var1 => value 1
var2 => value 2
var3 => value 3
protected => protected var
private => private var

As the output shows, the foreach iterated through all visible variables that can be accessed. To take it a step further you can implement one of PHP 5's internal interface named Iterator. This allows the object to decide what and how the object will be iterated.

Przykład #2 Object Iteration implementing Iterator

<?php
class MyIterator implements Iterator
{
    private 
$var = array();

    public function 
__construct($array)
    {
        if (
is_array($array)) {
            
$this->var $array;
        }
    }

    public function 
rewind() {
        echo 
"rewinding\n";
        
reset($this->var);
    }

    public function 
current() {
        
$var current($this->var);
        echo 
"current: $var\n";
        return 
$var;
    }

    public function 
key() {
        
$var key($this->var);
        echo 
"key: $var\n";
        return 
$var;
    }

    public function 
next() {
        
$var next($this->var);
        echo 
"next: $var\n";
        return 
$var;
    }

    public function 
valid() {
        
$var $this->current() !== false;
        echo 
"valid: {$var}\n";
        return 
$var;
    }
}

$values = array(1,2,3);
$it = new MyIterator($values);

foreach (
$it as $a => $b) {
    print 
"$a$b\n";
}
?>

Powyższy przykład wyświetli:

rewinding
current: 1
valid: 1
current: 1
key: 0
0: 1
next: 2
current: 2
valid: 1
current: 2
key: 1
1: 2
next: 3
current: 3
valid: 1
current: 3
key: 2
2: 3
next:
current:
valid:

You can also define your class so that it doesn't have to define all the Iterator functions by simply implementing the PHP 5 IteratorAggregate interface.

Przykład #3 Object Iteration implementing IteratorAggregate

<?php
class MyCollection implements IteratorAggregate
{
    private 
$items = array();
    private 
$count 0;

    
// Required definition of interface IteratorAggregate
    
public function getIterator() {
        return new 
MyIterator($this->items);
    }

    public function 
add($value) {
        
$this->items[$this->count++] = $value;
    }
}

$coll = new MyCollection();
$coll->add('value 1');
$coll->add('value 2');
$coll->add('value 3');

foreach (
$coll as $key => $val) {
    echo 
"key/value: [$key -> $val]\n\n";
}
?>

Powyższy przykład wyświetli:

rewinding
current: value 1
valid: 1
current: value 1
key: 0
key/value: [0 -> value 1]

next: value 2
current: value 2
valid: 1
current: value 2
key: 1
key/value: [1 -> value 2]

next: value 3
current: value 3
valid: 1
current: value 3
key: 2
key/value: [2 -> value 3]

next:
current:
valid:

Informacja: For more examples of iterators, see the SPL Extension.



Patterns

Patterns are ways to describe best practices and good designs. They show a flexible solution to common programming problems.

Factory

The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for "manufacturing" an object. A Parameterized Factory receives the name of the class to instantiate as argument.

Przykład #1 Parameterized Factory Method

<?php
class Example
{
    
// The parameterized factory method
    
public static function factory($type)
    {
        if (include_once 
'Drivers/' $type '.php') {
            
$classname 'Driver_' $type;
            return new 
$classname;
        } else {
            throw new 
Exception ('Driver not found');
        }
    }
}
?>

Defining this method in a class allows drivers to be loaded on the fly. If the Example class was a database abstraction class, loading a MySQL and SQLite driver could be done as follows:

<?php
// Load a MySQL Driver
$mysql Example::factory('MySQL');

// Load a SQLite Driver
$sqlite Example::factory('SQLite');
?>

Singleton

The Singleton pattern applies to situations in which there needs to be a single instance of a class. The most common example of this is a database connection. Implementing this pattern allows a programmer to make this single instance easily accessible by many other objects.

Przykład #2 Singleton Function

<?php
class Example
{
    
// Hold an instance of the class
    
private static $instance;
    
    
// A private constructor; prevents direct creation of object
    
private function __construct() 
    {
        echo 
'I am constructed';
    }

    
// The singleton method
    
public static function singleton() 
    {
        if (!isset(
self::$instance)) {
            
$c __CLASS__;
            
self::$instance = new $c;
        }

        return 
self::$instance;
    }
    
    
// Example method
    
public function bark()
    {
        echo 
'Woof!';
    }

    
// Prevent users to clone the instance
    
public function __clone()
    {
        
trigger_error('Clone is not allowed.'E_USER_ERROR);
    }

}

?>

This allows a single instance of the Example class to be retrieved.

<?php
// This would fail because the constructor is private
$test = new Example;

// This will always retrieve a single instance of the class
$test Example::singleton();
$test->bark();

// This will issue an E_USER_ERROR.
$test_clone = clone $test;

?>


Magic Methods

The function names __construct, __destruct, __call, __callStatic, __get, __set, __isset, __unset, __sleep, __wakeup, __toString, __invoke, __set_state and __clone are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.

Uwaga

PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality.

__sleep and __wakeup

serialize() checks if your class has a function with the magic name __sleep. If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.

The intended use of __sleep is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which do not need to be saved completely.

Conversely, unserialize() checks for the presence of a function with the magic name __wakeup. If present, this function can reconstruct any resources that the object may have.

The intended use of __wakeup is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.

Przykład #1 Sleep and wakeup

<?php
class Connection {
    protected 
$link;
    private 
$server$username$password$db;
    
    public function 
__construct($server$username$password$db)
    {
        
$this->server $server;
        
$this->username $username;
        
$this->password $password;
        
$this->db $db;
        
$this->connect();
    }
    
    private function 
connect()
    {
        
$this->link mysql_connect($this->server$this->username$this->password);
        
mysql_select_db($this->db$this->link);
    }
    
    public function 
__sleep()
    {
        return array(
'server''username''password''db');
    }
    
    public function 
__wakeup()
    {
        
$this->connect();
    }
}
?>

__toString

The __toString method allows a class to decide how it will react when it is converted to a string.

Przykład #2 Simple example

<?php
// Declare a simple class
class TestClass
{
    public 
$foo;

    public function 
__construct($foo) {
        
$this->foo $foo;
    }

    public function 
__toString() {
        return 
$this->foo;
    }
}

$class = new TestClass('Hello');
echo 
$class;
?>

Powyższy przykład wyświetli:

Hello

It is worth noting that before PHP 5.2.0 the __toString method was only called when it was directly combined with echo() or print(). Since PHP 5.2.0, it is called in any string context (e.g. in printf() with %s modifier) but not in other types contexts (e.g. with %d modifier). Since PHP 5.2.0, converting objects without __toString method to string would cause E_RECOVERABLE_ERROR.

__invoke

The __invoke method is called when a script tries to call an object as a function.

Informacja: This feature is available since PHP 5.3.0.

Przykład #3 Using __invoke

<?php
class CallableClass {
    function 
__invoke($x) {
        
var_dump($x);
    }
}
$obj = new CallableClass;
$obj(5);
var_dump(is_callable($obj));
?>

Powyższy przykład wyświetli:

int(5)
bool(true)

__set_state

This static method is called for classes exported by var_export() since PHP 5.1.0.

The only parameter of this method is an array containing exported properties in the form array('property' => value, ...).

Przykład #4 Using __set_state (since 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($atrue) . ';'); // $b = A::__set_state(array(
                                            //    'var1' => 5,
                                            //    'var2' => 'foo',
                                            // ));
var_dump($b);

?>

Powyższy przykład wyświetli:

object(A)#2 (2) {
  ["var1"]=>
  int(5)
  ["var2"]=>
  string(3) "foo"
}


Final Keyword

PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.

Przykład #1 Final methods example

<?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";
   }
}
// Results in Fatal error: Cannot override final method BaseClass::moreTesting()
?>

Przykład #2 Final class example

<?php
final class BaseClass {
   public function 
test() {
       echo 
"BaseClass::test() called\n";
   }

   
// Here it doesn't matter if you specify the function as final or not
   
final public function moreTesting() {
       echo 
"BaseClass::moreTesting() called\n";
   }
}

class 
ChildClass extends BaseClass {
}
// Results in Fatal error: Class ChildClass may not inherit from final class (BaseClass)
?>

Informacja: Properties cannot be declared final, only classes and methods may be declared as final.



Object Cloning

Creating a copy of an object with fully replicated properties is not always the wanted behavior. A good example of the need for copy constructors, is if you have an object which represents a GTK window and the object holds the resource of this GTK window, when you create a duplicate you might want to create a new window with the same properties and have the new object hold the resource of the new window. Another example is if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy.

An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly.

$copy_of_object = clone $object;

When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references.

Once the cloning is complete, if a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed.

Przykład #1 Cloning an object

<?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()
    {
        
// Force a copy of this->object, otherwise
        // it will point to same object.
        
$this->object1 = clone $this->object1;
    }
}

$obj = new MyCloneable();

$obj->object1 = new SubObject();
$obj->object2 = new SubObject();

$obj2 = clone $obj;


print(
"Original Object:\n");
print_r($obj);

print(
"Cloned Object:\n");
print_r($obj2);

?>

Powyższy przykład wyświetli:

Original Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 1
        )

    [object2] => SubObject Object
        (
            [instance] => 2
        )

)
Cloned Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 3
        )

    [object2] => SubObject Object
        (
            [instance] => 2
        )

)


Comparing Objects

In PHP 5, object comparison is more complicated than in PHP 4 and more in accordance to what one will expect from an Object Oriented Language (not that PHP 5 is such a language).

When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.

On the other hand, when using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.

An example will clarify these rules.

Przykład #1 Example of object comparison in 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 
"Two instances of the same class\n";
compareObjects($o$p);

echo 
"\nTwo references to the same instance\n";
compareObjects($o$q);

echo 
"\nInstances of two different classes\n";
compareObjects($o$r);
?>

Powyższy przykład wyświetli:

Two instances of the same class
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Two references to the same instance
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

Instances of two different classes
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Informacja: Extensions can define own rules for their objects comparison.



Type Hinting

PHP 5 introduces Type Hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype) or arrays (since PHP 5.1). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call.

Przykład #1 Type Hinting examples

<?php
// An example class
class MyClass
{
    
/**
     * A test function
     *
     * First parameter must be an object of type OtherClass
     */
    
public function test(OtherClass $otherclass) {
        echo 
$otherclass->var;
    }


    
/**
     * Another test function
     *
     * First parameter must be an array
     */
    
public function test_array(array $input_array) {
        
print_r($input_array);
    }
}

// Another example class
class OtherClass {
    public 
$var 'Hello World';
}
?>

Failing to satisfy the type hint results in a catchable fatal error.

<?php
// An instance of each class
$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);

// Works: Prints Hello World
$myclass->test($otherclass);

// Fatal Error: Argument 1 must be an array
$myclass->test_array('a string');

// Works: Prints the array
$myclass->test_array(array('a''b''c'));
?>

Type hinting also works with functions:

<?php
// An example class
class MyClass {
    public 
$var 'Hello World';
}

/**
 * A test function
 *
 * First parameter must be an object of type MyClass
 */
function MyFunction (MyClass $foo) {
    echo 
$foo->var;
}

// Works
$myclass = new MyClass;
MyFunction($myclass);
?>

Type hinting allowing NULL value:

<?php

/* Accepting NULL value */
function test(stdClass $obj NULL) {

}

test(NULL);
test(new stdClass);

?>

Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.



Late Static Bindings

As of PHP 5.3.0, PHP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance.

This feature was named "late static bindings" with an internal perspective in mind. "Late binding" comes from the fact that static:: will no longer be resolved using the class where the method is defined but it will rather be computed using runtime information. It was also called a "static binding" as it can be used for (but is not limited to) static method calls.

Limitations of self::

Static references to the current class like self:: or __CLASS__ are resolved using the class in which the function belongs, as in where it was defined:

Przykład #1 self:: usage

<?php
class {
    public static function 
who() {
        echo 
__CLASS__;
    }
    public static function 
test() {
        
self::who();
    }
}

class 
extends {
    public static function 
who() {
         echo 
__CLASS__;
    }
}

B::test();
?>

Powyższy przykład wyświetli:

A

Late Static Bindings' usage

Late static bindings tries to solve that limitation by introducing a keyword that references the class that was initially called at runtime. Basically, a keyword that would allow you to reference B from test() in the previous example. It was decided not to introduce a new keyword but rather use static that was already reserved.

Przykład #2 static:: simple usage

<?php
class {
    public static function 
who() {
        echo 
__CLASS__;
    }
    public static function 
test() {
        static::
who(); // Here comes Late Static Bindings
    
}
}

class 
extends {
    public static function 
who() {
         echo 
__CLASS__;
    }
}

B::test();
?>

Powyższy przykład wyświetli:

B

Informacja: static:: does not work like $this for static methods! $this-> follows the rules of inheritance while static:: doesn't. This difference is detailed later on this manual page.

Przykład #3 static:: usage in a non-static context

<?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();

?>

Powyższy przykład wyświetli:

TestChild
TestParent

Informacja: Late static bindings' resolution will stop at a fully resolved static call with no fallback. On the other hand, static calls using keywords like parent:: or self:: will forward the calling information.

Przykład #4 Forwarding and non-forwarding calls

<?php
class {
    public static function 
foo() {
        static::
who();
    }

    public static function 
who() {
        echo 
__CLASS__."\n";
    }
}

class 
extends {
    public static function 
test() {
        
A::foo();
        
parent::foo();
        
self::foo();
    }

    public static function 
who() {
        echo 
__CLASS__."\n";
    }
}
class 
extends {
    public static function 
who() {
        echo 
__CLASS__."\n";
    }
}

C::test();
?>

Powyższy przykład wyświetli:

A
C
C

Edge cases

There are lots of different ways to trigger a method call in PHP, like callbacks or magic methods. As late static bindings base their resolution on runtime information, it might give unexpected results in so-called edge cases.

Przykład #5 Late static bindings inside magic methods

<?php
class {

   protected static function 
who() {
        echo 
__CLASS__."\n";
   }

   public function 
__get($var) {
       return static::
who();
   }
}

class 
extends {

   protected static function 
who() {
        echo 
__CLASS__."\n";
   }
}

$b = new B;
$b->foo;
?>

Powyższy przykład wyświetli:

B


Objects and references

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.

Przykład #1 References and Objects

<?php
class {
    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";

?>

Powyższy przykład wyświetli:

2
2
2


Object Serialization

Serializing objects - objects in sessions

serialize() returns a string containing a byte-stream representation of any value that can be stored in PHP. unserialize() can use this string to recreate the original variable values. Using serialize to save an object will save all variables in an object. The methods in an object will not be saved, only the name of the class.

In order to be able to unserialize() an object, the class of that object needs to be defined. That is, if you have an object of class A and serialize this, you'll get a string that refers to class A and contains all values of variabled contained it. If you want to be able to unserialize this in another file, an object of class A, the definition of class A must be prest ent in in that file first. This can be done for example by storing the class definition of class A in an include file and including this file or making use of the spl_autoload_register() function.

<?php
// classa.inc:
  
  
class {
      public 
$one 1;
    
      public function 
show_one() {
          echo 
$this->one;
      }
  }
  
// page1.php:

  
include("classa.inc");
  
  
$a = new A;
  
$s serialize($a);
  
// store $s somewhere where page2.php can find it.
  
file_put_contents('store'$s);

// page2.php:
  
  // this is needed for the unserialize to work properly.
  
include("classa.inc");

  
$s file_get_contents('store');
  
$a unserialize($s);

  
// now use the function show_one() of the $a object.  
  
$a->show_one();
?>

If an application is using sessions and uses session_register() to register objects, these objects are serialized automatically at the end of each PHP page, and are unserialized automatically on each of the following pages. This means that these objects can show up on any of the application's pages once they become part of the session. However, session_register() is deprecated as of PHP 5.3.0, and removed as of PHP 6.0.0. Reliance on this function is not recommended.

It is strongly recommended that if an application serializes objects, for use later in the application, that the application include the class definition for that object throughout the application. Not doing so might result in an object being unserialized without a class definition, which will result in PHP giving the object a class of __PHP_Incomplete_Class_Name, which has no methods and would render the object useless.

So if in the example above $a became part of a session by running session_register("a"), you should include the file classa.inc on all of your pages, not only page1.php and page2.php.




Namespaces

Spis treści


Namespaces overview

What are namespaces? In the broadest definition namespaces are a way of encapsulating items. This can be seen as an abstract concept in many places. For example, in any operating system directories serve to group related files, and act as a namespace for the files within them. As a concrete example, the file foo.txt can exist in both directory /home/greg and in /home/other, but two copies of foo.txt cannot co-exist in the same directory. In addition, to access the foo.txt file outside of the /home/greg directory, we must prepend the directory name to the file name using the directory separator to get /home/greg/foo.txt. This same principle extends to namespaces in the programming world.

In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions:

  1. Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
  2. Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.

PHP Namespaces provide a way in which to group related classes, functions and constants. Here is an example of namespace syntax in PHP:

Przykład #1 Namespace syntax example

<?php
namespace my\name// see "Defining Namespaces" section

class MyClass {}
function 
myfunction() {}
const 
MYCONST 1;

$a = new MyClass;
$c = new \my\name\MyClass// see "Global Space" section

$a strlen('hi'); // see "Using namespaces: fallback to global
                   // function/constant" section

$d = namespace\MYCONST// see "namespace operator and __NAMESPACE__
                        // constant" section
$d __NAMESPACE__ '\MYCONST';
echo 
constant($d); // see "Namespaces and dynamic language features" section
?>

Namespaces are available in PHP as of PHP 5.3.0.



Defining namespaces

Although any valid PHP code can be contained within a namespace, only three type of code are affected by namespaces: classes, functions and constants.

Namespaces are declared using the namespace keyword. A file containing a namespace must declare the namespace at the top of the file before any other code - with one exception: the declare keyword.

Przykład #1 Declaring a single namespace

<?php
namespace MyProject;

const 
CONNECT_OK 1;
class 
Connection /* ... */ }
function 
connect() { /* ... */  }

?>

The only code construct allowed before a namespace declaration is the declare statement, for defining encoding of a source file. In addition, no non-PHP code may precede a namespace declaration, including extra whitespace:

Przykład #2 Declaring a single namespace

<html>
<?php
namespace MyProject// fatal error - namespace must be the first statement in the script
?>

In addition, unlike any other PHP construct, the same namespace may be defined in multiple files, allowing splitting up of a namespace's contents across the filesystem.



Declaring sub-namespaces

Much like directories and files, PHP namespaces also contain the ability to specify a hierarchy of namespace names. Thus, a namespace name can be defined with sub-levels:

Przykład #1 Declaring a single namespace with hierarchy

<?php
namespace MyProject\Sub\Level;

const 
CONNECT_OK 1;
class 
Connection /* ... */ }
function 
connect() { /* ... */  }

?>

The above example creates constant MyProject\Sub\Level\CONNECT_OK, class MyProject\Sub\Level\Connection and function MyProject\Sub\Level\connect.



Defining multiple namespaces in the same file

Multiple namespaces may also be declared in the same file. There are two allowed syntaxes.

Przykład #1 Declaring multiple namespaces, simple combination syntax

<?php
namespace MyProject;

const 
CONNECT_OK 1;
class 
Connection /* ... */ }
function 
connect() { /* ... */  }

namespace 
AnotherProject;

const 
CONNECT_OK 1;
class 
Connection /* ... */ }
function 
connect() { /* ... */  }
?>

This syntax is not recommended for combining namespaces into a single file. Instead it is recommended to use the alternate bracketed syntax.

Przykład #2 Declaring multiple namespaces, bracketed syntax

<?php
namespace MyProject {

const 
CONNECT_OK 1;
class 
Connection /* ... */ }
function 
connect() { /* ... */  }
}

namespace 
AnotherProject {

const 
CONNECT_OK 1;
class 
Connection /* ... */ }
function 
connect() { /* ... */  }
}
?>

It is strongly discouraged as a coding practice to combine multiple namespaces into the same file. The primary use case is to combine multiple PHP scripts into the same file.

To combine global non-namespaced code with namespaced code, only bracketed syntax is supported. Global code should be encased in a namespace statement with no namespace name as in:

Przykład #3 Declaring multiple namespaces and unnamespaced code

<?php
namespace MyProject {

const 
CONNECT_OK 1;
class 
Connection /* ... */ }
function 
connect() { /* ... */  }
}

namespace { 
// global code
session_start();
$a MyProject\connect();
echo 
MyProject\Connection::start();
}
?>

No PHP code may exist outside of the namespace brackets except for an opening declare statement.

Przykład #4 Declaring multiple namespaces and unnamespaced code

<?php
declare(encoding='UTF-8');
namespace 
MyProject {

const 
CONNECT_OK 1;
class 
Connection /* ... */ }
function 
connect() { /* ... */  }
}

namespace { 
// global code
session_start();
$a MyProject\connect();
echo 
MyProject\Connection::start();
}
?>



Using namespaces: Basics

Before discussing the use of namespaces, it is important to understand how PHP knows which namespaced element your code is requesting. A simple analogy can be made between PHP namespaces and a filesystem. There are three ways to access a file in a file system:

  1. Relative file name like foo.txt. This resolves to currentdirectory/foo.txt where currentdirectory is the directory currently occupied. So if the current directory is /home/foo, the name resolves to /home/foo/foo.txt.
  2. Relative path name like subdirectory/foo.txt. This resolves to currentdirectory/subdirectory/foo.txt.
  3. Absolute path name like /main/foo.txt. This resolves to /main/foo.txt.

The same principle can be applied to namespaced elements in PHP. For example, a class name can be referred to in three ways:

  1. Unqualified name, or an unprefixed class name like $a = new foo(); or foo::staticmethod();. If the current namespace is currentnamespace, this resolves to currentnamespace\foo. If the code is global, non-namespaced code, this resolves to foo. One caveat: unqualified names for functions and constants will resolve to global functions and constants if the namespaced function or constant is not defined. See Using namespaces: fallback to global function/constant for details.
  2. Qualified name, or a prefixed class name like $a = new subnamespace\foo(); or subnamespace\foo::staticmethod();. If the current namespace is currentnamespace, this resolves to currentnamespace\subnamespace\foo. If the code is global, non-namespaced code, this resolves to subnamespace\foo.
  3. Fully qualified name, or a prefixed name with global prefix operator like $a = new \currentnamespace\foo(); or \currentnamespace\foo::staticmethod();. This always resolves to the literal name specified in the code, currentnamespace\foo.

Here is an example of the three kinds of syntax in actual code:

file1.php

<?php
namespace Foo\Bar\subnamespace;

const 
FOO 1;
function 
foo() {}
class 
foo
{
    static function 
staticmethod() {}
}
?>

file2.php

<?php
namespace Foo\Bar;
include 
'file1.php';

const 
FOO 2;
function 
foo() {}
class 
foo
{
    static function 
staticmethod() {}
}

/* Unqualified name */
foo(); // resolves to function Foo\Bar\foo
foo::staticmethod(); // resolves to class Foo\Bar\foo, method staticmethod
echo FOO// resolves to constant Foo\Bar\FOO

/* Qualified name */
subnamespace\foo(); // resolves to function Foo\Bar\subnamespace\foo
subnamespace\foo::staticmethod(); // resolves to class Foo\Bar\subnamespace\foo,
                                  // method staticmethod
echo subnamespace\FOO// resolves to constant Foo\Bar\subnamespace\FOO
                                  
/* Fully qualified name */
\Foo\Bar\foo(); // resolves to function Foo\Bar\foo
\Foo\Bar\foo::staticmethod(); // resolves to class Foo\Bar\foo, method staticmethod
echo \Foo\Bar\FOO// resolves to constant Foo\Bar\FOO
?>

Note that to access any global class, function or constant, a fully qualified name can be used, such as \strlen() or \Exception or \INI_ALL.

Przykład #1 Accessing global classes, functions and constants from within a namespace

<?php
namespace Foo;

function 
strlen() {}
const 
INI_ALL 3;
class 
Exception {}

$a = \strlen('hi'); // calls global function strlen
$b = \INI_ALL// accesses global constant INI_ALL
$c = new \Exception('error'); // instantiates global class Exception
?>



Namespaces and dynamic language features

PHP's implementation of namespaces is influenced by its dynamic nature as a programming language. Thus, to convert code like the following example into namespaced code:

Przykład #1 Dynamically accessing elements

example1.php:

<?php
class classname
{
    function 
__construct()
    {
        echo 
__METHOD__,"\n";
    }
}
function 
funcname()
{
    echo 
__FUNCTION__,"\n";
}
const 
constname "global";

$a 'classname';
$obj = new $a// prints classname::__construct
$b 'funcname';
$b(); // prints funcname
echo constant('constname'), "\n"// prints global
?>

One must use the fully qualified name (class name with namespace prefix). Note that because there is no difference between a qualified and a fully qualified Name inside a dynamic class name, function name, or constant name, the leading backslash is not necessary.

Przykład #2 Dynamically accessing namespaced elements

<?php
namespace namespacename;
class 
classname
{
    function 
__construct()
    {
        echo 
__METHOD__,"\n";
    }
}
function 
funcname()
{
    echo 
__FUNCTION__,"\n";
}
const 
constname "namespaced";

include 
'example1.php';

$a 'classname';
$obj = new $a// prints classname::__construct
$b 'funcname';
$b(); // prints funcname
echo constant('constname'), "\n"// prints global

/* note that if using double quotes, "\\namespacename\\classname" must be used */
$a '\namespacename\classname';
$obj = new $a// prints namespacename\classname::__construct
$a 'namespacename\classname';
$obj = new $a// also prints namespacename\classname::__construct
$b 'namespacename\funcname';
$b(); // prints namespacename\funcname
$b '\namespacename\funcname';
$b(); // also prints namespacename\funcname
echo constant('\namespacename\constname'), "\n"// prints namespaced
echo constant('namespacename\constname'), "\n"// also prints namespaced
?>

Be sure to read the note about escaping namespace names in strings.



namespace keyword and __NAMESPACE__ constant

PHP supports two ways of abstractly accessing elements within the current namespace, the __NAMESPACE__ magic constant, and the namespace keyword.

The value of __NAMESPACE__ is a string that contains the current namespace name. In global, un-namespaced code, it contains an empty string.

Przykład #1 __NAMESPACE__ example, namespaced code

<?php
namespace MyProject;

echo 
'"'__NAMESPACE__'"'// outputs "MyProject"
?>

Przykład #2 __NAMESPACE__ example, global code

<?php

echo '"'__NAMESPACE__'"'// outputs ""
?>

The __NAMESPACE__ constant is useful for dynamically constructing names, for instance:

Przykład #3 using __NAMESPACE__ for dynamic name construction

<?php
namespace MyProject;

function 
get($classname)
{
    
$a __NAMESPACE__ '\\' $classname;
    return new 
$a;
}
?>

The namespace keyword can be used to explicitly request an element from the current namespace or a sub-namespace. It is the namespace equivalent of the self operator for classes.

Przykład #4 the namespace operator, inside a namespace

<?php
namespace MyProject;

use 
blah\blah as mine// see "Using namespaces: importing/aliasing"

blah\mine(); // calls function MyProject\blah\mine()
namespace\blah\mine(); // calls function MyProject\blah\mine()

namespace\func(); // calls function MyProject\func()
namespace\sub\func(); // calls function MyProject\sub\func()
namespace\cname::method(); // calls static method "method" of class MyProject\cname
$a = new namespace\sub\cname(); // instantiates object of class MyProject\sub\cname
$b = namespace\CONSTANT// assigns value of constant MyProject\CONSTANT to $b
?>

Przykład #5 the namespace operator, in global code

<?php

namespace\func(); // calls function func()
namespace\sub\func(); // calls function sub\func()
namespace\cname::method(); // calls static method "method" of class cname
$a = new namespace\sub\cname(); // instantiates object of class sub\cname
$b = namespace\CONSTANT// assigns value of constant CONSTANT to $b
?>



Using namespaces: Aliasing/Importing

The ability to refer to an external fully qualified name with an alias, or importing, is an important feature of namespaces. This is similar to the ability of unix-based filesystems to create symbolic links to a file or to a directory.

PHP namespaces support two kinds of aliasing or importing: aliasing a class name, and aliasing a namespace name. Note that importing a function or constant is not supported.

In PHP, aliasing is accomplished with the use operator. Here is an example showing all 3 kinds of importing:

Przykład #1 importing/aliasing with the use operator

<?php
namespace foo;
use 
My\Full\Classname as Another;

// this is the same as use My\Full\NSname as NSname
use My\Full\NSname;

// importing a global class
use \ArrayObject;

$obj = new namespace\Another// instantiates object of class foo\Another
$obj = new Another// instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
$a = new ArrayObject(array(1)); // instantiates object of class ArrayObject
// without the "use \ArrayObject" we would instantiate an object of class foo\ArrayObject
?>

Note that for namespaced names (fully qualified namespace names containing namespace separator, such as Foo\Bar as opposed to global names that do not, such as FooBar), the leading backslash is unnecessary and not allowed, as import names must be fully qualified, and are not processed relative to the current namespace.

PHP additionally supports a convenience shortcut to place multiple use statements on the same line

Przykład #2 importing/aliasing with the use operator, multiple use statements combined

<?php
use My\Full\Classname as AnotherMy\Full\NSname;

$obj = new Another// instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
?>

Importing is performed at compile-time, and so does not affect dynamic class, function or constant names.

Przykład #3 Importing and dynamic names

<?php
use My\Full\Classname as AnotherMy\Full\NSname;

$obj = new Another// instantiates object of class My\Full\Classname
$a 'Another';
$obj = new $a;      // instantiates object of class Another
?>

In addition, importing only affects unqualified and qualified names. Fully qualified names are absolute, and unaffected by imports.

Przykład #4 Importing and fully qualified names

<?php
use My\Full\Classname as AnotherMy\Full\NSname;

$obj = new Another// instantiates object of class My\Full\Classname
$obj = new \Another// instantiates object of class Another
$obj = new Another\thing// instantiates object of class My\Full\Classname\thing
$obj = new \Another\thing// instantiates object of class Another\thing
?>



Global space

Without any namespace definition, all class and function definitions are placed into the global space - as it was in PHP before namespaces were supported. Prefixing a name with \ will specify that the name is required from the global space even in the context of the namespace.

Przykład #1 Using global space specification

<?php
namespace A\B\C;

/* This function is A\B\C\fopen */
function fopen() { 
     
/* ... */
     
$f = \fopen(...); // call global fopen
     
return $f;

?>



Using namespaces: fallback to global function/constant

Inside a namespace, when PHP encounters a unqualified Name in a class name, function or constant context, it resolves these with different priorities. Class names always resolve to the current namespace name. Thus to access internal or non-namespaced user classes, One must refer to them with their fully qualified Name as in:

Przykład #1 Accessing global classes inside a namespace

<?php
namespace A\B\C;
class 
Exception extends \Exception {}

$a = new Exception('hi'); // $a is an object of class A\B\C\Exception
$b = new \Exception('hi'); // $b is an object of class Exception

$c = new ArrayObject// fatal error, class A\B\C\ArrayObject not found
?>

For functions and constants, PHP will fall back to global functions or constants if a namespaced function or constant does not exist.

Przykład #2 global functions/constants fallback inside a namespace

<?php
namespace A\B\C;

const 
E_ERROR 45;
function 
strlen($str)
{
    return \
strlen($str) - 1;
}

echo 
E_ERROR"\n"// prints "45"
echo INI_ALL"\n"// prints "7" - falls back to global INI_ALL

echo strlen('hi'), "\n"// prints "1"
if (is_array('hi')) { // prints "is not array"
    
echo "is array\n";
} else {
    echo 
"is not array\n";
}
?>



Name resolution rules

For the purposes of these resolution rules, here are some important definitions:

Namespace name definitions
Unqualified name

This is an identifier without a namespace separator, such as Foo

Qualified name

This is an identifier with a namespace separator, such as Foo\Bar

Fully qualified name

This is an identifier with a namespace separator that begins with a namespace separator, such as \Foo\Bar. namespace\Foo is also a fully qualified name.

Names are resolved following these resolution rules:

  1. Calls to fully qualified functions, classes or constants are resolved at compile-time. For instance new \A\B resolves to class A\B.
  2. All unqualified and qualified names (not fully qualified names) are translated during compilation according to current import rules. For example, if the namespace A\B\C is imported as C, a call to C\D\e() is translated to A\B\C\D\e().
  3. Inside a namespace, all qualified names not translated according to import rules have the current namespace prepended. For example, if a call to C\D\e() is performed within namespace A\B, it is translated to A\B\C\D\e().
  4. Unqualified class names are translated during compilation according to current import rules (full name substituted for short imported name). In example, if the namespace A\B\C is imported as C, new C() is translated to new A\B\C().
  5. Inside namespace (say A\B), calls to unqualified functions are resolved at run-time. Here is how a call to function foo() is resolved:
    1. It looks for a function from the current namespace: A\B\foo().
    2. It tries to find and call the global function foo().
  6. Inside namespace (say A\B), calls to unqualified or qualified class names (not fully qualified class names) are resolved at run-time. Here is how a call to new C() or new D\E() is resolved. For new C():
    1. It looks for a class from the current namespace: A\B\C.
    2. It attempts to autoload A\B\C.
    For new D\E():
    1. It looks for a class by prepending the current namespace: A\B\D\E.
    2. It attempts to autoload A\B\D\E.
    To reference any global class in the global namespace, its fully qualified name new \C() must be used.

Przykład #1 Name resolutions illustrated

<?php
namespace A;
use 
B\DC\as F;

// function calls

foo();      // first tries to call "foo" defined in namespace "A"
            // then calls global function "foo"

\foo();     // calls function "foo" defined in global scope

my\foo();   // calls function "foo" defined in namespace "A\my"

F();        // first tries to call "F" defined in namespace "A"
            // then calls global function "F"

// class references

new B();    // creates object of class "B" defined in namespace "A"
            // if not found, it tries to autoload class "A\B"

new D();    // using import rules, creates object of class "D" defined in namespace "B"
            // if not found, it tries to autoload class "B\D"

new F();    // using import rules, creates object of class "E" defined in namespace "C"
            // if not found, it tries to autoload class "C\E"

new \B();   // creates object of class "B" defined in global scope
            // if not found, it tries to autoload class "B"

new \D();   // creates object of class "D" defined in global scope
            // if not found, it tries to autoload class "D"

new \F();   // creates object of class "F" defined in global scope
            // if not found, it tries to autoload class "F"

// static methods/namespace functions from another namespace

B\foo();    // calls function "foo" from namespace "A\B"

B::foo();   // calls method "foo" of class "B" defined in namespace "A"
            // if class "A\B" not found, it tries to autoload class "A\B"

D::foo();   // using import rules, calls method "foo" of class "D" defined in namespace "B"
            // if class "B\D" not found, it tries to autoload class "B\D"

\B\foo();   // calls function "foo" from namespace "B"

\B::foo();  // calls method "foo" of class "B" from global scope
            // if class "B" not found, it tries to autoload class "B"

// static methods/namespace functions of current namespace

A\B::foo();   // calls method "foo" of class "B" from namespace "A\A"
              // if class "A\A\B" not found, it tries to autoload class "A\A\B"

\A\B::foo();  // calls method "foo" of class "B" from namespace "A\B"
              // if class "A\B" not found, it tries to autoload class "A\B"
?>


FAQ: things you need to know about namespaces

This FAQ is split into two sections: common questions, and some specifics of implementation that are helpful to understand fully.

First, the common questions.

  1. If I don't use namespaces, should I care about any of this?
  2. How do I use internal or global classes in a namespace?
  3. How do I use namespaces classes functions, or constants in their own namespace?
  4. How does a name like \my\name or \name resolve?
  5. How does a name like my\name resolve?
  6. How does an unqualified class name like name resolve?
  7. How does an unqualified function name or unqualified constant name like name resolve?

There are a few implementation details of the namespace implementations that are helpful to understand.

  1. Import names cannot conflict with classes defined in the same file.
  2. Nested namespaces are not allowed.
  3. Neither functions nor constants can be imported via the use statement.
  4. Dynamic namespace names (quoted identifiers) should escape backslash.
  5. Undefined Constants referenced using any backslash die with fatal error
  6. Cannot override special constants NULL, TRUE, FALSE, ZEND_THREAD_SAFE or ZEND_DEBUG_BUILD

If I don't use namespaces, should I care about any of this?

No. Namespaces do not affect any existing code in any way, or any as-yet-to-be-written code that does not contain namespaces. You can write this code if you wish:

Przykład #1 Accessing global classes outside a namespace

<?php
$a 
= new \stdClass;

This is functionally equivalent to:

Przykład #2 Accessing global classes outside a namespace

<?php
$a 
= new stdClass;

How do I use internal or global classes in a namespace?

Przykład #3 Accessing internal classes in namespaces

<?php
namespace foo;
$a = new \stdClass;

function 
test(\ArrayObject $typehintexample null) {}

$a = \DirectoryIterator::CURRENT_AS_FILEINFO;

// extending an internal or global class
class MyException extends \Exception {}
?>

How do I use namespaces classes, functions, or constants in their own namespace?

Przykład #4 Accessing internal classes, functions or constants in namespaces

<?php
namespace foo;

class 
MyClass {}

// using a class from the current namespace as a type hint
function test(MyClass $typehintexample null) {}
// another way to use a class from the current namespace as a type hint
function test(\foo\MyClass $typehintexample null) {}

// extending a class from the current namespace
class Extended extends MyClass {}

// accessing a global function
$a = \globalfunc();

// accessing a global constant
$b = \INI_ALL;
?>

How does a name like \my\name or \name resolve?

Names that begin with a \ always resolve to what they look like, so \my\name is in fact my\name, and \Exception is Exception.

Przykład #5 Fully Qualified names

<?php
namespace foo;
$a = new \my\name(); // instantiates "my\name" class
echo \strlen('hi'); // calls function "strlen"
$a = \INI_ALL// $a is set to the value of constant "INI_ALL"
?>

How does a name like my\name resolve?

Names that contain a backslash but do not begin with a backslash like my\name can be resolved in 2 different ways.

If there is an import statement that aliases another name to my, then the import alias is applied to the my in my\name.

Otherwise, the current namespace name is prepended to my\name.

Przykład #6 Qualified names

<?php
namespace foo;
use 
blah\blah as foo;

$a = new my\name(); // instantiates "foo\my\name" class
foo\bar::name(); // calls static method "name" in class "blah\blah\bar"
my\bar(); // calls function "foo\my\bar"
$a my\BAR// sets $a to the value of constant "foo\my\BAR"
?>

How does an unqualified class name like name resolve?

Class names that do not contain a backslash like name can be resolved in 2 different ways.

If there is an import statement that aliases another name to name, then the import alias is applied.

Otherwise, the current namespace name is prepended to name.

Przykład #7 Unqualified class names

<?php
namespace foo;
use 
blah\blah as foo;

$a = new name(); // instantiates "foo\name" class
foo::name(); // calls static method "name" in class "blah\blah"
?>

How does an unqualified function name or unqualified constant name like name resolve?

Function or constant names that do not contain a backslash like name can be resolved in 2 different ways.

First, the current namespace name is prepended to name.

Finally, if the constant or function name does not exist in the current namespace, a global constant or function name is used if it exists.

Przykład #8 Unqualified function or constant names

<?php
namespace foo;
use 
blah\blah as foo;

const 
FOO 1;

function 
my() {}
function 
foo() {}
function 
sort(&$a)
{
    
sort($a);
    
$a array_flip($a);
    return 
$a;
}

my(); // calls "foo\my"
$a strlen('hi'); // calls global function "strlen" because "foo\strlen" does not exist
$arr = array(1,3,2);
$b sort($arr); // calls function "foo\sort"
$c foo(); // calls function "foo\foo" - import is not applied

$a FOO// sets $a to value of constant "foo\FOO" - import is not applied
$b INI_ALL// sets $b to value of global constant "INI_ALL"
?>

Import names cannot conflict with classes defined in the same file.

The following script combinations are legal:

file1.php

<?php
namespace my\stuff;
class 
MyClass {}
?>

another.php

<?php
namespace another;
class 
thing {}
?>

file2.php

<?php
namespace my\stuff;
include 
'file1.php';
include 
'another.php';

use 
another\thing as MyClass;
$a = new MyClass// instantiates class "thing" from namespace another
?>

There is no name conflict, even though the class MyClass exists within the my\stuff namespace, because the MyClass definition is in a separate file. However, the next example causes a fatal error on name conflict because MyClass is defined in the same file as the use statement.

<?php
namespace my\stuff;
use 
another\thing as MyClass;
class 
MyClass {} // fatal error: MyClass conflicts with import statement
$a = new MyClass;
?>

Nested namespaces are not allowed.

PHP does not allow nesting namespaces

<?php
namespace my\stuff {
    namespace 
nested {
        class 
foo {}
    }
}
?>

However, it is easy to simulate nested namespaces like so:

<?php
namespace my\stuff\nested {
    class 
foo {}
}
?>

Neither functions nor constants can be imported via the use statement.

The only elements that are affected by use statements are namespaces and class names. In order to shorten a long constant or function, import its containing namespace

<?php
namespace mine;
use 
ultra\long\ns\name;

$a name\CONSTANT;
name\func();
?>

Dynamic namespace names (quoted identifiers) should escape backslash

It is very important to realize that because the backslash is used as an escape character within strings, it should always be doubled when used inside a string. Otherwise there is a risk of unintended consequences:

Przykład #9 Dangers of using namespaced names inside a double-quoted string

<?php
$a 
= new "dangerous\name"// \n is a newline inside double quoted strings!
$obj = new $a;

$a = new 'not\at\all\dangerous'// no problems here.
$obj = new $a;
?>

Inside a single-quoted string, the backslash escape sequence is much safer to use, but it is still recommended practice to escape backslashes in all strings as a best practice.

Undefined Constants referenced using any backslash die with fatal error

Any undefined constant that is unqualified like FOO will produce a notice explaining that PHP assumed FOO was the value of the constant. Any constant, qualified or fully qualified, that contains a backslash will produce a fatal error if not found.

Przykład #10 Undefined constants

<?php
namespace bar;
$a FOO// produces notice - undefined constants "FOO" assumed "FOO";
$a = \FOO// fatal error, undefined namespace constant FOO
$a Bar\FOO// fatal error, undefined namespace constant bar\Bar\FOO
$a = \Bar\FOO// fatal error, undefined namespace constant Bar\FOO
?>

Cannot override special constants NULL, TRUE, FALSE, ZEND_THREAD_SAFE or ZEND_DEBUG_BUILD

Any attempt to define a namespaced constant that is a special, built-in constant results in a fatal error

Przykład #11 Undefined constants

<?php
namespace bar;
const 
NULL 0// fatal error;
const true 'stupid'// also fatal error;
// etc.
?>




Exceptions

Spis treści

PHP 5 has an exception model similar to that of other programming languages. An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exeptions. Normal execution (when no exception is thrown within the try block, or when a catch matching the thrown exception's class is not present) will continue after that last catch block defined in sequence. Exceptions can be thrown (or re-thrown) within a catch block.

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler().

Informacja: Internal PHP functions mainly use Error reporting, only modern Object oriented extensions use exceptions. However, errors can be simply translated to exceptions with ErrorException.

Wskazówka

The Standard PHP Library (SPL) provides a good number of built-in exceptions.

Przykład #1 Throwing an Exception

<?php
function inverse($x) {
    if (!
$x) {
        throw new 
Exception('Division by zero.');
    }
    else return 
1/$x;
}

try {
    echo 
inverse(5) . "\n";
    echo 
inverse(0) . "\n";
} catch (
Exception $e) {
    echo 
'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>

Powyższy przykład wyświetli:

0.2
Caught exception: Division by zero.
Hello World

Przykład #2 Nested Exception

<?php

class MyException extends Exception { }

class 
Test {
    public function 
testing() {
        try {
            try {
                throw new 
MyException('foo!');
            } catch (
MyException $e) {
                
/* rethrow it */
                
throw $e;
            }
        } catch (
Exception $e) {
            
var_dump($e->getMessage());
        }
    }
}

$foo = new Test;
$foo->testing();

?>

Powyższy przykład wyświetli:

string(4) "foo!"

Extending Exceptions

A User defined Exception class can be defined by extending the built-in Exception class. The members and properties below, show what is accessible within the child class that derives from the built-in Exception class.

Przykład #1 The Built in Exception class

<?php
class Exception
{
    protected 
$message 'Unknown exception';   // exception message
    
private   $string;                          // __toString cache
    
protected $code 0;                        // user defined exception code
    
protected $file;                            // source filename of exception
    
protected $line;                            // source line of exception
    
private   $trace;                           // backtrace
    
private   $previous;                        // previous exception if nested exception

    
public function __construct($message null$code 0Exception $previous null);

    final private function 
__clone();           // Inhibits cloning of exceptions.

    
final public  function getMessage();        // message of exception
    
final public  function getCode();           // code of exception
    
final public  function getFile();           // source filename
    
final public  function getLine();           // source line
    
final public  function getTrace();          // an array of the backtrace()
    
final public  function getPrevious();       // previous exception
    
final public  function getTraceAsString();  // formatted string of trace

    /* Overrideable */
    
public function __toString();               // formatted string for display
}
?>

If a class extends the built-in Exception class and re-defines the constructor, it is highly recommended that it also call parent::__construct() to ensure all available data has been properly assigned. The __toString() method can be overridden to provide a custom output when the object is presented as a string.

Informacja: Exceptions cannot be cloned. Attempting to clone an Exception will result in a E_FATAL error.

Przykład #2 Extending the Exception class

<?php
/**
 * Define a custom exception class
 */
class MyException extends Exception
{
    
// Redefine the exception so message isn't optional
    
public function __construct($message$code 0Exception $previous null) {
        
// some code
    
        // make sure everything is assigned properly
        
parent::__construct($message$code$previous);
    }

    
// custom string representation of object
    
public function __toString() {
        return 
__CLASS__ ": [{$this->code}]: {$this->message}\n";
    }

    public function 
customFunction() {
        echo 
"A custom function for this type of exception\n";
    }
}


/**
 * Create a class to test the exception
 */
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 custom exception
                
throw new MyException('1 is an invalid parameter'5);
                break;

            case 
self::THROW_DEFAULT:
                
// throw default one.
                
throw new Exception('2 is not allowed as a parameter'6);
                break;

            default: 
                
// No exception, object will be created.
                
$this->var $avalue;
                break;
        }
    }
}


// Example 1
try {
    
$o = new TestException(TestException::THROW_CUSTOM);
} catch (
MyException $e) {      // Will be caught
    
echo "Caught my exception\n"$e;
    
$e->customFunction();
} catch (
Exception $e) {        // Skipped
    
echo "Caught Default Exception\n"$e;
}

// Continue execution
var_dump($o); // Null
echo "\n\n";


// Example 2
try {
    
$o = new TestException(TestException::THROW_DEFAULT);
} catch (
MyException $e) {      // Doesn't match this type
    
echo "Caught my exception\n"$e;
    
$e->customFunction();
} catch (
Exception $e) {        // Will be caught
    
echo "Caught Default Exception\n"$e;
}

// Continue execution
var_dump($o); // Null
echo "\n\n";


// Example 3
try {
    
$o = new TestException(TestException::THROW_CUSTOM);
} catch (
Exception $e) {        // Will be caught
    
echo "Default Exception caught\n"$e;
}

// Continue execution
var_dump($o); // Null
echo "\n\n";


// Example 4
try {
    
$o = new TestException();
} catch (
Exception $e) {        // Skipped, no exception
    
echo "Default Exception caught\n"$e;
}

// Continue execution
var_dump($o); // TestException
echo "\n\n";
?>



Referencje

Spis treści


Czym są referencje

W PHP referencje są środkiem dostępu do tej samej wartości zmiennej poprzez różne nazwy. Nie działają na takiej zasadzie jak wskaźniki w C, lecz są aliasami w tablicy symboli. Zwróc uwagę na to, że w PHP nazwa zmiennej oraz wartość zmiennej są dwiema różnymi rzeczami, wobec tego ta sama wartość może być dostępna poprzez różne nazwy. Najbliższą analogią jest Uniksowy system plików i ich nazw - nazwy zmiennych to wpisy katalogowe, a wartości to same pliki. Można myśleć o referencjach jak o twardych dowiązaniach w Uniksowym systemie plików.



Co robią referencje

W PHP referencje pozwalają na stworzenie dwu zmiennych zawierających tą samą zawartość. Więc poniższy skrypt:

<?php
$a 
=& $b 
?>

znaczy tyle, że $a oraz $b wskazują na tą samą zmienną.

Informacja: $a oraz $b są całkowicie równe, czyli nie $a wskazuje na $b lub odwrotnie, lecz $a oraz $b wskazują na to samo miejsce.

Ta sama składnia może być używana z funkcjami zwracającymi referencje, i z operatorem new (w PHP 4.0.4 i późniejszych):

<?php
$bar 
=& new foo_klasa();
$foo =& znajdx_zmienna($bar);
?>

Informacja: Brak operatora & powoduje powstanie kopii obiektu. Jeżeli użyjesz $this wewnątrz klasy, zmienna ta będzie pracować na bieżącym egzemplarzu danej klasy. Dowiązanie bez użycia & spowoduje powstanie kopii egzemplarza danej klasy (czyli naszego obiektu) i $this będzie pracować na kopii, co nie jest zwykle tym czego byśmy chcieli. Zwykle pożądane jest posiadanie tylko jednego egzemplarza z którym chcemy pracować, z powodów wydajności i zajętości pamięci.
Pomimo tego, że możliwe jest użycie operatora @ do wyciszenia ewentualnych błędów w konstruktorze podczas użycia go w konstrukcji @new, to zapis ten nie działa kiedy używana jest konstrukcja &new. Jest to ograniczenie silnika Zend (Zend Engine) i użycie takiego zapisu spowoduje błąd parsowania.

Drugą rzeczą na którą pozwalają referencje jest przekazywanie zmiennych przez-referencje. Możliwe jest to przez uczynienie zmiennej lokalnej w funkcji i zmiennej w zakresie wywoływania tej funkcji odwołujacych się do tej samej wartości. Na przykład:

<?php
function foo (&$zmienna)
{
    
$zmienna++;
}

$a=5;
foo ($a);
?>

spowoduje, że $a będzie równe 6. Dzieje się tak, ponieważ w funkcji foo zmienna $zmienna odwołuje się do tej samaj zawartości jak zmienna $a. Zobacz również bardiej dokładne wyjaśniena na temat przekazywania przez referencję.

Trzecią rzeczą którą umożliwiają referencje jest zwracanie przez referencje.



Czym nie są referencje

Jak powiedizano wcześniej, referencje nie są wskaźnikami. To znaczy, że poniższy zapis nie zadziała tak jak się wydaje:

<?php
function foo (&$zmienna)
{
    
$zmienna =& $GLOBALS["baz"];
}
foo($bar);
?>

To, co się faktycznie dzieje, to zmienna $zmienna w funkcji foo będzie związana ze zmienną $bar podczas wywołania, lecz zaraz potem będzie związana po raz wtóry, tym razem z $GLOBALS["baz"]. Nie ma sposobu by związać $bar w zakresie wywoływującym funkcję z czymś innym, używając mechanizmu referencji, ponieważ zmienna $bar nie jest dostępna w funkcji foo (jest tylko reprezentowana przez zmienną $zmienna, lecz $zmienna zawiera tylko wartość zmiennej, a nie jest wiązaniem nazwa-wartość w tablicy symboli).



Przekazywanie przez referencje

Możesz przekazać zmienną do funkcji poprzez referencję, by funkcja mogła modyfikować swoje parametry. Skłania jest jak następuje:

<?php
function foo (&$zmienna)
{
    
$zmienna++;
}

$a=5;
foo ($a);
// $a jest równe 6 w tym momencie
?>

Weź pod uwagę to, że nie ma znaku odwoływania się przez referencję przy wywoływaniu funkcji - istnieje tylko w definicji funkcji. Sama definicja funkcji jest wystarczającym miejscem do zaznaczenia przekazywania argumentów przez referencję.

Przez referencję mogą być przekazywane następujące rzeczy:

  • Zmienne, np. foo($a)
  • Instrukcja new, np. foo(new foobar())
  • Referencję, zwracane z funkcji, np.:

    <?php
    function &bar()
    {
        
    $a 5;
        return 
    $a;
    }
    foo(bar());
    ?>

    Zobacz również wyjaśnienia na temat zwracania przez referencję.

Każde inne wyrażenie nie powinno być przekazywane przez referencję, ponieważ wynik takiego przekazania jest nieprzewidywalny. Dla przykładu, poniższe przykłady przekazywania przez referencję są niepoprawne:

<?php
function bar() // Zwróć uwagę na brak &
{
    
$a 5;
    return 
$a;
}
foo(bar());

foo($a 5); // Wyrażenie, nie zmienna
foo(5); // Stała, nie zmienna
?>

Te wymagania są dla PHP 4.0.4 i wyższych wersji.



Zwracanie referencji

Zwracanie przez-referencję jest użyteczne gdy chcesz użyć funkcji do znalezienia zmiennej do której referencją powinna być dowiązana. Zwracając referencje używaj tej składni:

<?php
function &znajdz_zmienna ($param)
{
    
/* ...kod... */
    
return $znaleziona_zmienna;
}

$foo =& znajdz_zmienna ($bar);
$foo->2;
?>

W tym przykładzie, będzie zmieniona własność obiektu zwróconego przez funkcję znajdz_zmienna, a nie własność kopii obiektu, jak to by było bez użycia składni referencji.

Informacja: Inaczej niż przy przekazywaniu parametrów, tutaj musisz używać & w obu miejscach - by wskazać, że zwracasz przez-referencję, a nie kopię jak normalnie, i by zwrócić uwagę, że dla zmiennej $foo powinno być użyte powiązanie przez referencję, a nie zwykłe przypisanie.



Niszczenie referencji

Kiedy niszczysz referencje, zrywasz wiązanie między nazwą zmiennej a jej zawartością. Nie znaczy to, że ta zawartość będzie zniszczona. Na przykład:

<?php
$a 
1;
$b =& $a;
unset (
$a); 
?>

nie zniszczy $b, tylko $a.

Znów, pomocne będzie pomyślenie o tym jak o analogii do Uniksowego wywołania unlink.



Znajdywanie referencji

Wiele konstrukcji składniowych w PHP jest zaimplementowanych przy użyciu referencji, tak więc wszystko co zostało powiedziane wcześniej o referencjach dotyczyć będzie również tych konstrukcji. Pewne konstrukcje, jak przekazywanie i zwracanie przez referencje, są wspomniane wyżej. Innymi konstrukcjami używającymi mechanizmu referencji są:

Referencje konstrukcji global

Kiedy deklarujesz zmienną jako global $var to tak naprawdę tworzysz referencję do zmiennej globalnej. To znaczy, że działa to tak samo jak:

<?php
$zmienna 
=& $GLOBALS["zmienna"];
?>

To znaczy, na przykład, że usunięcie $zmienna nie usunie zmiennej globalnej.

$this

W metodach obiektowych, $this jest zawsze referencją do obiektu wywłującego daną metodę.




Predefined Variables

PHP provides a large number of predefined variables to all scripts. The variables represent everything from external variables to built-in environment variables, last error messages to last retrieved headers.

See also the FAQ titled "How does register_globals affect me?"


Superglobals

SuperglobalsSuperglobals are built-in variables that are always available in all scopes

Opis

Several predefined variables in PHP are "superglobals", which means they are available in all scopes throughout a script. There is no need to do global $variable; to access them within functions or methods.

These superglobal variables are:

Rejestr zmian

Wersja Opis
4.1.0 Superglobals were introduced to PHP.

Notatki

Informacja: Variable availability
By default, all of the superglobals are available but there are directives that affect this availability. For further information, refer to the documentation for variables_order.

Informacja: Dealing with register_globals
If the deprecated register_globals directive is set to on then the variables within will also be made available in the global scope of the script. For example, $_POST['foo'] would also exist as $foo.
For related information, see the FAQ titled "How does register_globals affect me?"

Informacja: Variable variables
Superglobals cannot be used as variable variables inside functions or class methods.



$GLOBALS

$GLOBALSReferences all variables available in global scope

Opis

An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

Przykłady

Przykład #1 $GLOBALS example

<?php
function test() {
    
$foo "local variable";

    echo 
'$foo in global scope: ' $GLOBALS["foo"] . "\n";
    echo 
'$foo in current scope: ' $foo "\n";
}

$foo "Example content";
test();
?>

Powyższy przykład wyświetli coś podobnego do:

$foo in global scope: Example content
$foo in current scope: local variable

Notatki

Informacja: To jest zmienna 'superglobalna' lub automatycznie ustawiona na globalną. To po prostu oznacza, że jest dostępna w każdym miejscu skryptu. Nie jest konieczne użycie global $zmienna; aby mieć do niej dostęp w funkcjach i metodach.

Informacja: Variable availability
Unlike all of the other superglobals, $GLOBALS has essentially always been available in PHP.



$_SERVER

$HTTP_SERVER_VARS [deprecated]

$_SERVER -- $HTTP_SERVER_VARS [deprecated]Server and execution environment information

Opis

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. That said, a large number of these variables are accounted for in the » CGI 1.1 specification, so you should be able to expect those.

$HTTP_SERVER_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_SERVER_VARS and $_SERVER are different variables and that PHP handles them as such)

Wykaz zmiennych

You may or may not find any of the following elements in $_SERVER. Note that few, if any, of these will be available (or indeed have any meaning) if running PHP on the command line.

'PHP_SELF'
The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar would be /test.php/foo.bar. The __FILE__ constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. Previously it was not available.
'argv'
Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string.
'argc'
Contains the number of command line parameters passed to the script (if run on the command line).
'GATEWAY_INTERFACE'
What revision of the CGI specification the server is using; i.e. 'CGI/1.1'.
'SERVER_ADDR'
The IP address of the server under which the current script is executing.
'SERVER_NAME'
The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.
'SERVER_SOFTWARE'
Server identification string, given in the headers when responding to requests.
'SERVER_PROTOCOL'
Name and revision of the information protocol via which the page was requested; i.e. 'HTTP/1.0';
'REQUEST_METHOD'
Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.

Informacja: PHP script is terminated after sending headers (it means after producing any output without output buffering) if the request method was HEAD.

'REQUEST_TIME'
The timestamp of the start of the request. Available since PHP 5.1.0.
'QUERY_STRING'
The query string, if any, via which the page was accessed.
'DOCUMENT_ROOT'
The document root directory under which the current script is executing, as defined in the server's configuration file.
'HTTP_ACCEPT'
Contents of the Accept: header from the current request, if there is one.
'HTTP_ACCEPT_CHARSET'
Contents of the Accept-Charset: header from the current request, if there is one. Example: 'iso-8859-1,*,utf-8'.
'HTTP_ACCEPT_ENCODING'
Contents of the Accept-Encoding: header from the current request, if there is one. Example: 'gzip'.
'HTTP_ACCEPT_LANGUAGE'
Contents of the Accept-Language: header from the current request, if there is one. Example: 'en'.
'HTTP_CONNECTION'
Contents of the Connection: header from the current request, if there is one. Example: 'Keep-Alive'.
'HTTP_HOST'
Contents of the Host: header from the current request, if there is one.
'HTTP_REFERER'
The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
'HTTP_USER_AGENT'
Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Among other things, you can use this value with get_browser() to tailor your page's output to the capabilities of the user agent.
'HTTPS'
Set to a non-empty value if the script was queried through the HTTPS protocol.

Informacja: Note that when using ISAPI with IIS, the value will be off if the request was not made through the HTTPS protocol.

'REMOTE_ADDR'
The IP address from which the user is viewing the current page.
'REMOTE_HOST'
The Host name from which the user is viewing the current page. The reverse dns lookup is based off the REMOTE_ADDR of the user.

Informacja: Your web server must be configured to create this variable. For example in Apache you'll need HostnameLookups On inside httpd.conf for it to exist. See also gethostbyaddr().

'REMOTE_PORT'
The port being used on the user's machine to communicate with the web server.
'SCRIPT_FILENAME'

The absolute pathname of the currently executing script.

Informacja: If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user.

'SERVER_ADMIN'
The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host.
'SERVER_PORT'
The port on the server machine being used by the web server for communication. For default setups, this will be '80'; using SSL, for instance, will change this to whatever your defined secure HTTP port is.
'SERVER_SIGNATURE'
String containing the server version and virtual host name which are added to server-generated pages, if enabled.
'PATH_TRANSLATED'
Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping.

Informacja: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly under the Apache 2 SAPI in contrast to the situation in Apache 1, where it's set to the same value as the SCRIPT_FILENAME server variable when it's not populated by Apache. This change was made to comply with the CGI specification that PATH_TRANSLATED should only exist if PATH_INFO is defined. Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO.

'SCRIPT_NAME'
Contains the current script's path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.
'REQUEST_URI'
The URI which was given in order to access this page; for instance, '/index.html'.
'PHP_AUTH_DIGEST'
When running under Apache as module doing Digest HTTP authentication this variable is set to the 'Authorization' header sent by the client (which you should then use to make the appropriate validation).
'PHP_AUTH_USER'
When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP authentication this variable is set to the username provided by the user.
'PHP_AUTH_PW'
When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP authentication this variable is set to the password provided by the user.
'AUTH_TYPE'
When running under Apache as module doing HTTP authenticated this variable is set to the authentication type.
'PATH_INFO'
Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. For instance, if the current script was accessed via the URL http://www.example.com/php/path_info.php/some/stuff?foo=bar, then $_SERVER['PATH_INFO'] would contain /some/stuff.

Rejestr zmian

Wersja Opis
4.1.0 Introduced $_SERVER that deprecated $HTTP_SERVER_VARS.

Przykłady

Przykład #1 $_SERVER example

<?php
echo $_SERVER['SERVER_NAME'];
?>

Powyższy przykład wyświetli coś podobnego do:

www.example.com

Notatki

Informacja: To jest zmienna 'superglobalna' lub automatycznie ustawiona na globalną. To po prostu oznacza, że jest dostępna w każdym miejscu skryptu. Nie jest konieczne użycie global $zmienna; aby mieć do niej dostęp w funkcjach i metodach.

Zobacz też:



$_GET

$HTTP_GET_VARS [deprecated]

$_GET -- $HTTP_GET_VARS [deprecated]HTTP GET variables

Opis

An associative array of variables passed to the current script via the URL parameters.

$HTTP_GET_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_GET_VARS and $_GET are different variables and that PHP handles them as such)

Rejestr zmian

Wersja Opis
4.1.0 Introduced $_GET that deprecated $HTTP_GET_VARS.

Przykłady

Przykład #1 $_GET example

<?php
echo 'Hello ' htmlspecialchars($_GET["name"]) . '!';
?>

Assuming the user entered http://example.com/?name=Hannes

Powyższy przykład wyświetli coś podobnego do:

Hello Hannes!

Notatki

Informacja: To jest zmienna 'superglobalna' lub automatycznie ustawiona na globalną. To po prostu oznacza, że jest dostępna w każdym miejscu skryptu. Nie jest konieczne użycie global $zmienna; aby mieć do niej dostęp w funkcjach i metodach.



$_POST

$HTTP_POST_VARS [deprecated]

$_POST -- $HTTP_POST_VARS [deprecated]HTTP POST variables

Opis

An associative array of variables passed to the current script via the HTTP POST method.

$HTTP_POST_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_POST_VARS and $_POST are different variables and that PHP handles them as such)

Rejestr zmian

Wersja Opis
4.1.0 Introduced $_POST that deprecated $HTTP_POST_VARS.

Przykłady

Przykład #1 $_POST example

<?php
echo 'Hello ' htmlspecialchars($_POST["name"]) . '!';
?>

Assuming the user POSTed name=Hannes

Powyższy przykład wyświetli coś podobnego do:

Hello Hannes!

Notatki

Informacja: To jest zmienna 'superglobalna' lub automatycznie ustawiona na globalną. To po prostu oznacza, że jest dostępna w każdym miejscu skryptu. Nie jest konieczne użycie global $zmienna; aby mieć do niej dostęp w funkcjach i metodach.



$_FILES

$HTTP_POST_FILES [deprecated]

$_FILES -- $HTTP_POST_FILES [deprecated]HTTP File Upload variables

Opis

An associative array of items uploaded to the current script via the HTTP POST method.

$HTTP_POST_FILES contains the same initial information, but is not a superglobal. (Note that $HTTP_POST_FILES and $_FILES are different variables and that PHP handles them as such)

Rejestr zmian

Wersja Opis
4.1.0 Introduced $_FILES that deprecated $HTTP_POST_FILES.

Notatki

Informacja: To jest zmienna 'superglobalna' lub automatycznie ustawiona na globalną. To po prostu oznacza, że jest dostępna w każdym miejscu skryptu. Nie jest konieczne użycie global $zmienna; aby mieć do niej dostęp w funkcjach i metodach.

Zobacz też:



$_REQUEST

$_REQUESTHTTP Request variables

Opis

An associative array that by default contains the contents of $_GET, $_POST i $_COOKIE.

Rejestr zmian

Wersja Opis
5.3.0 Introduced request_order. This directive affects the contents of $_REQUEST.
4.3.0 $_FILES information was removed from $_REQUEST.
4.1.0 Introduced $_REQUEST.

Notatki

Informacja: To jest zmienna 'superglobalna' lub automatycznie ustawiona na globalną. To po prostu oznacza, że jest dostępna w każdym miejscu skryptu. Nie jest konieczne użycie global $zmienna; aby mieć do niej dostęp w funkcjach i metodach.

Informacja: When running on the command line , this will not include the argv and argc entries; these are present in the $_SERVER array.

Informacja: The variables in $_REQUEST are provided to the script via the GET, POST, and COOKIE input mechanisms and therefore could be modified by the remote user and cannot be trusted. The presence and order of variables listed in this array is defined according to the PHP variables_order configuration directive.

Zobacz też:



$_SESSION

$HTTP_SESSION_VARS [deprecated]

$_SESSION -- $HTTP_SESSION_VARS [deprecated]Session variables

Opis

An associative array containing session variables available to the current script. See the Session functions documentation for more information on how this is used.

$HTTP_SESSION_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_SESSION_VARS and $_SESSION are different variables and that PHP handles them as such)

Rejestr zmian

Wersja Opis
4.1.0 Introduced $_SESSION that deprecated $HTTP_SESSION_VARS.

Notatki

Informacja: To jest zmienna 'superglobalna' lub automatycznie ustawiona na globalną. To po prostu oznacza, że jest dostępna w każdym miejscu skryptu. Nie jest konieczne użycie global $zmienna; aby mieć do niej dostęp w funkcjach i metodach.

Zobacz też:



$_ENV

$HTTP_ENV_VARS [deprecated]

$_ENV -- $HTTP_ENV_VARS [deprecated]Environment variables

Opis

An associative array of variables passed to the current script via the environment method.

These variables are imported into PHP's global namespace from the environment under which the PHP parser is running. Many are provided by the shell under which PHP is running and different systems are likely running different kinds of shells, a definitive list is impossible. Please see your shell's documentation for a list of defined environment variables.

Other environment variables include the CGI variables, placed there regardless of whether PHP is running as a server module or CGI processor.

$HTTP_ENV_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_ENV_VARS and $_ENV are different variables and that PHP handles them as such)

Rejestr zmian

Wersja Opis
4.1.0 Introduced $_ENV that deprecated $HTTP_ENV_VARS.

Przykłady

Przykład #1 $_ENV example

<?php
echo 'My username is ' .$_ENV["USER"] . '!';
?>

Assuming "bjori" executes this script

Powyższy przykład wyświetli coś podobnego do:

My username is bjori!

Notatki

Informacja: To jest zmienna 'superglobalna' lub automatycznie ustawiona na globalną. To po prostu oznacza, że jest dostępna w każdym miejscu skryptu. Nie jest konieczne użycie global $zmienna; aby mieć do niej dostęp w funkcjach i metodach.

Zobacz też:



$_COOKIE

$HTTP_COOKIE_VARS [deprecated]

$_COOKIE -- $HTTP_COOKIE_VARS [deprecated]HTTP Cookies

Opis

An associative array of variables passed to the current script via HTTP Cookies.

$HTTP_COOKIE_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_COOKIE_VARS and $_COOKIE are different variables and that PHP handles them as such)

Rejestr zmian

Wersja Opis
4.1.0 Introduced $_COOKIE that deprecated $HTTP_COOKIE_VARS.

Przykłady

Przykład #1 $_COOKIE example

<?php
echo 'Hello ' htmlspecialchars($_COOKIE["name"]) . '!';
?>

Assuming the "name" cookie has been set earlier

Powyższy przykład wyświetli coś podobnego do:

Hello Hannes!

Notatki

Informacja: To jest zmienna 'superglobalna' lub automatycznie ustawiona na globalną. To po prostu oznacza, że jest dostępna w każdym miejscu skryptu. Nie jest konieczne użycie global $zmienna; aby mieć do niej dostęp w funkcjach i metodach.



$php_errormsg

$php_errormsgThe previous error message

Opis

$php_errormsg is a variable containing the text of the last error message generated by PHP. This variable will only be available within the scope in which the error occurred, and only if the track_errors configuration option is turned on (it defaults to off).

Informacja: This variable is only available when track_errors is enabled in php.ini.

Ostrzeżenie

If a user defined error handler (set_error_handler()) is set $php_errormsg is only set if the error handler returns FALSE

Przykłady

Przykład #1 $php_errormsg example

<?php
@strpos();
echo 
$php_errormsg;
?>

Powyższy przykład wyświetli coś podobnego do:

Wrong parameter count for strpos()



$HTTP_RAW_POST_DATA

$HTTP_RAW_POST_DATARaw POST data

Opis

$HTTP_RAW_POST_DATA contains the raw POST data. See always_populate_raw_post_data



$http_response_header

$http_response_headerHTTP response headers

Opis

The $http_response_header array is similar to the get_headers() function. When using the HTTP wrapper, $http_response_header will be populated with the HTTP response headers.

Przykłady

Przykład #1 $http_response_header example

<?php
file_get_contents
("http://example.com");
var_dump($http_response_header);
?>

Powyższy przykład wyświetli coś podobnego do:

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

$argcThe number of arguments passed to script

Opis

Contains the number of arguments passed to the current script when running from the command line.

Informacja: The script's filename is always passed as an argument to the script, therefore the minimum value of $argc is 1.

Informacja: This variable is only available when register_argc_argv is enabled.

Przykłady

Przykład #1 $argc example

<?php
var_dump
($argc);
?>

When executing the example with: php script.php arg1 arg2 arg3

Powyższy przykład wyświetli coś podobnego do:

int(4)



$argv

$argvArray of arguments passed to script

Opis

Contains an array of all the arguments passed to the script when running from the command line.

Informacja: The first argument is always the current script's filename, therefore $argv[0] is the script's name.

Informacja: This variable is only available when register_argc_argv is enabled.

Przykłady

Przykład #1 $argv example

<?php
var_dump
($argv);
?>

When executing the example with: php script.php arg1 arg2 arg3

Powyższy przykład wyświetli coś podobnego do:

array(4) {
  [0]=>
  string(10) "script.php"
  [1]=>
  string(4) "arg1"
  [2]=>
  string(4) "arg2"
  [3]=>
  string(4) "arg3"
}


Spis treści



Predefined Exceptions

Spis treści

See also the SPL Exceptions


Exception

Wstęp

Exception is the base class for all Exceptions.

Krótki opis klasy

Exception
Exception {
/* Properties */
protected string $message ;
private string $string ;
protected int $code ;
protected string $file ;
protected int $line ;
private array $trace ;
/* Methods */
public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] )
final public string getMessage ( void )
final public Exception getPrevious ( void )
final public int getCode ( void )
final public string getFile ( void )
final public int getLine ( void )
final public array getTrace ( void )
final public string getTraceAsString ( void )
public string __toString ( void )
final private void __clone ( void )
}

Właściwości

message

The exception message

string

Internal Exception name

code

The Exception code

file

The filename where the exception was thrown

line

The line where the exception was thrown

trace

The stack trace


Exception::__construct

(PHP 5 >= 5.1.0)

Exception::__constructConstruct the exception

Opis

public Exception::__construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] )

Constructs the Exception.

Parametry

message

The Exception message to throw.

code

The Exception code.

previous

The previous exception used for the exception chaining.

Rejestr zmian

Wersja Opis
5.3.0 The previous parameter was added.



Exception::getMessage

(PHP 5 >= 5.1.0)

Exception::getMessageGets the Exception message

Opis

final public string Exception::getMessage ( void )

Returns the Exception message.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the Exception message as a string.

Przykłady

Przykład #1 Exception::getMessage() example

<?php
try {
    throw new 
Exception("Some error message");
} catch(
Exception $e) {
    echo 
$e->getMessage();
}
?>

Powyższy przykład wyświetli coś podobnego do:

Some error message



Exception::getPrevious

(PHP 5 >= 5.3.0)

Exception::getPreviousReturns previous Exception

Opis

final public Exception Exception::getPrevious ( void )

Returns previous Exception (the third parameter of Exception::__construct).

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the previous Exception if available or NULL otherwise.

Przykłady

Przykład #1 Exception::getPrevious example

Looping over, and printing out, exception trace.

<?php
class MyCustomException extends Exception {}

function 
doStuff() {
    try {
        throw new 
InvalidArgumentException("You are doing it wrong!"112);
    } catch(
Exception $e) {
        throw new 
MyCustomException("Something happend"911$e);
    }
}


try {
    
doStuff();
} catch(
Exception $e) {
    do {
        
printf("%s:%d %s (%d) [%s]\n"$e->getFile(), $e->getLine(), $e->getMessage(), $e->getCode(), get_class($e));
    } while(
$e $e->getPrevious());
}
?>

Powyższy przykład wyświetli coś podobnego do:

/home/bjori/ex.php:8 Something happend (911) [MyCustomException]
/home/bjori/ex.php:6 You are doing it wrong! (112) [InvalidArgumentException]



Exception::getCode

(PHP 5 >= 5.1.0)

Exception::getCodeGets the Exception code

Opis

final public int Exception::getCode ( void )

Returns the Exception code.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the Exception code as a integer.

Przykłady

Przykład #1 Exception::getCode() example

<?php
try {
    throw new 
Exception("Some error message"30);
} catch(
Exception $e) {
    echo 
"The exception code is: " $e->getCode();
}
?>

Powyższy przykład wyświetli coś podobnego do:

The exception code is: 30



Exception::getFile

(PHP 5 >= 5.1.0)

Exception::getFileGets the file in which the exception occurred

Opis

final public string Exception::getFile ( void )

Get the name of the file the exception was thrown from.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the filename in which the exception was thrown.

Przykłady

Przykład #1 Exception::getFile() example

<?php
try {
    throw new 
Exception;
} catch(
Exception $e) {
    echo 
$e->getFile();
}
?>

Powyższy przykład wyświetli coś podobnego do:

/home/bjori/tmp/ex.php



Exception::getLine

(PHP 5 >= 5.1.0)

Exception::getLineGets the line in which the exception occurred

Opis

final public int Exception::getLine ( void )

Returns line number where the exception was thrown.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the line number where the exception was thrown.

Przykłady

Przykład #1 Exception::getLine() example

<?php
try {
    throw new 
Exception("Some error message");
} catch(
Exception $e) {
    echo 
"The exception was thrown on line: " $e->getLine();
}
?>

Powyższy przykład wyświetli coś podobnego do:

The exception was thrown on line: 3



Exception::getTrace

(PHP 5 >= 5.1.0)

Exception::getTraceGets the stack trace

Opis

final public array Exception::getTrace ( void )

Returns the Exception stack trace.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the Exception stack trace as an array.

Przykłady

Przykład #1 Exception::getTrace() example

<?php
function test() {
 throw new 
Exception;
}

try {
 
test();
} catch(
Exception $e) {
 
var_dump($e->getTrace());
}
?>

Powyższy przykład wyświetli coś podobnego do:

array(1) {
  [0]=>
  array(4) {
    ["file"]=>
    string(22) "/home/bjori/tmp/ex.php"
    ["line"]=>
    int(7)
    ["function"]=>
    string(4) "test"
    ["args"]=>
    array(0) {
    }
  }
}



Exception::getTraceAsString

(PHP 5 >= 5.1.0)

Exception::getTraceAsStringGets the stack trace as a string

Opis

final public string Exception::getTraceAsString ( void )

Returns the Exception stack trace as a string.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the Exception stack trace as a string.

Przykłady

Przykład #1 Exception::getTraceAsString() example

<?php
function test() {
    throw new 
Exception;
}

try {
    
test();
} catch(
Exception $e) {
    echo 
$e->getTraceAsString();
}
?>

Powyższy przykład wyświetli coś podobnego do:

#0 /home/bjori/tmp/ex.php(7): test()
#1 {main}



Exception::__toString

(PHP 5 >= 5.1.0)

Exception::__toStringString representation of the exception

Opis

public string Exception::__toString ( void )

Returns the string representation of the exception.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the string representation of the exception.

Przykłady

Przykład #1 Exception::__toString() example

<?php
try {
    throw new 
Exception("Some error message");
} catch(
Exception $e) {
    echo 
$e;
}
?>

Powyższy przykład wyświetli coś podobnego do:

exception 'Exception' with message 'Some error message' in /home/bjori/tmp/ex.php:3
Stack trace:
#0 {main}



Exception::__clone

(PHP 5 >= 5.1.0)

Exception::__cloneClone the exception

Opis

final private void Exception::__clone ( void )

Tries to clone the Exception, which results in Fatal error.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

nie jest zwracana żadna wartość.

Błędy/Wyjątki

Exceptions are not clonable.


Spis treści



ErrorException

Wstęp

An Error Exception.

Krótki opis klasy

ErrorException
ErrorException extends Exception {
/* Properties */
protected int $severity ;
/* Methods */
public __construct ([ string $message [, int $code [, int $severity [, string $filename [, int $lineno ]]]]] )
final public int getSeverity ( void )
/* Inherited methods */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public int Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

Właściwości

severity

The severity of the exception

Przykłady

Przykład #1 Use set_error_handler() to change error messages into ErrorException.

<?php
function exception_error_handler($errno$errstr$errfile$errline ) {
    throw new 
ErrorException($errstr0$errno$errfile$errline);
}
set_error_handler("exception_error_handler");

/* Trigger exception */
strpos();
?>

Powyższy przykład wyświetli coś podobnego do:

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


ErrorException::__construct

(PHP 5 >= 5.1.0)

ErrorException::__constructConstruct the exception

Opis

public ErrorException::__construct ([ string $message [, int $code [, int $severity [, string $filename [, int $lineno ]]]]] )

Constructs the Exception.

Parametry

message

The Exception message to throw.

code

The Exception code.

severity

The severity level of the exception.

filename

The filename where the exception is thrown.

lineno

The line number where the exception is thrown.



ErrorException::getSeverity

(PHP 5 >= 5.1.0)

ErrorException::getSeverityGets the exception severity

Opis

final public int ErrorException::getSeverity ( void )

Returns the severity of the exception.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the severity level of the exception.

Przykłady

Przykład #1 ErrorException::getSeverity() example

<?php
try {
    throw new 
ErrorException("Exception message"075);
} catch(
ErrorException $e) {
    echo 
"This exception severity is: " $e->getSeverity();
}
?>

Powyższy przykład wyświetli coś podobnego do:

This exception severity is: 75


Spis treści




Predefined Interfaces

Spis treści

See also the SPL Interfaces


The Traversable interface

Wstęp

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.

Informacja: Internal (built-in) classes that implement this interface can be used in a foreach construct and do not need to implement IteratorAggregate or Iterator.

Informacja: This is an internal engine interface which cannot be implemented in PHP scripts. Either IteratorAggregate or Iterator must be used instead.

Zestawienie interfejsu

Traversable
Traversable {
}

This interface has no methods, its only purpose is to be the base interface for all traversable classes.



The Iterator interface

Wstęp

Interface for external iterators or objects that can be iterated themselves internally.

Zestawienie interfejsu

Iterator
Iterator extends Traversable {
/* Methods */
abstract public mixed current ( void )
abstract public scalar key ( void )
abstract public void next ( void )
abstract public void rewind ( void )
abstract public boolean valid ( void )
}

Przykład #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";
}
?>

Powyższy przykład wyświetli coś podobnego do:

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"

Iterator::current

(PHP 5 >= 5.1.0)

Iterator::currentReturn the current element

Opis

abstract public mixed Iterator::current ( void )

Returns the current element.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Can return any type.



Iterator::key

(PHP 5 >= 5.1.0)

Iterator::keyReturn the key of the current element

Opis

abstract public scalar Iterator::key ( void )

Returns the key of the current element.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns scalar on success, integer 0 on failure.

Błędy/Wyjątki

Issues E_WARNING on failure.



Iterator::next

(PHP 5 >= 5.1.0)

Iterator::nextMove forward to next element

Opis

abstract public void Iterator::next ( void )

Moves the current position to the next element.

Informacja: This method is called after each foreach loop.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Any returned value is ignored.



Iterator::rewind

(PHP 5 >= 5.1.0)

Iterator::rewindRewind the Iterator to the first element

Opis

abstract public void Iterator::rewind ( void )

Rewinds back to the first element of the Iterator.

Informacja: This is the first method called when starting a foreach loop. It will not be executed after foreach loops.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Any returned value is ignored.



Iterator::valid

(PHP 5 >= 5.1.0)

Iterator::validChecks if current position is valid

Opis

abstract public boolean Iterator::valid ( void )

This method is called after Iterator::rewind and Iterator::next to check if the current position is valid.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The return value will be casted to boolean and then evaluated. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.


Spis treści



The IteratorAggregate interface

Wstęp

Interface to create an external Iterator.

Zestawienie interfejsu

IteratorAggregate
IteratorAggregate extends Traversable {
/* Methods */
abstract public Traversable getIterator ( void )
}

Przykład #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";
}
?>

Powyższy przykład wyświetli coś podobnego do:

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"


IteratorAggregate::getIterator

(PHP 5 >= 5.1.0)

IteratorAggregate::getIteratorRetrieve an external iterator

Opis

abstract public Traversable IteratorAggregate::getIterator ( void )

Returns an external iterator.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An instance of an object implementing Iterator or Traversable

Błędy/Wyjątki

Throws an Exception on failure.


Spis treści



The ArrayAccess interface

Wstęp

Interface to provide accessing objects as arrays.

Zestawienie interfejsu

ArrayAccess
ArrayAccess {
/* Methods */
abstract public boolean offsetExists ( mixed $offset )
abstract public mixed offsetGet ( mixed $offset )
abstract public void offsetSet ( mixed $offset , mixed $value )
abstract public void offsetUnset ( mixed $offset )
}

Przykład #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"]);

?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
int(2)
bool(false)
string(7) "A value"

ArrayAccess::offsetExists

(PHP 5 >= 5.1.0)

ArrayAccess::offsetExistsWhether a offset exists

Opis

abstract public boolean ArrayAccess::offsetExists ( mixed $offset )

Whether or not an offset exists.

This method is executed when using isset() or empty() on objects implementing ArrayAccess.

Informacja: When using empty() ArrayAccess::offsetGet() will be called and checked if empty only if ArrayAccess::offsetExists() returns TRUE.

Parametry

offset

An offset to check for.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Informacja: The return value will be casted to boolean if non-boolean was returned.

Przykłady

Przykład #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"]));
?>

Powyższy przykład wyświetli coś podobnego do:

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)



ArrayAccess::offsetGet

(PHP 5 >= 5.1.0)

ArrayAccess::offsetGetOffset to retrieve

Opis

abstract public mixed ArrayAccess::offsetGet ( mixed $offset )

Returns the value at specified offset.

This method is executed when checking if offset is empty().

Parametry

offset

The offset to retrieve.

Zwracane wartości

Can return all value types.

Zobacz też:



ArrayAccess::offsetSet

(PHP 5 >= 5.1.0)

ArrayAccess::offsetSetOffset to set

Opis

abstract public void ArrayAccess::offsetSet ( mixed $offset , mixed $value )

Assigns a value to the specified offset.

Parametry

offset

The offset to assign the value to.

value

The value to set.

Zwracane wartości

nie jest zwracana żadna wartość.



ArrayAccess::offsetUnset

(PHP 5 >= 5.1.0)

ArrayAccess::offsetUnsetOffset to unset

Opis

abstract public void ArrayAccess::offsetUnset ( mixed $offset )

Unsets an offset.

Informacja: This method will not be called when type-casting to (unset)

Parametry

offset

The offset to unset.

Zwracane wartości

nie jest zwracana żadna wartość.


Spis treści



The Serializable interface

Wstęp

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.

Zestawienie interfejsu

Serializable
Serializable {
/* Methods */
abstract public string serialize ( void )
abstract public mixed unserialize ( string $serialized )
}

Przykład #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());
?>

Powyższy przykład wyświetli coś podobnego do:

string(15) "My private data"

Serializable::serialize

(PHP 5 >= 5.1.0)

Serializable::serializeString representation of object

Opis

abstract public string Serializable::serialize ( void )

Should return the string representation of the object.

Informacja: This method acts as the destructor of the object. The __destruct() method will not be called after this method.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the string representation of the object or NULL

Błędy/Wyjątki

Throws Exception when returning other types then strings and NULL

Zobacz też:



Serializable::unserialize

(PHP 5 >= 5.1.0)

Serializable::unserializeConstructs the object

Opis

abstract public mixed Serializable::unserialize ( string $serialized )

Called during unserialization of the object.

Informacja: This method acts as the constructor of the object. The __construct() method will not be called after this method.

Parametry

serialized

The string representation of the object.

Zwracane wartości

Returns the original value unserialized.

Zobacz też:


Spis treści




Context options and parameters

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().


Socket context options

Socket context optionsSocket context option listing

Opis

Socket context options are available for all wrappers that work over sockets, like tcp, http and ftp.

Opcje

bindto

Used to specify the IP address (either IPv4 or IPv6) and/or the port number that PHP will use to access the network. The syntax is ip:port. Setting the IP or the port to 0 will let the system choose the IP and/or port.

Informacja: As FTP creates two socket connections during normal operation, the port number cannot be specified using this option.

Rejestr zmian

Wersja Opis
5.1.0 Added bindto.

Przykłady

Przykład #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 optionsHTTP context option listing

Opis

Context options for http:// and https:// transports.

Opcje

method string

GET, POST, or any other HTTP method supported by the remote server.

Defaults to GET.

header string

Additional headers to be sent during request. Values in this option will override other values (such as User-agent:, Host:, and Authentication:).

user_agent string

Value to send with User-Agent: header. This value will only be used if user-agent is not specified in the header context option above.

By default the user_agent php.ini setting is used.

content string

Additional data to be sent after the headers. Typically used with POST or PUT requests.

proxy string

URI specifying address of proxy server. (e.g. tcp://proxy.example.com:5100).

request_fulluri boolean

When set to TRUE, the entire URI will be used when constructing the request. (i.e. GET http://www.example.com/path/to/file.html HTTP/1.0). While this is a non-standard request format, some proxy servers require it.

Defaults to FALSE.

max_redirects integer

The max number of redirects to follow. Value 1 or less means that no redirects are followed.

Defaults to 20.

protocol_version float

HTTP protocol version.

Defaults to 1.0.

Informacja: PHP prior to 5.3.0 does not implement chunked transfer decoding. If this value is set to 1.1 it is your responsibility to be 1.1 compliant.

timeout float

Read timeout in seconds, specified by a float (e.g. 10.5).

By default the default_socket_timeout php.ini setting is used.

ignore_errors boolean

Fetch the content even on failure status codes.

Defaults to FALSE

Rejestr zmian

Wersja Opis
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 .

Przykłady

Przykład #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);

?>

Notatki

Informacja: 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.



FTP context options

FTP context optionsFTP context option listing

Opis

Context options for ftp:// and ftps:// transports.

Opcje

overwrite boolean

Allow overwriting of already existing files on remote server. Applies to write mode (uploading) only.

Defaults to FALSE.

resume_pos integer

File offset at which to begin transfer. Applies to read mode (downloading) only.

Defaults to 0 (Beginning of File).

proxy string

Proxy FTP request via http proxy server. Applies to file read operations only. Ex: tcp://squid.example.com:8000.

Rejestr zmian

Wersja Opis
5.1.0 Added proxy .
5.0.0 Added overwrite and resume_pos .

Notatki

Informacja: 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.



SSL context options

SSL context optionsSSL context option listing

Opis

Context options for ssl:// and tls:// transports.

Opcje

verify_peer boolean

Require verification of SSL certificate used.

Defaults to FALSE.

allow_self_signed boolean

Allow self-signed certificates.

Defaults to FALSE

cafile string

Location of Certificate Authority file on local filesystem which should be used with the verify_peer context option to authenticate the identity of the remote peer.

capath string

If cafile is not specified or if the certificate is not found there, the directory pointed to by capath is searched for a suitable certificate. capath must be a correctly hashed certificate directory.

local_cert string

Path to local certificate file on filesystem. It must be a PEM encoded file which contains your certificate and private key. It can optionally contain the certificate chain of issuers.

passphrase string

Passphrase with which your local_cert file was encoded.

CN_match string

Common Name we are expecting. PHP will perform limited wildcard matching. If the Common Name does not match this, the connection attempt will fail.

verify_depth integer

Abort if the certificate chain is too deep.

Defaults to no verification.

ciphers string

Sets the list of available ciphers. The format of the string is described in » ciphers(1).

Defaults to DEFAULT.

capture_peer_cert boolean

If set to TRUE a peer_certificate context option will be created containing the peer certificate.

capture_peer_chain boolean

If set to TRUE a peer_certificate_chain context option will be created containing the certificate chain.

Rejestr zmian

Wersja Opis
5.0.0 Added capture_peer_cert , capture_peer_chain and ciphers .

Notatki

Informacja: 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://.

Zobacz też:



CURL context options

CURL context optionsCURL context option listing

Opis

CURL context options are available when the CURL extension was compiled using the --with-curlwrappers configure option.

Opcje

method string

GET, POST, or any other HTTP method supported by the remote server.

Defaults to GET.

header string

Additional headers to be sent during request. Values in this option will override other values (such as User-agent:, Host:, and Authentication:).

user_agent string

Value to send with User-Agent: header.

By default the user_agent php.ini setting is used.

content string

Additional data to be sent after the headers. This option is not used for GET or HEAD requests.

proxy string

URI specifying address of proxy server. (e.g. tcp://proxy.example.com:5100).

max_redirects integer

The max number of redirects to follow. Value 1 or less means that no redirects are followed.

Defaults to 20.

curl_verify_ssl_host boolean

Verify the host.

Defaults to FALSE

Informacja: This option is available for both the http and ftp protocol wrappers.

curl_verify_ssl_peer boolean

Require verification of SSL certificate used.

Defaults to FALSE

Informacja: This option is available for both the http and ftp protocol wrappers.

Przykłady

Przykład #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);

?>

Zobacz też:



Phar context options

Phar context optionsPhar context option listing

Opis

Context options for phar:// wrapper.

Opcje

compress int

One of Phar compression constants.

metadata mixed

Phar metadata. See Phar::setMetadata().



Context parameters

Context parametersContext parameter listing

Opis

These parameters can be set on a context using the stream_context_set_params() function.

Opcje

notification callback

A callback to be called when an event occurs on a stream.

See stream_notification_callback() for more details.


Spis treści




Bezpieczeństwo


Introduction

PHP is a powerful language and the interpreter, whether included in a web server as a module or executed as a separate CGI binary, is able to access files, execute commands and open network connections on the server. These properties make anything run on a web server insecure by default. PHP is designed specifically to be a more secure language for writing CGI programs than Perl or C, and with correct selection of compile-time and runtime configuration options, and proper coding practices, it can give you exactly the combination of freedom and security you need.

As there are many different ways of utilizing PHP, there are many configuration options controlling its behaviour. A large selection of options guarantees you can use PHP for a lot of purposes, but it also means there are combinations of these options and server configurations that result in an insecure setup.

The configuration flexibility of PHP is equally rivalled by the code flexibility. PHP can be used to build complete server applications, with all the power of a shell user, or it can be used for simple server-side includes with little risk in a tightly controlled environment. How you build that environment, and how secure it is, is largely up to the PHP developer.

This chapter starts with some general security advice, explains the different configuration option combinations and the situations they can be safely used, and describes different considerations in coding for different levels of security.



General considerations

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.



Installed as CGI binary

Spis treści


Possible attacks

Using PHP as a CGI binary is an option for setups that for some reason do not wish to integrate PHP as a module into server software (like Apache), or will use PHP with different kinds of CGI wrappers to create safe chroot and setuid environments for scripts. This setup usually involves installing executable PHP binary to the web server cgi-bin directory. CERT advisory » CA-96.11 recommends against placing any interpreters into cgi-bin. Even if the PHP binary can be used as a standalone interpreter, PHP is designed to prevent the attacks this setup makes possible:

  • Accessing system files: http://my.host/cgi-bin/php?/etc/passwd The query information in a URL after the question mark (?) is passed as command line arguments to the interpreter by the CGI interface. Usually interpreters open and execute the file specified as the first argument on the command line. When invoked as a CGI binary, PHP refuses to interpret the command line arguments.
  • Accessing any web document on server: http://my.host/cgi-bin/php/secret/doc.html The path information part of the URL after the PHP binary name, /secret/doc.html is conventionally used to specify the name of the file to be opened and interpreted by the CGI program. Usually some web server configuration directives (Apache: Action) are used to redirect requests to documents like http://my.host/secret/script.php to the PHP interpreter. With this setup, the web server first checks the access permissions to the directory /secret, and after that creates the redirected request http://my.host/cgi-bin/php/secret/script.php. Unfortunately, if the request is originally given in this form, no access checks are made by web server for file /secret/script.php, but only for the /cgi-bin/php file. This way any user able to access /cgi-bin/php is able to access any protected document on the web server. In PHP, runtime configuration directives cgi.force_redirect, doc_root and user_dir can be used to prevent this attack, if the server document tree has any directories with access restrictions. See below for full the explanation of the different combinations.


Case 1: only public files served

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).



Case 2: using cgi.force_redirect

The configuration directive cgi.force_redirect 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. PHP older than 4.2.0 used --enable-force-cgi-redirect compile time option for this.

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.



Case 3: setting doc_root or user_dir

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.



Case 4: PHP parser outside of web tree

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.




Installed as an Apache module

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.



Filesystem Security

Spis treści

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.

Przykład #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:

Przykład #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.

  • Only allow limited permissions to the PHP web user binary.
  • Check all variables which are submitted.

Here is an improved script:

Przykład #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($logstringENT_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:

Przykład #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.


Null bytes related issues

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:

Przykład #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:

Przykład #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';
}
?>



Database Security

Spis treści

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.


Designing Databases

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.



Connecting to Database

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.



Encrypted Storage Model

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().

Przykład #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.';
}

?>


SQL Injection

Many web developers are unaware of how SQL queries can be tampered with, and assume that an SQL query is a trusted command. It means that SQL queries are able to circumvent access controls, thereby bypassing standard authentication and authorization checks, and sometimes SQL queries even may allow access to host operating system level commands.

Direct SQL Command Injection is a technique where an attacker creates or alters existing SQL commands to expose hidden data, or to override valuable ones, or even to execute dangerous system level commands on the database host. This is accomplished by the application taking user input and combining it with static parameters to build a SQL query. The following examples are based on true stories, unfortunately.

Owing to the lack of input validation and connecting to the database on behalf of a superuser or the one who can create users, the attacker may create a superuser in your database.

Przykład #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.

Informacja: 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.

Przykład #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.

Przykład #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.

Przykład #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.

Informacja: 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.

Avoiding techniques

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.

  • Never connect to the database as a superuser or as the database owner. Use always customized users with very limited privileges.
  • Check if the given input has the expected data type. PHP has a wide range of input validating functions, from the simplest ones found in Variable Functions and in Character Type Functions (e.g. is_numeric(), ctype_digit() respectively) and onwards to the Perl compatible Regular Expressions support.
  • 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().

    Przykład #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);

    ?>

  • Quote each non numeric user supplied value that is passed to the database with the database-specific string escape function (e.g. mysql_real_escape_string(), sqlite_escape_string(), etc.). If a database-specific string escape mechanism is not available, the addslashes() and str_replace() functions may be useful (depending on database type). See the first example. As the example shows, adding quotes to the static part of the query is not enough, making this query easily crackable.
  • Do not print out any database specific information, especially about the schema, by fair means or foul. See also Error Reporting and Error Handling and Logging Functions.
  • You may use stored procedures and previously defined cursors to abstract data access so that users do not directly access tables or views, but this solution has another impacts.

Besides these, you benefit from logging queries either within your script or by the database itself, if it supports 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.




Error Reporting

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:

Przykład #1 Attacking Variables with a custom HTML page

<form method="post" action="attacktarget?username=badfoo&amp;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:

Przykład #2 Exploiting common debugging variables

<form method="post" action="attacktarget?errors=Y&amp;showerrors=1&amp;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.

Przykład #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");
}
?>



Using Register Globals

Ostrzeżenie

Ta opcja jest PRZESTARZA�?A od PHP 5.3.0 i USUNI�?TA w PHP 6.0.0 Używanie tej opcji nie jest zalecane.

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:

Przykład #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).

Przykład #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.

Przykład #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.

Informacja: Tablice superglobalne: informacja o dostępności
Tablice superglobalne, takie jak $_GET, $_POST, $_SERVER, itd. są dostępne od PHP 4.1.0. Aby uzyskać więcej informacji, należy zapoznać się z superglobals



User Submitted Data

The greatest weakness in many PHP programs is not inherent in the language itself, but merely an issue of code not being written with security in mind. For this reason, you should always take the time to consider the implications of a given piece of code, to ascertain the possible damage if an unexpected variable is submitted to it.

Przykład #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:

  • Will this script only affect the intended files?
  • Can unusual or undesirable data be acted upon?
  • Can this script be used in unintended ways?
  • Can this be used in conjunction with other scripts in a negative manner?
  • Will any transactions be adequately logged?

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).



Magic Quotes

Spis treści

Ostrzeżenie

Ta opcja jest PRZESTARZA�?A od PHP 5.3.0 i USUNI�?TA w PHP 6.0.0 Używanie tej opcji nie jest zalecane.

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.


What are Magic Quotes

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:

  • magic_quotes_gpc Affects HTTP Request data (GET, POST, and COOKIE). Cannot be set at runtime, and defaults to on in PHP. See also get_magic_quotes_gpc().
  • magic_quotes_runtime If enabled, most functions that return data from an external source, including databases and text files, will have quotes escaped with a backslash. Can be set at runtime, and defaults to off in PHP. See also set_magic_quotes_runtime() and get_magic_quotes_runtime().
  • magic_quotes_sybase If enabled, a single-quote is escaped with a single-quote instead of a backslash. If on, it completely overrides magic_quotes_gpc. Having both directives enabled means only single quotes are escaped as ''. Double quotes, backslashes and NULL's will remain untouched and unescaped. See also ini_get() for retrieving its value.


Why did we use Magic Quotes

Ostrzeżenie

Ta opcja jest PRZESTARZA�?A od PHP 5.3.0 i USUNI�?TA w PHP 6.0.0 Używanie tej opcji nie jest zalecane.

  • There is no reason to use magic quotes because they are no longer a supported part of PHP. However, they did exist and did help a few beginners blissfully and unknowingly write better (more secure) code. But, when dealing with code that relies upon this behavior it's better to update the code instead of turning magic quotes on. So why did this feature exist? Simple, to help prevent SQL Injection. Today developers are better aware of security and end up using database specific escaping mechanisms and/or prepared statements instead of relying upon features like magical quotes.


Why not to use Magic Quotes

Ostrzeżenie

Ta opcja jest PRZESTARZA�?A od PHP 5.3.0 i USUNI�?TA w PHP 6.0.0 Używanie tej opcji nie jest zalecane.

  • Portability Assuming it to be on, or off, affects portability. Use get_magic_quotes_gpc() to check for this, and code accordingly.
  • Performance Because not every piece of escaped data is inserted into a database, there is a performance loss for escaping all this data. Simply calling on the escaping functions (like addslashes()) at runtime is more efficient. Although php.ini-development enables these directives by default, php.ini-production disables it. This recommendation is mainly due to performance reasons.
  • Inconvenience Because not all data needs escaping, it's often annoying to see escaped data where it shouldn't be. For example, emailing from a form, and seeing a bunch of \' within the email. To fix, this may require excessive use of stripslashes().


Disabling Magic Quotes

Ostrzeżenie

Ta opcja jest PRZESTARZA�?A od PHP 5.3.0 i USUNI�?TA w PHP 6.0.0 Używanie tej opcji nie jest zalecane.

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.

Przykład #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.

Przykład #2 Disabling magic quotes at runtime

<?php
if (get_magic_quotes_gpc()) {
    
$process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
    while (list(
$key$val) = each($process)) {
        foreach (
$val as $k => $v) {
            unset(
$process[$key][$k]);
            if (
is_array($v)) {
                
$process[$key][stripslashes($k)] = $v;
                
$process[] = &$process[$key][stripslashes($k)];
            } else {
                
$process[$key][stripslashes($k)] = stripslashes($v);
            }
        }
    }
    unset(
$process);
}
?>




Hiding PHP

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:

Przykład #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:

Przykład #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:

Przykład #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.



Keeping Current

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.




Możliwości


Uwierzytelnianie HTTP w PHP

Uwierzytelnianie HTTP jest obsługiwana przez PHP tylko wtedy, gdy PHP pracuje jako moduł Apache'a, nie jest dostępna w trybie CGI. W skrypcie można użyć funkcji header() by wysłać do przeglądarki komunikat "Wymagana autoryzacja", co spowoduje wyświetlenie okienka z polami Użytkownik i Hasło. Po wypełnieniu przez użytkownika tych pól, URL zawierający skrypt PHP zostanie ponownie wywołany z ustawionymi predefiniowanymi zmiennymi PHP_AUTH_USER, PHP_AUTH_PW i AUTH_TYPE zawierającymi odpowiednio nazwę użytkownika, hasło i typ autoryzacji. Zmienne te będą dostępne w tablicach $_SERVER oraz $HTTP_SERVER_VARS. Obecnie obsługiwane są autoryzacje typu "Basic" i "Digest" (od PHP 5.1.0). Więcej informacji znajdziesz w opisie funkcji header().

Informacja: Notatka dotycząca wersji PHP
Zmienne superglobalne, takie jak $_SERVER, udostępniono w PHP » 4.1.0.

Przykładowy skrypt wymuszający autoryzację klienta:

Przykład #1 Uwierzytelnianie Basic HTTP

<?php
  
if (!isset($_SERVER['PHP_AUTH_USER'])) { 
    
header('WWW-Authenticate: Basic realm="My Realm"');
    
header('HTTP/1.0 401 Unauthorized');
    echo 
'Tekst do wysłania, jeśli użytkownik wciśnie przycisk Anuluj';
    exit;
  } else {
    echo 
"<p>Hej {$_SERVER['PHP_AUTH_USER']}.</p>"
    echo 
"<p>Twoje hasło to {$_SERVER['PHP_AUTH_PW']}.</p>"
  }
?>

Przykład #2 Przykład uwierzytelnianie Digest HTTP

Ten przykład pokazuje jak zaimplementować proste umierzytelnianie Digest HTTP. Po więcej informacji przeczytaj » RFC 2617.

<?php
$realm 
'Zastrzeżona strefa';

//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(
'Tekst do wysłania kiedy użytkownik kliknie klawisz anuluj');
}


// analiza zmiennej PHP_AUTH_DIGEST
if (!($data http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
    !isset(
$users[$data['username']]))
    die(
'Nieprawidłowe listy uwierzytelniające!');


// tworzenie prawidłowej odpowiedzi
$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(
'Nieprawidłowe listy uwierzytelniające!');

// ok, prawidłowa nazwa użytkownika i hasło
echo 'Jesteś zalogowany jako: ' $data['username'];


// function to parse the http auth header
function http_digest_parse($txt)
{
    
// zabezpieczenie przeciwko brakującym informacjom
    
$needed_parts = array('nonce'=>1'nc'=>1'cnonce'=>1'qop'=>1'username'=>1'uri'=>1'response'=>1);
    
$data = array();

    
preg_match_all('@(\w+)=(?:([\'"])([^\2]+)\2|([^\s,]+))@'$txt$matchesPREG_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;
}
?>

Informacja: Kompatybilność
Należy uważać z linijkami dodawanymi do nagłówka HTTP. W celu zachowania maksymalnej zgodności ze wszystkimi klientami, słowo Basic powinno zaczynać się dużą literą "B", wartość realm powinna być otoczona cudzysłowami (nie apostrofami), i dokładnie jeden znak odstępu powinien poprzedzać kod 401 w linii HTTP/1.0 401. Parametry autoryzacyjne muszą być oddzielone przecinkami jak pokazano to w przykładzie digest powyżej.

Zamiast wyświetlać wartość PHP_AUTH_USER i PHP_AUTH_PW, jak to zrobiono w powyższym przykładzie, zechcesz zapewne sprawdzić poprawność nazwy użytkownika i hasła. Na przykład poprzez zapytanie do bazy danych lub odnalezienie użytkownika w pliku dbm.

Należy uważać na kapryśne przeglądarki Internet Explorer. Są wrażliwe na kolejność wysyłanych nagłówków HTTP. Wysłanie nagłowka WWW-Authenticate przed HTTP/1.0 401 powinno rozwiązać problem.

Aby zapobiec sytuacji w której ktoś napisze skrypt wykradający hasło wysłane tradycyjnym zewnętrznym mechanizmem, zmienne PHP_AUTH nie będą ustawiane, jeśli dla danej strony aktywna jest autoryzacja zewnętrzna i tryb bezpieczny jest włączony. Bez względu na to, REMOTE_USER może zostać użyte do zidentyfikowania użytkownika autoryzowanego zewnętrznie Zatem, możesz użyć $_SERVER['REMOTE_USER'].

Informacja: Konfiguracja
Aby wykryć czy miała miejsce zewnętrzna autoryzacja, PHP sprwadza obecność dyrektywy AuthType.

Powyższa metoda nie zapobiega jednak wykradaniu haseł do stron wymagających autoryzacji przez kogoś, kto na tym samym serwerze kontroluje strony nie wymagające autoryzacji.

Zarówno Netscape Navigator jak i Internet Explorer opróżnią bufor autoryzacji po otrzymaniu od serwera kodu 401. Można w ten sposób wylogowanić użytkownika i zmusić go do ponownego wysłania nazwy użytkownika i hasła. Tej metody można użyć do wylogowania użytkownika po określonym czasie lub stworzenia przycisku "Wyloguj".

Przykład #3 Uwierzytelnianie HTTP z wymuszeniem przelogowania

<?php
  
function authenticate() {
    
header('WWW-Authenticate: Basic realm="Testowy system autoryzacji"');
    
header('HTTP/1.0 401 Unauthorized');
    echo 
"Musisz podać poprawny login i hasło by wejść na tę stronę\n";
    exit;
  }
 
  if (!isset(
$_SERVER['PHP_AUTH_USER']) ||
    (
$_POST['SeenBefore'] == && $_POST['OldAuth'] == $_SERVER['PHP_AUTH_USER'])) {
    
authenticate();
  } else {
    echo 
"<p>Witaj: {$_SERVER['PHP_AUTH_USER']}<br />";
    echo 
"Poprzednio: {$_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";
}
?>

Powyższa metoda nie jest wymagana przez autoryzację HTTP typu "Basic", więc nie można na niej polegać. Testy z przeglądarką Lynx pokazały, że Lynx nie usuwa danych o autoryzacji po odebraniu od serwera kodu 401, zatem przejście wstecz a następnie do przodu otworzy stronę, chyba, że wymagania co do danych autoryzacji zmieniły się. Użytkownik może jednak użyć klawisza '_' by usunąc dane o autoryzacji.

Zwóć uwagę, że do wersji PHP 4.3.3, Autoryzacja HTTP nie działała na serwerze Microsoft IIS z PHP w wersji CGI z powodu ograniczeń IIS. Aby zmusić go do działania w PHP 4.3.3+ musisz wyedytować "Bezpieczeństwo katalogów" w konfiguracji IIS. Kliknij na "Edytuj" i zaznacz wyłącznie "Anonimowy Dostęp", wszystkie inne pola powinny pozostać nie zaznaczone.

Inne ogranicznie jest jeśli używasz modułu IIS (ISAPI) i PHP 4, nie możesz wtedy użyć zmiennych PHP_AUTH_* ale zamiast nich, dostępna jest zmienna HTTP_AUTHORIZATION. Na przykład rozważ następujący kod: list($user, $pw) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));

Informacja: Notatka IIS:
Aby Autoryzacja HTTP działała z IIS, dyrektywa PHP cgi.rfc2616_headers musi być ustawiona na 0 (domyślna wartość).

Informacja: Jeśli włączony jest tryb bezpieczny, uid skryptu jest doklejany do pola realm nagłówka WWW-Authenticate.



Ciasteczka (cookies)

PHP obsługuje ciasteczka HTTP (cookies). Jest to mechanizm służący do przechowywania danych w przeglądarce i w ten sposób śledzenia lub identyfikowania powracających użytkowników. Można je ustawiać używając funkcji setcookie(). Ciasteczka stanowią część nagłówka HTTP, więc funkcja setcookie() musi być wywoływana zanim jakiekolwiek dane zostaną wysłane do przeglądarki. Występuje tu to samo ograniczenie, co w przypadku header(). Możesz skorzystać z funkcji buforujących, aby opóźnić wysłanie danych do czasu, gdy zdecydujesz o wysłaniu ciasteczek lub dodatkowych nagłówków.

Każde ciasteczko wysłane do ciebie od klienta, będzie automatycznie dołączone do globalnej tablicy $_COOKIE jeśli variables_order zawiera "C". Jeśli chcesz przypisać wiele wartości do pojedynczego ciasteczka, po prostu dodaj [] do nazwy ciasteczka.

W zależności od register_globals, z ciastek mogą zostać utworzone zwykłe zmienne PHP. Jednakże nie jest zalecane poleganie na nich, ponieważ ta właściwość jest często wyłączana ze względu na bezpieczeństwo. We wcześniejszych wersjach PHP, tworzona jest tablica $HTTP_COOKIE_VARS, jeśli ustawiona została dyrektywa konfiguracyjna track_vars. (To jest ustawione zawsze od PHP 4.0.3.)

Po więcej informacji, włącznie z uwagami o błędach przeglądarek, sięgnij do opisu funkcji setcookie() i setrawcookie().



Sessions

Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site. All information is in the Session reference section.



Dealing with XForms

» 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.

Przykład #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.

Przykład #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>

Informacja: As of this writing, many browsers do not support XForms. Check your browser version if the above examples fails.



Handling file uploads

Spis treści


POST method uploads

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).

Informacja: 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.

Przykład #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.

Informacja: 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.

$_FILES['userfile']['name']

The original name of the file on the client machine.

$_FILES['userfile']['type']

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.

$_FILES['userfile']['size']

The size, in bytes, of the uploaded file.

$_FILES['userfile']['tmp_name']

The temporary filename of the file in which the uploaded file was stored on the server.

$_FILES['userfile']['error']

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.

Przykład #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.

Przykład #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.



Error Messages Explained

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'].

UPLOAD_ERR_OK

Value: 0; There is no error, the file uploaded with success.

UPLOAD_ERR_INI_SIZE

Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.

UPLOAD_ERR_FORM_SIZE

Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.

UPLOAD_ERR_PARTIAL

Value: 3; The uploaded file was only partially uploaded.

UPLOAD_ERR_NO_FILE

Value: 4; No file was uploaded.

UPLOAD_ERR_NO_TMP_DIR

Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.

UPLOAD_ERR_CANT_WRITE

Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.

UPLOAD_ERR_EXTENSION

Value: 8; File upload stopped by extension. Introduced in PHP 5.2.0.

Informacja: These became PHP constants in PHP 4.3.0.



Common Pitfalls

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.

Informacja: 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.

Ostrzeżenie

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[]).



Uploading multiple files

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:

Przykład #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.



PUT method support

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.

Przykład #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($putdata1024))
  
fwrite($fp$data);

/* Close the streams */
fclose($fp);
fclose($putdata);
?>




Korzystanie ze zdalnych plików

Jeśli parametr allow_url_fopen w pliku php.ini zostanie włączony, będzie można używać adresów HTTP i FTP w większości funkcji, które jako parametr przyjmują nazwę pliku, włączając w to instrukcje include(), include_once(), require() oraz require_once() (od PHP 5.2.0, musi być włączona opcja allow_url_include). Więcej informacji o protokołach obsługiwanych przez PHP. znajduje się w List of Supported Protocols/Wrappers.

Informacja: PHP dla Windows, w wersji wcześniejszej niż 4.3 nie obsługiwało zdalnego dostępu do plików przy użyciu instrukcji: include(), include_once(), require() i require_once() oraz rodziny funkcji imagecreatefromXXX z rozszerzenia GD and Image Funkcje.

Możesz wykorzystać tę własność aby otworzyć plik na zdalnym serwrze, przetworzyć jego zawartość i użyć wyników w zapytaniu do bazy danych, lub po prostu wyświetlić plik dostosowując jego wygląd do swojej strony.

Przykład #1 Pobieranie tytułu zdalnej strony

<?php
$file 
fopen ("http://www.example.com/""r");
if (!
$file) {
    echo 
"<p>Nie można otworzyć zdalnego pliku.\n";
    exit;
}
while (!
feof ($file)) {
    
$line fgets ($file1024);
    
/* Zadziała tylko wtedy, gdy tytuł i jego znaczniki są w tej samej linii */
    
if (preg_match ("@\<title\>(.*)\</title\>@i"$line$out)) {
        
$title $out[1];
        break;
    }
}
fclose($file);
?>

Możesz również zapisywać pliki na serwerach FTP (zakładając, że połączyłeś się jako użytkownik z odpowiednimi prawami dostepu). Przy użyciu tej metody możesz jedynie tworzyć nowe pliki. Jeśli spróbujesz nadpisać istniejący plik, wywołanie funkcji fopen() zwróci błąd.

Przykład #2 Zapisywanie danych na zdalnym serwerze.

<?php
$file 
fopen ("ftp://ftp.example.com/incoming/outputfile""w");
if (!
$file) {
    echo 
"<p>Nie można otworzyć zdalnego pliku do zapisu.\n";
    exit;
}
/* Tutaj zapisujemy dane. */
fwrite ($file$_SERVER['HTTP_USER_AGENT'] . "\n");
fclose ($file);
?>

Informacja: Być może powyższy przykład nasunął ci pomysł, by użyć tej metody do zdalnego zapisywania logów. Niestety taka próba się nie powiedzie, gdyż wywołanie fopen() zwróci błąd, jeśli zdalny plik już istnieje. Aby zrealizować zdalne logowanie powinieneś przyjrzeć się funkcji syslog().



Obsługa połączeń

PHP wewnętrznie zarządza stanem połączenia. Mogą wystąpić trzy stany:

  • 0 - NORMAL
  • 1 - ABORTED (przerwany)
  • 2 - TIMEOUT (przekroczony czas)

Kiedy skrypt PHP się wykonuje, aktywny jest stan NORMAL. Jeśli klient się rozłączy, stan przechodzi w ABORTED. Zwykle ma to miejsce gdy użytkownik naciśnie przycisk STOP w przeglądarce. Jeśli przekroczony zostanie narzucony limit czasu (patrz set_time_limit()), stan zmienia się na TIMEOUT.

Możesz zdecydować czy po rozłączeniu klienta praca skryptu ma zostać przerwana. Czasem przydatne jest by skrypty działały do końca, nawet gdy braknie przeglądarki do której można wysyłać dane. Domyślnie, po rozłączeniu się klienta, działanie skryptu jest przerywane. To zachowanie można zmienić dzięki opcji ignore_user_abort w php.ini, jak również dyrektywie Apache httpd.conf php_value ignore_user_abort lub funkcji ignore_user_abort(). Jeśli nie każesz PHP ignorować rozłączeń klienta, a klient rozłączy się, skrypt zakończy działanie. Jedyny wyjątek wystąpi, jeśli zarejestrujesz funkcję zamykającą, używając register_shutdown_function(). Wtedy, gdy użytkownik wciśnie przycisk STOP i przy kolejnej próbie wysłania wyniku PHP wykryje przerwanie połączenia, zostanie wykonana funkcja zamykająca. Będzie ona również wywoływana przy normalnym zakończeniu pracy skryptu, zatem, by wykonać inne czynności gdy klient się rozłączy, można użyć funkcji connection_aborted(). Zwraca ona TRUE jeśli połączenie zostało przerwane.

Skrypt może zostać również zakończony przez wbudowany licznik czasu. Domyślnie czas ten wynosi 30 sekund. Wartość tę można zmienić używając opcji max_execution_time w php.ini, jak również dyrektywy Apache httpd.conf php_value max_execution_time lub funkcji set_time_limit(). Kiedy czas na wykonanie się skończy, skrypt zostanie przerwany podobnie jak w przypadku rozłączenia się klienta (patrz wyżej). Jeśli funkcja zamykająca była zarejestrowana, zostanie wywołana. Wewnątrz funkcji zamykającej możesz sprawdzić czy została ona wywołana wskutek przekroczenia czasu. Do tego celu użyj funkcji connection_status(). Funkcja zwróci 2, jeśli to przekroczenie limitu czasu spowodowało wywołanie funkcji zamykającej.

Należy zwrócić uwagę, że stany ABORTED i TIMEOUT mogą być aktywne jednocześnie. Jest to możliwe, jeśli każesz PHP ignorować rozłączenia klienta. PHP będzie brało pod uwagę fakt, że połączenie z klientem mogło zostać zerwane, ale skrypt będzie pracował dalej. Gdy minie czas przeznaczony na wykonanie skryptu, zostanie on przerwany i uruchomiona zostanie funkcja zamykająca (jeśli była ustawiona). W tym momencie funkcje connection_timeout() i connection_aborted() będą zwracały TRUE. Możesz także sprawdzić oba stany przy pomocy funkcji connection_status() w takim wypadku zwróci ona 3.



Stałe połączenia z bazami danych

Stałe połączenia (persistent connections) to połączenia, które nie są zamykane po wykonaniu skryptu. Kiedy skrypt próbuje nawiązać stałe połączenie, PHP sprawdza czy istnieje już identyczne połączenie (otwarte wcześniej) i jeśli istnieje, używa go. Jeżeli nie, tworzone jest nowe. Połączenie 'identyczne' to połączenie z tym samym hostem, z taką samą nazwą użytkownika i hasłem.

Ludzie niezbyt dobrze znający zasady działania serwerów mogą czasem brać stałe połączenia za coś, czym te nie są. Stałe połączenia nie stwarzają możliwości otwarcia połączenia dla konkretnego użytkonika, nie pozwalają na skuteczne stworzenie systemu transakcji, i nie robią wielu innych rzeczy. Powiedzmy to jasno, stałe połączenia nie oferują nic ponad to, co robią 'zwykłe' połączenia.

Dlaczego?

Jest to związane z zasadą działania serwerów. Są trzy sposoby na które serwer może wykorzystac PHP do generowania stron.

Pierwsza metoda to wykorzystanie PHP jako "wrappera" CGI. Przy wywołaniu skryptu każdorazowo uruchamiany i niszczony jest egzamplarz PHP. Jako, że jest on niszczony po każdym wywołaniu, wszystkie zasoby przez niego posiadane (na przykład połączenia z bazą danych) są tracone. W tym przypadku używanie stałych połączeń nie przynosi korzyści, one po prostu nie są stałe.

Druga, najpopularniejsza metoda, to uruchomienie PHP jako modułu w wieloprocesowym serwerze, co obecnie dotyczy jedynie serwera Apache. Serwer wieloprocesowy zwykle uruchamia jeden proces (rodzica), który koordynuje inne procesy (potomne) zajmujące się dostarczaniem stron. Kiedy nadchodzi żądanie od klienta, jest ono przekazywane jednemu z procesów potomnych, który w danym momencie nie obsługuje innego klienta. Oznacza to, że gdy ten sam klient wyśle do serwera kolejne żądanie, może zostać obsłużony przez inny proces niż za pierwszym razem. Stałe połączenie w tym przypadku oznacza, że każdy proces potomny ustanawia połączenie z serwerem SQL przy pierwszym wywołaniu strony, która takiego połączenia używa.

Ostatnia metoda to wykorzystanie PHP jako wtyczki (plug-in) do serwera wielowątkowego. Obecnie PHP4 zawiera obsługę mechanizmów ISAPI, WSAPI i NSAPI (w Windows), które umożliwiają uruchomienie PHP jako wtyczki do wielowątkowych serwerów takich jak Netscape FastTrack (iPlanet), Microsoft Internet Information Server (IIS) i O'Reilly WebSite Pro. Zachowanie PHP jest zasadniczo takie samo jak w przypadku opisanego wcześniej modelu wieloprocesowego.

Skoro stałe połączenia nie dostarczają większej funkcjonalności, do czego mogą być przydatne?

Odpowiedź jest niezwykle prosta -- wydajność. Stałe połączenia sprawdzają się w przypadku, gdy koszt nawiązania połączenia z SQL serwerem jest wysoki. To czy koszt jest duży czy nie zależy od wielu czynników. Na przykład od typu bazy danych, od tego czy znajduje się ona na tym samym serwerze, od obciążenia maszyny, która obsługuje serwer SQL, itd. Jeśli zatem koszt połączenia jest wysoki, stałe połączenia znacznie pomagają. Sprawiają, że proces potomny łączy się z serwerem SQL tylko raz podczas swojego życia, zamiast otwierać połączenie za każdym razem gdy zażąda tego skrypt. Oznacza to, że każdy proces potomny, który nawiązał stałe połączenie, będzie posiadał własne połączenie z serwerem bazy danych. Dla przykładu, jeżeli 20 procesów potomnych uruchomi skrypt, który ustanowi stałe połączenie z serwerem SQL, będziesz mieć 20 różnych połączeń z serwerem, jedno na każdy proces.

Trzeba jednak zauważyć, że może to mieć swoje ujemne strony w przypadku, gdy limit połączeń do bazy danych zostanie przekroczony przez stałe połączenia z procesów potomnych. Jeśli twoja baza danych posiada limit szesnastu jednoczesnych połączeń, a w danej chwili obciążenie jest wysokie, siedemnasty proces nie będzie mógł się połączyć. Jeśli twoje skrypty zawierają błędy, które nie pozwalają zamknąć połączeń (na przykłąd nieskończone pętle), baza danych z limitem 16 połączeń może szybko zostać zapchana. Poszukaj w dokumentacji swojej bazy danych w jaki sposób radzi sobie ona z porzuconymi lub bezczynnymi połączeniami.

Ostrzeżenie

Istnieje kilka zagrożeń, które należy brać pod uwagę decydując się na używanie stałych połączeń. Jednym z nich jest sytuacja, w której skrypt blokujący tabelę, z jakiegokolwiek powodu nie może zdjąć blokady. Wtedy kolejne skrypty korzystające z tego samego połączenia będą zablokowane i może zajść potrzeba ponownego uruchomienia serwera httpd lub serwera bazy danych. Kolejne zagrożenie dotyczy transakcji. Jeśli skrypt używający transakcji zakończy działanie przed zakończeniem bloku transakcji, to zostanie on (blok) przeniesiony do następnego skryptu. W obu przypadkach można użyć register_shutdown_function(), aby zarejestrować funkcję porządkującą, która odblokuje tabele lub wycofa transakcje. Najlepiej jednak jest zrezygnować ze stałych połączeń w skryptach używających blokowania tabel lub transakcji.

Istotne podsumowanie. Stałe połączenia zostały zaprojektowane tak, by odpowiadać zwykłym połączeniom. Oznacza to, że zawsze możesz zastąpić stałe połączenia zwykłymi i nie zmieni to zachowania skryptu. Natomiast może zmienić (i zapewne zmieni) jego wydajność!

Zobacz także fbsql_pconnect(), ibase_pconnect(), ifx_pconnect(), ingres_pconnect(), msql_pconnect(), mssql_pconnect(), mysql_pconnect(), ociplogon(), odbc_pconnect(), oci_pconnect(), pfsockopen(), pg_pconnect() i sybase_pconnect().



Tryb bezpieczny

Spis treści

Tryb bezpieczny (ang. safe mode) jest próbą rozwiązania problemów bezpieczeństwa na współdzielonym serwerze. Co prawda rozwiązywanie ich na poziomie PHP nie jest najlepszym rozwiązaniem, ale jeśli nie ma możliwości zrobienia tego na poziomie serwera www lub systemu operacyjnego, na wielu serwerach, zwłaszcza u usługodawców internetowych, używa się trybu bezpiecznego.

Ostrzeżenie

Tryb bezpieczny został usunięty w PHP 6.0.0.


Zabezpieczenia i tryb bezpieczny

Dyrektywy konfiguracyjne zabezpieczeń i trybu bezpiecznego
Nazwa Wartość domyślna Możliwość zmian Rejestr zmian
safe_mode "0" PHP_INI_SYSTEM Usunięta w PHP 6.0.0.
safe_mode_gid "0" PHP_INI_SYSTEM Dostępna od PHP 4.1.0. Usunięta w PHP 6.0.0.
safe_mode_include_dir NULL PHP_INI_SYSTEM Dostępna od PHP 4.1.0. Usunięta w PHP 6.0.0.
safe_mode_exec_dir "" PHP_INI_SYSTEM Usunięta w PHP 6.0.0.
safe_mode_allowed_env_vars "PHP_" PHP_INI_SYSTEM Usunięta w PHP 6.0.0.
safe_mode_protected_env_vars "LD_LIBRARY_PATH" PHP_INI_SYSTEM Usunięta w PHP 6.0.0.
open_basedir NULL PHP_INI_ALL PHP_INI_SYSTEM w PHP < 5.3.0
disable_functions "" tylko php.ini Dostępna od PHP 4.0.1.
disable_classes "" tylko php.ini Dostępna od PHP 4.3.2.

Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

safe_mode boolean

Określa czy należy włączyć w PHP tryb bezpieczny. Jeśli PHP zostało skompilowane z parametrem --enable-safe-mode to domyślną wartością jest On. W przeciwnym przypadku domyślną wartością jest Off.

safe_mode_gid boolean

Domyślnie tryb bezpieczny sprawdza, czy właścicielem uruchamianego skryptu lub pliku, do którego funkcja chce uzyskać dostęp, jest ten sam użytkownik (UID). Jeśli chcemy aby porównywana dotyczyły całej grupy (GID), należy włączyć safe_mode_gid. Określa czy używać UID (FALSE) lub GID (TRUE) podczas sprawdzania dostępu do pliku.

safe_mode_include_dir string

Sprawdza czy nie nastąpiło obejście UID/GID podczas dołączania plików z tego katalogu i jego podkatalogów (ścieżka do katalogu powinna być podana w include_path lub też powinna być dołączona pełna nazwa ścieżki).

Od PHP 4.2.0 ta dyrektywa może zawierać dwukropek (w Windows średnik) oddzielający ścieżki, podobnie jak w przypadku dyrektywy include_path, a nie tylko pojedyńczy katalog. Rejestrowanie ścieżki określane jest obecnie przez przedrostek, a nie nazwę katalogu. To oznacza, że "safe_mode_include_dir = /dir/incl" pozwala uzyskać dostęp do "/dir/include" i "/dir/incls" (jeżeli istnieją). Gdy chcemy ograniczyć dostęp tylko do określonego katalogu, dodajemy na końcu ukośnik. Na przykład: "safe_mode_include_dir = /dir/incl/" Jeśli wartość dyrektywy jest pusta, to żadne pliki - inne niż należące do UID/GID nie mogą być dołączone (w PHP 4.2.3 i od PHP 4.3.3). We wcześniejszych wersjach mogły być dołączane wszystkie pliki.
safe_mode_exec_dir string

Jeśli PHP działa w trybie bezpiecznym, system() i inne funkcje wykonujące programy systemowe otrzymają odmowę uruchomienia programów, tych które nie znajdują się w tym katalogu. Używamy / jako separatora katalogu dla wszystkich środowisk, włącznie z Windows.

safe_mode_allowed_env_vars string

Ustawienie pewnych zmiennych środowiskowych może być potencjalnym naruszeniem bezpieczeństwa. Ta dyrektywa zawiera listę przedrostków oddzielonych przecinkami. W trybie bezpiecznym użytkownik może wyłącznie zmieniać zmienne środowiskowe, których nazwy zaczynają się od przedrostków tutaj wymienionych. Domyślnie użytkownicy mają tylko możliwość ustawiania zmiennych środowiskowych zaczynających się od PHP_ (np. PHP_FOO=BAR).

Informacja: Jeśli ta dyrektywa jest pusta, PHP pozwoli użytkownikowi zmieniać WSZYSTKIE zmienne środowiskowe!

safe_mode_protected_env_vars string

Ta dyretywa zawiera listę zmiennych środowiskowych oddzielonych przecinkami, których użytkownik końcowy nie może zmienić za pomocą putenv(). Te zmienne są zawsze chronione nawet jeśli safe_mode_allowed_env_vars pozwala na ich zmianę.

open_basedir string

Ograniczenie dla plików polegające na tym, że mogą one być otwierane przez PHP wyłącznie w określonem drzewie katalogów. Działanie tej dyrektywy NIE zależy od tego czy tryb bezpieczny jest włączony czy wyłączony.

Gdy skrypt próbuje otworzyć plik za pomocą np. fopen() lub gzopen(), sprawdzana jest lokalizacja tego pliku. Jeśli plik znajduje się poza określonym drzewem katalogów, wtedy PHP odmówi dostępu do otwarcia go. Wszystkie dowiązania symboliczne są sprawdzane, tak więc nie jest możliwe obejście tej restrykcji za pomocą dowiązań symbolicznych. Jeśli plik nie istnieje wówczas dowiązanie symboliczne nie może być sprawdzone, a pełna ścieżka nazwy pliku jest porównywana z open_basedir .

Specjalna wartość . wskazuje, że roboczy katalog skryptu ma być traktowany jako katalog podstawowy. To jest jednakże nieco niebezpieczne, jako że katalog roboczy skryptu można łatwo zmienić za pomocą chdir().

W httpd.conf, open_basedir może być wyłączony (np. dla niektórych hostów wirtualnych) ten sam efekt uzyskamy za pomocą innej dyrektywy konfiguracyjnej: "php_admin_value open_basedir none".

W Windows oddzielamy katalogi za pomocą średnika, natomiast we wszystkich innych systemach operacyjnych za pomocą dwukropka. Gdy PHP działa jako moduł serwera Apache, ścieżki open_basedir z katalogów nadrzędnych są automatycznie dziedziczone.

Restrykcja określona za pomocą open_basedir jest obecnie przedrostkiem a nie nazwą katalogu. To oznacza, że "open_basedir = /dir/incl" pozwala uzyskać dostęp do "/dir/include" i "/dir/incls" (jeżeli istnieją). Gdy chcemy ograniczyć dostęp tylko do określonego katalogu, dodajemy na końcu ukośnik. Na przykład: "open_basedir = /dir/incl/"

Domyślnie PHP ma dostęp do plików we wszystkich lokalizacjach.

Informacja: Od PHP 5.3.0 open_basedir może być zmieniany (zacieśniany) w czasie wykonywania skryptu. To znaczy, że jeśli open_basedir jest ustawiony na /www/ w php.ini to skrypt może ograniczyć dostęp np. do /www/tmp/ poprzez zmianę konfiguracji w czasie rzeczywistym, za pomocą ini_set().

disable_functions string
Ta dyrektywa pozwala nam wyłączyć pewne funkcje dla zwiększenia bezpieczeństwa. Zawiera ona listę nazw funkcji oddzielonych przecinkami. disable_functions nie zależy od trybu bezpiecznego. Ta dyrektywa musi być ustawiona w php.ini Nie można jej ustawić np. w httpd.conf.
disable_classes string
Ta dyrektywa pozwala nam wyłączyć pewne klasy dla zwiększenia bezpieczeństwa. Zawiera ona listę nazw klas oddzielonych przecinkami. disable_classes nie zależy od trybu bezpiecznego. Ta dyrektywa musi być ustawiona w php.ini Nie można jej ustawić np. w httpd.conf.

Informacja: Availability note
Ta dyrektywa została dodana w PHP 4.3.2

Patrz także: register_globals, display_errors, i log_errors.

Gdy opcja safe_mode jest włączona, PHP sprawdza czy właścicielem wykonywanego skryptu jest właściciel pliku, na którym chce operować funkcja, lub czy jest to katalog tego samego użytkownika. Na Przykład:

-rw-rw-r--    1 rasmus   rasmus       33 Jul  1 19:20 script.php
-rw-r--r--    1 root     root       1116 May 26 18:01 /etc/passwd

Uruchomienie script.php:

<?php
 readfile
('/etc/passwd');
?>

zwraca błąd jeśli tryb bezpieczny jest włączony:

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

Jednakże mogą być środowiska, gdzie zbyt restrykcyjna weryfikacja UID nie jest stosownym rozwiązaniem, a łagodniejsze sprawdzanie GID jest w pełni wystarczające. Można to zmienić za pomocą safe_mode_gid. Ustawienie tej opcji na On włącza łagodniejsze sprawdzanie GID, a ustawienie na Off (domyślnie) przełącza na sprawdzanie UID.

Jeśli zamiast safe_mode ustawiamy katalog open_basedir wtedy wszystkie operacje na plikach będą ograniczone do plików znajdujących się w nim. Na przykład (Apache httpd.conf):

<Directory /docroot>
  php_admin_value open_basedir /docroot
</Directory>

Jeśli uruchominy plik script.php z ustawieniem open_basedir wówczas otrzymamy wynik:

Warning: open_basedir restriction in effect. File is in wrong directory in
/docroot/script.php on line 2

Możemy wyłączyć obsługę wybranych funkcji. Zauważmy, że dyrektywa disable_functions nie może być ustawiana poza plikiem php.ini co oznacza, że nie możemy wyłączyć funkcji dla wybranego wirtualnego hosta lub katalogu zdefiniowanego w pliku httpd.conf. Jeśli dodamy następującą dyrektywę do naszego pliku php.ini:

disable_functions = readfile,system

Otrzymamy następujący wynik:

Warning: readfile() has been disabled for security reasons in
/docroot/script.php on line 2

Ostrzeżenie

Naturalnie restrykcje PHP nie obowiązują w plikach wykonywalnych.



Funkcje ograniczane/wyłączone w trybie bezpiecznym

Jest to najprawdopodobniej wciąż niekompletna lista funkcji ograniczonych przez tryb bezpieczny.

Funkcje ograniczone w trybie bezpiecznym
Funkcja Ogranicznenia
dbmopen() Sprawdza czy pliki lub katalogi, na których będą wykonane operacje, mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.
dbase_open() Sprawdza czy pliki lub katalogi, na których będą wykonane operacje, mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.
filepro() Sprawdza czy pliki lub katalogi, na których będą wykonane operacje, mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.
filepro_rowcount() Sprawdza czy pliki lub katalogi, na których będą wykonane operacje, mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.
filepro_retrieve() Sprawdza czy pliki lub katalogi, na których będą wykonane operacje, mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.
ifx_* Podlega ograniczeniom narzuconym przez sql_safe_mode, (!= tryb bezpieczny)
ingres_* Podlega ograniczeniom narzuconym przez sql_safe_mode, (!= tryb bezpieczny)
mysql_* Podlega ograniczeniom narzuconym przez sql_safe_mode, (!= tryb bezpieczny)
pg_lo_import() Sprawdza czy pliki lub katalogi, na których będą wykonane operacje, mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.
posix_mkfifo() Sprawdza, czy katalog, na którym mają zostać wykonane operacje, ma takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.
putenv() Podlega dyrektywom safe_mode_protected_env_vars i safe_mode_allowed_env_vars;. Zobacz również dokumantację do putenv()
move_uploaded_file() Sprawdza czy pliki lub katalogi, na których będą wykonane operacje, mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.
chdir() Sprawdza, czy katalog, na którym mają zostać wykonane operacje, ma takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.
dl() Ta funkcja jest niedostępna jeśli PHP działa w trybie bezpiecznym
lewy apostrof Ta funkcja jest niedostępna jeśli PHP działa w trybie bezpiecznym
shell_exec() (funkcja równoważna z lewym apostrofem) Ta funkcja jest niedostępna jeśli PHP działa w trybie bezpiecznym
exec() Możemy uruchamiać programy jedynie z katalogu zdefiniowanego za pomocą dyrektywy safe_mode_exec_dir. Ze względów praktycznych obecnie nie ma możliwości stosowania .. w ścieżce do programu. Wykonywana jest escapeshellcmd() na argumencie tej funkcji.
system() Możemy uruchamiać programy jedynie z katalogu zdefiniowanego za pomocą dyrektywy safe_mode_exec_dir. Ze względów praktycznych obecnie nie ma możliwości stosowania .. w ścieżce do programu. Wykonywana jest escapeshellcmd() na argumencie tej funkcji.
passthru() Możemy uruchamiać programy jedynie z katalogu zdefiniowanego za pomocą dyrektywy safe_mode_exec_dir. Ze względów praktycznych obecnie nie ma możliwości stosowania .. w ścieżce do programu. Wykonywana jest escapeshellcmd() na argumencie tej funkcji.
popen() Możemy uruchamiać programy jedynie z katalogu zdefiniowanego za pomocą dyrektywy safe_mode_exec_dir. Ze względów praktycznych obecnie nie ma możliwości stosowania .. w ścieżce do programu. Wykonywana jest escapeshellcmd() na argumencie tej funkcji.
fopen() Sprawdza, czy katalog, na którym mają zostać wykonane operacje, ma takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.
mkdir() Sprawdza, czy katalog, na którym mają zostać wykonane operacje, ma takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.
rmdir() Sprawdza, czy katalog, na którym mają zostać wykonane operacje, ma takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.
rename() Sprawdza czy pliki lub katalogi, na których będą wykonane operacje, mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany. Sprawdza, czy katalog, na którym mają zostać wykonane operacje, ma takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.
unlink() Sprawdza czy pliki lub katalogi, na których będą wykonane operacje, mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany. Sprawdza, czy katalog, na którym mają zostać wykonane operacje, ma takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.
copy() Sprawdza czy pliki lub katalogi, na których będą wykonane operacje, mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany. Sprawdza, czy katalog, na którym mają zostać wykonane operacje, ma takie same UID (owner) jak skrypt, który jest aktualnie wykonywany. (dla źródła i przeznaczenia )
chgrp() Sprawdza czy pliki lub katalogi, na których będą wykonane operacje, mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.
chown() Sprawdza czy pliki lub katalogi, na których będą wykonane operacje, mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.
chmod() Sprawdza czy pliki lub katalogi, na których będą wykonane operacje, mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany. Dodatkowo, nie można ustawić bitów SUID, SGID i sticky bit
touch() Sprawdza czy pliki lub katalogi, na których będą wykonane operacje, mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany. Sprawdza, czy katalog, na którym mają zostać wykonane operacje, ma takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.
symlink() Sprawdza czy pliki lub katalogi, na których będą wykonane operacje, mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany. Sprawdza, czy katalog, na którym mają zostać wykonane operacje, ma takie same UID (owner) jak skrypt, który jest aktualnie wykonywany. (notatka: sprawdzany jest jedynie element, do którego utworzone jest dowiązanie symboliczne)
link() Sprawdza czy pliki lub katalogi, na których będą wykonane operacje, mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany. Sprawdza, czy katalog, na którym mają zostać wykonane operacje, ma takie same UID (owner) jak skrypt, który jest aktualnie wykonywany. (notatka: sprawdzany jest jedynie element, do którego utworzone jest dowiązanie)
apache_request_headers() W trybie bezpiecznym, nie są zwracane nagłówki zaczynające się od 'authorization' (wielkość liter nie ma znaczenia).
header() W trybie bezpiecznym UID skryptu jest dodawana do nazwy - części nagłówka Uwierzytelnienia-WWW, jeśli ustawimy ten nagłówek (używane w Uwierzytelnieniu HTTP).
PHP_AUTH variables W trybie bezpiecznym zmienne PHP_AUTH_USER, PHP_AUTH_PW, i AUTH_TYPE nie są dostępne w $_SERVER. Niezależnie od tego, możemy nadal używać REMOTE_USER dla użytkownika. (notatka: dostępna tylko od PHP 4.3.0)
highlight_file(), show_source() Sprawdza czy pliki lub katalogi, na których będą wykonane operacje, mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany. Sprawdza, czy katalog, na którym mają zostać wykonane operacje, ma takie same UID (owner) jak skrypt, który jest aktualnie wykonywany. (notatka: dostępna tylko od PHP 4.2.1)
parse_ini_file() Sprawdza czy pliki lub katalogi, na których będą wykonane operacje, mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany. Sprawdza, czy katalog, na którym mają zostać wykonane operacje, ma takie same UID (owner) jak skrypt, który jest aktualnie wykonywany. (notatka: dostępna tylko od PHP 4.2.1)
set_time_limit() Nie ma żadnego skutku, gdy PHP działa w trybie tryb bezpieczny.
max_execution_time Nie ma żadnego skutku, gdy PHP działa w trybie tryb bezpieczny.
mail() W trybie bezpiecznym, piąty parametr jest nieaktywny. (notatka: dostępna tylko od PHP 4.2.3)
session_start() Właściciel skryptu musi być również właścicielem katalogusession.save_path, gdy wartość session.save_handler jest ustawiona na files.
Wszystkie funkcje systemu plików oraz strumieni. Sprawdza czy pliki lub katalogi, na których będą wykonane operacje, mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany. Sprawdza, czy katalog, na którym mają zostać wykonane operacje, ma takie same UID (owner) jak skrypt, który jest aktualnie wykonywany. (zobacz opcję safe_mode_include_dir php.ini.




Using PHP from the command line

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.

Informacja: 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.

Informacja: 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.

Informacja: 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:

    Overridden php.ini directives
    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']

    Informacja: 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:

    CLI specific Constants
    Constant Description
    STDIN

    An already opened stream to stdin. This saves opening it with

    <?php

    $stdin 
    fopen('php://stdin''r');

    ?>

    If you want to read single line from stdin, you can use

    <?php
    $line 
    trim(fgets(STDIN)); // reads one line from STDIN
    fscanf(STDIN"%d\n"$number); // reads number from STDIN
    ?>

    STDOUT

    An already opened stream to stdout. This saves opening it with

    <?php

    $stdout 
    fopen('php://stdout''w');

    ?>

    STDERR

    An already opened stream to stderr. This saves opening it with

    <?php

    $stderr 
    fopen('php://stderr''w');

    ?>

    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.

    Informacja: 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.

    Informacja: 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:

  1. 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.

    Informacja: If you need to pass arguments to your scripts you need to pass -- as the first argument when using the -f switch.

  2. 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.

    Informacja: 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.

  3. 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:

Przykład #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.

Command line options
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.

Informacja: Files included through auto_prepend_file and auto_append_file are parsed in this mode but with some restrictions - e.g. functions have to be defined before called.

Informacja: Autoloading is not available if using PHP in CLI interactive mode.

-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.

Informacja: To pass arguments to scripts the first argument needs to be --, otherwise PHP will interperate them as PHP options.

-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.

Informacja: This option does not work together with the -r option.

-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.

Informacja: Care has to be taken when using this form of PHP to not collide with command line variable substitution done by the shell.

Example showing a parser error

$ php -r "$foo = get_defined_constants();"
Command line code(1) : Parse error - parse error, unexpected '='

The problem here is that the sh/bash performs variable substitution even when using double quotes ". Since the variable $foo is unlikely to be defined, it expands to nothing which results in the code passed to PHP for execution actually reading:

$ php -r " = get_defined_constants();"

The correct way would be to use single quotes '. Variables in single-quoted strings are not expanded by sh/bash.

$ php -r '$foo = get_defined_constants(); var_dump($foo);'
array(370) {
  ["E_ERROR"]=>
  int(1)
  ["E_WARNING"]=>
  int(2)
  ["E_PARSE"]=>
  int(4)
  ["E_NOTICE"]=>
  int(8)
  ["E_CORE_ERROR"]=>
  [...]

If you are using a shell different from sh/bash, you might experience further issues. Feel free to open a bug report at » http://bugs.php.net/. One can still easily run into troubles when trying to get shell variables into the code or using backslashes for escaping. You've been warned.

Informacja: -r is available in the CLI SAPI and not in the CGI SAPI.

Informacja: This option is meant for a very basic stuff. Thus some configuration directives (e.g. auto_prepend_file and auto_append_file) are ignored in this mode.

-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.

Przykład #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.

Informacja: This option does not work together with the -r option.

-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.

Informacja: This option does not work together with the -r option.

-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.

Przykład #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.

Przykład #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.

Przykład #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.

Przykład #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.

Przykład #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.

Przykład #8 Script intended to be run from command line (script.php)

#!/usr/bin/php
<?php

if ($argc != || 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:

Przykład #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.




Opis funkcji

Wskazówka

Zobacz też: Wykaz i klasyfikacja rozszerzeń.


Wpływ na zachowanie PHP


Alternative PHP Cache


Wstęp

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.



Instalacja/Konfiguracja

Spis treści


Wymagania

Do zbudowania tego rozszerzenia nie są wymagane żadne zewnętrzne biblioteki.



Instalacja

To rozszerzenie » PECL nie jest dołączane do PHP.

Informacje na temat instalacji tego rozszerzenia PECL można znaleźć w podręczniku w rozdziale zatytułowanym Instalacja rozszerzeń PECL. Dodatkowe informacje, takie jak nowe wersje, pliki do pobrania, pliki źródłowe, informacje o opiekunach czy rejestr zmian, można znaleźć tutaj: » http://pecl.php.net/package/apc.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Informacja: 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.

Informacja: For more in-depth, highly technical implementation details, see the » developer-supplied TECHNOTES file .



Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku 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.

APC configuration options
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.

Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

apc.enabled boolean

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).

apc.shm_segments integer

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.

apc.shm_size integer

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.

apc.optimization integer

The optimization level. Zero disables the optimizer, and higher values use more aggressive optimizations. Expect very modest speed improvements. This is experimental.

apc.num_files_hint integer

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.

apc.user_entries_hint integer

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.

apc.ttl integer

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.

apc.user_ttl integer

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.

apc.gc_ttl integer

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.

apc.cache_by_default boolean

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.

apc.filters string

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.

apc.mmap_file_mask string

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.

apc.slam_defense integer

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.

apc.file_update_protection integer

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.

apc.enable_cli integer

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.

apc.max_file_size integer

Prevent files larger than this value from getting cached. Defaults to 1M.

apc.stat integer

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.

apc.write_lock boolean

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.

apc.report_autofilter boolean

Logs any scripts that were automatically excluded from being cached due to early/late binding issues.

apc.include_once_override boolean

Optimize include_once() and require_once() calls and avoid the expensive system calls used.

apc.rfc1867 boolean

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.

Przykład #1 An apc.rfc1867 example

<?php
print_r
(apc_fetch("upload_$_POST[APC_UPLOAD_PROGRESS]"));
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [total] => 1142543
    [current] => 1142543
    [rate] => 1828068.8
    [filename] => test
    [name] => file
    [temp_filename] => /tmp/php8F
    [cancel_upload] => 0
    [done] => 1
)

apc.rfc1867_prefix string

Key prefix to use for the user cache entry generated by rfc1867 upload progress functionality.

apc.rfc1867_name string

Specify the hidden form entry name that activates APC upload progress and specifies the user cache key suffix.

apc.rfc1867_freq string

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.

apc.localcache boolean

This enables a lock-free local process shadow-cache which reduces lock contention when the cache is being written to.

apc.localcache.size integer

The size of the local process shadow-cache, should be set to a sufficiently large value, approximately half of apc.num_files_hint.

apc.coredump_unmap boolean

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.

Ostrzeżenie

This feature is potentially dangerous. Unmapping the shared memory segment in a fatal signal handler may cause undefined behaviour if a fatal error occurs.

Informacja: 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.

apc.stat_ctime integer

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.



Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.




Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.



APC Funkcje


apc_add

(PECL apc >= 3.0.13)

apc_add Cache a variable in the data store

Opis

bool apc_add ( string $key , mixed $var [, int $ttl = 0 ] )

Caches a variable in the data store, only if it's not already stored.

Informacja: Unlike many other mechanisms in PHP, variables stored using apc_add() will persist between requests (until the value is removed from the cache).

Parametry

key

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().)

var

The variable to store

ttl

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.).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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";
?>

Powyższy przykład wyświetli:

string(3) "BAR"
string(3) "BAR"

Zobacz też:



apc_cache_info

(PECL apc >= 2.0.0)

apc_cache_info Retrieves cached information from APC's data store

Opis

array apc_cache_info ([ string $cache_type [, bool $limited = false ]] )

Retrieves cached information and meta-data from APC's data store.

Zwracane wartości

Array of cached data (and meta-data) or FALSE on failure

Informacja: apc_cache_info() will raise a warning if it is unable to retrieve APC cache data. This typically occurs when APC is not enabled.

Parametry

cache_type

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.

limited

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.

Rejestr zmian

Wersja Opis
3.0.11 The limited parameter was introduced.
3.0.16 The "filehits" option for the cache_type parameter was introduced.

Przykłady

Przykład #1 A apc_cache_info() example

<?php
print_r
(apc_cache_info());
?>

Powyższy przykład wyświetli coś podobnego do:

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)
)



apc_clear_cache

(PECL apc >= 2.0.0)

apc_clear_cache Clears the APC cache

Opis

bool apc_clear_cache ([ string $cache_type ] )

Clears the user/system cache.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Parametry

cache_type

If cache_type is "user", the user cache will be cleared; otherwise, the system cache (cached files) will be cleared.

Zobacz też:



apc_compile_file

(PECL apc >= 3.0.13)

apc_compile_file Stores a file in the bytecode cache, bypassing all filters.

Opis

bool apc_compile_file ( string $filename )

Stores a file in the bytecode cache, bypassing all filters.

Parametry

filename

Full or relative path to a PHP file that will be compiled and stored in the bytecode cache.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.



apc_define_constants

(PECL apc >= 3.0.0)

apc_define_constants Defines a set of constants for retrieval and mass-definition

Opis

bool apc_define_constants ( string $key , array $constants [, bool $case_sensitive = true ] )

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.

Informacja: 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).

Parametry

key

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().

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.

case_sensitive

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.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 apc_define_constants() example

<?php
$constants 
= array(
    
'ONE'   => 1,
    
'TWO'   => 2,
    
'THREE' => 3,
);
apc_define_constants('numbers'$constants);
echo 
ONETWOTHREE;
?>

Powyższy przykład wyświetli:

123

Zobacz też:



apc_delete

(PECL apc >= 3.0.0)

apc_delete Removes a stored variable from the cache

Opis

bool apc_delete ( string $key )

Removes a stored variable from the cache.

Parametry

key

The key used to store the value (with apc_store()).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 A apc_delete() example

<?php
$bar 
'BAR';
apc_store('foo'$bar);
apc_delete('foo');
// this is obviously useless in this form
?>

Zobacz też:



apc_fetch

(PECL apc >= 3.0.0)

apc_fetch Fetch a stored variable from the cache

Opis

mixed apc_fetch ( mixed $key [, bool &$success ] )

Fetchs a stored variable from the cache.

Parametry

key

The key used to store the value (with apc_store()). If an array is passed then each element is fetched and returned.

success

Set to TRUE in success and FALSE in failure.

Zwracane wartości

The stored variable or array of variables on success; FALSE on failure

Przykłady

Przykład #1 A apc_fetch() example

<?php
$bar 
'BAR';
apc_store('foo'$bar);
var_dump(apc_fetch('foo'));
?>

Powyższy przykład wyświetli:

string(3) "BAR"

Zobacz też:



apc_load_constants

(PECL apc >= 3.0.0)

apc_load_constants Loads a set of constants from the cache

Opis

bool apc_load_constants ( string $key [, bool $case_sensitive = true ] )

Loads a set of constants from the cache.

Parametry

key

The name of the constant set (that was stored with apc_define_constants()) to be retrieved.

case_sensitive

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.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 apc_load_constants() example

<?php
$constants 
= array(
    
'ONE'   => 1,
    
'TWO'   => 2,
    
'THREE' => 3,
);
apc_define_constants('numbers'$constants);
apc_load_constants('numbers');
echo 
ONETWOTHREE;
?>

Powyższy przykład wyświetli:

123

Zobacz też:



apc_sma_info

(PECL apc >= 2.0.0)

apc_sma_info Retrieves APC's Shared Memory Allocation information

Opis

array apc_sma_info ([ bool $limited = false ] )

Retrieves APC's Shared Memory Allocation information.

Parametry

limited

When set to FALSE (default) apc_sma_info() will return a detailed information about each segment.

Zwracane wartości

Array of Shared Memory Allocation data; FALSE on failure.

Przykłady

Przykład #1 A apc_sma_info() example

<?php
print_r
(apc_sma_info());
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [num_seg] => 1
    [seg_size] => 31457280
    [avail_mem] => 31448408
    [block_lists] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [size] => 31448408
                            [offset] => 8864
                        )

                )

        )

)



apc_store

(PECL apc >= 3.0.0)

apc_store Cache a variable in the data store

Opis

bool apc_store ( string $key , mixed $var [, int $ttl = 0 ] )

Cache a variable in the data store.

Informacja: Unlike many other mechanisms in PHP, variables stored using apc_store() will persist between requests (until the value is removed from the cache).

Parametry

key

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.

var

The variable to store

ttl

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.).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 A apc_store() example

<?php
$bar 
'BAR';
apc_store('foo'$bar);
var_dump(apc_fetch('foo'));
?>

Powyższy przykład wyświetli:

string(3) "BAR"

Zobacz też:


Spis treści




Advanced PHP debugger


Wstęp

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.

Uwaga

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).



Instalacja/Konfiguracja

Spis treści


Wymagania

Do zbudowania tego rozszerzenia nie są wymagane żadne zewnętrzne biblioteki.



Instalacja

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 z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » 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)



Building on Win32

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.



Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

APD Configuration Options
Name Default Changeable Changelog
apd.dumpdir NULL PHP_INI_ALL  
apd.statement_tracing "0" PHP_INI_ALL Available since apd 0.9.

Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

apd.dumpdir string

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().

apd.statement_tracing boolean

Specfies whether or not to do per-line tracings. Turning this on (1) will impact the performance of your application.



Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.




Stałe predefiniowane

Poniższe stałe są zdefiniowane w tym rozszerzeniu i stają się dostępne, gdy rozszerzenie jest dokompilowane z PHP, lub załadowane dynamicznie przy starcie.

APD constants
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  


Przykłady

Spis treści


How to use PHP-APD in your scripts

  1. 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.

  2. Now run your script. The dump output will be written to apd.dumpdir/pprof_pid.ext.

    Wskazówka

    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

  3. 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.

  4. To generate a calltree file that you can import into the KCacheGrind profile analysis application, issue the pprof2calltree comand.




APD Funkcje

Contact information

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.


apd_breakpoint

(PECL apd >= 0.2)

apd_breakpointStops the interpreter and waits on a CR from the socket

Opis

bool apd_breakpoint ( int $debug_level )

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.

Parametry

poziom_debugowania

Liczba, która powstaje poprzez dodanie do siebie stałych XXX_TRACE.

Użycie MEMORY_TRACE nie jest zalecane. Jest bardzo powolne i nie wydaje się zbyt dokładne. Stała ASSIGNMENT_TRACE nie jest jeszcze zaimplementowana.

Aby włączyć wszystkie funkcjonalne śledzenia (TIMING, FUNCTIONS, ARGS SUMMARY (takie jak strace -c)) użyj wartości 99

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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);



apd_callstack

(PECL apd 0.2-0.4)

apd_callstackReturns the current call stack as an array

Opis

array apd_callstack ( void )

Returns the current call stack as an array

Zwracane wartości

An array containing the current call stack.

Przykłady

Przykład #1 apd_callstack() example

<?php
print_r
(apd_callstack());
?>



apd_clunk

(PECL apd 0.2-0.4)

apd_clunkThrow a warning and a callstack

Opis

void apd_clunk ( string $warning [, string $delimiter ] )

Behaves like perl's Carp::cluck. Throw a warning and a callstack.

Parametry

warning

The warning to throw.

delimiter

The delimiter. Default to <BR />.

Zwracane wartości

nie jest zwracana żadna wartość.

Przykłady

Przykład #1 apd_clunk() example

<?php
apd_clunk
("Some Warning""<br/>");
?>

Zobacz też:

  • apd_croak() - Throw an error, a callstack and then exit



apd_continue

(PECL apd >= 0.2)

apd_continueRestarts the interpreter

Opis

bool apd_continue ( int $debug_level )

Usually sent via the socket to restart the interpreter.

Parametry

poziom_debugowania

Liczba, która powstaje poprzez dodanie do siebie stałych XXX_TRACE.

Użycie MEMORY_TRACE nie jest zalecane. Jest bardzo powolne i nie wydaje się zbyt dokładne. Stała ASSIGNMENT_TRACE nie jest jeszcze zaimplementowana.

Aby włączyć wszystkie funkcjonalne śledzenia (TIMING, FUNCTIONS, ARGS SUMMARY (takie jak strace -c)) użyj wartości 99

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 apd_continue() example

<?php
apd_continue
(0);
?>



apd_croak

(PECL apd 0.2-0.4)

apd_croakThrow an error, a callstack and then exit

Opis

void apd_croak ( string $warning [, string $delimiter ] )

Behaves like perl's Carp::croak. Throw an error, a callstack and then exit.

Parametry

warning

The warning to throw.

delimiter

The delimiter. Default to <BR />.

Zwracane wartości

nie jest zwracana żadna wartość.

Przykłady

Przykład #1 apd_croak() example

<?php
apd_croak
("Some Warning","<P>");
?>

Zobacz też:



apd_dump_function_table

(Unknown)

apd_dump_function_tableOutputs the current function table

Opis

void apd_dump_function_table ( void )

Outputs the current function table.

Zwracane wartości

nie jest zwracana żadna wartość.

Przykłady

Przykład #1 apd_dump_function_table() example

<?php
apd_dump_function_table
();
?>



apd_dump_persistent_resources

(PECL apd 0.2-0.4)

apd_dump_persistent_resourcesReturn all persistent resources as an array

Opis

array apd_dump_persistent_resources ( void )

Return all persistent resources as an array.

Zwracane wartości

An array containing the current call stack.

Przykłady

Przykład #1 apd_dump_persistent_resources() example

<?php
print_r
(apd_dump_persistent_resources());
?>

Zobacz też:



apd_dump_regular_resources

(PECL apd 0.2-0.4)

apd_dump_regular_resourcesReturn all current regular resources as an array

Opis

array apd_dump_regular_resources ( void )

Return all current regular resources as an array.

Zwracane wartości

An array containing the current regular resources.

Przykłady

Przykład #1 apd_dump_regular_resources() example

<?php
print_r
(apd_dump_regular_resources());
?>

Zobacz też:



apd_echo

(PECL apd >= 0.2)

apd_echoEcho to the debugging socket

Opis

bool apd_echo ( string $output )

Usually sent via the socket to request information about the running script.

Parametry

output

The debugged variable.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 apd_echo() example

<?php
apd_echo
($i);
?>



apd_get_active_symbols

(PECL apd 0.2)

apd_get_active_symbolsGet an array of the current variables names in the local scope

Opis

array apd_get_active_symbols ( void )

Returns the names of all the variables defined in the active scope, (not their values).

Zwracane wartości

A multidimensional array with all the variables.

Przykłady

Przykład #1 apd_get_active_symbols() example

<?php
apd_echo
(apd_get_active_symbols());
?>



apd_set_pprof_trace

(PECL apd >= 0.2)

apd_set_pprof_traceStarts the session debugging

Opis

string apd_set_pprof_trace ([ string $dump_directory [, string $fragment = "pprof" ]] )

Starts debugging to pprof_{process_id} in the dump directory.

Parametry

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.

fragment

Zwracane wartości

Returns path of the destination file.

Przykłady

Przykład #1 apd_set_pprof_trace() example

<?php
apd_set_pprof_trace
();
?>

Zobacz też:



apd_set_session_trace_socket

(PECL apd >= 0.2)

apd_set_session_trace_socketStarts the remote session debugging

Opis

bool apd_set_session_trace_socket ( string $tcp_server , int $socket_type , int $port , int $debug_level )

Connects to the specified tcp_server (eg. tcplisten) and sends debugging data to the socket.

Parametry

tcp_server

IP or Unix Domain socket (like a file) of the TCP server.

socket_type

Can be AF_UNIX for file based sockets or APD_AF_INET for standard tcp/ip.

port

You can use any port, but higher numbers are better as most of the lower numbers may be used by other system services.

poziom_debugowania

Liczba, która powstaje poprzez dodanie do siebie stałych XXX_TRACE.

Użycie MEMORY_TRACE nie jest zalecane. Jest bardzo powolne i nie wydaje się zbyt dokładne. Stała ASSIGNMENT_TRACE nie jest jeszcze zaimplementowana.

Aby włączyć wszystkie funkcjonalne śledzenia (TIMING, FUNCTIONS, ARGS SUMMARY (takie jak strace -c)) użyj wartości 99

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 apd_set_session_trace_socket() example

<?php
  apd_set_session_trace_socket
("127.0.0.1",APD_AF_INET,7112,0);
?>



apd_set_session_trace

(PECL apd 0.2-0.4)

apd_set_session_traceStarts the session debugging

Opis

void apd_set_session_trace ( int $debug_level [, string $dump_directory ] )

Starts debugging to apd_dump_{process_id} in the dump directory.

Parametry

poziom_debugowania

Liczba, która powstaje poprzez dodanie do siebie stałych XXX_TRACE.

Użycie MEMORY_TRACE nie jest zalecane. Jest bardzo powolne i nie wydaje się zbyt dokładne. Stała ASSIGNMENT_TRACE nie jest jeszcze zaimplementowana.

Aby włączyć wszystkie funkcjonalne śledzenia (TIMING, FUNCTIONS, ARGS SUMMARY (takie jak strace -c)) użyj wartości 99

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.

Zwracane wartości

nie jest zwracana żadna wartość.

Przykłady

Przykład #1 apd_set_session_trace() example

<?php
apd_set_session_trace
(99);
?>



apd_set_session

(PECL apd 0.2-0.4)

apd_set_sessionChanges or sets the current debugging level

Opis

void apd_set_session ( int $debug_level )

This can be used to increase or decrease debugging in a different area of your application.

Parametry

poziom_debugowania

Liczba, która powstaje poprzez dodanie do siebie stałych XXX_TRACE.

Użycie MEMORY_TRACE nie jest zalecane. Jest bardzo powolne i nie wydaje się zbyt dokładne. Stała ASSIGNMENT_TRACE nie jest jeszcze zaimplementowana.

Aby włączyć wszystkie funkcjonalne śledzenia (TIMING, FUNCTIONS, ARGS SUMMARY (takie jak strace -c)) użyj wartości 99

Zwracane wartości

nie jest zwracana żadna wartość.

Przykłady

Przykład #1 apd_set_session() example

<?php
apd_set_session
(9);
?>



override_function

(PECL apd >= 0.2)

override_functionOverrides built-in functions

Opis

bool override_function ( string $function_name , string $function_args , string $function_code )

Overrides built-in functions by replacing them in the symbol table.

Parametry

function_name

The function to override.

function_args

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.

function_code

The new code for the function.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 override_function() example

<?php
override_function
('test''$a,$b''echo "DOING TEST"; return $a * $b;');
?>



rename_function

(PECL apd >= 0.2)

rename_functionRenames orig_name to new_name in the global function table

Opis

bool rename_function ( string $original_name , string $new_name )

Renames a orig_name to new_name in the global function table. Useful for temporarily overriding built-in functions.

Parametry

original_name

The original function name.

new_name

The new name for the original_name function.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 rename_function() example

<?php
rename_function
('mysql_connect''debug_mysql_connect' );
?>


Spis treści




PHP bytecode Compiler


Wstęp

Ostrzeżenie

Ten moduł jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie tych funkcji, ich nazw, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tego modułu na własne ryzyko.

Bcompiler was written for several reasons:

  • To encode entire script in a proprietary PHP application
  • To encode some classes and/or functions in a proprietary PHP application
  • To enable the production of php-gtk applications that could be used on client desktops, without the need for a php.exe.
  • To do the feasibility study for a PHP to C converter

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.



Instalacja/Konfiguracja

Spis treści


Wymagania

Do zbudowania tego rozszerzenia nie są wymagane żadne zewnętrzne biblioteki.



Instalacja

short installation note:

  • You need at least PHP 4.3.0 for the compression to work
  • To install on PHP 4.3.0 and later at the Unix command prompt type pear install bcompiler
  • To install on Windows, until the binary package distribution mechanism is finished please search the archives of the pear-general mailing list for pre-built packages. (or send an email to it if you could not find a reference)
  • To install on older versions you need to make some slight changes to the build.
  • untar the bcompiler.tgz archive into php4/ext.(Get it directly from PECL » http://pecl.php.net/get/bcompiler)
  • If the new directory is now called something like bcompiler-0.x, then you should rename it to bcompiler (except you only want to build it as self-contained php-module).
  • If you are using versions before PHP 4.3.0, the you will need to copy the Makefile.in.old to Makefile.in and config.m4.old to config.m4.
  • run phpize in ext/bcompiler
  • run ./buildconf in php4
  • run configure with --enable-bcompiler (and your other options)
  • make; make install
  • that's it.



Konfiguracja wykonawcza

To rozszerzenie nie definiuje posiada żadnych dyrektyw konfiguracyjnych w pliku php.ini.



Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.




Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.



bcompiler Funkcje

Contact Information

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.


bcompiler_load_exe

(PECL bcompiler >= 0.4)

bcompiler_load_exeReads and creates classes from a bcompiler exe file

Opis

bool bcompiler_load_exe ( string $filename )

Reads data from a bcompiler exe file and creates classes from the bytecodes.

Parametry

filename

The exe file path, as a string.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 bcompiler_load_exe() example

<?php

bcompiler_load_exe
("/tmp/example.exe");
print_r(get_defined_classes());

?>

Notatki

Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Zobacz też:



bcompiler_load

(PECL bcompiler >= 0.4)

bcompiler_loadReads and creates classes from a bz compressed file

Opis

bool bcompiler_load ( string $filename )

Reads data from a bzcompressed file and creates classes from the bytecodes.

Parametry

filename

The bzcompressed file path, as a string.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 bcompiler_load() example

<?php

bcompiler_load
("/tmp/example");

print_r(get_defined_classes());

?>

Notatki

Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Informacja: 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.

Zobacz też:



bcompiler_parse_class

(PECL bcompiler >= 0.4)

bcompiler_parse_classReads the bytecodes of a class and calls back to a user function

Opis

bool bcompiler_parse_class ( string $class , string $callback )

Reads the bytecodes of a class and calls back to a user function.

Parametry

class

The class name, as a string.

callback

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 bcompiler_parse_class() example

<?php

function readByteCodes($data) {
    
print_r($data);
}

bcompiler_parse_class("DB","readByteCodes");

?>

Notatki

Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Informacja: This function has been removed from bcompiler and is no longer available as of bcompiler 0.5.



bcompiler_read

(PECL bcompiler >= 0.4)

bcompiler_readReads and creates classes from a filehandle

Opis

bool bcompiler_read ( resource $filehandle )

Reads data from a open file handle and creates classes from the bytecodes.

Parametry

filehandle

A file handle as returned by fopen().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 bcompiler_read() example

<?php
$fh 
fopen("/tmp/example","r");
bcompiler_read($fh);
fclose($fh);
print_r(get_defined_classes());

?>

Notatki

Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Informacja: 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.



bcompiler_write_class

(PECL bcompiler >= 0.4)

bcompiler_write_classWrites an defined class as bytecodes

Opis

bool bcompiler_write_class ( resource $filehandle , string $className [, string $extends ] )

Reads the bytecodes from PHP for an existing class, and writes them to the open file handle.

Parametry

filehandle

A file handle as returned by fopen().

className

The class name, as a string.

extends

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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);

?>

Notatki

Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Informacja: 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.

Zobacz też:



bcompiler_write_constant

(PECL bcompiler >= 0.5)

bcompiler_write_constantWrites a defined constant as bytecodes

Opis

bool bcompiler_write_constant ( resource $filehandle , string $constantName )

Reads the bytecodes from PHP for an existing constant, and writes them to the open file handle.

Parametry

filehandle

A file handle as returned by fopen().

constantName

The name of the defined constant, as a string.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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);

?>

Notatki

Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Zobacz też:




bcompiler_write_file

(PECL bcompiler >= 0.6)

bcompiler_write_fileWrites a php source file as bytecodes

Opis

bool bcompiler_write_file ( resource $filehandle , string $filename )

This function complies specified source file into bytecodes, and writes them to the open file handle.

Parametry

filehandle

A file handle as returned by fopen().

filename

The source file path, as a string.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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";
*/
?>

Notatki

Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Zobacz też:




bcompiler_write_function

(PECL bcompiler >= 0.5)

bcompiler_write_functionWrites an defined function as bytecodes

Opis

bool bcompiler_write_function ( resource $filehandle , string $functionName )

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).

Parametry

filehandle

A file handle as returned by fopen().

functionName

The function name, as a string.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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);

?>

Notatki

Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Zobacz też:



bcompiler_write_functions_from_file

(PECL bcompiler >= 0.5)

bcompiler_write_functions_from_fileWrites all functions defined in a file as bytecodes

Opis

bool bcompiler_write_functions_from_file ( resource $filehandle , string $fileName )

Searches for all functions declared in the given file, and writes their correspondent bytecodes to the open file handle.

Parametry

filehandle

A file handle as returned by fopen().

fileName

The file to be compiled. You must always include or require the file you intend to compile.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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);

?>

Notatki

Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Zobacz też:



bcompiler_write_header

(PECL bcompiler >= 0.3)

bcompiler_write_headerWrites the bcompiler header

Opis

bool bcompiler_write_header ( resource $filehandle [, string $write_ver ] )

Writes the header part of a bcompiler file.

Parametry

filehandle

A file handle as returned by fopen().

write_ver

Can be used to write bytecode in a previously used format, so that you can use it with older versions of bcompiler.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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);

?>

Notatki

Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Zobacz też:



bcompiler_write_included_filename

(PECL bcompiler >= 0.5)

bcompiler_write_included_filenameWrites an included file as bytecodes

Opis

bool bcompiler_write_included_filename ( resource $filehandle , string $filename )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.


Spis treści




Error Handling and Logging


Wstęp

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.



Instalacja/Konfiguracja

Spis treści


Wymagania

Do zbudowania tego rozszerzenia nie są wymagane żadne zewnętrzne biblioteki.



Instalacja

By używać tych funkcji, nie trzeba niczego instalować. Są one częścią jądra PHP.



Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Errors and Logging Configuration Options
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  

Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

error_reporting integer

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.

Informacja: 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.

Informacja: 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.

Informacja: 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 (includes all errors, not just E_ALL).

display_errors string

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.

Informacja: This is a feature to support your development and should never be used on production systems (e.g. systems connected to the internet).

Informacja: 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.

display_startup_errors boolean

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.

log_errors boolean

Tells whether script error messages should be logged to the server's error log or error_log. This option is thus server-specific.

Informacja: You're strongly advised to use error logging in place of error displaying on production web sites.

log_errors_max_len integer

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.

Jeśli użyty zostanie typ integer, wartość zostanie liczona w bajtach. Można także użyć notacji skrótowej opisanej w FAQ.
ignore_repeated_errors boolean

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_repeated_source boolean

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.

report_memleaks boolean

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

track_errors boolean

If enabled, the last error message will always be present in the variable $php_errormsg.

html_errors boolean

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.

xmlrpc_errors boolean

Turns off normal error reporting and formats errors as XML-RPC error message.

xmlrpc_error_number integer

Used as the value of the XML-RPC faultCode element.

docref_root string

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.

Informacja: 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).

docref_ext string

See docref_root.

Informacja: The value of docref_ext must begin with a dot ".".

error_prepend_string string

String to output before an error message.

error_append_string string

String to output after an error message.

error_log string

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.



Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.




Stałe predefiniowane

Poniższe stałe są częścią jądra PHP a więc są zawsze widoczne.

Informacja: 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.

Errors and Logging
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.



Przykłady

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.

Przykład #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_ERRORE_USER_WARNINGE_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($err3"/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(23"foo");
$b = array(5.54.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";

?>



Error Handling Funkcje

Zobacz też:

See also syslog().


debug_backtrace

(PHP 4 >= 4.3.0, PHP 5)

debug_backtraceGenerates a backtrace

Opis

array debug_backtrace ([ bool $provide_object = true ] )

debug_backtrace() generates a PHP backtrace.

Parametry

provide_object

Whether or not to populate the "object" index. Defaults to TRUE.

Zwracane wartości

Returns an associative array. The possible returned elements are as follows:

Possible returned elements from debug_backtrace()
Nazwa Typ Opis
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).

Rejestr zmian

Wersja Opis
5.2.5 Added the optional parameter provide_object .
5.1.1 Added the current object as a possible return element.

Przykłady

Przykład #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"
  }
}

Zobacz też:



debug_print_backtrace

(PHP 5)

debug_print_backtrace Prints a backtrace

Opis

void debug_print_backtrace ( void )

debug_print_backtrace() prints a PHP backtrace. It prints the function calls, included/required files and eval()ed stuff.

Parametry

This function has no parameters.

Zwracane wartości

nie jest zwracana żadna wartość.

Przykłady

Przykład #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';
?>

Powyższy przykład wyświetli coś podobnego do:

#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]

Zobacz też:



error_get_last

(PHP 5 >= 5.2.0)

error_get_lastGet the last occurred error

Opis

array error_get_last ( void )

Gets information about the last error that occurred.

Zwracane wartości

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.

Przykłady

Przykład #1 An error_get_last() example

<?php
echo $a;
print_r(error_get_last());
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [type] => 8
    [message] => Undefined variable: a
    [file] => C:\WWW\index.php
    [line] => 2
)



error_log

(PHP 4, PHP 5)

error_logSend an error message somewhere

Opis

bool error_log ( string $message [, int $message_type = 0 [, string $destination [, string $extra_headers ]]] )

Sends an error message to the web server's error log, a TCP port or to a file.

Parametry

message

The error message that should be logged.

message_type

Says where the error should go. The possible message types are as follows:

error_log() log types
0 message is sent to PHP's system logger, using the Operating System's system logging mechanism or a file, depending on what the error_log configuration directive is set to. 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.

destination

The destination. Its meaning depends on the message_type parameter as described above.

extra_headers

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.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja Opis
5.2.7 The possible value of 4 was added to message_type .

Przykłady

Przykład #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");
?>



error_reporting

(PHP 4, PHP 5)

error_reportingSets which PHP errors are reported

Opis

int error_reporting ([ int $level ] )

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.

Parametry

level

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.

Zwracane wartości

Returns the old error_reporting level.

Rejestr zmian

Wersja Opis
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.

Przykłady

Przykład #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);

?>

Notatki

Ostrzeżenie

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).

Wskazówka

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.

Zobacz też:



restore_error_handler

(PHP 4 >= 4.0.1, PHP 5)

restore_error_handlerRestores the previous error handler function

Opis

bool restore_error_handler ( void )

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).

Zwracane wartości

This function always returns TRUE.

Przykłady

Przykład #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();
?>

Powyższy przykład wyświetli:

Invalid serialized value.

Notatki

Informacja: Calling restore_error_handler() from the error_handler function is ignored.

Zobacz też:



restore_exception_handler

(PHP 5)

restore_exception_handler Restores the previously defined exception handler function

Opis

bool restore_exception_handler ( void )

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).

Zwracane wartości

This function always returns TRUE.

Przykłady

Przykład #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...');
?>

Powyższy przykład wyświetli:

[exception_handler_1] This triggers the first exception handler...

Zobacz też:



set_error_handler

(PHP 4 >= 4.0.1, PHP 5)

set_error_handlerSets a user-defined error handler function

Opis

mixed set_error_handler ( callback $error_handler [, int $error_types = E_ALL | E_STRICT ] )

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.

Parametry

error_handler

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:

handler ( int $errno , string $errstr [, string $errfile [, int $errline [, array $errcontext ]]] )

errno
The first parameter, errno , contains the level of the error raised, as an integer.
errstr
The second parameter, errstr , contains the error message, as a string.
errfile
The third parameter is optional, errfile , which contains the filename that the error was raised in, as a string.
errline
The fourth parameter is optional, errline , which contains the line number the error was raised at, as an integer.
errcontext
The fifth parameter is optional, errcontext , which is an array that points to the active symbol table at the point the error occurred. In other words, errcontext will contain an array of every variable that existed in the scope the error was triggered in. User error handler must not modify error context.

If the function returns FALSE then the normal error handler continues.

error_types

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.

Zwracane wartości

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.

Rejestr zmian

Wersja Opis
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.

Przykłady

Przykład #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(23"foo"5.543.321.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($aM_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
?>

Powyższy przykład wyświetli coś podobnego do:

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 />

Zobacz też:



set_exception_handler

(PHP 5)

set_exception_handler Sets a user-defined exception handler function

Opis

callback set_exception_handler ( callback $exception_handler )

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.

Parametry

exception_handler

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.

Zwracane wartości

Returns the name of the previously defined exception handler, or NULL on error. If no previous handler was defined, NULL is also returned.

Przykłady

Przykład #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";
?>

Zobacz też:



trigger_error

(PHP 4 >= 4.0.1, PHP 5)

trigger_errorGenerates a user-level error/warning/notice message

Opis

bool trigger_error ( string $error_msg [, int $error_type = E_USER_NOTICE ] )

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.

Parametry

error_msg

The designated error message for this error. It's limited to 1024 characters in length. Any additional characters beyond 1024 will be truncated.

error_type

The designated error type for this error. It only works with the E_USER family of constants, and will default to E_USER_NOTICE.

Zwracane wartości

This function returns FALSE if wrong error_type is specified, TRUE otherwise.

Przykłady

Przykład #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);
}
?>

Zobacz też:



user_error

(PHP 4, PHP 5)

user_errorAlias of trigger_error()

Opis

Ta funkcja jest aliasem dla: trigger_error().


Spis treści




htaccess-like support for all SAPIs


Wstęp

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.).



Instalacja/Konfiguracja

Spis treści


Wymagania

PHP version 5.2.0 or greater.



Instalacja

Informacje na temat instalacji tego rozszerzenia PECL można znaleźć w podręczniku w rozdziale zatytułowanym Instalacja rozszerzeń PECL. Dodatkowe informacje, takie jak nowe wersje, pliki do pobrania, pliki źródłowe, informacje o opiekunach czy rejestr zmian, można znaleźć tutaj: » http://pecl.php.net/package/htscanner



Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

htscanner Opcje konfiguracyjne
Nazwa Domyślnie Możliwość zmian 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  

Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

htscanner.config_file string

Filename to use as configuration file.

htscanner.default_docroot string

Default document root.

htscanner.default_ttl int

Cache time out for the configuration data, in seconds.

htscanner.stop_on_error int

Stop on error (parse error, cannot set an ini setting).



Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.





Inclusion hierarchy viewer


Wstęp

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.



Instalacja/Konfiguracja

Spis treści


Wymagania

PHP version 5.1.0 or greater.

The included gengraph.php file utilizes the » graphviz library, however, this is not required.



Instalacja

Informacje na temat instalacji tego rozszerzenia PECL można znaleźć w podręczniku w rozdziale zatytułowanym Instalacja rozszerzeń PECL. Dodatkowe informacje, takie jak nowe wersje, pliki do pobrania, pliki źródłowe, informacje o opiekunach czy rejestr zmian, można znaleźć tutaj: » http://pecl.php.net/package/inclued



Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

inclued Opcje konfiguracyjne
Nazwa Domyślnie Możliwość zmian Changelog
inclued.enabled Off PHP_INI_*  
inclued.dumpdir Off PHP_INI_*  

Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

inclued.enabled int

Whether or not to enable inclued.

inclued.dumpdir int

Location (path) to the directory that stores inclued files. If set, each PHP request will create a file.

Uwaga

Because every request creates a file, this directory may fill up fast!



Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.




Stałe predefiniowane

Poniższe stałe są zdefiniowane w tym rozszerzeniu i stają się dostępne, gdy rozszerzenie jest dokompilowane z PHP, lub załadowane dynamicznie przy starcie.

To rozszerzenie nie posiada żadnych stałych.



Przykłady

Spis treści


Example that implements inclued into an application

This example demonstrates the process of implementing inclued into an existing application, and viewing the results.

Przykład #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($fpjson_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.

Przykład #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




inclued Funkcje


inclued_get_data

(PECL inclued >= 0.1.0)

inclued_get_dataGet the inclued data

Opis

array inclued_get_data ( void )

Get the inclued data.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The inclued data.

Przykłady

Przykład #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);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
  [includes] => Array
    (
      [0] => Array
        (
          [operation] => include
          [op_type] => 2
          [filename] => x.php
          [opened_path] => /tmp/x.php
          [fromfile] => /tmp/z.php
          [fromline] => 2
        )
    )
)

Zobacz też:


Spis treści




PHP Options and Information


Wstęp

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.



Instalacja/Konfiguracja

Spis treści


Wymagania

Do zbudowania tego rozszerzenia nie są wymagane żadne zewnętrzne biblioteki.



Instalacja

By używać tych funkcji, nie trzeba niczego instalować. Są one częścią jądra PHP.



Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

PHP Options/Inf Configuration Options
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.

Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

assert.active boolean

Enable assert() evaluation.

assert.bail boolean

Terminate script execution on failed assertions.

assert.warning boolean

Issue a PHP warning for each failed assertion.

assert.callback string

user function to call on failed assertions

assert.quiet_eval boolean

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()

enable_dl boolean

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 tryb bezpieczny. In tryb bezpieczny, it's always impossible to use dl().

max_execution_time integer

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 tryb bezpieczny. 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.

max_input_time integer

This sets the maximum time in seconds a script is allowed to parse input data, like POST, GET and file uploads.

max_input_nesting_level integer

Sets the max nesting depth of input variables (i.e. $_GET, $_POST..)

magic_quotes_gpc boolean
Ostrzeżenie

Ta opcja jest PRZESTARZA�?A od PHP 5.3.0 i USUNI�?TA w PHP 6.0.0 Używanie tej opcji nie jest zalecane.

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.

Informacja: In PHP 4, also $_ENV variables are escaped.

Informacja: 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()

magic_quotes_runtime boolean
Ostrzeżenie

Ta opcja jest PRZESTARZA�?A od PHP 5.3.0 i USUNI�?TA w PHP 6.0.0 Używanie tej opcji nie jest zalecane.

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):

zend.enable_gc boolean

Enables or disables the circular reference collector.



Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.




Stałe predefiniowane

Poniższe stałe są częścią jądra PHP a więc są zawsze widoczne.

Pre-defined phpcredits() constants
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.
phpinfo() constants
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().

assert() constants
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.

Windows specific constants
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.

Windows suitemask bitfields
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 Options/Info Funkcje


assert_options

(PHP 4, PHP 5)

assert_optionsSet/get the various assert flags

Opis

mixed assert_options ( int $what [, mixed $value ] )

Set the various assert() control options or just query their current settings.

Parametry

what

Assert Options
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

value

An optional new value for the option.

Zwracane wartości

Returns the original setting of any option or FALSE on errors.

Przykłady

Przykład #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';
?>

Zobacz też:

  • assert() - Checks if assertion is FALSE



assert

(PHP 4, PHP 5)

assertChecks if assertion is FALSE

Opis

bool assert ( mixed $assertion )

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)

Parametry

assertion

The assertion.

Zwracane wartości

FALSE if the assertion is false, TRUE otherwise.

Przykłady

Przykład #1 Handle a failed assertion with a custom handler

<?php
// Active assert and make it quiet
assert_options(ASSERT_ACTIVE1);
assert_options(ASSERT_WARNING0);
assert_options(ASSERT_QUIET_EVAL1);

// 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("")');
?>

Zobacz też:



dl

(PHP 4, PHP 5)

dlLoads a PHP extension at runtime

Opis

int dl ( string $library )

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()).

Ostrzeżenie

Ta funkcja jest PRZESTARZA�?A od PHP 5.3.0 i USUNI�?TA w PHP 6.0.0. Używanie tej funkcji nie jest zalecane.

Parametry

library

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

  • whether PHP has been built with --enable-debug or not
  • whether PHP has been built with (experimental) ZTS (Zend Thread Safety) support or not
  • the current internal ZEND_MODULE_API_NO (Zend internal module API number, which is basically the date on which a major module API change happened, e.g. 20010901)

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.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. 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 tryb bezpieczny 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.

Przykłady

Przykład #1 dl() examples

<?php
// Example loading an extension based on OS
if (!extension_loaded('sqlite')) {
    if (
strtoupper(substr(PHP_OS03)) === '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);
}
?>

Rejestr zmian

Wersja Opis
5.3.0 This function now throws an E_DEPRECATED notice on all sapi's except for CLI, CGI and Embed.

Notatki

Informacja: 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 !

Informacja: As of PHP 5, the dl() function is deprecated in every SAPI except CLI. Use Extension Loading Directives method instead.

Informacja: Since PHP 6 this function is disabled in all SAPIs, except CLI, CGI and embed.

Informacja: dl() is case sensitive on Unix platforms.

Informacja: Ta funkcja jest niedostępna jeśli PHP działa w trybie bezpiecznym

Zobacz też:



extension_loaded

(PHP 4, PHP 5)

extension_loadedFind out whether an extension is loaded

Opis

bool extension_loaded ( string $name )

Finds out whether the extension is loaded.

Parametry

name

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]

Zwracane wartości

Returns TRUE if the extension identified by name is loaded, FALSE otherwise.

Przykłady

Przykład #1 extension_loaded() example

<?php
if (!extension_loaded('gd')) {
    if (!
dl('gd.so')) {
        exit;
    }
}
?>

Rejestr zmian

Wersja Opis
5.0.0 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 extensions available which also use uppercase letters. Prior to PHP 5, this function compared the names case sensitively.

Zobacz też:



gc_collect_cycles

(PHP 5 >= 5.3.0)

gc_collect_cyclesForces collection of any existing garbage cycles

Opis

int gc_collect_cycles ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Forces collection of any existing garbage cycles.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns number of collected cycles.



gc_disable

(PHP 5 >= 5.3.0)

gc_disableDeactivates the circular reference collector

Opis

void gc_disable ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Deactivates the circular reference collector.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

nie jest zwracana żadna wartość.



gc_enable

(PHP 5 >= 5.3.0)

gc_enableActivates the circular reference collector

Opis

void gc_enable ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Activates the circular reference collector.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

nie jest zwracana żadna wartość.



gc_enabled

(PHP 5 >= 5.3.0)

gc_enabledReturns status of the circular reference collector

Opis

bool gc_enabled ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns status of the circular reference collector.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the garbage collector is enabled, FALSE otherwise.



get_cfg_var

(PHP 4, PHP 5)

get_cfg_varGets the value of a PHP configuration option

Opis

string get_cfg_var ( string $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.

Parametry

option

The configuration option name.

Zwracane wartości

Returns the current value of the PHP configuration variable specified by option , or FALSE if an error occurs.

Rejestr zmian

Wersja Opis
5.3.0 get_cfg_var() was fixed to be able to return "array" ini options.

Zobacz też:



get_current_user

(PHP 4, PHP 5)

get_current_userGets the name of the owner of the current PHP script

Opis

string get_current_user ( void )

Returns the name of the owner of the current PHP script.

Zwracane wartości

Returns the username as a string.

Przykłady

Przykład #1 get_current_user() example

<?php
echo 'Current script owner: ' get_current_user();
?>

Powyższy przykład wyświetli coś podobnego do:

Current script owner: SYSTEM

Zobacz też:



get_defined_constants

(PHP 4 >= 4.1.0, PHP 5)

get_defined_constantsReturns an associative array with the names of all the constants and their values

Opis

array get_defined_constants ([ bool $categorize ] )

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.

Parametry

categorize

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));
?>

Powyższy przykład wyświetli coś podobnego do:

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
        )

)

Zwracane wartości

Rejestr zmian

Wersja Opis
5.0.0 The categorize parameter was added.

Przykłady

Przykład #1 get_defined_constants() Example

<?php
print_r
(get_defined_constants());
?>

Powyższy przykład wyświetli coś podobnego do:

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
)

Zobacz też:



get_extension_funcs

(PHP 4, PHP 5)

get_extension_funcsReturns an array with the names of the functions of a module

Opis

array get_extension_funcs ( string $module_name )

This function returns the names of all the functions defined in the module indicated by module_name .

Parametry

module_name

The module name.

Informacja: This parameter must be in lowercase.

Zwracane wartości

Returns an array with all the functions, or FALSE if module_name is not a valid extension.

Przykłady

Przykład #1 Prints the XML functions

<?php
print_r
(get_extension_funcs("xml"));
?>

Powyższy przykład wyświetli coś podobnego do:

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
)

Zobacz też:



get_include_path

(PHP 4 >= 4.3.0, PHP 5)

get_include_pathGets the current include_path configuration option

Opis

string get_include_path ( void )

Gets the current include_path configuration option value.

Zwracane wartości

Returns the path, as a string.

Przykłady

Przykład #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');
?>

Zobacz też:



get_included_files

(PHP 4, PHP 5)

get_included_filesReturns an array with the names of included or required files

Opis

array get_included_files ( void )

Gets the names of all files that have been included using include(), include_once(), require() or require_once().

Zwracane wartości

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.

Rejestr zmian

Wersja Opis
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().

Przykłady

Przykład #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";
}

?>

Powyższy przykład wyświetli:

abc.php
test1.php
test2.php
test3.php
test4.php

Notatki

Informacja: Files included using the auto_prepend_file configuration directive are not included in the returned array.

Zobacz też:



get_loaded_extensions

(PHP 4, PHP 5)

get_loaded_extensionsReturns an array with the names of all modules compiled and loaded

Opis

array get_loaded_extensions ([ bool $zend_extensions = false ] )

This function returns the names of all the modules compiled and loaded in the PHP interpreter.

Parametry

zend_extensions

Return zend_extensions or not, defaults to FALSE (do not list zend_extensions).

Zwracane wartości

Returns an indexed array of all the modules names.

Rejestr zmian

Wersja Opis
5.2.4 The optional zend_extensions parameter was added

Przykłady

Przykład #1 get_loaded_extensions() Example

<?php
print_r
(get_loaded_extensions());
?>

Powyższy przykład wyświetli coś podobnego do:

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
)

Zobacz też:



get_magic_quotes_gpc

(PHP 4, PHP 5)

get_magic_quotes_gpcGets the current configuration setting of magic quotes gpc

Opis

int get_magic_quotes_gpc ( void )

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.

Zwracane wartości

Returns 0 if magic quotes gpc are off, 1 otherwise.

Przykłady

Przykład #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')";
?>

Notatki

Informacja: 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: ''

Zobacz też:



get_magic_quotes_runtime

(PHP 4, PHP 5)

get_magic_quotes_runtimeGets the current active configuration setting of magic_quotes_runtime

Opis

int get_magic_quotes_runtime ( void )

Returns the current active configuration setting of magic_quotes_runtime.

Zwracane wartości

Returns 0 if magic quotes runtime is off, 1 otherwise.

Przykłady

Przykład #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);
}
?>

Zobacz też:



get_required_files

(PHP 4, PHP 5)

get_required_filesAlias dla get_included_files()

Opis

Ta funkcja jest aliasem dla: get_included_files().



getenv

(PHP 4, PHP 5)

getenvGets the value of an environment variable

Opis

string getenv ( string $varname )

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.

Parametry

varname

The variable name.

Zwracane wartości

Returns the value of the environment variable varname , or FALSE on an error.

Przykłady

Przykład #1 getenv() Example

<?php
// Example use of getenv()
$ip getenv('REMOTE_ADDR');

// Or simply use a Superglobal ($_SERVER or $_ENV)
$ip $_SERVER['REMOTE_ADDR'];
?>

Zobacz też:



getlastmod

(PHP 4, PHP 5)

getlastmodGets time of last page modification

Opis

int getlastmod ( void )

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().

Zwracane wartości

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.

Przykłady

Przykład #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());
?>

Zobacz też:



getmygid

(PHP 4 >= 4.1.0, PHP 5)

getmygidGet PHP script owner's GID

Opis

int getmygid ( void )

Gets the group ID of the current script.

Zwracane wartości

Returns the group ID of the current script, or FALSE on error.

Zobacz też:



getmyinode

(PHP 4, PHP 5)

getmyinodeGets the inode of the current script

Opis

int getmyinode ( void )

Gets the inode of the current script.

Zwracane wartości

Returns the current script's inode as an integer, or FALSE on error.

Zobacz też:



getmypid

(PHP 4, PHP 5)

getmypidGets PHP's process ID

Opis

int getmypid ( void )

Gets the current PHP process ID.

Zwracane wartości

Returns the current PHP process ID, or FALSE on error.

Notatki

Ostrzeżenie

Process IDs are not unique, thus they are a weak entropy source. We recommend against relying on pids in security-dependent contexts.

Zobacz też:



getmyuid

(PHP 4, PHP 5)

getmyuidGets PHP script owner's UID

Opis

int getmyuid ( void )

Gets the user ID of the current script.

Zwracane wartości

Returns the user ID of the current script, or FALSE on error.

Zobacz też:



getopt

(PHP 4 >= 4.3.0, PHP 5)

getoptGets options from the command line argument list

Opis

array getopt ( string $options [, array $longopts ] )

Parses options passed to the script.

Parametry

options
Each character in this string will be used as option characters and matched against options passed to the script starting with a single hyphen (-). For example, an option string "x" recognizes an option -x.
longopts
An array of options. Each element in this array will be used as option strings and matched against options passed to the script starting with two hyphens (--). For example, an longopts element "opt" recognizes an option --opt.

Informacja: Prior to PHP5.3.0 this parameter was only available on few systems

The options parameter may contain the following elements:

  • Individual characters (do not accept values)
  • Characters followed by a colon (parameter requires value)
  • Characters followed by two colons (optional value)

Option values are the first argument after the string. It does not matter if a value has leading white space or not.

Informacja: Optional values do not accept " " (space) as a separator.

Informacja: 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).

Zwracane wartości

This function will return an array of option / argument pairs or FALSE on failure.

Rejestr zmian

Wersja Opis
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.

Przykłady

Przykład #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)
}

Przykład #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)
}

Przykład #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)
}



getrusage

(PHP 4, PHP 5)

getrusageGets the current resource usages

Opis

array getrusage ([ int $who = 0 ] )

This is an interface to getrusage(2). It gets data returned from the system call.

Parametry

who

If who is 1, getrusage will be called with RUSAGE_CHILDREN.

Zwracane wartości

Returns an associative array containing the data returned from the system call. All entries are accessible by using their documented field names.

Przykłady

Przykład #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)
?>

Notatki

Informacja: Ta funkcja nie jest dostępna na platformie Windows.

Zobacz też:

  • Your system's man page on getrusage(2)



ini_alter

(PHP 4, PHP 5)

ini_alterAlias dla ini_set()

Opis

Ta funkcja jest aliasem dla: ini_set().



ini_get_all

(PHP 4 >= 4.2.0, PHP 5)

ini_get_allGets all configuration options

Opis

array ini_get_all ([ string $extension [, bool $details = true ]] )

Returns all the registered configuration options.

Parametry

extension

An optional extension name. If set, the function return only options specific for that extension.

details

Retrieve details settings or only the current value for each setting. Default is TRUE (retrieve details).

Zwracane wartości

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.

Informacja: It's possible for a directive to have multiple access levels, which is why access shows the appropriate bitmask values.

Rejestr zmian

Wersja Opis
5.3.0 Added details .

Przykłady

Przykład #1 ini_get_all() examples

<?php
print_r
(ini_get_all("pcre"));
print_r(ini_get_all());
?>

Powyższy przykład wyświetli coś podobnego do:

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
        )

    ...

)

Przykład #2 Disabling details

<?php
print_r
(ini_get_all("pcre"false)); // Added in PHP 5.3.0
print_r(ini_get_all(nullfalse)); // Added in PHP 5.3.0
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [pcre.backtrack_limit] => 100000
    [pcre.recursion_limit] => 100000
)
Array
(
    [allow_call_time_pass_reference] => 0
    [allow_url_fopen] => 1
    ...
)

Zobacz też:



ini_get

(PHP 4, PHP 5)

ini_getGets the value of a configuration option

Opis

string ini_get ( string $varname )

Returns the value of the configuration option on success.

Parametry

varname

The configuration option name.

Zwracane wartości

Returns the value of the configuration option as a string on success, or an empty string on failure or for null values.

Przykłady

Przykład #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;
}

?>

Powyższy przykład wyświetli coś podobnego do:


display_errors = 1
register_globals = 0
post_max_size = 8M
post_max_size+1 = 9
post_max_size in bytes = 8388608

Notatki

Informacja: 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.

Informacja: 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.

Zobacz też:



ini_restore

(PHP 4, PHP 5)

ini_restoreRestores the value of a configuration option

Opis

void ini_restore ( string $varname )

Restores a given configuration option to its original value.

Parametry

varname

The configuration option name.

Zwracane wartości

nie jest zwracana żadna wartość.

Przykłady

Przykład #1 ini_restore() example

<?php
$setting 
'y2k_compliance';

echo 
'Current value for \'' $setting '\': ' ini_get($setting), PHP_EOL;

ini_set($settingini_get($setting) ? 1);
echo 
'New value for \'' $setting '\': ' ini_get($setting), PHP_EOL;

ini_restore($setting);
echo 
'Original value for \'' $setting '\': ' ini_get($setting), PHP_EOL;
?>

Powyższy przykład wyświetli:

Current value for 'y2k_compliance': 1
New value for 'y2k_compliance': 0
Original value for 'y2k_compliance': 1

Zobacz też:



ini_set

(PHP 4, PHP 5)

ini_setSets the value of a configuration option

Opis

string ini_set ( string $varname , string $newvalue )

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.

Parametry

varname

Not all the available options can be changed using ini_set(). There is a list of all available options in the appendix.

newvalue

The new value for the option.

Zwracane wartości

Returns the old value on success, FALSE on failure.

Przykłady

Przykład #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');
?>

Zobacz też:



magic_quotes_runtime

(PHP 4, PHP 5)

magic_quotes_runtimeAlias dla set_magic_quotes_runtime()

Opis

Ta funkcja jest aliasem dla: set_magic_quotes_runtime()



main

mainDummy for main()

Opis

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.

Known errors that point to main()
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



memory_get_peak_usage

(PHP 5 >= 5.2.0)

memory_get_peak_usageReturns the peak of memory allocated by PHP

Opis

int memory_get_peak_usage ([ bool $real_usage = false ] )

Returns the peak of memory, in bytes, that's been allocated to your PHP script.

Parametry

real_usage

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.

Zwracane wartości

Returns the memory peak in bytes.

Rejestr zmian

Wersja Opis
5.2.1 Compiling with --enable-memory-limit is no longer required for this function to exist.
5.2.0 real_usage was added.

Zobacz też:



memory_get_usage

(PHP 4 >= 4.3.2, PHP 5)

memory_get_usageReturns the amount of memory allocated to PHP

Opis

int memory_get_usage ([ bool $real_usage = false ] )

Returns the amount of memory, in bytes, that's currently being allocated to your PHP script.

Parametry

real_usage

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.

Zwracane wartości

Returns the memory amount in bytes.

Rejestr zmian

Wersja Opis
5.2.1 Compiling with --enable-memory-limit is no longer required for this function to exist.
5.2.0 real_usage was added.

Przykłady

Przykład #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

?>

Zobacz też:



php_ini_loaded_file

(PHP 5 >= 5.2.4)

php_ini_loaded_fileRetrieve a path to the loaded php.ini file

Opis

string php_ini_loaded_file ( void )

Check if a php.ini file is loaded, and retrieve its path.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The loaded php.ini path, or FALSE if one is not loaded.

Przykłady

Przykład #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';
}
?>

Powyższy przykład wyświetli coś podobnego do:

Loaded php.ini: /usr/local/php/php.ini

Zobacz też:



php_ini_scanned_files

(PHP 4 >= 4.3.0, PHP 5)

php_ini_scanned_filesReturn a list of .ini files parsed from the additional ini dir

Opis

string php_ini_scanned_files ( void )

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.

Zwracane wartości

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().

Przykłady

Przykład #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";
        }
    }
}
?>

Zobacz też:



php_logo_guid

(PHP 4, PHP 5)

php_logo_guidGets the logo guid

Opis

string php_logo_guid ( void )

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.

Zwracane wartości

Returns PHPE9568F34-D428-11d2-A769-00AA001ACF42.

Przykłady

Przykład #1 php_logo_guid() example

<?php

echo '<img src="' $_SERVER['PHP_SELF'] .
     
'?=' php_logo_guid() . '" alt="PHP Logo !" />';

?>

Zobacz też:



php_sapi_name

(PHP 4 >= 4.0.1, PHP 5)

php_sapi_nameReturns the type of interface between web server and PHP

Opis

string php_sapi_name ( void )

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.

Zwracane wartości

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.

Przykłady

Przykład #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_type03) == 'cgi') {
    echo 
"You are using CGI PHP\n";
} else {
    echo 
"You are not using CGI PHP\n";
}
?>

Notatki

Informacja: An alternative approach
The PHP constant PHP_SAPI has the same value as php_sapi_name().

Wskazówka

A potential gotcha

The defined SAPI may not be obvious, because for example instead of apache it may be defined as apache2handler or apache2filter.

Zobacz też:



php_uname

(PHP 4 >= 4.0.2, PHP 5)

php_unameReturns information about the operating system PHP is running on

Opis

string php_uname ([ string $mode = "a" ] )

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.

Parametry

mode

mode is a single character that defines what information is returned:

  • 'a': This is the default. Contains all modes in the sequence "s n r v m".
  • 's': Operating system name. eg. FreeBSD.
  • 'n': Host name. eg. localhost.example.com.
  • 'r': Release name. eg. 5.1.2-RELEASE.
  • 'v': Version information. Varies a lot between operating systems.
  • 'm': Machine type. eg. i386.

Zwracane wartości

Returns the description, as a string.

Przykłady

Przykład #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_OS03)) === '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:

Przykład #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;      // ;
?>

Zobacz też:



phpcredits

(PHP 4, PHP 5)

phpcreditsPrints out the credits for PHP

Opis

bool phpcredits ([ int $flag = CREDITS_ALL ] )

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.

Parametry

flag

To generate a custom credits page, you may want to use the flag parameter. flag is optional, and it defaults to CREDITS_ALL.

Pre-defined phpcredits() flags
name description
CREDITS_ALL All the credits, equivalent to using: CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_FULLPAGE. It generates a complete stand-alone HTML page with the appropriate tags.
CREDITS_DOCS The credits for the documentation team
CREDITS_FULLPAGE Usually used in combination with the other flags. Indicates that 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

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Prints the general credits

<?php
phpcredits
(CREDITS_GENERAL);
?>

Przykład #2 Prints the core developers and the documentation group

<?php
phpcredits
(CREDITS_GROUP CREDITS_DOCS CREDITS_FULLPAGE);
?>

Przykład #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>

Zobacz też:



phpinfo

(PHP 4, PHP 5)

phpinfoOutputs lots of PHP information

Opis

bool phpinfo ([ int $what = INFO_ALL ] )

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.

Parametry

what

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.

phpinfo() options
Name (constant) Value Description
INFO_GENERAL 1 The configuration line, php.ini location, build date, Web Server, System and more.
INFO_CREDITS 2 PHP 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.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja Opis
5.2.2 The "Loaded Configuration File" information was added, when before only "Configuration File (php.ini) Path" existed.

Przykłady

Przykład #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);

?>

Notatki

Informacja: 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.

Informacja: phpinfo() outputs plain text instead of HTML when using the CLI mode.

Zobacz też:



phpversion

(PHP 4, PHP 5)

phpversionGets the current PHP version

Opis

string phpversion ([ string $extension ] )

Returns a string containing the version of the currently running PHP parser or extension.

Parametry

extension

An optional extension name.

Zwracane wartości

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.

Przykłady

Przykład #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');
?>

Przykład #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 explode('.',PHP_VERSION);

    
define('PHP_VERSION_ID', ($version[0] * 10000 $version[1] * 100 $version[2]));
}

// 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[1]);
    
define('PHP_RELEASE_VERSION',     $version[2]);

    
// and so on, ...
}
?>

Notatki

Informacja: This information is also available in the predefined constant PHP_VERSION. More versioning information is available using the PHP_VERSION_* constants.

Zobacz też:



putenv

(PHP 4, PHP 5)

putenvSets the value of an environment variable

Opis

bool putenv ( string $setting )

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.

Parametry

setting

The setting, like "FOO=BAR"

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Setting an environment variable

<?php
putenv
("UNIQID=$uniqid");
?>

Notatki

Ostrzeżenie

These directives have only effect when safe-mode itself is enabled!

Zobacz też:

  • getenv() - Gets the value of an environment variable



restore_include_path

(PHP 4 >= 4.3.0, PHP 5)

restore_include_pathRestores the value of the include_path configuration option

Opis

void restore_include_path ( void )

Restores the include_path configuration option back to its original master value as set in php.ini

Zwracane wartości

nie jest zwracana żadna wartość.

Przykłady

Przykład #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

?>

Zobacz też:



set_include_path

(PHP 4 >= 4.3.0, PHP 5)

set_include_pathSets the include_path configuration option

Opis

string set_include_path ( string $new_include_path )

Sets the include_path configuration option for the duration of the script.

Parametry

new_include_path

The new value for the include_path

Zwracane wartości

Returns the old include_path on success or FALSE on failure.

Przykłady

Przykład #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');
?>

Przykład #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);
?>

Zobacz też:



set_magic_quotes_runtime

(PHP 4, PHP 5)

set_magic_quotes_runtimeSets the current active configuration setting of magic_quotes_runtime

Opis

bool set_magic_quotes_runtime ( bool $new_setting )

Set the current active configuration setting of magic_quotes_runtime.

Ostrzeżenie

Ta funkcja jest PRZESTARZA�?A od PHP 5.3.0 i USUNI�?TA w PHP 6.0.0. Używanie tej funkcji nie jest zalecane.

Parametry

new_setting

FALSE for off, TRUE for on.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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($fp64), PHP_EOL;

// With magic_quotes_runtime
rewind($fp);
set_magic_quotes_runtime(true);

echo 
'With magic_quotes_runtime: ' fread($fp64), PHP_EOL;

// Clean up
fclose($fp);
?>

Powyższy przykład wyświetli:

Without magic_quotes_runtime: 'PHP' is a Recursive acronym
With magic_quotes_runtime: \'PHP\' is a Recursive acronym

Zobacz też:



set_time_limit

(PHP 4, PHP 5)

set_time_limitLimits the maximum execution time

Opis

void set_time_limit ( int $seconds )

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.

Parametry

seconds

The maximum execution time, in seconds. If set to zero, no time limit is imposed.

Zwracane wartości

nie jest zwracana żadna wartość.

Notatki

Ostrzeżenie

This function has no effect when PHP is running in tryb bezpieczny. There is no workaround other than turning off safe mode or changing the time limit in the php.ini.

Informacja: 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.



sys_get_temp_dir

(PHP 5 >= 5.2.1)

sys_get_temp_dirReturns directory path used for temporary files

Opis

string sys_get_temp_dir ( void )

Returns the path of the directory PHP stores temporary files in by default.

Zwracane wartości

Returns the path of the temporary directory.

Przykłady

Przykład #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;
?>

Powyższy przykład wyświetli coś podobnego do:

C:\Windows\Temp\TuxA318.tmp

Zobacz też:



version_compare

(PHP 4 >= 4.1.0, PHP 5)

version_compareCompares two "PHP-standardized" version number strings

Opis

mixed version_compare ( string $version1 , string $version2 [, string $operator ] )

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.

Parametry

version1

First version number.

version2

Second version number.

operator

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.

Zwracane wartości

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.

Przykłady

The examples below use the PHP_VERSION constant, because it contains the value of the PHP version that is executing the code.

Przykład #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";
}
?>

Notatki

Informacja: The PHP_VERSION constant holds current PHP version.

Informacja: Note that pre-release versions, such as 5.3.0-dev, are considered lower than their final release counterparts (like 5.3.0).

Zobacz też:



zend_logo_guid

(PHP 4, PHP 5)

zend_logo_guidGets the Zend guid

Opis

string zend_logo_guid ( void )

This function returns the ID which can be used to display the Zend logo using the built-in image.

Zwracane wartości

Returns PHPE9568F35-D428-11d2-A769-00AA001ACF42.

Przykłady

Przykład #1 zend_logo_guid() example

<?php

echo '<img src="' $_SERVER['PHP_SELF'] .
     
'?=' zend_logo_guid() . '" alt="Zend Logo !" />';

?>

Zobacz też:



zend_thread_id

(PHP 5)

zend_thread_idReturns a unique identifier for the current thread

Opis

int zend_thread_id ( void )

This function returns a unique identifier for the current thread.

Zwracane wartości

Returns the thread id as an integer.

Przykłady

Przykład #1 zend_thread_id() example

<?php
$thread_id 
zend_thread_id();

echo 
'Current thread id is: ' $thread_id;
?>

Powyższy przykład wyświetli coś podobnego do:

Current thread id is: 7864

Notatki

Informacja: This function is only available if PHP has been built with ZTS (Zend Thread Safety) support and debug mode (--enable-debug).



zend_version

(PHP 4, PHP 5)

zend_versionGets the version of the current Zend engine

Opis

string zend_version ( void )

Returns a string containing the version of the currently running Zend Engine.

Zwracane wartości

Returns the Zend Engine version number, as a string.

Przykłady

Przykład #1 zend_version() example

<?php
echo "Zend engine version: " zend_version();
?>

Powyższy przykład wyświetli coś podobnego do:

Zend engine version: 2.2.0

Zobacz też:


Spis treści




Memtrack


Wstęp

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.

Ostrzeżenie

Ten moduł jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie tych funkcji, ich nazw, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tego modułu na własne ryzyko.



Instalacja/Konfiguracja

Spis treści


Wymagania

Do zbudowania tego rozszerzenia nie są wymagane żadne zewnętrzne biblioteki.



Instalacja

Informacje na temat instalacji tego rozszerzenia PECL można znaleźć w podręczniku w rozdziale zatytułowanym Instalacja rozszerzeń PECL. Dodatkowe informacje, takie jak nowe wersje, pliki do pobrania, pliki źródłowe, informacje o opiekunach czy rejestr zmian, można znaleźć tutaj: » http://pecl.php.net/package/memtrack



Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Memtrack Configuration Options
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

Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

memtrack.enabled boolean

Disables or enables the extension. Default value is 0, i.e. disabled.

memtrack.soft_limit int

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.

memtrack.hard_limit int

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.

memtrack.vm_limit int

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).

memtrack.ignore_functions string

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.



Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.




Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.



Przykłady

Spis treści


Basic example on using memtrack extension:

Przykład #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

Powyższy przykład wyświetli coś podobnego do:

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




Object property and method call overloading


Wstęp

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.

Ostrzeżenie

Ten moduł jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie tych funkcji, ich nazw, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tego modułu na własne ryzyko.

Ostrzeżenie

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.



Instalacja/Konfiguracja

Spis treści


Wymagania

Do zbudowania tego rozszerzenia nie są wymagane żadne zewnętrzne biblioteki.



Instalacja

Aby używać tych funkcji musimy skompilować PHP z opcją --enable-overload. Począwszy od PHP 4.3.0 to rozszerzenie jest domyślnie włączone. Możemy wyłączyć obsługę przeciążania podczas kompilacji PHP za pomocą opcji --disable--overload.

PHP w wersji dla systemów Windows posiada wbudowaną obsługę dla tego rozszerzenia. Nie trzeba ładować żadnych dodatkowych rozszerzeń, aby używać tych funkcji.

Informacja: Obsługa przeciążania jest dostępna od PHP 4.3.0.



Konfiguracja wykonawcza

To rozszerzenie nie definiuje posiada żadnych dyrektyw konfiguracyjnych w pliku php.ini.



Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.




Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.



Przykłady

Spis treści


Some simple examples on using the overload() function:

Przykład #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->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->= array($val);
var_dump($o->a[0]->prop);

?>




Object overloading Funkcje


overload

(PHP 4 >= 4.3.0)

overloadUmożliwienie przeciążania właściwości i wołania metod dla klasy

Opis

void overload ([ string $nazwa_klasy ] )

Funkcja overload() umożliwia przeciążanie właściwości i wołania metod dla klasy identyfikowanej parametrem nazwa_klasy . Zobacz przykład w sekcji wprowadzającej tej części.


Spis treści

  • overload — Umożliwienie przeciążania właściwości i wołania metod dla klasy



Output Buffering Control


Wstęp

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.

Informacja: 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.



Instalacja/Konfiguracja

Spis treści


Wymagania

Do zbudowania tego rozszerzenia nie są wymagane żadne zewnętrzne biblioteki.



Instalacja

By używać tych funkcji, nie trzeba niczego instalować. Są one częścią jądra PHP.



Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Output Control configuration options
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.

Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

output_buffering boolean/integer

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.

output_handler string

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.

Informacja: You cannot use both mb_output_handler() with ob_iconv_handler() and you cannot use both ob_gzhandler() and zlib.output_compression.

Informacja: Only built-in functions can be used with this directive. For user defined functions, use ob_start().

implicit_flush boolean

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().



Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.




Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.



Przykłady

Spis treści


Przykłady

Przykład #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.)




Output Control Funkcje

Zobacz też:

See also header() and setcookie().


flush

(PHP 4, PHP 5)

flushFlush the output buffer

Opis

void flush ( void )

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.

Zwracane wartości

nie jest zwracana żadna wartość.



ob_clean

(PHP 4 >= 4.2.0, PHP 5)

ob_cleanClean (erase) the output buffer

Opis

void ob_clean ( void )

This function discards the contents of the output buffer.

This function does not destroy the output buffer like ob_end_clean() does.

Zwracane wartości

nie jest zwracana żadna wartość.

Zobacz też:

  • ob_flush() - Flush (send) the output buffer
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering
  • ob_end_clean() - Clean (erase) the output buffer and turn off output buffering



ob_end_clean

(PHP 4, PHP 5)

ob_end_cleanClean (erase) the output buffer and turn off output buffering

Opis

bool ob_end_clean ( void )

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.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. 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).

Błędy/Wyjątki

If the function fails it generates an E_NOTICE.

Rejestr zmian

Wersja Opis
4.2.0 The boolean return value was added.

Przykłady

The following example shows an easy way to get rid of all output buffers:

Przykład #1 ob_end_clean() example

<?php
ob_start
();
echo 
'Text that won\'t get displayed.';
ob_end_clean();
?>

Zobacz też:



ob_end_flush

(PHP 4, PHP 5)

ob_end_flushFlush (send) the output buffer and turn off output buffering

Opis

bool ob_end_flush ( void )

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.

Informacja: This function is similar to ob_get_flush(), except that ob_get_flush() returns the buffer as a string.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. 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).

Błędy/Wyjątki

If the function fails it generates an E_NOTICE.

Rejestr zmian

Wersja Opis
4.2.0 The boolean return value was added.

Przykłady

Przykład #1 ob_end_flush() example

The following example shows an easy way to flush and end all output buffers:

<?php
  
while (@ob_end_flush());
?>

Zobacz też:



ob_flush

(PHP 4 >= 4.2.0, PHP 5)

ob_flushFlush (send) the output buffer

Opis

void ob_flush ( void )

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.

Zwracane wartości

nie jest zwracana żadna wartość.

Zobacz też:



ob_get_clean

(PHP 4 >= 4.3.0, PHP 5)

ob_get_cleanGet current buffer contents and delete current output buffer

Opis

string ob_get_clean ( void )

Gets the current buffer contents and delete current output buffer.

ob_get_clean() essentially executes both ob_get_contents() and ob_end_clean().

Zwracane wartości

Returns the contents of the output buffer and end output buffering. If output buffering isn't active then FALSE is returned.

Przykłady

Przykład #1 A simple ob_get_clean() example

<?php

ob_start
();

echo 
"Hello World";

$out ob_get_clean();
$out strtolower($out);

var_dump($out);
?>

Powyższy przykład wyświetli:


string(11) "hello world"

Zobacz też:



ob_get_contents

(PHP 4, PHP 5)

ob_get_contentsReturn the contents of the output buffer

Opis

string ob_get_contents ( void )

Gets the contents of the output buffer without clearing it.

Zwracane wartości

This will return the contents of the output buffer or FALSE, if output buffering isn't active.

Przykłady

Przykład #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);
?>

Powyższy przykład wyświetli:

string(6) "Hello "
string(11) "Hello World"

Zobacz też:



ob_get_flush

(PHP 4 >= 4.3.0, PHP 5)

ob_get_flushFlush the output buffer, return it as a string and turn off output buffering

Opis

string ob_get_flush ( void )

ob_get_flush() flushes the output buffer, return it as a string and turns off output buffering.

Informacja: This function is similar to ob_end_flush(), except that this function returns the buffer as a string.

Zwracane wartości

Returns the output buffer or FALSE if no buffering is active.

Przykłady

Przykład #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());
?>

Powyższy przykład wyświetli:

Array
(
    [0] => default output handler
)
Array
(
)

Zobacz też:



ob_get_length

(PHP 4 >= 4.0.2, PHP 5)

ob_get_lengthReturn the length of the output buffer

Opis

int ob_get_length ( void )

This will return the length of the contents in the output buffer.

Zwracane wartości

Returns the length of the output buffer contents or FALSE if no buffering is active.

Przykłady

Przykład #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;
?>

Powyższy przykład wyświetli:

6, 11

Zobacz też:



ob_get_level

(PHP 4 >= 4.2.0, PHP 5)

ob_get_levelReturn the nesting level of the output buffering mechanism

Opis

int ob_get_level ( void )

Returns the nesting level of the output buffering mechanism.

Zwracane wartości

Returns the level of nested output buffering handlers or zero if output buffering is not active.

Zobacz też:



ob_get_status

(PHP 4 >= 4.2.0, PHP 5)

ob_get_statusGet status of output buffers

Opis

array ob_get_status ([ bool $full_status = FALSE ] )

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.

Parametry

full_status

TRUE to return all active output buffer levels. If FALSE or not set, only the top level output buffer is returned.

Zwracane wartości

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
)

Simple ob_get_status() results
Key:level
Value:Output nesting level
Key:type
Value:PHP_OUTPUT_HANDLER_INTERNAL (0) or PHP_OUTPUT_HANDLER_USER (1)
Key:status
Value:One of PHP_OUTPUT_HANDLER_START (0), PHP_OUTPUT_HANDLER_CONT (1) or PHP_OUTPUT_HANDLER_END (2)
Key:name
Value:Name of active output handler or ' default output handler' if none is set
Key:del
Value:Erase-flag as set by ob_start()

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:

Full ob_get_status() results
Key:chunk_size
Value:Chunk size as set by ob_start()
Key:size
Value:...
Key:blocksize
Value:...

Zobacz też:



ob_gzhandler

(PHP 4 >= 4.0.4, PHP 5)

ob_gzhandlerob_start callback function to gzip output buffer

Opis

string ob_gzhandler ( string $buffer , int $mode )

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.

Parametry

buffer

mode

Zwracane wartości

Rejestr zmian

Wersja Opis
4.0.5 The mode parameter was added.

Przykłady

Przykład #1 ob_gzhandler() example

<?php

ob_start
("ob_gzhandler");

?>
<html>
<body>
<p>This should be a compressed page.</p>
</html>
<body>

Notatki

Informacja: ob_gzhandler() requires the zlib extension.

Informacja: You cannot use both ob_gzhandler() and zlib.output_compression. Also note that using zlib.output_compression is preferred over ob_gzhandler().

Zobacz też:



ob_implicit_flush

(PHP 4, PHP 5)

ob_implicit_flushTurn implicit flush on/off

Opis

void ob_implicit_flush ([ int $flag ] )

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.

Parametry

flag

TRUE to turn implicit flushing on, FALSE otherwise. Defaults to TRUE.

Zwracane wartości

nie jest zwracana żadna wartość.

Zobacz też:



ob_list_handlers

(PHP 4 >= 4.3.0, PHP 5)

ob_list_handlersList all output handlers in use

Opis

array ob_list_handlers ( void )

Lists all output handlers in use.

Zwracane wartości

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".

Przykłady

Przykład #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();
?>

Powyższy przykład wyświetli:

Array
(
    [0] => default output handler
)

Array
(
    [0] => ob_gzhandler
)

Array
(
    [0] => default output handler
)

Zobacz też:

  • ob_end_clean() - Clean (erase) the output buffer and turn off output buffering
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering
  • ob_get_flush() - Flush the output buffer, return it as a string and turn off output buffering
  • ob_start() - Turn on output buffering



ob_start

(PHP 4, PHP 5)

ob_startTurn on output buffering

Opis

bool ob_start ([ callback $output_callback [, int $chunk_size [, bool $erase ]]] )

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.

Ostrzeżenie

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.

Parametry

output_callback

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.

Informacja: 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.

chunk_size

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.

erase

If the optional parameter erase is set to FALSE, the buffer will not be deleted until the script finishes.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja Opis
6.0.0 Value 1 is no more special.
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.

Przykłady

Przykład #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
();

?>

Powyższy przykład wyświetli:

<html>
<body>
<p>It's like comparing oranges to oranges.</p>
</body>
</html>

Zobacz też:



output_add_rewrite_var

(PHP 4 >= 4.3.0, PHP 5)

output_add_rewrite_varAdd URL rewriter values

Opis

bool output_add_rewrite_var ( string $name , string $value )

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.

Informacja: Calling this function will implicitly start output buffering if it is not active already.

Parametry

name

The variable name.

value

The variable value.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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());
?>

Powyższy przykład wyświetli:

<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
)

Zobacz też:



output_reset_rewrite_vars

(PHP 4 >= 4.3.0, PHP 5)

output_reset_rewrite_varsReset URL rewriter values

Opis

bool output_reset_rewrite_vars ( void )

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()).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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>';
?>

Powyższy przykład wyświetli:

<a href="file.php?PHPSESSID=xxx&var=value">link</a>
<a href="file.php">link</a>

Zobacz też:


Spis treści




runkit


Wstęp

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.



Stałe predefiniowane

Poniższe stałe są zdefiniowane w tym rozszerzeniu i stają się dostępne, gdy rozszerzenie jest dokompilowane z PHP, lub załadowane dynamicznie przy starcie.

RUNKIT_IMPORT_FUNCTIONS (integer)
runkit_import() flag indicating that normal functions should be imported from the specified file.
RUNKIT_IMPORT_CLASS_METHODS (integer)
runkit_import() flag indicating that class methods should be imported from the specified file.
RUNKIT_IMPORT_CLASS_CONSTS (integer)
runkit_import() flag indicating that class constants should be imported from the specified file. Note that this flag is only meaningful in PHP versions 5.1.0 and above.
RUNKIT_IMPORT_CLASS_PROPS (integer)
runkit_import() flag indicating that class standard properties should be imported from the specified file.
RUNKIT_IMPORT_CLASSES (integer)
runkit_import() flag representing a bitwise OR of the RUNKIT_IMPORT_CLASS_* constants.
RUNKIT_IMPORT_OVERRIDE (integer)
runkit_import() flag indicating that if any of the imported functions, methods, constants, or properties already exist, they should be replaced with the new definitions. If this flag is not set, then any imported definitions which already exist will be discarded.
RUNKIT_ACC_PUBLIC (integer)
PHP 5 specific flag to runkit_method_add()
RUNKIT_ACC_PROTECTED (integer)
PHP 5 specific flag to runkit_method_add()
RUNKIT_ACC_PRIVATE (integer)
PHP 5 specific flag to runkit_method_add()
CLASSKIT_ACC_PUBLIC (integer)
PHP 5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.
CLASSKIT_ACC_PROTECTED (integer)
PHP 5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.
CLASSKIT_ACC_PRIVATE (integer)
PHP 5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.
CLASSKIT_AGGREGATE_OVERRIDE (integer)
PHP 5 specific flag to classkit_import() Only defined when classkit compatibility is enabled.
RUNKIT_VERSION (string)
Defined to the current version of the runkit package.
CLASSKIT_VERSION (string)
Defined to the current version of the runkit package. Only defined when classkit compatibility is enabled.


Instalacja/Konfiguracja

Spis treści


Wymagania

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.



Instalacja

To rozszerzenie » PECL nie jest dołączane do PHP.

Informacje na temat instalacji tego rozszerzenia PECL można znaleźć w podręczniku w rozdziale zatytułowanym Instalacja rozszerzeń PECL. Dodatkowe informacje, takie jak nowe wersje, pliki do pobrania, pliki źródłowe, informacje o opiekunach czy rejestr zmian, można znaleźć tutaj: » http://pecl.php.net/package/runkit.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/



Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Runkit Configuration Options
Name Default Changeable Changelog
runkit.superglobal "" PHP_INI_PERDIR  
runkit.internal_override "0" PHP_INI_SYSTEM  

Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

runkit.superglobal string
Comma-separated list of variable names to be treated as superglobals. This value should be set in the systemwide php.ini file, but may work in perdir configuration contexts depending on your SAPI.

Przykład #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();
?>
runkit.internal_override boolean
Enables ability to modify/rename/remove internal functions.



Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.




runkit Funkcje


Runkit_Sandbox

(PECL runkit >= 0.7.0)

Runkit_Sandbox Runkit Sandbox Class -- PHP Virtual Machine

Opis

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.

Informacja: Obsługa rozszerzenia Sandbox (wymagane dla runkit_lint(), runkit_lint_file(), i klasy Runkit_Sandbox) jest dostępna tylko w PHP 5.1.0 lub specjalnie zmodyfikowanych wersjach PHP 5.0, i wymaga włączonego bezpieczeństwa wątków. Więcej informacji można znaleźć w pliku README dołączonym do pakietu runkit.

Constructor

void Runkit_Sandbox::__construct ([ array $options ] )

options is an associative array containing any combination of the special ini options listed below.

safe_mode

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.

safe_mode_gid

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.

safe_mode_include_dir

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

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.

allow_url_fopen

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

disable_functions

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.

disable_classes

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.

runkit.superglobal

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.

runkit.internal_override

Ini option runkit.internal_override may be disabled (but not re-enabled) within sandboxes.

Przykład #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);
?>

Accessing Variables

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.

Przykład #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));');
?>

Powyższy przykład wyświetli:

bar
barbaz
bool(false)

Calling PHP Functions

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().

Przykład #3 Calling sandbox functions

<?php
$sandbox 
= new Runkit_Sandbox();

echo 
$sandbox->str_replace('a','f','abc');
?>

Powyższy przykład wyświetli:

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.

Przykład #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');
?>

Powyższy przykład wyświetli:

bar
baz

Changing Sandbox Settings

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.

Sandbox Settings / Status Indicators
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.  



Runkit_Sandbox_Parent

(PECL runkit >= 0.7.0)

Runkit_Sandbox_Parent Runkit Anti-Sandbox Class

Opis

void Runkit_Sandbox_Parent::__construct ( void )

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.

Informacja: Obsługa rozszerzenia Sandbox (wymagane dla runkit_lint(), runkit_lint_file(), i klasy Runkit_Sandbox) jest dostępna tylko w PHP 5.1.0 lub specjalnie zmodyfikowanych wersjach PHP 5.0, i wymaga włączonego bezpieczeństwa wątków. Więcej informacji można znaleźć w pliku README dołączonym do pakietu 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.

Przykład #1 Working with variables in a sandbox

<?php
$sandbox 
= new Runkit_Sandbox();
$sandbox['parent_access'] = true;
?>

Accessing the Parent's Variables

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.

Przykład #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);');
}
?>

Powyższy przykład wyświetli:

string(6) "Global"
string(7) "three()"
string(5) "two()"
string(5) "one()"
string(6) "Global"
string(6) "Global"

Calling the Parent's Functions

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.



runkit_class_adopt

(PECL runkit >= 0.7.0)

runkit_class_adopt Convert a base class to an inherited class, add ancestral methods when appropriate

Opis

bool runkit_class_adopt ( string $classname , string $parentname )

Parametry

classname

Name of class to be adopted

parentname

Parent class which child class is extending

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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();
?>

Powyższy przykład wyświetli:

Parent Function Output

Zobacz też:



runkit_class_emancipate

(PECL runkit >= 0.7.0)

runkit_class_emancipate Convert an inherited class to a base class, removes any method whose scope is ancestral

Opis

bool runkit_class_emancipate ( string $classname )

Parametry

classname

Name of class to emancipate

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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();
?>

Powyższy przykład wyświetli:

Parent Function Output
Fatal error: Call to undefined function:  parentFunc() in example.php on line 12

Zobacz też:

  • runkit_class_adopt() - Convert a base class to an inherited class, add ancestral methods when appropriate



runkit_constant_add

(PECL runkit >= 0.7.0)

runkit_constant_add Similar to define(), but allows defining in class definitions as well

Opis

bool runkit_constant_add ( string $constname , mixed $value )

Parametry

constname

Name of constant to declare. Either a string to indicate a global constant, or classname::constname to indicate a class constant.

value

NULL, Bool, Long, Double, String, or Resource value to store in the new constant.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



runkit_constant_redefine

(PECL runkit >= 0.7.0)

runkit_constant_redefine Redefine an already defined constant

Opis

bool runkit_constant_redefine ( string $constname , mixed $newvalue )

Parametry

constname

Constant to redefine. Either string indicating global constant, or classname::constname indicating class constant.

newvalue

New value to assign to constant.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



runkit_constant_remove

(PECL runkit >= 0.7.0)

runkit_constant_remove Remove/Delete an already defined constant

Opis

bool runkit_constant_remove ( string $constname )

Parametry

constname

Name of constant to remove. Either a string indicating a global constant, or classname::constname indicating a class constant.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



runkit_function_add

(PECL runkit >= 0.7.0)

runkit_function_add Add a new function, similar to create_function()

Opis

bool runkit_function_add ( string $funcname , string $arglist , string $code )

Parametry

funcname

Name of function to be created

arglist

Comma separated argument list

code

Code making up the function

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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);
?>

Powyższy przykład wyświetli:

The value of a is 1
The value of b is 2

Zobacz też:



runkit_function_copy

(PECL runkit >= 0.7.0)

runkit_function_copy Copy a function to a new function name

Opis

bool runkit_function_copy ( string $funcname , string $targetname )

Parametry

funcname

Name of existing function

targetname

Name of new function to copy definition to

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 A runkit_function_copy() example

<?php
function original() {
  echo 
"In a function\n";
}
runkit_function_copy('original','duplicate');
original();
duplicate();
?>

Powyższy przykład wyświetli:

In a function
In a function

Zobacz też:



runkit_function_redefine

(PECL runkit >= 0.7.0)

runkit_function_redefine Replace a function definition with a new implementation

Opis

bool runkit_function_redefine ( string $funcname , string $arglist , string $code )

Informacja: Domyślnie, tylko funkcje przestrzeni użytkownika mogą być usunięte, przemianowane lub zmodyfikowane. Aby uzyskać możliwość modyfikacji funkcji wewnętrznych, należy włączyć opcję runkit.internal_override w pliku php.ini.

Parametry

funcname

Name of function to redefine

arglist

New list of arguments to be accepted by function

code

New code implementation

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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();
?>

Powyższy przykład wyświetli:

Original Testme Implementation
New Testme Implementation

Zobacz też:



runkit_function_remove

(PECL runkit >= 0.7.0)

runkit_function_remove Remove a function definition

Opis

bool runkit_function_remove ( string $funcname )

Informacja: Domyślnie, tylko funkcje przestrzeni użytkownika mogą być usunięte, przemianowane lub zmodyfikowane. Aby uzyskać możliwość modyfikacji funkcji wewnętrznych, należy włączyć opcję runkit.internal_override w pliku php.ini.

Parametry

funcname

Name of function to be deleted

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



runkit_function_rename

(PECL runkit >= 0.7.0)

runkit_function_rename Change a function's name

Opis

bool runkit_function_rename ( string $funcname , string $newname )

Informacja: Domyślnie, tylko funkcje przestrzeni użytkownika mogą być usunięte, przemianowane lub zmodyfikowane. Aby uzyskać możliwość modyfikacji funkcji wewnętrznych, należy włączyć opcję runkit.internal_override w pliku php.ini.

Parametry

funcname

Current function name

newname

New function name

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



runkit_import

(PECL runkit >= 0.7.0)

runkit_import Process a PHP file importing function and class definitions, overwriting where appropriate

Opis

bool runkit_import ( string $filename [, int $flags = RUNKIT_IMPORT_CLASS_METHODS ] )

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.

Parametry

filename

Filename to import function and class definitions from

flags

Bitwise OR of the RUNKIT_IMPORT_* family of constants.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.



runkit_lint_file

(PECL runkit >= 0.7.0)

runkit_lint_file Check the PHP syntax of the specified file

Opis

bool runkit_lint_file ( string $filename )

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.

Informacja: Obsługa rozszerzenia Sandbox (wymagane dla runkit_lint(), runkit_lint_file(), i klasy Runkit_Sandbox) jest dostępna tylko w PHP 5.1.0 lub specjalnie zmodyfikowanych wersjach PHP 5.0, i wymaga włączonego bezpieczeństwa wątków. Więcej informacji można znaleźć w pliku README dołączonym do pakietu runkit.

Parametry

filename

File containing PHP Code to be lint checked

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



runkit_lint

(PECL runkit >= 0.7.0)

runkit_lint Check the PHP syntax of the specified php code

Opis

bool runkit_lint ( string $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.

Informacja: Obsługa rozszerzenia Sandbox (wymagane dla runkit_lint(), runkit_lint_file(), i klasy Runkit_Sandbox) jest dostępna tylko w PHP 5.1.0 lub specjalnie zmodyfikowanych wersjach PHP 5.0, i wymaga włączonego bezpieczeństwa wątków. Więcej informacji można znaleźć w pliku README dołączonym do pakietu runkit.

Parametry

code

PHP Code to be lint checked

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



runkit_method_add

(PECL runkit >= 0.7.0)

runkit_method_addDynamically adds a new method to a given class

Opis

bool runkit_method_add ( string $classname , string $methodname , string $args , string $code [, int $flags = RUNKIT_ACC_PUBLIC ] )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Parametry

classname

The class to which this method will be added

methodname

The name of the method to add

args

Comma-delimited list of arguments for the newly-created method

code

The code to be evaluated when methodname is called

flags

The type of method to create, can be RUNKIT_ACC_PUBLIC, RUNKIT_ACC_PROTECTED or RUNKIT_ACC_PRIVATE

Informacja: This parameter is only used as of PHP 5, because, prior to this, all methods were public.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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(124);
?>

Powyższy przykład wyświetli:

16

Zobacz też:



runkit_method_copy

(PECL runkit >= 0.7.0)

runkit_method_copyCopies a method from class to another

Opis

bool runkit_method_copy ( string $dClass , string $dMethod , string $sClass [, string $sMethod ] )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Parametry

dClass

Destination class for copied method

dMethod

Destination method name

sClass

Source class of the method to copy

sMethod

Name of the method to copy from the source class. If this parameter is omitted, the value of dMethod is assumed.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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();
?>

Powyższy przykład wyświetli:

foo!

Zobacz też:



runkit_method_redefine

(PECL runkit >= 0.7.0)

runkit_method_redefineDynamically changes the code of the given method

Opis

bool runkit_method_redefine ( string $classname , string $methodname , string $args , string $code [, int $flags = RUNKIT_ACC_PUBLIC ] )

Informacja: Ta funkcja nie może być użyta do manipulacji aktualnie działającej (lub powiązanej) metody. This function cannot

Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Parametry

classname

The class in which to redefine the method

methodname

The name of the method to redefine

args

Comma-delimited list of arguments for the redefined method

code

The new code to be evaluated when methodname is called

flags

The redefined method can be RUNKIT_ACC_PUBLIC, RUNKIT_ACC_PROTECTED or RUNKIT_ACC_PRIVATE

Informacja: This parameter is only used as of PHP 5, because, prior to this, all methods were public.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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();
?>

Powyższy przykład wyświetli:

Before: foo!
After: bar!

Zobacz też:



runkit_method_remove

(PECL runkit >= 0.7.0)

runkit_method_removeDynamically removes the given method

Opis

bool runkit_method_remove ( string $classname , string $methodname )

Informacja: Ta funkcja nie może być użyta do manipulacji aktualnie działającej (lub powiązanej) metody. This function cannot

Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Parametry

classname

The class in which to remove the method

methodname

The name of the method to remove

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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'));

?>

Powyższy przykład wyświetli:

bar

Zobacz też:



runkit_method_rename

(PECL runkit >= 0.7.0)

runkit_method_renameDynamically changes the name of the given method

Opis

bool runkit_method_rename ( string $classname , string $methodname , string $newname )

Informacja: Ta funkcja nie może być użyta do manipulacji aktualnie działającej (lub powiązanej) metody. This function cannot

Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Parametry

classname

The class in which to rename the method

methodname

The name of the method to rename

newname

The new name to give to the renamed method

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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();
?>

Powyższy przykład wyświetli:

foo!

Zobacz też:



runkit_return_value_used

(PECL runkit >= 0.8.0)

runkit_return_value_usedDetermines if the current functions return value will be used

Opis

bool runkit_return_value_used ( void )

Zwracane wartości

Returns TRUE if the function's return value is used by the calling scope, otherwise FALSE

Przykłady

Przykład #1 runkit_return_value_used() example

<?php
function foo() {
  
var_dump(runkit_return_value_used());
}

foo();
$f foo();
?>

Powyższy przykład wyświetli:

bool(false)
bool(true)



runkit_sandbox_output_handler

(PECL runkit >= 0.7.0)

runkit_sandbox_output_handler Specify a function to capture and/or process output from a runkit sandbox

Opis

mixed runkit_sandbox_output_handler ( object $sandbox [, mixed $callback ] )

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.

Informacja: Obsługa rozszerzenia Sandbox (wymagane dla runkit_lint(), runkit_lint_file(), i klasy Runkit_Sandbox) jest dostępna tylko w PHP 5.1.0 lub specjalnie zmodyfikowanych wersjach PHP 5.0, i wymaga włączonego bezpieczeństwa wątków. Więcej informacji można znaleźć w pliku README dołączonym do pakietu runkit.

Informacja: 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.

Parametry

sandbox

Object instance of Runkit_Sandbox class on which to set output handling.

callback

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.

Zwracane wartości

Returns the name of the previously defined output handler callback, or FALSE if no handler was previously defined.

Przykłady

Przykład #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;
?>

Powyższy przykład wyświetli:

Sandbox Complete

Hello
string(9) "Excuse me"
I lost myself.



runkit_superglobals

(PECL runkit >= 0.7.0)

runkit_superglobals Return numerically indexed array of registered superglobals

Opis

array runkit_superglobals ( void )

Zwracane wartości

Returns a numerically indexed array of the currently registered superglobals. i.e. _GET, _POST, _REQUEST, _COOKIE, _SESSION, _SERVER, _ENV, _FILES

Zobacz też:


Spis treści




Break the silence operator


Wstęp

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.



Instalacja/Konfiguracja

Spis treści


Wymagania

PHP version 5.2.0 or greater.



Instalacja

Informacje na temat instalacji tego rozszerzenia PECL można znaleźć w podręczniku w rozdziale zatytułowanym Instalacja rozszerzeń PECL. Dodatkowe informacje, takie jak nowe wersje, pliki do pobrania, pliki źródłowe, informacje o opiekunach czy rejestr zmian, można znaleźć tutaj: » http://pecl.php.net/package/scream



Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

scream Opcje konfiguracyjne
Nazwa Domyślnie Możliwość zmian Changelog
scream.enabled Off PHP_INI_ALL  

Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

scream.enabled int

Whether or not to enable scream.



Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.




Przykłady

Spis treści


Example that shows the effect of scream

This example demonstrates how scream affects the behaviour of PHP's error handler.

Przykład #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');
?>

Powyższy przykład wyświetli coś podobnego do:

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

Informacja: Usually one would set this in the php.ini configuration file instead of changing the code.





Windows Cache for PHP


Wstęp

Windows Cache Extension for PHP is a PHP accelerator that is used to increase the speed of PHP applications running on Windows and Windows Server. Once the Windows Cache Extension for PHP is enabled and loaded by the PHP engine, PHP applications can take advantage of the functionality without any code modifications.

The Windows Cache Extension includes 3 different types of caches. The following describes the purpose of each cache type and the benefits it provides.

  • PHP Opcode Cache - PHP is a script processing engine, which reads an input stream of data that contains text and/or PHP instructions and produces another stream of data, most commonly in the HTML format. This means that on a web server the PHP engine reads, parses, compiles and executes a PHP script each time that it is requested by a Web client. The reading, parsing and compilation operations put additional load on the web server's CPU and file system and thus affect the overall performance of a PHP web application. The PHP bytecode (opcode) cache is used to store the compiled script bytecode in shared memory so that it can be re-used by PHP engine for subsequent executions of the same script.

  • File Cache - Even with the PHP bytecode cache enabled, the PHP engine has to accesses the script files on a file system. When PHP scripts are stored on a remote UNC file share, the file operations introduce a significant performance overhead. The Windows Cache Extension for PHP includes a file cache that is used to store the content of the PHP script files in shared memory, which reduces the amount of file system operations performed by PHP engine.

  • Relative File Path Cache - PHP scripts very often include or operate with files by using relative file paths. Every relative file path has to be converted to an absolute file path by the PHP engine. When a PHP application uses many PHP files and accesses them by relative paths, the operation of resolving relative paths to absolute paths may negatively impact the application's performance. The Windows Cache Extension for PHP provides a Relative File Path cache, which is used to store the mappings between relative and absolute file paths, thereby reducing the number of relative path resolutions that the PHP engine has to perform.



Instalacja/Konfiguracja

Spis treści


Wymagania

The extension is currently supported only on the following configurations:

Windows OS:

  • Windows XP SP3 with IIS 5.1 and » FastCGI Extension
  • Windows Server 2003 with IIS 6.0 and » FastCGI Extension
  • Windows Vista SP1 with IIS 7.0 and FastCGI Module
  • Windows Server 2008 with IIS 7.0 and FastCGI Module
  • Windows 7 with IIS 7.5 and FastCGI Module
  • Windows Server 2008 R2 with IIS 7.5 and FastCGI Module

PHP:

  • PHP 5.2.X, Non-thread-safe build
  • PHP 5.3 X86, Non-thread-safe VC9 build

Informacja: The WinCache Extension can only be used when IIS is configured to run PHP via FastCGI.



Instalacja

To rozszerzenie » PECL nie jest dołączane do PHP.

Informacje na temat instalacji tego rozszerzenia PECL można znaleźć w podręczniku w rozdziale zatytułowanym Instalacja rozszerzeń PECL. Dodatkowe informacje, takie jak nowe wersje, pliki do pobrania, pliki źródłowe, informacje o opiekunach czy rejestr zmian, można znaleźć tutaj: » http://pecl.php.net/package/wincache.

There are two packages for this extension: one package is for PHP versions 5.2.X, and the other package is for PHP 5.3.X. Select the package that is appropriate for the PHP version being used.

To install and enable the extension, follow these steps:

  1. Unpack the package into some temporary location.

  2. Copy the php_wincache.dll file into the PHP extensions folder. Typically this folder is called "ext" and it is located in the same folder with all PHP binary files. For example: C:\Program Files\PHP\ext.

  3. Using a text editor, open the php.ini file, which is usually located in the same folder where all PHP binary files are. For example: C:\Program Files\PHP\php.ini.

  4. Add the following line at the end of the php.ini file: extension = php_wincache.dll.

  5. Save and close the php.ini file.

  6. Recycle the IIS Application Pools for PHP to pick up the configuration changes. To check that the extension has been enabled, create a file called phpinfo.php with a PHP code that calls phpinfo function.

  7. Save the phpinfo.php file in the root folder of a IIS web site that uses PHP, then open a browser and make a request to http://localhost/phpinfo.php. Search within the returned web page for a section called wincache. If the extension is enabled, then the phpinfo output will list the configuration settings provided by the WinCache.

Informacja: Do not forget to remove phpinfo.php file from the web site's root folder after verifying that extension has been enabled.



Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

The following table lists and explains the configuration settings provided by the WinCache extension:

WinCache configuration options
Name Default Minimum Maximum Changeable Changelog
wincache.fcenabled "1" "0" "1" PHP_INI_ALL Available since WinCache 1.0.0
wincache.fcenabledfilter "NULL" "NULL" "NULL" PHP_INI_SYSTEM Available since WinCache 1.0.0
wincache.fcachesize "24" "5" "85" PHP_INI_SYSTEM Available since WinCache 1.0.0
wincache.maxfilesize "256" "10" "2048" PHP_INI_SYSTEM Available since WinCache 1.0.0
wincache.ocenabled "1" "0" "1" PHP_INI_ALL Available since WinCache 1.0.0
wincache.ocenabledfilter "NULL" "NULL" "NULL" PHP_INI_SYSTEM Available since WinCache 1.0.0
wincache.ocachesize "96" "15" "255" PHP_INI_SYSTEM Available since WinCache 1.0.0
wincache.filecount "4096" "1024" "16384" PHP_INI_SYSTEM Available since WinCache 1.0.0
wincache.chkinterval "30" "0" "300" PHP_INI_SYSTEM Available since WinCache 1.0.0
wincache.ttlmax "1200" "0" "7200" PHP_INI_SYSTEM Available since WinCache 1.0.0
wincache.enablecli 0 0 1 PHP_INI_SYSTEM Available since WinCache 1.0.0
wincache.ignorelist NULL NULL NULL PHP_INI_ALL Available since WinCache 1.0.0
wincache.namesalt NULL NULL NULL PHP_INI_SYSTEM Available since WinCache 1.0.0

Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

wincache.fcenabled boolean
Enables or disables the file cache functionality.
wincache.fcenabledfilter string
Defines a comma-separated list of IIS web site identifiers where file cache should be enabled or disabled. This setting works in conjunction with wincache.fcenabled: if wincache.fcenabled is set to 1, then the sites listed in the wincache.fcenabledfilter will have the file cache turned off; if wincache.fcenabled is set to 0, then the sites listed in the wincache.fcenabledfilter will have the file cache turned on.
wincache.fcachesize integer
Defines the maximum memory size (in megabytes) that is allocated for the file cache. If the total size of all the cached files exceeds the value specified in this setting, then most stale files will be removed from the file cache.
wincache.maxfilesize integer
Defines the maximum allowed size (in kilobytes) for a single file to be cached. If a file size exceeds the specified value, the file will not be cached. This setting applies to the file cache only.
wincache.ocenabled boolean
Enables or disables the opcode cache functionality
wincache.ocenabledfilter string
Defines a comma-separated list of IIS web site identifiers where opcode cache should be enabled or disabled. This setting works in conjunction with wincache.ocenabled: if wincache.ocenabled is set to 1, then the sites listed in the wincache.ocenabledfilter will have the opcode cache turned off; if wincache.ocenabled is set to 0, then the sites listed in the wincache.ocenabledfilter will have the opcode cache turned on.
wincache.ocachesize integer
Defines the maximum memory size (in megabytes) that is allocated for the opcode cache. If the cached opcode size exceeds the specified value, then most stale opcode will be removed from the cache. Note that the opcode cache size must be at least 3 times bigger than file cache size. If that is not the case the opcode cache size will be automatically increased.
wincache.filecount integer
Defines how many files are expected to be cached by the extension, so that appropriate memory size is allocated at the startup time. If the number of files exceeds the specified value, the WinCache will re-allocate more memory as needed.
wincache.chkinterval integer
Defines how often (in seconds) the extension checks for file changes in order to refresh the cache. Setting it to 0 will disable the refreshing of the cache. The file changes will not be reflected in the cache unless the cache entry for that file is removed by scavenger or IIS application pool is recycled or wincache_refresh_if_changed function is called.
wincache.ttlmax integer
Defines the maximum time to live (in seconds) for a cached entry without being used. Setting it to 0 will disable the cache scavenger, so the cached entries will never be removed from the cache during the lifetime of the IIS worker process.
wincache.enablecli boolean
Defines if caching is enabled when PHP is running in command line (CLI) mode.
wincache.ignorelist string

Defines a list of files that should not be cached by the extension. The files list is specified by using file names only, separated by the pipe symbol - "|".

Przykład #1 wincache.ignorelist example

wincache.ignorelist = "index.php|misc.php|admin.php"

wincache.namesalt boolean
Defines a string that will be used when naming the extension specific objects that are stored in shared memory. This is used to avoid conflicts that may be caused if other applications within an IIS worker process tries to access shared memory.



WinCache Statistics Script

The installation package for WinCache includes a PHP script, wincache.php, that can be used to obtain cache information and statistics.

If the WinCache extension was installed via the Microsoft Web Platform Installer, then this script is located in %SystemDrive%\Program Files\IIS\Windows Cache for PHP\. On a 64-bit version of the Windows Server operating system, the script is located in %SystemDrive%\Program Files (x86)\IIS\Windows Cache for PHP. If the extension was installed manually, then the wincache.php will be located in the same folder from which the content of the installation package was extracted.

To use wincache.php, copy it into a root folder of a Web site or into any subfolder. To protect the script, open it in any text editor and replace the values for USERNAME and PASSWORD constants. If any other IIS authentication is enabled on the server, then follow the instructions in the comments:

Przykład #1 Authentication configuration for wincache.php

/**
 * ======================== CONFIGURATION SETTINGS ==============================
 * If you do not want to use authentication for this page, set USE_AUTHENTICATION to 0.
 * If you use authentication then replace the default password.
 */
define('USE_AUTHENTICATION', 1);
define('USERNAME', 'wincache');
define('PASSWORD', 'wincache');

/**
 * The Basic PHP authentication will work only when IIS is configured to support 
 * Anonymous Authentication' and nothing else. If IIS is configured to support/use
 * any other kind of authentication like Basic/Negotiate/Digest etc, this will not work.
 * In that case use the array below to define the names of users in your 
 * domain/network/workgroup which you want to grant access to.
 */
$user_allowed = array('DOMAIN\user1', 'DOMAIN\user2', 'DOMAIN\user3');

/**
 * If the array contains string 'all', then all the users authenticated by IIS
 * will have access to the page. Uncomment the below line and comment above line
 * to grant access to all users who gets authenticated by IIS.
 */
/* $user_allowed = array('all'); */

/** ===================== END OF CONFIGURATION SETTINGS ========================== */

Informacja: Always protect the wincache.php script by using either the built-in authentication or the server's authentication mechanism. Leaving this script unprotected may compromise the security of your web application and web server.



Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.




Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.



WinCache Funkcje


wincache_fcache_fileinfo

(PECL wincache >= 1.0.0)

wincache_fcache_fileinfo Retrieves information about files cached in the file cache

Opis

array wincache_fcache_fileinfo ( void )

Retrieves information about file cache content and its usage.

Zwracane wartości

Array of meta data about file cache or FALSE on failure

The array returned by this function contains the following elements:

  • total_cache_uptime - total time in seconds that the file cache has been active
  • total_file_count - total number of files that are currently in the file cache
  • total_hit_count - number of times the files have been served from the file cache
  • total_miss_count - number of times the files have not been found in the file cache
  • file_entries - an array that contains the information about all the cached files:

    • file_name - absolute file name of the cached file
    • add_time - time in seconds since the file has been added to the file cache
    • use_time - time in seconds since the file has been accessed in the file cache
    • last_check - time in seconds since the file has been checked for modifications
    • hit_count - number of times the file has been served from the cache
    • file_size - size of the cached file in bytes

Przykłady

Przykład #1 A wincache_fcache_fileinfo() example

<pre>
<?php
print_r
(wincache_fcache_fileinfo());
?>
</pre>

Powyższy przykład wyświetli:

Array
(   [total_cache_uptime] => 3234
    [total_file_count] => 5
    [total_hit_count] => 0
    [total_miss_count] => 1
    [file_entries] => Array
        (
            [1] => Array
                (
                    [file_name] => c:\inetpub\wwwroot\checkcache.php
                    [add_time] => 1
                    [use_time] => 0
                    [last_check] => 1
                    [hit_count] => 1
                    [file_size] => 2435
                )
            [2] => Array (...iterates for each cached file)
        )
)

Zobacz też:



wincache_fcache_meminfo

(PECL wincache >= 1.0.0)

wincache_fcache_meminfo Retrieves information about file cache memory usage

Opis

array wincache_fcache_meminfo ( void )

Retrieves information about memory usage by file cache.

Zwracane wartości

Array of meta data about file cache memory usage or FALSE on failure

The array returned by this function contains the following elements:

  • memory_total - amount of memory in bytes allocated for the file cache
  • memory_free - amount of free memory in bytes available for the file cache
  • num_used_blks - number of memory blocks used by the file cache
  • num_free_blks - number of free memory blocks available for the file cache
  • memory_overhead - amount of memory in bytes used for the file cache internal structures

Przykłady

Przykład #1 A wincache_fcache_meminfo() example

<pre>
<?php
print_r
(wincache_fcache_meminfo());
?>
</pre>

Powyższy przykład wyświetli:

Array
(
    [memory_total] => 134217728
    [memory_free] => 131339120
    [num_used_blks] => 361
    [num_free_blks] => 3
    [memory_overhead] => 5856
)

Zobacz też:



wincache_ocache_fileinfo

(PECL wincache >= 1.0.0)

wincache_ocache_fileinfo Retrieves information about files cached in the opcode cache

Opis

array wincache_ocache_fileinfo ( void )

Retrieves information about opcode cache content and its usage.

Zwracane wartości

Array of meta data about opcode cache or FALSE on failure

The array returned by this function contains the following elements:

  • total_cache_uptime - total time in seconds that the opcode cache has been active
  • total_file_count - total number of files that are currently in the opcode cache
  • total_hit_count - number of times the compiled opcode have been served from the cache
  • total_miss_count - number of times the compiled opcode have not been found in the cache
  • file_entries - an array that contains the information about all the cached files:

    • file_name - absolute file name of the cached file
    • add_time - time in seconds since the file has been added to the opcode cache
    • use_time - time in seconds since the file has been accessed in the opcode cache
    • last_check - time in seconds since the file has been checked for modifications
    • hit_count - number of times the file has been served from the cache
    • function_count - number of functions in the cached file
    • class_count - number of classes in the cached file

Przykłady

Przykład #1 A wincache_ocache_fileinfo() example

<pre>
<?php
print_r
(wincache_ocache_fileinfo());
?>
</pre>

Powyższy przykład wyświetli:

Array
(
    [total_cache_uptime] => 17357
    [total_file_count] => 121
    [total_hit_count] => 36562
    [total_miss_count] => 201
    [file_entries] => Array
        (
            [1] => Array
                (
                    [file_name] => c:\inetpub\wwwroot\checkcache.php
                    [add_time] => 17356
                    [use_time] => 7
                    [last_check] => 10
                    [hit_count] => 454
                    [function_count] => 0
                    [class_count] => 1
                )
            [2] => Array (...iterates for each cached file)
        )
)

Zobacz też:



wincache_ocache_meminfo

(PECL wincache >= 1.0.0)

wincache_ocache_meminfo Retrieves information about opcode cache memory usage

Opis

array wincache_ocache_meminfo ( void )

Retrieves information about memory usage by opcode cache.

Zwracane wartości

Array of meta data about opcode cache memory usage or FALSE on failure

The array returned by this function contains the following elements:

  • memory_total - amount of memory in bytes allocated for the opcode cache
  • memory_free - amount of free memory in bytes available for the opcode cache
  • num_used_blks - number of memory blocks used by the opcode cache
  • num_free_blks - number of free memory blocks available for the opcode cache
  • memory_overhead - amount of memory in bytes used for the opcode cache internal structures

Przykłady

Przykład #1 A wincache_ocache_meminfo() example

<pre>
<?php
print_r
(wincache_ocache_meminfo());
?>
</pre>

Powyższy przykład wyświetli:

Array
(
    [memory_total] => 134217728
    [memory_free] => 112106972
    [num_used_blks] => 15469
    [num_free_blks] => 4
    [memory_overhead] => 247600
)

Zobacz też:



wincache_refresh_if_changed

(PECL wincache >= 1.0.0)

wincache_refresh_if_changed Refreshes the cache entries for the cached files

Opis

bool wincache_refresh_if_changed ([ array $files ] )

Refreshes the cache entries for the files, whose names were passed in the input argument. If no argument is specified then refreshes all the entries in the cache.

Parametry

files

An array of file names for files that need to be refreshed. An absolute or relative file paths can be used.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

WinCache performs regular checks on the cached files to ensure that if any file has changed then the corresponding entry in the cache is updated. By default this check is performed every 30 seconds. If, for example, a PHP script updates another PHP script where the application's configuration settings are stored, then it may happen that after the configuration settings have been saved to a file, the application is still using old settings for some time until the cache is refreshed. In those cases it may be preferrable to refresh the cache right after the file has been changed. The following example shows how this can be done.

Przykład #1 A wincache_refresh_if_changed() example

<?php 
$filename 
'C:\inetpub\wwwroot\config.php';
$handle fopen($filename'w+');
if (
$handle === FALSE) die('Failed to open file '.$filename.' for writing');
fwrite($handle'<?php $setting=something; ?>');
fclose($handle);
wincache_refresh_if_changed(array($filename));
?>

Zobacz też:



wincache_rplist_fileinfo

(PECL wincache >= 1.0.0)

wincache_rplist_fileinfo Retrieves information about relative file path cache

Opis

array wincache_rplist_fileinfo ( void )

Retrieves information about cached mappings between relative file paths and corresponding absolute file paths.

Zwracane wartości

Array of meta data about the relative file path cache or FALSE on failure

The array returned by this function contains the following elements:

  • total_file_count - total number of relative file path mappings stored in the cache
  • rplist_entries - an array that contains the information about all the cached relative file paths:

    • relative_path - relative path to a file
    • subkey_data - corresponding absolute path to a file

Przykłady

Przykład #1 A wincache_rplist_fileinfo() example

<pre>
<?php
print_r
(wincache_rplist_fileinfo());
?>
</pre>

Powyższy przykład wyświetli:

Array
(
    [total_file_count] => 5
    [rplist_entries] => Array
        (
            [1] => Array
                (
                    [relative_path] => checkcache.php
                    [subkey_data] => c:\inetpub\wwwroot|c:\inetpub\wwwroot\checkcache.php
                )

            [2] => Array (...iterates for each cached file)
        )
)

Zobacz też:



wincache_rplist_meminfo

(PECL wincache >= 1.0.0)

wincache_rplist_meminfo Retrieves information about memory usage by the relative file path cache

Opis

array wincache_rplist_meminfo ( void )

Retrieves information about memory usage by relative file path cache.

Zwracane wartości

Array of meta data that describes memory usage by relative file path cache. or FALSE on failure

The array returned by this function contains the following elements:

  • memory_total - amount of memory in bytes allocated for the relative file path cache
  • memory_free - amount of free memory in bytes available for the relative file path cache
  • num_used_blks - number of memory blocks used by the relative file path cache
  • num_free_blks - number of free memory blocks available for the relative file path cache
  • memory_overhead - amount of memory in bytes used for the internal structures of relative file path cache

Przykłady

Przykład #1 A wincache_rplist_meminfo() example

<pre>
<?php
print_r
(wincache_rplist_meminfo());
?>
</pre>

Powyższy przykład wyświetli:

Array
(
    [memory_total] => 9437184
    [memory_free] => 9416744
    [num_used_blks] => 23
    [num_free_blks] => 1
    [memory_overhead] => 416
)

Zobacz też:


Spis treści



Building for Windows

Spis treści


Prerequisites

Building WinCache extension will require:

  1. PHP source code
  2. PHP build environment
  3. WinCache source code

For completing first two steps, follow the step-by-step guide for how to » build PHP on Windows.

For getting the WinCache source code follow the instructions described in Downloading PECL extensions.



Compiling and building

The following steps describe how to compile and build WinCache on Windows OS:

  1. Open a command prompt which is used to build PHP

  2. Go to the root folder where PHP sources are present

  3. Run the command:

    cscript.exe win32\build\buildconf.js

  4. Run the command:

    configure.bat --help

    The output will contain a new flag --enable-wincache.

  5. Run the command:

    configure.js [all options used to build PHP] --enable-wincache

    --enable-wincache is the only extra option which is required to ensure that WinCache extension gets built properly. This option will build WinCache and will statically link it with PHP dll. To build WinCache extension as a stand-alone DLL use the option --enable-wincache=shared.

  6. Run the command:

    nmake



Verifying the build

The following steps describe how to verify that WinCache has been built correctly:

  1. Go to the folder where the PHP binaries are built

  2. Run the command:

    php.exe -n -d extension=php_wincache.dll -re wincache

    If WinCache has been built properly, the output of this command will list the INI directives and functions supported by WinCache.






Przetwarzanie formatów audio


Tagi ID3


Wstęp

Te funkcje umożliwiają odczyt i modyfikację znaczników ID3. Znaczniki ID3 są używane w plikach MP3 do przechowywania metadanych, takich jak: tytułu piosenki, informacji o artyście, albumie, gatunku, roku wydania, oraz numerze utworu.

Od wersji 0.2 możliwe jest wydobywanie informacji tekstowych ze znaczników ID3 v2.2+ .



Instalacja/Konfiguracja

Spis treści


Wymagania

Do zbudowania tego rozszerzenia nie są wymagane żadne zewnętrzne biblioteki.



Instalacja

ID3 jest częścią PECL, i może być zainstalowany za pomocą instalatora PEAR. Aby zainstalować PHP z obsługą ID3, należy pobrać kod źródłowy, umieścić go w php-src/ext/id3 i skompilować PHP z opcją --enable-id3.



Konfiguracja wykonawcza

To rozszerzenie nie definiuje posiada żadnych dyrektyw konfiguracyjnych w pliku php.ini.



Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.




Predefined Constants

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.

ID3_V1_0 (integer)
ID3_V1_0 is used if you are working with ID3 V1.0 tags. These tags may contain the fields title, artist, album, genre, year and comment.
ID3_V1_1 (integer)
ID3_V1_1 is used if you are working with ID3 V1.1 tags. These tags may all information contained in v1.0 tags plus the track number.
ID3_V2_1 (integer)
ID3_V2_1 is used if you are working with ID3 V2.1 tags.
ID3_V2_2 (integer)
ID3_V2_2 is used if you are working with ID3 V2.2 tags.
ID3_V2_3 (integer)
ID3_V2_3 is used if you are working with ID3 V2.3 tags.
ID3_V2_4 (integer)
ID3_V2_4 is used if you are working with ID3 V2.4 tags.
ID3_BEST (integer)
ID3_BEST is used if would like to let the id3 functions determine which tag version should be used.



Funkcje ID3


id3_get_frame_long_name

(PECL id3 >= 0.2)

id3_get_frame_long_nameGet the long name of an ID3v2 frame

Opis

string id3_get_frame_long_name ( string $frameId )

id3_get_frame_long_name() returns the long name for an ID3v2 frame.

Parametry

frameId

An ID3v2 frame

Zwracane wartości

Returns the frame long name or FALSE on errors.

Przykłady

Przykład #1 id3_get_frame_long_name() example

<?php
$longName 
id3_get_frame_long_name("TOLY");
echo 
$longName;
?>

Powyższy przykład wyświetli:

Original lyricist(s)/text writer(s)

Zobacz też:



id3_get_frame_short_name

(PECL id3 >= 0.2)

id3_get_frame_short_nameGet the short name of an ID3v2 frame

Opis

string id3_get_frame_short_name ( string $frameId )

id3_get_frame_short_name() returns the short name for an ID3v2 frame.

Parametry

frameId

An ID3v2 frame

Zwracane wartości

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().

Przykłady

Przykład #1 id3_get_frame_short_name() example

<?php
$shortName 
id3_get_frame_short_name("TOLY");
echo 
$shortName;
?>

Powyższy przykład wyświetli:

originalLyricist

Zobacz też:



id3_get_genre_id

(PECL id3 >= 0.1)

id3_get_genre_idGet the id for a genre

Opis

int id3_get_genre_id ( string $genre )

id3_get_genre_id() returns the id for a genre.

Parametry

genre

An integer ranging from 0 to 147

Zwracane wartości

The genre id or FALSE on errors.

Przykłady

Przykład #1 id3_get_genre_id() example

<?php
$id 
id3_get_genre_id("Alternative");
echo 
$id;
?>

Powyższy przykład wyświetli:

20

Zobacz też:



id3_get_genre_list

(PECL id3 >= 0.1)

id3_get_genre_listGet all possible genre values

Opis

array id3_get_genre_list ( void )

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.

Zwracane wartości

Returns an array containing all possible genres that may be stored in an ID3 tag.

Przykłady

Przykład #1 id3_get_genre_list() example

<?php
$genres 
id3_get_genre_list();
print_r($genres);
?>

Powyższy przykład wyświetli:

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
)

Zobacz też:



id3_get_genre_name

(PECL id3 >= 0.1)

id3_get_genre_nameGet the name for a genre id

Opis

string id3_get_genre_name ( int $genre_id )

id3_get_genre_name() returns the name for a genre id.

Parametry

genre_id

An integer ranging from 0 to 147

Zwracane wartości

Returns the name as a string.

Przykłady

Przykład #1 id3_get_genre_name() example

<?php
$genre 
id3_get_genre_name(20);
echo 
$genre;
?>

Powyższy przykład wyświetli:

Alternative

Zobacz też:



id3_get_tag

(PECL id3 >= 0.1)

id3_get_tagGet all information stored in an ID3 tag

Opis

array id3_get_tag ( string $filename [, int $version = ID3_BEST ] )

id3_get_tag() is used to get all information stored in the id3 tag of the specified file.

Parametry

filename

The path to the MP3 file

Instead of a filename you may also pass a valid stream resource

version

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.

Zwracane wartości

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.

Przykłady

Przykład #1 id3_get_tag() example

<?php
$tag 
id3_get_tag"path/to/example.mp3" );
print_r($tag);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [title] => DN-38416
    [artist] => Re:\Legion
    [album] => Reflections
    [year] => 2004
    [genre] => 19
)

Przykład #2 id3_get_tag() example

<?php
$tag 
id3_get_tag"path/to/example2.mp3"ID3_V2_3 );
print_r($tag);
?>

Powyższy przykład wyświetli coś podobnego do:

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
)

Zobacz też:



id3_get_version

(PECL id3 >= 0.1)

id3_get_versionGet version of an ID3 tag

Opis

int id3_get_version ( string $filename )

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.

Parametry

filename

The path to the MP3 file

Instead of a filename you may also pass a valid stream resource

Zwracane wartości

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.

Przykłady

Przykład #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";
}
?>

Powyższy przykład wyświetli coś podobnego do:

Contains a 1.x tag
Contains a 1.1 tag

Zobacz też:



id3_remove_tag

(PECL id3 >= 0.1)

id3_remove_tagRemove an existing ID3 tag

Opis

bool id3_remove_tag ( string $filename [, int $version = ID3_V1_0 ] )

id3_remove_tag() is used to remove the information stored of an ID3 tag.

Parametry

filename

The path to the MP3 file

Instead of a filename you may also pass a valid stream resource

version

Allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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

Notatki

Informacja: 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.

Zobacz też:



id3_set_tag

(PECL id3 >= 0.1)

id3_set_tagUpdate information stored in an ID3 tag

Opis

bool id3_set_tag ( string $filename , array $tag [, int $version = ID3_V1_0 ] )

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.

Parametry

filename

The path to the MP3 file

Instead of a filename you may also pass a valid stream resource

tag

An associative array of tag keys and values

The following keys may be used in the associative array:

Keys 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

version

Allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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"$dataID3_V1_0 );
if (
$result === true) {
    echo 
"Tag succesfully updated\n";
}
?>

If the file is writable, this will output:

Tag succesfully updated

Notatki

Informacja: Currently id3_remove_tag() only supports version 1.0 and 1.1.

Zobacz też:


Spis treści




KTaglib


Wstęp

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.

Informacja: At the moment ktaglib is able to read and write ID3v1 and ID3v2 tags.



Instalacja/Konfiguracja

Spis treści


Wymagania

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.



Instalacja

KTaglib support in PHP is not enabled by default. You will need to configure PHP --with-ktaglib[=DIR]

Informacja: KTaglib is part of PECL.




Stałe predefiniowane

Poniższe stałe są zdefiniowane w tym rozszerzeniu i stają się dostępne, gdy rozszerzenie jest dokompilowane z PHP, lub załadowane dynamicznie przy starcie.

KTaglib uses class constants. Most of the constants are mappings to the according Taglib enums and constants.

KTaglib_MPEG_Header::Version1 (integer)
ID3 version is 1.0
KTaglib_MPEG_Header::Version2 (integer)
ID3 version is 2.0
KTaglib_MPEG_Header::Version2_5 (integer)
ID3 version is 2.5
KTaglib_ID3v2_AttachedPictureFrame::Other (integer)
Picture type Other
KTaglib_ID3v2_AttachedPictureFrame::FileIcon (integer)
Picture type FileIcon
KTaglib_ID3v2_AttachedPictureFrame::OtherFileIcon (integer)
Picture type OtherFileIcon
KTaglib_ID3v2_AttachedPictureFrame::FrontCover (integer)
Picture type FrontCover
KTaglib_ID3v2_AttachedPictureFrame::BackCover (integer)
Picture type BackCover
KTaglib_ID3v2_AttachedPictureFrame::LeafletPage (integer)
Picture type LeafletPage
KTaglib_ID3v2_AttachedPictureFrame::Media (integer)
Picture type Media
KTaglib_ID3v2_AttachedPictureFrame::LeadArtist (integer)
Picture type LeadArtist
KTaglib_ID3v2_AttachedPictureFrame::Artist (integer)
Picture type Artist
KTaglib_ID3v2_AttachedPictureFrame::Conductor (integer)
Picture type Condutor
KTaglib_ID3v2_AttachedPictureFrame::Band (integer)
Picture type Band
KTaglib_ID3v2_AttachedPictureFrame::Composer (integer)
Picture type Composer
KTaglib_ID3v2_AttachedPictureFrame::Lyricist (integer)
Picture type Lyricist
KTaglib_ID3v2_AttachedPictureFrame::RecordingLocation (integer)
Picture type RecordingLocation
KTaglib_ID3v2_AttachedPictureFrame::DuringRecording (integer)
Picture type DuringRecording
KTaglib_ID3v2_AttachedPictureFrame::DuringPerformance (integer)
Picture type DuringPerformance
KTaglib_ID3v2_AttachedPictureFrame::MovieScreenCapture (integer)
Picture type MovieScreenCapture
KTaglib_ID3v2_AttachedPictureFrame::ColouredFish (integer)
Picture type ColouredFish
KTaglib_ID3v2_AttachedPictureFrame::Illustration (integer)
Picture type Illustration
KTaglib_ID3v2_AttachedPictureFrame::BandLogo (integer)
Picture type BandLogo


The KTagLib_MPEG_File class

Wstęp

Represents an MPEG file. MPEG files can have ID3v1, ID3v2 tags and audio properties.

Class synopsis

KTagLib_MPEG_File
KTagLib_MPEG_File {
}

KTaglib_MPEG_File::__construct

(0.0.1)

KTaglib_MPEG_File::__constructOpens a new file

Opis

KTaglib_MPEG_File::__construct ( string $filename )

Opens a new MPEG file.

Parametry

filename

The file to read

Przykłady

Przykład #1 Opens a new MP3 file and read the title

<?php
$mpeg 
= new KTaglib_MPEG_File('example.mp3');
echo 
$mpeg->getID3v1Tag()->getTitle();
?>



KTaglib_MPEG_File::getAudioProperties

(0.0.1)

KTaglib_MPEG_File::getAudioPropertiesReturns an object that provides access to the audio properties

Opis

public KTaglib_MPEG_File: KTaglib_MPEG_File::getAudioProperties ( void )

Returns an object that provides access to the audio properties of the mpeg file.

Zwracane wartości

Returns an KTaglib_MPEG_AudioProperties object or false.



KTaglib_MPEG_File::getID3v1Tag

(0.0.1)

KTaglib_MPEG_File::getID3v1TagReturns an object representing an ID3v1 tag

Opis

public KTaglib_ID3v1_Tag KTaglib_MPEG_File::getID3v1Tag ([ bool $create = false ] )

Returns an object that represents an ID3v1 tag, which can be used to get information about the ID3v1 tag.

Zwracane wartości

Returns an KTaglib_MPEG_ID3v1Tag object or false if there is no ID3v1 tag.



KTaglib_MPEG_File::getID3v2Tag

(0.0.1)

KTaglib_MPEG_File::getID3v2TagReturns a ID3v2 object

Opis

public KTaglib_ID3v2_Tag KTaglib_MPEG_File::getID3v2Tag ([ bool $create = false ] )

Returns a ID3v2 object for the mpeg file. If no ID3v2 Tag is present, an KTaglib_TagNotFoundException is thrown.

Zwracane wartości

Returns the KTaglib_ID3v2_Tag object of the MPEG file or false if there is no ID3v2 tag


Spis treści



The KTaglib_MPEG_AudioProperties class

Wstęp

Represents the audio properties of a MPEG file, like length, bitrate or samplerate.

Class synopsis

KTaglib_MPEG_Audioproperties
KTaglib_MPEG_AudioProperties {
}

KTaglib_MPEG_AudioProperties::getBitrate

(0.0.1)

KTaglib_MPEG_AudioProperties::getBitrateReturns the bitrate of the MPEG file

Opis

public int KTaglib_MPEG_AudioProperties::getBitrate ( void )

Returns the bitrate of the MPEG file

Zwracane wartości

Returns the bitrate as an integer



KTaglib_MPEG_AudioProperties::getChannels

(0.0.1)

KTaglib_MPEG_AudioProperties::getChannelsReturns the amount of channels of a MPEG file

Opis

public int KTaglib_MPEG_AudioProperties::getChannels ( void )

Returns the amount of channels of the MPEG file

Zwracane wartości

Returns the channel count as an integer



KTaglib_MPEG_AudioProperties::getLayer

(0.0.1)

KTaglib_MPEG_AudioProperties::getLayerReturns the layer of a MPEG file

Opis

public int KTaglib_MPEG_AudioProperties::getLayer ( void )

Returns the layer of the MPEG file (usually 3 for MP3).

Zwracane wartości

Returns the layer as an integer



KTaglib_MPEG_AudioProperties::getLength

(0.0.1)

KTaglib_MPEG_AudioProperties::getLengthReturns the length of a MPEG file

Opis

public int KTaglib_MPEG_AudioProperties::getLength ( void )

Returns the length of the MPEG file

Zwracane wartości

Returns the length as an integer



KTaglib_MPEG_AudioProperties::getSampleBitrate

(0.0.1)

KTaglib_MPEG_AudioProperties::getSampleBitrateReturns the sample bitrate of a MPEG file

Opis

public int KTaglib_MPEG_AudioProperties::getSampleBitrate ( void )

Returns the sample bitrate of the MPEG file

Zwracane wartości

Returns the sample bitrate as an integer



KTaglib_MPEG_AudioProperties::getVersion

(0.0.1)

KTaglib_MPEG_AudioProperties::getVersionReturns the version of a MPEG file

Opis

public int KTaglib_MPEG_AudioProperties::getVersion ( void )

Returns the version of the MPEG file header. The possible versions are defined in Tag_MPEG_Header (Version1, Version2, Version2.5).

Zwracane wartości

Returns the version



KTaglib_MPEG_AudioProperties::isCopyrighted

(0.0.1)

KTaglib_MPEG_AudioProperties::isCopyrightedReturns the length of a MPEG file

Opis

public bool KTaglib_MPEG_AudioProperties::isCopyrighted ( void )

Returns true if the MPEG file is copyrighted

Zwracane wartości

Returns true if the MPEG file is copyrighted



KTaglib_MPEG_AudioProperties::isOriginal

(0.0.1)

KTaglib_MPEG_AudioProperties::isOriginalReturns the length of a MPEG file

Opis

public bool KTaglib_MPEG_AudioProperties::isOriginal ( void )

Returns true if the file is marked as the original file

Zwracane wartości

Returns true if the file is marked as the original file



KTaglib_MPEG_AudioProperties::isProtectionEnabled

(0.0.1)

KTaglib_MPEG_AudioProperties::isProtectionEnabledReturns the length of a MPEG file

Opis

public bool KTaglib_MPEG_AudioProperties::isProtectionEnabled ( void )

Returns true if protection mechanism (like DRM) are enabled for this file

Zwracane wartości

Returns true if protection mechanism (like DRM) are enabled for this file


Spis treści



The KTaglib_Tag class

Wstęp

Base class for ID3v1 or ID3v2 tags

Class synopsis

KTaglib_Tag
KTaglib_Tag {
}

KTaglib_Tag::getAlbum

(0.0.1)

KTaglib_Tag::getAlbumReturns the title string from a ID3 tag

Opis

public string KTaglib_Tag::getAlbum ( void )

Returns the album string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Zwracane wartości

Returns the album string



KTaglib_Tag::getArtist

(0.0.1)

KTaglib_Tag::getArtistReturns the artist string from a ID3 tag

Opis

public string KTaglib_Tag::getArtist ( void )

Returns the artist string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Zwracane wartości

Returns the artist string



KTaglib_Tag::getComment

(0.0.1)

KTaglib_Tag::getCommentReturns the comment from a ID3 tag

Opis

public string KTaglib_Tag::getComment ( void )

Returns the comment of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Zwracane wartości

Returns the comment string



KTaglib_Tag::getGenre

(0.0.1)

KTaglib_Tag::getGenreReturns the genre from a ID3 tag

Opis

public string KTaglib_Tag::getGenre ( void )

Returns the genre of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Zwracane wartości

Returns the genre string



KTaglib_Tag::getTitle

(0.0.1)

KTaglib_Tag::getTitleReturns the title string from a ID3 tag

Opis

public string KTaglib_Tag::getTitle ( void )

Returns the title string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Zwracane wartości

Returns the title string



KTaglib_Tag::getTrack

(0.0.1)

KTaglib_Tag::getTrackReturns the track number from a ID3 tag

Opis

public int KTaglib_Tag::getTrack ( void )

Returns the track number of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Zwracane wartości

Returns the track number as an integer



KTaglib_Tag::getYear

(0.0.1)

KTaglib_Tag::getYearReturns the year from a ID3 tag

Opis

public int KTaglib_Tag::getYear ( void )

Returns the year of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Zwracane wartości

Returns the year as an integer



KTaglib_Tag::isEmpty

(0.0.1)

KTaglib_Tag::isEmptyReturns true if the tag is empty

Opis

public bool KTaglib_Tag::isEmpty ( void )

Returns true if the tag exists, but is empty. This method is implemented in ID3v1 and ID3v2 tags.

Zwracane wartości

Returns true if the tag is empty, otherwise false.


Spis treści



The KTagLib_ID3v2_Tag class

Wstęp

Represents and ID3v2 tag. It provides a list of ID3v2 frames and can be used to add and remove additional frames.

Class synopsis

KTagLib_ID3v2_Tag
extends KTagLib_Tag {
}

KTaglib_ID3v2_Tag::addFrame

(0.0.1)

KTaglib_ID3v2_Tag::addFrameAdd a frame to the ID3v2 tag

Opis

public bool KTaglib_ID3v2_Tag::addFrame ( KTagLib_ID3v2_Frame $frame )

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.

Zwracane wartości

Returns true on success, otherwise false.



KTaglib_ID3v2_Tag::getFrameList

(0.0.1)

KTaglib_ID3v2_Tag::getFrameListReturns an array of ID3v2 frames, associated with the ID3v2 tag

Opis

public array KTaglib_ID3v2_Tag::getFrameList ( void )

Returns an array of ID3v2 frames, associated with the ID3v2 tag.

Zwracane wartości

Return an array of KTaglib_ID3v2_Frame objects


Spis treści



The KTagLib_ID3v2_Frame class

Wstęp

The base class for ID3v2 frames. ID3v2 tags are separated in various specialized frames. Some frames can exists multiple times.

Class synopsis

KTagLib_ID3v2_Frame
extends KTagLib_Tag {
}

KTaglib_ID3v2_Frame::getSize

(0.0.1)

KTaglib_ID3v2_Frame::getSizeReturns the size of the frame in bytes

Opis

public int KTaglib_ID3v2_Frame::getSize ( void )

Returns the size of the frame in bytes. Please refer to id3.org to see what ID3v2 frames are and how they are defined.

Zwracane wartości

Returns the size of the frame in bytes



KTaglib_ID3v2_Frame::__toString

(0.0.1)

KTaglib_ID3v2_Frame::__toStringReturns a string representation of the frame

Opis

public string KTaglib_ID3v2_Frame::__toString ( void )

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

Zwracane wartości

Returns a string representation of the frame.


Spis treści



The KTaglib_ID3v2_AttachedPictureFrame class

Wstęp

Represents an ID3v2 frame that can hold a picture.

Class synopsis

KTaglib_ID3v2_AttachedPictureFrame
extends KTagLib_ID3v2_Frame {
}

KTaglib_ID3v2_AttachedPictureFrame::getDescription

(0.0.1)

KTaglib_ID3v2_AttachedPictureFrame::getDescriptionReturns a description for the picture in a picture frame

Opis

public string KTaglib_ID3v2_AttachedPictureFrame::getDescription ( void )

Returns the attached description for a picture frame in an ID3v2.x frame.

Zwracane wartości

Returns a description for the picture in a picture frame



KTaglib_ID3v2_AttachedPictureFrame::getMimeType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::getMimeTypeReturns the mime type of the picture

Opis

public string KTaglib_ID3v2_AttachedPictureFrame::getMimeType ( void )

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.

Zwracane wartości

Returns the mime type of the image represented by the attached picture frame.



KTaglib_ID3v2_AttachedPictureFrame::getType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::getTypeReturns the type of the image

Opis

public int KTaglib_ID3v2_AttachedPictureFrame::getType ( void )

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.

Zwracane wartości

Returns the integer representation of the type.



KTaglib_ID3v2_AttachedPictureFrame::savePicture

(0.0.1)

KTaglib_ID3v2_AttachedPictureFrame::savePictureSaves the picture to a file

Opis

public bool KTaglib_ID3v2_AttachedPictureFrame::savePicture ( string $filename )

Saves the attached picture to the given filename.

Zwracane wartości

Returns true on success, otherwise false



KTaglib_ID3v2_AttachedPictureFrame::setMimeType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::setMimeTypeSet's the mime type of the picture

Opis

public string KTaglib_ID3v2_AttachedPictureFrame::getMimeType ( string $type )

Sets the mime type of the image. This should in most cases be "image/png" or "image/jpeg".



KTaglib_ID3v2_AttachedPictureFrame::setPicture

(0.0.1)

KTaglib_ID3v2_AttachedPictureFrame::setPictureSets the frame picture to the given image

Opis

public void KTaglib_ID3v2_AttachedPictureFrame::setPicture ( string $filename )

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.

Zwracane wartości

Returns true on success, otherwise false



KTaglib_ID3v2_AttachedPictureFrame::setType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::setTypeSet the type of the image

Opis

public void KTaglib_ID3v2_AttachedPictureFrame::setType ( int $type )

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.


Spis treści




OGG/Vorbis


Wstęp

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.



Instalacja/Konfiguracja

Spis treści


Wymagania

This extension requires PHP >= 4.3.0, » libogg >= 1.0, and » libvorbis >= 1.0.



Instalacja

Informacje na temat instalacji tego rozszerzenia PECL można znaleźć w podręczniku w rozdziale zatytułowanym Instalacja rozszerzeń PECL. Dodatkowe informacje, takie jak nowe wersje, pliki do pobrania, pliki źródłowe, informacje o opiekunach czy rejestr zmian, można znaleźć tutaj: » http://pecl.php.net/package/oggvorbis



Konfiguracja wykonawcza

To rozszerzenie nie definiuje posiada żadnych dyrektyw konfiguracyjnych w pliku php.ini.



Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.




Stałe predefiniowane

Poniższe stałe są zdefiniowane w tym rozszerzeniu i stają się dostępne, gdy rozszerzenie jest dokompilowane z PHP, lub załadowane dynamicznie przy starcie.

OGG/Vorbis supports PCM encodings in the following formats
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.


Context options

OGG/Vorbis tuning options
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')


Przykłady

Spis treści


Examples on using the ogg:// wrapper.

Przykład #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($fp8192)) {
  
/* 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);

?>

Przykład #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);
?>





OpenAL Audio Bindings


Wstęp

Platform independent audio bindings. Requires the » OpenAL library.



Instalacja/Konfiguracja

Spis treści


Wymagania

Do zbudowania tego rozszerzenia nie są wymagane żadne zewnętrzne biblioteki.



Instalacja

To rozszerzenie » PECL nie jest dołączane do PHP.

Informacje na temat instalacji tego rozszerzenia PECL można znaleźć w podręczniku w rozdziale zatytułowanym Instalacja rozszerzeń PECL. Dodatkowe informacje, takie jak nowe wersje, pliki do pobrania, pliki źródłowe, informacje o opiekunach czy rejestr zmian, można znaleźć tutaj: » http://pecl.php.net/package/openal.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/



Konfiguracja wykonawcza

To rozszerzenie nie definiuje posiada żadnych dyrektyw konfiguracyjnych w pliku php.ini.



Typy zasobów

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().




Stałe predefiniowane

Poniższe stałe są zdefiniowane w tym rozszerzeniu i stają się dostępne, gdy rozszerzenie jest dokompilowane z PHP, lub załadowane dynamicznie przy starcie.

ALC_FREQUENCY (integer)
Context Attribute
ALC_REFRESH (integer)
Context Attribute
ALC_SYNC (integer)
Context Attribute
AL_FREQUENCY (integer)
Buffer Setting
AL_BITS (integer)
Buffer Setting
AL_CHANNELS (integer)
Buffer Setting
AL_SIZE (integer)
Buffer Setting
AL_BUFFER (integer)
Source/Listener Setting (Integer)
AL_SOURCE_RELATIVE (integer)
Source/Listener Setting (Integer)
AL_SOURCE_STATE (integer)
Source/Listener Setting (Integer)
AL_PITCH (integer)
Source/Listener Setting (Float)
AL_GAIN (integer)
Source/Listener Setting (Float)
AL_MIN_GAIN (integer)
Source/Listener Setting (Float)
AL_MAX_GAIN (integer)
Source/Listener Setting (Float)
AL_MAX_DISTANCE (integer)
Source/Listener Setting (Float)
AL_ROLLOFF_FACTOR (integer)
Source/Listener Setting (Float)
AL_CONE_OUTER_GAIN (integer)
Source/Listener Setting (Float)
AL_CONE_INNER_ANGLE (integer)
Source/Listener Setting (Float)
AL_CONE_OUTER_ANGLE (integer)
Source/Listener Setting (Float)
AL_REFERENCE_DISTANCE (integer)
Source/Listener Setting (Float)
AL_POSITION (integer)
Source/Listener Setting (Float Vector)
AL_VELOCITY (integer)
Source/Listener Setting (Float Vector)
AL_DIRECTION (integer)
Source/Listener Setting (Float Vector)
AL_ORIENTATION (integer)
Source/Listener Setting (Float Vector)
AL_FORMAT_MONO8 (integer)
PCM Format
AL_FORMAT_MONO16 (integer)
PCM Format
AL_FORMAT_STEREO8 (integer)
PCM Format
AL_FORMAT_STEREO16 (integer)
PCM Format
AL_INITIAL (integer)
Source State
AL_PLAYING (integer)
Source State
AL_PAUSED (integer)
Source State
AL_STOPPED (integer)
Source State
AL_LOOPING (integer)
Source State
AL_TRUE (integer)
Boolean value recognized by OpenAL
AL_FALSE (integer)
Boolean value recognized by OpenAL


OpenAL Funkcje


openal_buffer_create

(PECL openal >= 0.1.0)

openal_buffer_create Generate OpenAL buffer

Opis

resource openal_buffer_create ( void )

Zwracane wartości

Returns an Open AL(Buffer) resource on success or FALSE on failure.

Zobacz też:



openal_buffer_data

(PECL openal >= 0.1.0)

openal_buffer_data Load a buffer with data

Opis

bool openal_buffer_data ( resource $buffer , int $format , string $data , int $freq )

Parametry

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

format

Format of data , one of: AL_FORMAT_MONO8, AL_FORMAT_MONO16, AL_FORMAT_STEREO8 i AL_FORMAT_STEREO16

data

Block of binary audio data in the format and freq specified.

freq

Frequency of data given in Hz.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



openal_buffer_destroy

(PECL openal >= 0.1.0)

openal_buffer_destroy Destroys an OpenAL buffer

Opis

bool openal_buffer_destroy ( resource $buffer )

Parametry

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



openal_buffer_get

(PECL openal >= 0.1.0)

openal_buffer_get Retrieve an OpenAL buffer property

Opis

int openal_buffer_get ( resource $buffer , int $property )

Parametry

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

property

Specific property, one of: AL_FREQUENCY, AL_BITS, AL_CHANNELS i AL_SIZE.

Zwracane wartości

Returns an integer value appropriate to the property requested or FALSE on failure.

Zobacz też:



openal_buffer_loadwav

(PECL openal >= 0.1.0)

openal_buffer_loadwav Load a .wav file into a buffer

Opis

bool openal_buffer_loadwav ( resource $buffer , string $wavfile )

Parametry

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

wavfile

Path to .wav file on local file system.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



openal_context_create

(PECL openal >= 0.1.0)

openal_context_create Create an audio processing context

Opis

resource openal_context_create ( resource $device )

Parametry

device

An Open AL(Device) resource (previously created by openal_device_open()).

Zwracane wartości

Returns an Open AL(Context) resource on success or FALSE on failure.

Zobacz też:



openal_context_current

(PECL openal >= 0.1.0)

openal_context_current Make the specified context current

Opis

bool openal_context_current ( resource $context )

Parametry

context

An Open AL(Context) resource (previously created by openal_context_create()).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



openal_context_destroy

(PECL openal >= 0.1.0)

openal_context_destroy Destroys a context

Opis

bool openal_context_destroy ( resource $context )

Parametry

context

An Open AL(Context) resource (previously created by openal_context_create()).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



openal_context_process

(PECL openal >= 0.1.0)

openal_context_process Process the specified context

Opis

bool openal_context_process ( resource $context )

Parametry

context

An Open AL(Context) resource (previously created by openal_context_create()).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



openal_context_suspend

(PECL openal >= 0.1.0)

openal_context_suspend Suspend the specified context

Opis

bool openal_context_suspend ( resource $context )

Parametry

context

An Open AL(Context) resource (previously created by openal_context_create()).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



openal_device_close

(PECL openal >= 0.1.0)

openal_device_close Close an OpenAL device

Opis

bool openal_device_close ( resource $device )

Parametry

device

An Open AL(Device) resource (previously created by openal_device_open()) to be closed.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



openal_device_open

(PECL openal >= 0.1.0)

openal_device_open Initialize the OpenAL audio layer

Opis

resource openal_device_open ([ string $device_desc ] )

Parametry

device_desc

Open an audio device optionally specified by device_desc . If device_desc is not specified the first available audio device will be used.

Zwracane wartości

Returns an Open AL(Device) resource on success or FALSE on failure.

Zobacz też:



openal_listener_get

(PECL openal >= 0.1.0)

openal_listener_get Retrieve a listener property

Opis

mixed openal_listener_get ( int $property )

Parametry

property

Property to retrieve, one of: AL_GAIN (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)) i AL_ORIENTATION (array(float,float,float)).

Zwracane wartości

Returns a float or array of floats (as appropriate) or FALSE on failure.

Zobacz też:



openal_listener_set

(PECL openal >= 0.1.0)

openal_listener_set Set a listener property

Opis

bool openal_listener_set ( int $property , mixed $setting )

Parametry

property

Property to set, one of: AL_GAIN (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)) i AL_ORIENTATION (array(float,float,float)).

setting

Value to set, either float, or an array of floats as appropriate.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



openal_source_create

(PECL openal >= 0.1.0)

openal_source_create Generate a source resource

Opis

resource openal_source_create ( void )

Zwracane wartości

Returns an Open AL(Source) resource on success or FALSE on failure.

Zobacz też:



openal_source_destroy

(PECL openal >= 0.1.0)

openal_source_destroy Destroy a source resource

Opis

bool openal_source_destroy ( resource $source )

Parametry

source

An Open AL(Source) resource (previously created by openal_source_create()).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



openal_source_get

(PECL openal >= 0.1.0)

openal_source_get Retrieve an OpenAL source property

Opis

mixed openal_source_get ( resource $source , int $property )

Parametry

source

An Open AL(Source) resource (previously created by openal_source_create()).

property

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)).

Zwracane wartości

Returns the type associated with the property being retrieved or FALSE on failure.

Zobacz też:



openal_source_pause

(PECL openal >= 0.1.0)

openal_source_pause Pause the source

Opis

bool openal_source_pause ( resource $source )

Parametry

source

An Open AL(Source) resource (previously created by openal_source_create()).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



openal_source_play

(PECL openal >= 0.1.0)

openal_source_play Start playing the source

Opis

bool openal_source_play ( resource $source )

Parametry

source

An Open AL(Source) resource (previously created by openal_source_create()).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



openal_source_rewind

(PECL openal >= 0.1.0)

openal_source_rewind Rewind the source

Opis

bool openal_source_rewind ( resource $source )

Parametry

source

An Open AL(Source) resource (previously created by openal_source_create()).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



openal_source_set

(PECL openal >= 0.1.0)

openal_source_set Set source property

Opis

bool openal_source_set ( resource $source , int $property , mixed $setting )

Parametry

source

An Open AL(Source) resource (previously created by openal_source_create()).

property

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)).

setting

Value to assign to specified property . Refer to the description of property for a description of the value(s) expected.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



openal_source_stop

(PECL openal >= 0.1.0)

openal_source_stop Stop playing the source

Opis

bool openal_source_stop ( resource $source )

Parametry

source

An Open AL(Source) resource (previously created by openal_source_create()).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



openal_stream

(PECL openal >= 0.1.0)

openal_stream Begin streaming on a source

Opis

resource openal_stream ( resource $source , int $format , int $rate )

Parametry

source

An Open AL(Source) resource (previously created by openal_source_create()).

format

Format of data , one of: AL_FORMAT_MONO8, AL_FORMAT_MONO16, AL_FORMAT_STEREO8 i AL_FORMAT_STEREO16

rate

Frequency of data to stream given in Hz.

Zwracane wartości

Returns a stream resource on success or FALSE on failure.

Zobacz też:


Spis treści





Serwisy uwierzytelnienia


Kerberos V


Wstęp

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.



Instalacja/Konfiguracja

Spis treści


Wymagania

Do zbudowania tego rozszerzenia nie są wymagane żadne zewnętrzne biblioteki.



Instalacja

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.



Konfiguracja wykonawcza

To rozszerzenie nie definiuje posiada żadnych dyrektyw konfiguracyjnych w pliku php.ini.



Typy zasobów

This extension defines a KADM5 handle returned by kadm5_init_with_password().




Stałe predefiniowane

Spis treści

Poniższe stałe są zdefiniowane w tym rozszerzeniu i stają się dostępne, gdy rozszerzenie jest dokompilowane z PHP, lub załadowane dynamicznie przy starcie.


Constants for Attribute Flags

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:

Attributes for use by the KDC
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



Constants for Options

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:

Options for creating/modifying/retrieving principals
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.




Przykłady

Spis treści


This simple example shows how to connect, query, print resulting principals and disconnect from a KADM5 database.

Przykład #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);
?>




KADM5 Funkcje


kadm5_chpass_principal

(PECL kadm5 >= 0.2.3)

kadm5_chpass_principalChanges the principal's password

Opis

bool kadm5_chpass_principal ( resource $handle , string $principal , string $password )

kadm5_chpass_principal() sets the new password password for the principal .

Parametry

handle

A KADM5 handle.

principal

The principal.

password

The new password.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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);
?>



kadm5_create_principal

(PECL kadm5 >= 0.2.3)

kadm5_create_principalCreates a kerberos principal with the given parameters

Opis

bool kadm5_create_principal ( resource $handle , string $principal [, string $password [, array $options ]] )

Creates a principal with the given password .

Parametry

handle

A KADM5 handle.

principal

The principal.

password

If password is omitted or is NULL, a random key will be generated.

options

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.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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);
?>

Zobacz też:



kadm5_delete_principal

(PECL kadm5 >= 0.2.3)

kadm5_delete_principalDeletes a kerberos principal

Opis

bool kadm5_delete_principal ( resource $handle , string $principal )

Removes the principal from the Kerberos database.

Parametry

handle

A KADM5 handle.

principal

The removed principal.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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);
?>

Zobacz też:



kadm5_destroy

(PECL kadm5 >= 0.2.3)

kadm5_destroyCloses the connection to the admin server and releases all related resources

Opis

bool kadm5_destroy ( resource $handle )

Closes the connection to the admin server and releases all related resources.

Parametry

handle

A KADM5 handle.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



kadm5_flush

(PECL kadm5 >= 0.2.3)

kadm5_flushFlush all changes to the Kerberos database

Opis

bool kadm5_flush ( resource $handle )

Flush all changes to the Kerberos database, leaving the connection to the Kerberos admin server open.

Parametry

handle

A KADM5 handle.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.



kadm5_get_policies

(PECL kadm5 >= 0.2.3)

kadm5_get_policiesGets all policies from the Kerberos database

Opis

array kadm5_get_policies ( resource $handle )

Gets an array containing the policies's names.

Parametry

handle

A KADM5 handle.

Zwracane wartości

Returns array of policies on success or FALSE on failure.

Przykłady

Przykład #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);
?>



kadm5_get_principal

(PECL kadm5 >= 0.2.3)

kadm5_get_principalGets the principal's entries from the Kerberos database

Opis

array kadm5_get_principal ( resource $handle , string $principal )

Gets the principal's entries from the Kerberos database.

Parametry

handle

A KADM5 handle.

principal

The principal.

Zwracane wartości

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.

Przykłady

Przykład #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);
?>

Zobacz też:



kadm5_get_principals

(PECL kadm5 >= 0.2.3)

kadm5_get_principalsGets all principals from the Kerberos database

Opis

array kadm5_get_principals ( resource $handle )

kadm5_get_principals() returns an array containing the principals's names.

Parametry

handle

A KADM5 handle.

Zwracane wartości

Returns array of principals on success or FALSE on failure.

Przykłady

Przykład #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);
?>

Zobacz też:



kadm5_init_with_password

(PECL kadm5 >= 0.2.3)

kadm5_init_with_passwordOpens a connection to the KADM5 library

Opis

resource kadm5_init_with_password ( string $admin_server , string $realm , string $principal , string $password )

Opens a connection with the KADM5 library using the principal and the given password to obtain initial credentials from the admin_server .

Parametry

admin_server

The server.

realm

Defines the authentication domain for the connection.

principal

The principal.

password

If password is omitted or is NULL, a random key will be generated.

Zwracane wartości

Returns a KADM5 handle on success or FALSE on failure.

Przykłady

Przykład #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);
?>

Notatki

Informacja: Connection should be closed after use with kadm5_destroy().

Zobacz też:

  • kadm5_destroy() - Closes the connection to the admin server and releases all related resources



kadm5_modify_principal

(PECL kadm5 >= 0.2.3)

kadm5_modify_principalModifies a kerberos principal with the given parameters

Opis

bool kadm5_modify_principal ( resource $handle , string $principal , array $options )

Modifies a principal according to the given options .

Parametry

handle

A KADM5 handle.

principal

The principal.

options

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.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #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);
?>

Zobacz też:


Spis treści




Radius


Wstęp

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.

Informacja: An exact description for libradius can be found » here. A detailed description of the configuration file can be found » here.



Instalacja/Konfiguracja

Spis treści


Wymagania

Do zbudowania tego rozszerzenia nie są wymagane żadne zewnętrzne biblioteki.



Instalacja

Howto install the package?

  • untar the package (usually into php4/ext)
  • rename radius-x.x to radius
  • run ./buildconf in php4
  • run ./configure --enable-radius
  • make; make install

or if you would like to have it as .so:

  • untar the package
  • run phpize in the radius-x.x directory
  • run ./configure in the radius-x.x directory
  • make; make install

For Windows I recommend to use the php_radius.dll from » http://snaps.php.net/. Nie dołączone rozszerzenia PECL można pobrać z: » http://pecl4win.php.net/



Konfiguracja wykonawcza

To rozszerzenie nie definiuje posiada żadnych dyrektyw konfiguracyjnych w pliku php.ini.



Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.




Stałe predefiniowane

Poniższe stałe są zdefiniowane w tym rozszerzeniu i stają się dostępne, gdy rozszerzenie jest dokompilowane z PHP, lub załadowane dynamicznie przy starcie.

RADIUS_ACCESS_REQUEST ()
Authentication Request
RADIUS_ACCESS_ACCEPT ()
Access accepted
RADIUS_ACCESS_REJECT ()
Access rejected
RADIUS_ACCOUNTING_REQUEST ()
Accounting request
RADIUS_ACCOUNTING_RESPONSE ()
Accounting response
RADIUS_ACCESS_CHALLENGE ()
Accsess challenge
RADIUS_USER_NAME (string)
Username
RADIUS_USER_PASSWORD (string)
Password
RADIUS_CHAP_PASSWORD (string)
Chap Password: chappass = md5(ident + plaintextpass + challenge)
RADIUS_NAS_IP_ADDRESS (string)
NAS IP-Adress
RADIUS_NAS_PORT (int)
NAS Port
RADIUS_SERVICE_TYPE (int)

Type of Service, one of:

  • RADIUS_LOGIN
  • RADIUS_FRAMED
  • RADIUS_CALLBACK_LOGIN
  • RADIUS_CALLBACK_FRAMED
  • RADIUS_OUTBOUND
  • RADIUS_ADMINISTRATIVE
  • RADIUS_NAS_PROMPT
  • RADIUS_AUTHENTICATE_ONLY
  • RADIUS_CALLBACK_NAS_PROMPT

RADIUS_FRAMED_PROTOCOL (int)

Framed Protocol, one of:

  • RADIUS_PPP
  • RADIUS_SLIP
  • RADIUS_ARAP
  • RADIUS_GANDALF
  • RADIUS_XYLOGICS

RADIUS_FRAMED_IP_ADDRESS (string)
IP-Address
RADIUS_FRAMED_IP_NETMASK (string)
Netmask
RADIUS_FRAMED_ROUTING (int)
Routing
RADIUS_FILTER_ID (string)
Filter ID
RADIUS_FRAMED_MTU (int)
MTU
RADIUS_FRAMED_COMPRESSION (int)

Compression, one of:

  • RADIUS_COMP_NONE
  • RADIUS_COMP_VJ
  • RADIUS_COMP_IPXHDR

RADIUS_LOGIN_IP_HOST (string)
Login IP Host
RADIUS_LOGIN_SERVICE (int)
Login Service
RADIUS_LOGIN_TCP_PORT (int)
Login TCP Port
RADIUS_REPLY_MESSAGE (string)
Reply Message
RADIUS_CALLBACK_NUMBER (string)
Callback Number
RADIUS_CALLBACK_ID (string)
Callback ID
RADIUS_FRAMED_ROUTE (string)
Framed Route
RADIUS_FRAMED_IPX_NETWORK (string)
Framed IPX Network
RADIUS_STATE (string)
State
RADIUS_CLASS (int)
Class
RADIUS_VENDOR_SPECIFIC (int)
Vendor specific attribute
RADIUS_SESSION_TIMEOUT (int)
Session timeout
RADIUS_IDLE_TIMEOUT (int)
Idle timeout
RADIUS_TERMINATION_ACTION (int)
Termination action
RADIUS_CALLED_STATION_ID (int)
Called Station Id
RADIUS_CALLING_STATION_ID (string)
Calling Station Id
RADIUS_NAS_IDENTIFIER (int)
NAS ID
RADIUS_PROXY_STATE (int)
Proxy State
RADIUS_LOGIN_LAT_SERVICE (int)
Login LAT Service
RADIUS_LOGIN_LAT_NODE (int)
Login LAT Node
RADIUS_LOGIN_LAT_GROUP (int)
Login LAT Group
RADIUS_FRAMED_APPLETALK_LINK (int)
Framed Appletalk Link
RADIUS_FRAMED_APPLETALK_NETWORK (int)
Framed Appletalk Network
RADIUS_FRAMED_APPLETALK_ZONE (int)
Framed Appletalk Zone
RADIUS_CHAP_CHALLENGE (string)
Challenge
RADIUS_NAS_PORT_TYPE (int)

NAS port type, one of:

  • RADIUS_ASYNC
  • RADIUS_SYNC
  • RADIUS_ISDN_SYNC
  • RADIUS_ISDN_ASYNC_V120
  • RADIUS_ISDN_ASYNC_V110
  • RADIUS_VIRTUAL
  • RADIUS_PIAFS
  • RADIUS_HDLC_CLEAR_CHANNEL
  • RADIUS_X_25
  • RADIUS_X_75
  • RADIUS_G_3_FAX
  • RADIUS_SDSL
  • RADIUS_ADSL_CAP
  • RADIUS_ADSL_DMT
  • RADIUS_IDSL
  • RADIUS_ETHERNET
  • RADIUS_XDSL
  • RADIUS_CABLE
  • RADIUS_WIRELESS_OTHER
  • RADIUS_WIRELESS_IEEE_802_11

RADIUS_PORT_LIMIT (int)
Port Limit
RADIUS_LOGIN_LAT_PORT (int)
Login LAT Port
RADIUS_CONNECT_INFO (string)
Connect info
RADIUS_ACCT_STATUS_TYPE (int)

Accounting status type, one of:

  • RADIUS_START
  • RADIUS_STOP
  • RADIUS_ACCOUNTING_ON
  • RADIUS_ACCOUNTING_OFF

RADIUS_ACCT_DELAY_TIME (int)
Accounting delay time
RADIUS_ACCT_INPUT_OCTETS (int)
Accounting input bytes
RADIUS_ACCT_OUTPUT_OCTETS (int)
Accounting output bytes
RADIUS_ACCT_SESSION_ID (int)
Accounting session ID
RADIUS_ACCT_AUTHENTIC (int)

Accounting authentic, one of:

  • RADIUS_AUTH_RADIUS
  • RADIUS_AUTH_LOCAL
  • RADIUS_AUTH_REMOTE

RADIUS_ACCT_SESSION_TIME (int)
Accounting session time
RADIUS_ACCT_INPUT_PACKETS (int)
Accounting input packets
RADIUS_ACCT_OUTPUT_PACKETS (int)
Accounting output packets
RADIUS_ACCT_TERMINATE_CAUSE (int)

Accounting terminate cause, one of:

  • RADIUS_TERM_USER_REQUEST
  • RADIUS_TERM_LOST_CARRIER
  • RADIUS_TERM_LOST_SERVICE
  • RADIUS_TERM_IDLE_TIMEOUT
  • RADIUS_TERM_SESSION_TIMEOUT
  • RADIUS_TERM_ADMIN_RESET
  • RADIUS_TERM_ADMIN_REBOOT
  • RADIUS_TERM_PORT_ERROR
  • RADIUS_TERM_NAS_ERROR
  • RADIUS_TERM_NAS_REQUEST
  • RADIUS_TERM_NAS_REBOOT
  • RADIUS_TERM_PORT_UNNEEDED
  • RADIUS_TERM_PORT_PREEMPTED
  • RADIUS_TERM_PORT_SUSPENDED
  • RADIUS_TERM_SERVICE_UNAVAILABLE
  • RADIUS_TERM_CALLBACK
  • RADIUS_TERM_USER_ERROR
  • RADIUS_TERM_HOST_REQUEST

RADIUS_ACCT_MULTI_SESSION_ID (string)
Accounting multi session ID
RADIUS_ACCT_LINK_COUNT (int)
Accounting link count
RADIUS_VENDOR_MICROSOFT (int)

Microsoft specific vendor attributes (» RFC 2548), one of:

  • RADIUS_MICROSOFT_MS_CHAP_RESPONSE
  • RADIUS_MICROSOFT_MS_CHAP_ERROR
  • RADIUS_MICROSOFT_MS_CHAP_PW_1
  • RADIUS_MICROSOFT_MS_CHAP_PW_2
  • RADIUS_MICROSOFT_MS_CHAP_LM_ENC_PW
  • RADIUS_MICROSOFT_MS_CHAP_NT_ENC_PW
  • RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_POLICY
  • RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_TYPES
  • RADIUS_MICROSOFT_MS_RAS_VENDOR
  • RADIUS_MICROSOFT_MS_CHAP_DOMAIN
  • RADIUS_MICROSOFT_MS_CHAP_CHALLENGE
  • RADIUS_MICROSOFT_MS_CHAP_MPPE_KEYS
  • RADIUS_MICROSOFT_MS_BAP_USAGE
  • RADIUS_MICROSOFT_MS_LINK_UTILIZATION_THRESHOLD
  • RADIUS_MICROSOFT_MS_LINK_DROP_TIME_LIMIT
  • RADIUS_MICROSOFT_MS_MPPE_SEND_KEY
  • RADIUS_MICROSOFT_MS_MPPE_RECV_KEY
  • RADIUS_MICROSOFT_MS_RAS_VERSION
  • RADIUS_MICROSOFT_MS_OLD_ARAP_PASSWORD
  • RADIUS_MICROSOFT_MS_NEW_ARAP_PASSWORD
  • RADIUS_MICROSOFT_MS_ARAP_PASSWORD_CHANGE_REASON
  • RADIUS_MICROSOFT_MS_FILTER
  • RADIUS_MICROSOFT_MS_ACCT_AUTH_TYPE
  • RADIUS_MICROSOFT_MS_ACCT_EAP_TYPE
  • RADIUS_MICROSOFT_MS_CHAP2_RESPONSE
  • RADIUS_MICROSOFT_MS_CHAP2_SUCCESS
  • RADIUS_MICROSOFT_MS_CHAP2_PW
  • RADIUS_MICROSOFT_MS_PRIMARY_DNS_SERVER
  • RADIUS_MICROSOFT_MS_SECONDARY_DNS_SERVER
  • RADIUS_MICROSOFT_MS_PRIMARY_NBNS_SERVER
  • RADIUS_MICROSOFT_MS_SECONDARY_NBNS_SERVER
  • RADIUS_MICROSOFT_MS_ARAP_CHALLENGE



Przykłady

Howto start?

  • get a radius resource
  • configure the library
  • create the request
  • put attributes
  • send the request
  • receive attributes
  • close the radius resource (optional)

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.



Radius Funkcje

Contact Information

If you have comments, bugfixes, enhancements or want to help to develop this you can send me a mail at » mbretter@php.net.


radius_acct_open

(PECL radius >= 1.1.0)

radius_acct_openCreates a Radius handle for accounting

Opis

resource radius_acct_open ( void )

Zwracane wartości

Returns a handle on success, FALSE on error. This function only fails if insufficient memory is available.

Przykłady

Przykład #1 radius_acct_open() example

<?php
$res 
radius_acct_open ()
    or die (
"Could not create handle");
print(
"Handle successfully created");
?>



radius_add_server

(PECL radius >= 1.1.0)

radius_add_serverAdds a server

Opis

bool radius_add_server ( resource $radius_handle , string $hostname , int $port , string $secret , int $timeout , int $max_tries )

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.

Parametry

radius_handle

hostname

The hostname parameter specifies the server host, either as a fully qualified domain name or as a dotted-quad IP address in text form.

port

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.

secret

The shared secret for the server host is passed to the secret parameter. The Radius protocol ignores all but the leading 128 bytes of the shared secret.

timeout

The timeout for receiving replies from the server is passed to the timeout parameter, in units of seconds.

max_tries

The maximum number of repeated requests to make before giving up is passed into the max_tries .

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 radius_add_server() example

<?php
if (!radius_add_server($res'radius.example.com'1812'testing123'33)) {
    echo 
'RadiusError:' radius_strerror($res). "\n<br>";
    exit;
}
?>

Zobacz też:

  • radius_config() - Causes the library to read the given configuration file



radius_auth_open

(PECL radius >= 1.1.0)

radius_auth_openCreates a Radius handle for authentication

Opis

resource radius_auth_open ( void )

Zwracane wartości

Returns a handle on success, FALSE on error. This function only fails if insufficient memory is available.

Przykłady

Przykład #1 radius_auth_open() example

<?php
$radh 
radius_auth_open()
    or die (
"Could not create handle");
echo 
"Handle successfully created";
?>



radius_close

(PECL radius >= 1.1.0)

radius_closeFrees all ressources

Opis

bool radius_close ( resource $radius_handle )

It is not needed to call this function because php frees all resources at the end of each request.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.



radius_config

(PECL radius >= 1.1.0)

radius_configCauses the library to read the given configuration file

Opis

bool radius_config ( resource $radius_handle , string $file )

Before issuing any Radius requests, the library must be made aware of the servers it can contact. The easiest way to configure the library is to call radius_config(). radius_config() causes the library to read a configuration file whose format is described in » radius.conf.

Parametry

radius_handle

file

The pathname of the configuration file is passed as the file argument to radius_config(). The library can also be configured programmatically by calls to radius_add_server().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



radius_create_request

(PECL radius >= 1.1.0)

radius_create_requestCreate accounting or authentication request

Opis

bool radius_create_request ( resource $radius_handle , int $type )

A Radius request consists of a code specifying the kind of request, and zero or more attributes which provide additional information. To begin constructing a new request, call radius_create_request().

Informacja: Attention: You must call this function, before you can put any attribute!

Parametry

radius_handle

type

Type is RADIUS_ACCESS_REQUEST or RADIUS_ACCOUNTING_REQUEST.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 radius_create_request() example

<?php
if (!radius_create_request($resRADIUS_ACCESS_REQUEST)) {
    echo 
'RadiusError:' radius_strerror($res). "\n<br />";
    exit;
}
?>

Zobacz też:



radius_cvt_addr

(PECL radius >= 1.1.0)

radius_cvt_addrConverts raw data to IP-Address

Opis

string radius_cvt_addr ( string $data )

Przykłady

Przykład #1 radius_cvt_addr() example

<?php
while ($resa radius_get_attr($res)) {

    if (!
is_array($resa)) {
        
printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    
$attr $resa['attr'];
    
$data $resa['data'];
    
    switch (
$attr) {

    case 
RADIUS_FRAMED_IP_ADDRESS:
        
$ip radius_cvt_addr($data);
        echo 
"IP: $ip<br>\n";
        break;

    case 
RADIUS_FRAMED_IP_NETMASK:
        
$mask radius_cvt_addr($data);
        echo 
"MASK: $mask<br>\n";
        break;
    }
}
?>

Zobacz też:



radius_cvt_int

(PECL radius >= 1.1.0)

radius_cvt_intConverts raw data to integer

Opis

int radius_cvt_int ( string $data )

Przykłady

Przykład #1 radius_cvt_int() example

<?php
while ($resa radius_get_attr($res)) {

    if (!
is_array($resa)) {
        
printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    
$attr $resa['attr'];
    
$data $resa['data'];
    
    switch (
$attr) {

    case 
RADIUS_FRAMED_MTU:
        
$mtu radius_cvt_int($data);
        echo 
"MTU: $mtu<br>\n";
        break;
    }
}
?>

Zobacz też:



radius_cvt_string

(PECL radius >= 1.1.0)

radius_cvt_stringConverts raw data to string

Opis

string radius_cvt_string ( string $data )

Przykłady

Przykład #1 radius_cvt_string() example

<?php
while ($resa radius_get_attr($res)) {

    if (!
is_array($resa)) {
        
printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    
$attr $resa['attr'];
    
$data $resa['data'];
    
    switch (
$attr) {

    case 
RADIUS_FILTER_ID:
        
$id radius_cvt_string($data);
        echo 
"Filter ID: $id<br>\n";
        break;
    }
}
?>

Zobacz też:



radius_demangle_mppe_key

(PECL radius >= 1.2.0)

radius_demangle_mppe_keyDerives mppe-keys from mangled data

Opis

string radius_demangle_mppe_key ( resource $radius_handle , string $mangled )

When using MPPE with MS-CHAPv2, the send- and recv-keys are mangled (see » RFC 2548), however this function is useless, because I don't think that there is or will be a PPTP-MPPE implementation in PHP.

Zwracane wartości

Returns the demangled string, or FALSE on error.



radius_demangle

(PECL radius >= 1.2.0)

radius_demangleDemangles data

Opis

string radius_demangle ( resource $radius_handle , string $mangled )

Some data (Passwords, MS-CHAPv1 MPPE-Keys) is mangled for security reasons, and must be demangled before you can use them.

Zwracane wartości

Returns the demangled string, or FALSE on error.



radius_get_attr

(PECL radius >= 1.1.0)

radius_get_attrExtracts an attribute

Opis

mixed radius_get_attr ( resource $radius_handle )

Like Radius requests, each response may contain zero or more attributes. After a response has been received successfully by radius_send_request(), its attributes can be extracted one by one using radius_get_attr(). Each time radius_get_attr() is called, it gets the next attribute from the current response.

Zwracane wartości

Returns an associative array containing the attribute-type and the data, or error number <= 0.

Przykłady

Przykład #1 radius_get_attr() example

<?php
while ($resa radius_get_attr($res)) {

    if (!
is_array($resa)) {
        
printf("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    
$attr $resa['attr'];
    
$data $resa['data'];
    
printf("Got Attr:%d %d Bytes %s\n"$attrstrlen($data), bin2hex($data));
}
?>

Zobacz też:



radius_get_vendor_attr

(PECL radius >= 1.1.0)

radius_get_vendor_attrExtracts a vendor specific attribute

Opis

array radius_get_vendor_attr ( string $data )

If radius_get_attr() returns RADIUS_VENDOR_SPECIFIC, radius_get_vendor_attr() may be called to determine the vendor.

Zwracane wartości

Returns an associative array containing the attribute-type, vendor and the data, or FALSE on error.

Przykłady

Przykład #1 radius_get_vendor_attr() example

<?php
while ($resa radius_get_attr($res)) {

    if (!
is_array($resa)) {
        
printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    
$attr $resa['attr'];
    
$data $resa['data'];
    
printf("Got Attr:%d %d Bytes %s\n"$attrstrlen($data), bin2hex($data));
    if (
$attr == RADIUS_VENDOR_SPECIFIC) {

        
$resv radius_get_vendor_attr($data);
        if (
is_array($resv)) {
            
$vendor $resv['vendor'];
            
$attrv $resv['attr'];
            
$datav $resv['data'];    
            
printf("Got Vendor Attr:%d %d Bytes %s\n"$attrvstrlen($datav), bin2hex($datav));
        }
        
    }
}
?>

Zobacz też:



radius_put_addr

(PECL radius >= 1.1.0)

radius_put_addrAttaches an IP-Address attribute

Opis

bool radius_put_addr ( resource $radius_handle , int $type , string $addr )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.



radius_put_attr

(PECL radius >= 1.1.0)

radius_put_attrAttaches a binary attribute

Opis

bool radius_put_attr ( resource $radius_handle , int $type , string $value )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 radius_put_attr() example

<?php
mt_srand
(time());
$chall mt_rand();
$chapval md5(pack('Ca*','sepp' $chall));
$pass pack('CH*'1$chapval);
if (!
radius_put_attr($resRADIUS_CHAP_PASSWORD$pass)) {
    echo 
'RadiusError:' radius_strerror($res). "\n<br />";
    exit;
}
?>

Zobacz też:



radius_put_int

(PECL radius >= 1.1.0)

radius_put_intAttaches an integer attribute

Opis

bool radius_put_int ( resource $radius_handle , int $type , int $value )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 radius_put_int() example

<?php
if (!radius_put_int($resRAD_FRAMED_PROTOCOLRAD_PPP)) {
   echo 
'RadiusError:' radius_strerror($res). "\n<br />";
   exit;
}
?>

Zobacz też:



radius_put_string

(PECL radius >= 1.1.0)

radius_put_stringAttaches a string attribute

Opis

bool radius_put_string ( resource $radius_handle , int $type , string $value )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 radius_put_string() example

<?php
if (!radius_put_string($resRADIUS_USER_NAME'billy')) {
    echo 
'RadiusError:' radius_strerror($res). "\n<br />";
    exit;
}
?>

Zobacz też:



radius_put_vendor_addr

(PECL radius >= 1.1.0)

radius_put_vendor_addrAttaches a vendor specific IP-Address attribute

Opis

bool radius_put_vendor_addr ( resource $radius_handle , int $vendor , int $type , string $addr )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.



radius_put_vendor_attr

(PECL radius >= 1.1.0)

radius_put_vendor_attrAttaches a vendor specific binary attribute

Opis

bool radius_put_vendor_attr ( resource $radius_handle , int $vendor , int $type , string $value )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 radius_put_vendor_attr() example

<?php
if (!radius_put_vendor_attr($resRADIUS_VENDOR_MICROSOFTRAD_MICROSOFT_MS_CHAP_CHALLENGE$challenge)) {
    echo 
'RadiusError:' radius_strerror($res). "\n<br />";
    exit;
}
?>

Zobacz też:



radius_put_vendor_int

(PECL radius >= 1.1.0)

radius_put_vendor_intAttaches a vendor specific integer attribute

Opis

bool radius_put_vendor_int ( resource $radius_handle , int $vendor , int $type , int $value )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



radius_put_vendor_string

(PECL radius >= 1.1.0)

radius_put_vendor_stringAttaches a vendor specific string attribute

Opis

bool radius_put_vendor_string ( resource $radius_handle , int $vendor , int $type , string $value )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



radius_request_authenticator

(PECL radius >= 1.1.0)

radius_request_authenticatorReturns the request authenticator

Opis

string radius_request_authenticator ( resource $radius_handle )

The request authenticator is needed for demangling mangled data like passwords and encryption-keys.

Zwracane wartości

Returns the request authenticator as string, or FALSE on error.

Zobacz też:



radius_send_request

(PECL radius >= 1.1.0)

radius_send_requestSends the request and waites for a reply

Opis

int radius_send_request ( resource $radius_handle )

After the Radius request has been constructed, it is sent by radius_send_request().

The radius_send_request() function sends the request and waits for a valid reply, retrying the defined servers in round-robin fashion as necessary.

Zwracane wartości

If a valid response is received, radius_send_request() returns the Radius code which specifies the type of the response. This will typically be RADIUS_ACCESS_ACCEPT, RADIUS_ACCESS_REJECT, or RADIUS_ACCESS_CHALLENGE. If no valid response is received, radius_send_request() returns FALSE.

Zobacz też:



radius_server_secret

(PECL radius >= 1.1.0)

radius_server_secretReturns the shared secret

Opis

string radius_server_secret ( resource $radius_handle )

The shared secret is needed as salt for demangling mangled data like passwords and encryption-keys.

Zwracane wartości

Returns the server's shared secret as string, or FALSE on error.



radius_strerror

(PECL radius >= 1.1.0)

radius_strerrorReturns an error message

Opis

string radius_strerror ( resource $radius_handle )

If Radius-functions fail then they record an error message. This error message can be retrieved with this function.

Zwracane wartości

Returns error messages as string from failed radius functions.


Spis treści





Kalendarz i rozszerzenia pokrewne


Calendar


Wstęp

The calendar extension presents a series of functions to simplify converting between different calendar formats. The intermediary or standard it is based on is the Julian Day Count. The Julian Day Count is a count of days starting from January 1st, 4713 B.C. To convert between calendar systems, you must first convert to Julian Day Count, then to the calendar system of your choice. Julian Day Count is very different from the Julian Calendar! For more information on Julian Day Count, visit » http://www.hermetic.ch/cal_stud/jdn.htm. For more information on calendar systems visit » http://www.fourmilab.ch/documents/calendar/. Excerpts from this page are included in these instructions, and are in quotes.



Instalacja/Konfiguracja

Spis treści


Wymagania

Do zbudowania tego rozszerzenia nie są wymagane żadne zewnętrzne biblioteki.



Instalacja

To get these functions to work, you have to compile PHP with --enable-calendar.

PHP w wersji dla systemów Windows posiada wbudowaną obsługę dla tego rozszerzenia. Nie trzeba ładować żadnych dodatkowych rozszerzeń, aby używać tych funkcji.



Konfiguracja wykonawcza

To rozszerzenie nie definiuje posiada żadnych dyrektyw konfiguracyjnych w pliku php.ini.



Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.




Stałe predefiniowane

Poniższe stałe są zdefiniowane w tym rozszerzeniu i stają się dostępne, gdy rozszerzenie jest dokompilowane z PHP, lub załadowane dynamicznie przy starcie.

CAL_GREGORIAN (integer)
CAL_JULIAN (integer)
CAL_JEWISH (integer)
CAL_FRENCH (integer)
CAL_NUM_CALS (integer)
CAL_DOW_DAYNO (integer)
CAL_DOW_SHORT (integer)
CAL_DOW_LONG (integer)
CAL_MONTH_GREGORIAN_SHORT (integer)
CAL_MONTH_GREGORIAN_LONG (integer)
CAL_MONTH_JULIAN_SHORT (integer)
CAL_MONTH_JULIAN_LONG (integer)
CAL_MONTH_JEWISH (integer)
CAL_MONTH_FRENCH (integer)

The following constants are available since PHP 4.3.0 :

CAL_EASTER_DEFAULT (integer)
CAL_EASTER_ROMAN (integer)
CAL_EASTER_ALWAYS_GREGORIAN (integer)
CAL_EASTER_ALWAYS_JULIAN (integer)

The following constants are available since PHP 5.0.0 :

CAL_JEWISH_ADD_ALAFIM_GERESH (integer)
CAL_JEWISH_ADD_ALAFIM (integer)
CAL_JEWISH_ADD_GERESHAYIM (integer)


Calendar Funkcje


cal_days_in_month

(PHP 4 >= 4.1.0, PHP 5)

cal_days_in_monthReturn the number of days in a month for a given year and calendar

Opis

int cal_days_in_month ( int $calendar , int $month , int $year )

This function will return the number of days in the month of year for the specified calendar .

Parametry

calendar

Calendar to use for calculation

month

Month in the selected calendar

year

Year in the selected calendar

Zwracane wartości

The length in days of the selected month in the given calendar

Przykłady

Przykład #1 cal_days_in_month() example

<?php
$num 
cal_days_in_month(CAL_GREGORIAN82003); // 31
echo "There was $num days in August 2003";
?>



cal_from_jd

(PHP 4 >= 4.1.0, PHP 5)

cal_from_jdConverts from Julian Day Count to a supported calendar

Opis

array cal_from_jd ( int $jd , int $calendar )

cal_from_jd() converts the Julian day given in jd into a date of the specified calendar . Supported calendar values are CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH.

Parametry

jd

Julian day as integer

calendar

Calendar to convert to

Zwracane wartości

Returns an array containing calendar information like month, day, year, day of week, abbreviated and full names of weekday and month and the date in string form "month/day/year".

Przykłady

Przykład #1 cal_from_jd() example

<?php
$today 
unixtojd(mktime(0008162003));
print_r(cal_from_jd($todayCAL_GREGORIAN));
?>

Powyższy przykład wyświetli:

Array
(
    [date] => 8/16/2003
    [month] => 8
    [day] => 16
    [year] => 2003
    [dow] => 6
    [abbrevdayname] => Sat
    [dayname] => Saturday
    [abbrevmonth] => Aug
    [monthname] => August
)

Zobacz też:

  • cal_to_jd() - Converts from a supported calendar to Julian Day Count
  • jdtofrench() - Converts a Julian Day Count to the French Republican Calendar
  • jdtogregorian() - Converts Julian Day Count to Gregorian date
  • jdtojewish() - Converts a Julian day count to a Jewish calendar date
  • jdtojulian() - Converts a Julian Day Count to a Julian Calendar Date
  • jdtounix() - Convert Julian Day to Unix timestamp



cal_info

(PHP 4 >= 4.1.0, PHP 5)

cal_infoReturns information about a particular calendar

Opis

array cal_info ([ int $calendar = -1 ] )

cal_info() returns information on the specified calendar .

Calendar information is returned as an array containing the elements calname, calsymbol, month, abbrevmonth and maxdaysinmonth. The names of the different calendars which can be used as calendar are as follows:

  • 0 or CAL_GREGORIAN - Gregorian Calendar
  • 1 or CAL_JULIAN - Julian Calendar
  • 2 or CAL_JEWISH - Jewish Calendar
  • 3 or CAL_FRENCH - French Revolutionary Calendar

If no calendar is specified information on all supported calendars is returned as an array.

Parametry

calendar

Calendar to return information for. If no calendar is specified information about all calendars is returned.

Zwracane wartości

Rejestr zmian

Wersja Opis
Since 5.0 The calendar parameter becomes optional and defaults to "all calendars" if omitted.

Przykłady

Przykład #1 cal_info() example

<?php
$info 
cal_info(0);
print_r($info);
?>

Powyższy przykład wyświetli:

Array
(
    [months] => Array
        (
            [1] => January
            [2] => February
            [3] => March
            [4] => April
            [5] => May
            [6] => June
            [7] => July
            [8] => August
            [9] => September
            [10] => October
            [11] => November
            [12] => December
        )

    [abbrevmonths] => Array
        (
            [1] => Jan
            [2] => Feb
            [3] => Mar
            [4] => Apr
            [5] => May
            [6] => Jun
            [7] => Jul
            [8] => Aug
            [9] => Sep
            [10] => Oct
            [11] => Nov
            [12] => Dec
        )

    [maxdaysinmonth] => 31
    [calname] => Gregorian
    [calsymbol] => CAL_GREGORIAN
)



cal_to_jd

(PHP 4 >= 4.1.0, PHP 5)

cal_to_jdConverts from a supported calendar to Julian Day Count

Opis

int cal_to_jd ( int $calendar , int $month , int $day , int $year )

cal_to_jd() calculates the Julian day count for a date in the specified calendar . Supported calendar s are CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH.

Parametry

calendar

Calendar to convert from, one of CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH or CAL_FRENCH.

month

The month as a number, the valid range depends on the calendar

day

The day as a number, the valid range depends on the calendar

year

The year as a number, the valid range depends on the calendar

Zwracane wartości

A Julian Day number.

Zobacz też:

  • cal_from_jd() - Converts from Julian Day Count to a supported calendar
  • frenchtojd() - Converts a date from the French Republican Calendar to a Julian Day Count
  • gregoriantojd() - Converts a Gregorian date to Julian Day Count
  • jewishtojd() - Converts a date in the Jewish Calendar to Julian Day Count
  • juliantojd() - Converts a Julian Calendar date to Julian Day Count
  • unixtojd() - Convert Unix timestamp to Julian Day



easter_date

(PHP 4, PHP 5)

easter_dateGet Unix timestamp for midnight on Easter of a given year

Opis

int easter_date ([ int $year ] )

Returns the Unix timestamp corresponding to midnight on Easter of the given year.

Ostrzeżenie

This function will generate a warning if the year is outside of the range for Unix timestamps (i.e. before 1970 or after 2037).

The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.

(The code is based on a C program by Simon Kershaw, <webmaster at ely.anglican dot org>)

Parametry

year

The year as a number between 1970 an 2037

Zwracane wartości

The easter date as a unix timestamp.

Rejestr zmian

Wersja Opis
Since 4.3.0 The year parameter is optional and defaults to the current year according to the local time if omitted.

Przykłady

Przykład #1 easter_date() example

<?php

echo date("M-d-Y"easter_date(1999));        // Apr-04-1999
echo date("M-d-Y"easter_date(2000));        // Apr-23-2000
echo date("M-d-Y"easter_date(2001));        // Apr-15-2001

?>

Zobacz też:

  • easter_days() - Get number of days after March 21 on which Easter falls for a given year for calculating Easter before 1970 or after 2037



easter_days

(PHP 4, PHP 5)

easter_daysGet number of days after March 21 on which Easter falls for a given year

Opis

int easter_days ([ int $year [, int $method = CAL_EASTER_DEFAULT ]] )

Returns the number of days after March 21 on which Easter falls for a given year. If no year is specified, the current year is assumed.

This function can be used instead of easter_date() to calculate Easter for years which fall outside the range of Unix timestamps (i.e. before 1970 or after 2037).

The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.

(The code is based on a C program by Simon Kershaw, <webmaster at ely.anglican dot org>)

Parametry

year

The year as a positive number

method

Allows to calculate easter dates based on the Gregorian calendar during the years 1582 - 1752 when set to CAL_EASTER_ROMAN. See the calendar constants for more valid constants.

Zwracane wartości

The number of days after March 21st that the Easter Sunday is in the given year .

Rejestr zmian

Wersja Opis
Since 4.3.0 The year parameter is optional and defaults to the current year according to the local time if omitted.
Since 4.3.0 The method parameter was introduced.

Przykłady

Przykład #1 easter_days() example

<?php

echo easter_days(1999);        // 14, i.e. April 4
echo easter_days(1492);        // 32, i.e. April 22
echo easter_days(1913);        //  2, i.e. March 23

?>

Zobacz też:

  • easter_date() - Get Unix timestamp for midnight on Easter of a given year



FrenchToJD

(PHP 4, PHP 5)

FrenchToJDConverts a date from the French Republican Calendar to a Julian Day Count

Opis

int frenchtojd ( int $month , int $day , int $year )

Converts a date from the French Republican Calendar to a Julian Day Count.

These routines only convert dates in years 1 through 14 (Gregorian dates 22 September 1792 through 22 September 1806). This more than covers the period when the calendar was in use.

Parametry

month

The month as a number from 1 (for Vendémiaire) to 13 (for the period of 5-6 days at the end of each year)

day

The day as a number from 1 to 30

year

The year as a number between 1 and 14

Zwracane wartości

The julian day for the given french revolution date as an integer.

Zobacz też:

  • jdtofrench() - Converts a Julian Day Count to the French Republican Calendar
  • cal_to_jd() - Converts from a supported calendar to Julian Day Count



GregorianToJD

(PHP 4, PHP 5)

GregorianToJDConverts a Gregorian date to Julian Day Count

Opis

int gregoriantojd ( int $month , int $day , int $year )

Valid Range for Gregorian Calendar 4714 B.C. to 9999 A.D.

Although this function can handle dates all the way back to 4714 B.C., such use may not be meaningful. The Gregorian calendar was not instituted until October 15, 1582 (or October 5, 1582 in the Julian calendar). Some countries did not accept it until much later. For example, Britain converted in 1752, The USSR in 1918 and Greece in 1923. Most European countries used the Julian calendar prior to the Gregorian.

Parametry

month

The month as a number from 1 (for January) to 12 (for December)

day

The day as a number from 1 to 31

year

The year as a number between -4714 and 9999

Zwracane wartości

The julian day for the given gregorian date as an integer.

Przykłady

Przykład #1 Calendar functions

<?php
$jd 
GregorianToJD(10111970);
echo 
"$jd\n";
$gregorian JDToGregorian($jd);
echo 
"$gregorian\n";
?>

Zobacz też:

  • jdtogregorian() - Converts Julian Day Count to Gregorian date
  • cal_to_jd() - Converts from a supported calendar to Julian Day Count



JDDayOfWeek

(PHP 4, PHP 5)

JDDayOfWeekReturns the day of the week

Opis

mixed jddayofweek ( int $julianday [, int $mode = CAL_DOW_DAYNO ] )

Returns the day of the week. Can return a string or an integer depending on the mode.

Parametry

julianday

A julian day number as integer

mode
Calendar week modes
Mode Meaning
0 (Default) Return the day number as an int (0=Sunday, 1=Monday, etc)
1 Returns string containing the day of week (English-Gregorian)
2 Return a string containing the abbreviated day of week (English-Gregorian)

Zwracane wartości

The gregorian weekday as either an integer or string.



JDMonthName

(PHP 4, PHP 5)

JDMonthNameReturns a month name

Opis

string jdmonthname ( int $julianday , int $mode )

Returns a string containing a month name. mode tells this function which calendar to convert the Julian Day Count to, and what type of month names are to be returned.

Calendar modes
Mode Meaning Values
0 Gregorian - abbreviated Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
1 Gregorian January, February, March, April, May, June, July, August, September, October, November, December
2 Julian - abbreviated Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
3 Julian January, February, March, April, May, June, July, August, September, October, November, December
4 Jewish Tishri, Heshvan, Kislev, Tevet, Shevat, AdarI, AdarII, Nisan, Iyyar, Sivan, Tammuz, Av, Elul
5 French Republican Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra

Parametry

jday

The Julian Day to operate on

calendar

The calendar to take the month name from

Zwracane wartości

The month name for the given Julian Day and calendar .



JDToFrench

(PHP 4, PHP 5)

JDToFrenchConverts a Julian Day Count to the French Republican Calendar

Opis

string jdtofrench ( int $juliandaycount )

Converts a Julian Day Count to the French Republican Calendar.

Parametry

julianday

A julian day number as integer

Zwracane wartości

The french revolution date as a string in the form "month/day/year"

Zobacz też:

  • frenchtojd() - Converts a date from the French Republican Calendar to a Julian Day Count
  • cal_from_jd() - Converts from Julian Day Count to a supported calendar



JDToGregorian

(PHP 4, PHP 5)

JDToGregorianConverts Julian Day Count to Gregorian date

Opis

string jdtogregorian ( int $julianday )

Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year".

Parametry

julianday

A julian day number as integer

Zwracane wartości

The gregorian date as a string in the form "month/day/year"

Zobacz też:



jdtojewish

(PHP 4, PHP 5)

jdtojewishConverts a Julian day count to a Jewish calendar date

Opis

string jdtojewish ( int $juliandaycount [, bool $hebrew = false [, int $fl = 0 ]] )

Converts a Julian Day Count to the Jewish Calendar.

Parametry

julianday

A julian day number as integer

hebrew

If the hebrew parameter is set to TRUE, the fl parameter is used for Hebrew, string based, output format.

fl

The available formats are: CAL_JEWISH_ADD_ALAFIM_GERESH, CAL_JEWISH_ADD_ALAFIM, CAL_JEWISH_ADD_GERESHAYIM.

Zwracane wartości

The jewish date as a string in the form "month/day/year"

Rejestr zmian

Wersja Opis
5.0.0 The fl parameter was added.
4.3.0 The hebrew parameter was added.

Przykłady

Przykład #1 jdtojewish() Example

<?php
echo jdtojewish(gregoriantojd(1082002), true,
       
CAL_JEWISH_ADD_GERESHAYIM CAL_JEWISH_ADD_ALAFIM CAL_JEWISH_ADD_ALAFIM_GERESH); 
?>

Zobacz też:

  • jewishtojd() - Converts a date in the Jewish Calendar to Julian Day Count
  • cal_from_jd() - Converts from Julian Day Count to a supported calendar



JDToJulian

(PHP 4, PHP 5)

JDToJulianConverts a Julian Day Count to a Julian Calendar Date

Opis

string jdtojulian ( int $julianday )

Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year".

Parametry

julianday

A julian day number as integer

Zwracane wartości

The julian date as a string in the form "month/day/year"

Zobacz też:

  • juliantojd() - Converts a Julian Calendar date to Julian Day Count
  • cal_from_jd() - Converts from Julian Day Count to a supported calendar



jdtounix

(PHP 4, PHP 5)

jdtounixConvert Julian Day to Unix timestamp

Opis

int jdtounix ( int $jday )

This function will return a Unix timestamp corresponding to the Julian Day given in jday or FALSE if jday is not inside the Unix epoch (Gregorian years between 1970 and 2037 or 2440588 <= jday <= 2465342 ). The time returned is localtime (and not GMT).

Parametry

jday

A julian day number between 2440588 and 2465342.

Zwracane wartości

The unix timestamp for the start of the given julian day.

Zobacz też:

  • unixtojd() - Convert Unix timestamp to Julian Day



JewishToJD

(PHP 4, PHP 5)

JewishToJDConverts a date in the Jewish Calendar to Julian Day Count

Opis

int jewishtojd ( int $month , int $day , int $year )

Although this function can handle dates all the way back to the year 1 (3761 B.C.), such use may not be meaningful. The Jewish calendar has been in use for several thousand years, but in the early days there was no formula to determine the start of a month. A new month was started when the new moon was first observed.

Parametry

month

The month as a number from 1 to 13

day

The day as a number from 1 to 30

year

The year as a number between 1 and 9999

Zwracane wartości

The julian day for the given jewish date as an integer.

Zobacz też:

  • jdtojewish() - Converts a Julian day count to a Jewish calendar date
  • cal_to_jd() - Converts from a supported calendar to Julian Day Count



JulianToJD

(PHP 4, PHP 5)

JulianToJDConverts a Julian Calendar date to Julian Day Count

Opis

int juliantojd ( int $month , int $day , int $year )

Valid Range for Julian Calendar 4713 B.C. to 9999 A.D.

Although this function can handle dates all the way back to 4713 B.C., such use may not be meaningful. The calendar was created in 46 B.C., but the details did not stabilize until at least 8 A.D., and perhaps as late at the 4th century. Also, the beginning of a year varied from one culture to another - not all accepted January as the first month.

Uwaga

Remember, the current calendar system being used worldwide is the Gregorian calendar. gregoriantojd() can be used to convert such dates to their Julian Day count.

Parametry

month

The month as a number from 1 (for January) to 12 (for December)

day

The day as a number from 1 to 31

year

The year as a number between -4713 and 9999

Zwracane wartości

The julian day for the given julian date as an integer.

Zobacz też:

  • jdtojulian() - Converts a Julian Day Count to a Julian Calendar Date
  • cal_to_jd() - Converts from a supported calendar to Julian Day Count



unixtojd

(PHP 4, PHP 5)

unixtojdConvert Unix timestamp to Julian Day

Opis

int unixtojd ([ int $timestamp = time() ] )

Return the Julian Day for a Unix timestamp (seconds since 1.1.1970), or for the current day if no timestamp is given.

Parametry

timestamp

A unix timestamp to convert.

Zwracane wartości

A julian day number as integer.

Zobacz też:

  • jdtounix() - Convert Julian Day to Unix timestamp


Spis treści

  • cal_days_in_month — Return the number of days in a month for a given year and calendar
  • cal_from_jd — Converts from Julian Day Count to a supported calendar
  • cal_info — Returns information about a particular calendar
  • cal_to_jd — Converts from a supported calendar to Julian Day Count
  • easter_date — Get Unix timestamp for midnight on Easter of a given year
  • easter_days — Get number of days after March 21 on which Easter falls for a given year
  • FrenchToJD — Converts a date from the French Republican Calendar to a Julian Day Count
  • GregorianToJD — Converts a Gregorian date to Julian Day Count
  • JDDayOfWeek — Returns the day of the week
  • JDMonthName — Returns a month name
  • JDToFrench — Converts a Julian Day Count to the French Republican Calendar
  • JDToGregorian — Converts Julian Day Count to Gregorian date
  • jdtojewish — Converts a Julian day count to a Jewish calendar date
  • JDToJulian — Converts a Julian Day Count to a Julian Calendar Date
  • jdtounix — Convert Julian Day to Unix timestamp
  • JewishToJD — Converts a date in the Jewish Calendar to Julian Day Count
  • JulianToJD — Converts a Julian Calendar date to Julian Day Count
  • unixtojd — Convert Unix timestamp to Julian Day



Data i Czas


Wstęp

Te funkcje pozwalają pobierać datę i czas z serwera, na którym uruchomione są skrypty PHP. Można ich używać do formatowania daty i czasu na wiele różnych sposobów.

Informacja: Proszę pamiętać, że poniższe funkcje są zależne od lokalnych ustawień danego serwera. Należy się upewnić, że podczas pracy z nimi bierzemy pod uwagę czas zimowy i lata przestępne (należy użyć np. $date = strtotime('+7 days', $date), a nie $date += 7*24*60*60).

Informacja: Strefy czasowe, do których odwołujemy się w tym rozdziale można znaleźć w Lista obsługiwanych stref czasowych.



Instalacja/Konfiguracja

Spis treści


Wymagania

Do zbudowania tego rozszerzenia nie są wymagane żadne zewnętrzne biblioteki.



Instalacja

By używać tych funkcji, nie trzeba niczego instalować. Są one częścią jądra PHP.

Informacja: Pobieranie najnowszej bazy danych stref czasowych
Najnowszą wersję bazy danych stref czasowych można zainstalować poprzez PECL » timezonedb. Dla użytkowików Windows, prekompilowana biblioteka DLL może być pobrana ze strony PECL4WIN: » php_timezonedb.dll.

Informacja: Eksperymentalna obsługa daty i czasu w PHP 5.1.x
Chociaż klasa DateTime (i powiązane z nią funkcje) są włączone domyślnie dopiero od PHP 5.2.0, to jest możliwe dodanie eksperymentalnej obsługi już w PHP 5.1.x, poprzez użycie następującego znacznika przed przystąpieniem do konfiguracji/kompilacji: CFLAGS=-DEXPERIMENTAL_DATE_SUPPORT=1



Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Date/Time Configuration Options
Name Default Changeable Changelog
date.default_latitude "31.7667" PHP_INI_ALL Available since PHP 5.0.0.
date.default_longitude "35.2333" PHP_INI_ALL Available since PHP 5.0.0.
date.sunrise_zenith "90.583333" PHP_INI_ALL Available since PHP 5.0.0.
date.sunset_zenith "90.583333" PHP_INI_ALL Available since PHP 5.0.0.
date.timezone "" PHP_INI_ALL Available since PHP 5.1.0.

Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

date.default_latitude float

The default latitude.

date.default_longitude float

The default longitude.

date.sunrise_zenith float

The default sunrise zenith.

date.sunset_zenith float

The default sunset zenith.

date.timezone string

The default timezone used by all date/time functions if the TZ environment variable isn't set. The precedence order is described in the date_default_timezone_get() page. See Lista obsługiwanych stref czasowych for a list of supported timezones.

Informacja: The first four configuration options are currently only used by date_sunrise() and date_sunset().



Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.




Stałe predefiniowane

The DATE_ constants are defined since PHP 5.1.1 and they offer standard date representations, which can be used along with the date format functions (like date()).

Following constants exists since PHP 5.1.2 and specify a format returned by functions date_sunrise() and date_sunset().

SUNFUNCS_RET_TIMESTAMP (integer)
Timestamp
SUNFUNCS_RET_STRING (integer)
Hours:minutes (example: 08:02)
SUNFUNCS_RET_DOUBLE (integer)
Hours as floating point number (example 8.75)


Lista obsługiwanych stref czasowych

Spis treści

Tutaj znajdziesz kompletną listę stref czasowych obsługiwanych przez PHP, co oznacza, że mogą być użyte np. w date_default_timezone_set().

Informacja: Najnowsza wersja bazy danych stref czasowych może być zainstalowana przez PECL » timezonedb. Dla użytkowników Windows, skompilowane DLL mogą być ściagnięte ze strony PECL4Win: » php_timezonedb.dll.

Informacja: This list is based upon the timezone database version 2009.19.


Africa

Africa
Africa/Abidjan Africa/Accra Africa/Addis_Ababa Africa/Algiers Africa/Asmara
Africa/Asmera Africa/Bamako Africa/Bangui Africa/Banjul Africa/Bissau
Africa/Blantyre Africa/Brazzaville Africa/Bujumbura Africa/Cairo Africa/Casablanca
Africa/Ceuta Africa/Conakry Africa/Dakar Africa/Dar_es_Salaam Africa/Djibouti
Africa/Douala Africa/El_Aaiun Africa/Freetown Africa/Gaborone Africa/Harare
Africa/Johannesburg Africa/Kampala Africa/Khartoum Africa/Kigali Africa/Kinshasa
Africa/Lagos Africa/Libreville Africa/Lome Africa/Luanda Africa/Lubumbashi
Africa/Lusaka Africa/Malabo Africa/Maputo Africa/Maseru Africa/Mbabane
Africa/Mogadishu Africa/Monrovia Africa/Nairobi Africa/Ndjamena Africa/Niamey
Africa/Nouakchott Africa/Ouagadougou Africa/Porto-Novo Africa/Sao_Tome Africa/Timbuktu
Africa/Tripoli Africa/Tunis Africa/Windhoek    


America

America
America/Adak America/Anchorage America/Anguilla America/Antigua America/Araguaina
America/Argentina/Buenos_Aires America/Argentina/Catamarca America/Argentina/ComodRivadavia America/Argentina/Cordoba America/Argentina/Jujuy
America/Argentina/La_Rioja America/Argentina/Mendoza America/Argentina/Rio_Gallegos America/Argentina/Salta America/Argentina/San_Juan
America/Argentina/San_Luis America/Argentina/Tucuman America/Argentina/Ushuaia America/Aruba America/Asuncion
America/Atikokan America/Atka America/Bahia America/Barbados America/Belem
America/Belize America/Blanc-Sablon America/Boa_Vista America/Bogota America/Boise
America/Buenos_Aires America/Cambridge_Bay America/Campo_Grande America/Cancun America/Caracas
America/Catamarca America/Cayenne America/Cayman America/Chicago America/Chihuahua
America/Coral_Harbour America/Cordoba America/Costa_Rica America/Cuiaba America/Curacao
America/Danmarkshavn America/Dawson America/Dawson_Creek America/Denver America/Detroit
America/Dominica America/Edmonton America/Eirunepe America/El_Salvador America/Ensenada
America/Fort_Wayne America/Fortaleza America/Glace_Bay America/Godthab America/Goose_Bay
America/Grand_Turk America/Grenada America/Guadeloupe America/Guatemala America/Guayaquil
America/Guyana America/Halifax America/Havana America/Hermosillo America/Indiana/Indianapolis
America/Indiana/Knox America/Indiana/Marengo America/Indiana/Petersburg America/Indiana/Tell_City America/Indiana/Vevay
America/Indiana/Vincennes America/Indiana/Winamac America/Indianapolis America/Inuvik America/Iqaluit
America/Jamaica America/Jujuy America/Juneau America/Kentucky/Louisville America/Kentucky/Monticello
America/Knox_IN America/La_Paz America/Lima America/Los_Angeles America/Louisville
America/Maceio America/Managua America/Manaus America/Marigot America/Martinique
America/Mazatlan America/Mendoza America/Menominee America/Merida America/Mexico_City
America/Miquelon America/Moncton America/Monterrey America/Montevideo America/Montreal
America/Montserrat America/Nassau America/New_York America/Nipigon America/Nome
America/Noronha America/North_Dakota/Center America/North_Dakota/New_Salem America/Panama America/Pangnirtung
America/Paramaribo America/Phoenix America/Port-au-Prince America/Port_of_Spain America/Porto_Acre
America/Porto_Velho America/Puerto_Rico America/Rainy_River America/Rankin_Inlet America/Recife
America/Regina America/Resolute America/Rio_Branco America/Rosario America/Santarem
America/Santiago America/Santo_Domingo America/Sao_Paulo America/Scoresbysund America/Shiprock
America/St_Barthelemy America/St_Johns America/St_Kitts America/St_Lucia America/St_Thomas
America/St_Vincent America/Swift_Current America/Tegucigalpa America/Thule America/Thunder_Bay
America/Tijuana America/Toronto America/Tortola America/Vancouver America/Virgin
America/Whitehorse America/Winnipeg America/Yakutat America/Yellowknife  


Antarctica

Antarctica
Antarctica/Casey Antarctica/Davis Antarctica/DumontDUrville Antarctica/Mawson Antarctica/McMurdo
Antarctica/Palmer Antarctica/Rothera Antarctica/South_Pole Antarctica/Syowa Antarctica/Vostok


Arctic

Arctic
Arctic/Longyearbyen


Asia

Asia
Asia/Aden Asia/Almaty Asia/Amman Asia/Anadyr Asia/Aqtau
Asia/Aqtobe Asia/Ashgabat Asia/Ashkhabad Asia/Baghdad Asia/Bahrain
Asia/Baku Asia/Bangkok Asia/Beirut Asia/Bishkek Asia/Brunei
Asia/Calcutta Asia/Choibalsan Asia/Chongqing Asia/Chungking Asia/Colombo
Asia/Dacca Asia/Damascus Asia/Dhaka Asia/Dili Asia/Dubai
Asia/Dushanbe Asia/Gaza Asia/Harbin Asia/Ho_Chi_Minh Asia/Hong_Kong
Asia/Hovd Asia/Irkutsk Asia/Istanbul Asia/Jakarta Asia/Jayapura
Asia/Jerusalem Asia/Kabul Asia/Kamchatka Asia/Karachi Asia/Kashgar
Asia/Kathmandu Asia/Katmandu Asia/Kolkata Asia/Krasnoyarsk Asia/Kuala_Lumpur
Asia/Kuching Asia/Kuwait Asia/Macao Asia/Macau Asia/Magadan
Asia/Makassar Asia/Manila Asia/Muscat Asia/Nicosia Asia/Novokuznetsk
Asia/Novosibirsk Asia/Omsk Asia/Oral Asia/Phnom_Penh Asia/Pontianak
Asia/Pyongyang Asia/Qatar Asia/Qyzylorda Asia/Rangoon Asia/Riyadh
Asia/Saigon Asia/Sakhalin Asia/Samarkand Asia/Seoul Asia/Shanghai
Asia/Singapore Asia/Taipei Asia/Tashkent Asia/Tbilisi Asia/Tehran
Asia/Tel_Aviv Asia/Thimbu Asia/Thimphu Asia/Tokyo Asia/Ujung_Pandang
Asia/Ulaanbaatar Asia/Ulan_Bator Asia/Urumqi Asia/Vientiane Asia/Vladivostok
Asia/Yakutsk Asia/Yekaterinburg Asia/Yerevan    


Atlantic

Atlantic
Atlantic/Azores Atlantic/Bermuda Atlantic/Canary Atlantic/Cape_Verde Atlantic/Faeroe
Atlantic/Faroe Atlantic/Jan_Mayen Atlantic/Madeira Atlantic/Reykjavik Atlantic/South_Georgia
Atlantic/St_Helena Atlantic/Stanley      


Australia

Australia
Australia/ACT Australia/Adelaide Australia/Brisbane Australia/Broken_Hill Australia/Canberra
Australia/Currie Australia/Darwin Australia/Eucla Australia/Hobart Australia/LHI
Australia/Lindeman Australia/Lord_Howe Australia/Melbourne Australia/North Australia/NSW
Australia/Perth Australia/Queensland Australia/South Australia/Sydney Australia/Tasmania
Australia/Victoria Australia/West Australia/Yancowinna    


Europe

Europe
Europe/Amsterdam Europe/Andorra Europe/Athens Europe/Belfast Europe/Belgrade
Europe/Berlin Europe/Bratislava Europe/Brussels Europe/Bucharest Europe/Budapest
Europe/Chisinau Europe/Copenhagen Europe/Dublin Europe/Gibraltar Europe/Guernsey
Europe/Helsinki Europe/Isle_of_Man Europe/Istanbul Europe/Jersey Europe/Kaliningrad
Europe/Kiev Europe/Lisbon Europe/Ljubljana Europe/London Europe/Luxembourg
Europe/Madrid Europe/Malta Europe/Mariehamn Europe/Minsk Europe/Monaco
Europe/Moscow Europe/Nicosia Europe/Oslo Europe/Paris Europe/Podgorica
Europe/Prague Europe/Riga Europe/Rome Europe/Samara Europe/San_Marino
Europe/Sarajevo Europe/Simferopol Europe/Skopje Europe/Sofia Europe/Stockholm
Europe/Tallinn Europe/Tirane Europe/Tiraspol Europe/Uzhgorod Europe/Vaduz
Europe/Vatican Europe/Vienna Europe/Vilnius Europe/Volgograd Europe/Warsaw
Europe/Zagreb Europe/Zaporozhye Europe/Zurich    


Indian

Indian
Indian/Antananarivo Indian/Chagos Indian/Christmas Indian/Cocos Indian/Comoro
Indian/Kerguelen Indian/Mahe Indian/Maldives Indian/Mauritius Indian/Mayotte
Indian/Reunion        


Pacific

Pacific
Pacific/Apia Pacific/Auckland Pacific/Chatham Pacific/Easter Pacific/Efate
Pacific/Enderbury Pacific/Fakaofo Pacific/Fiji Pacific/Funafuti Pacific/Galapagos
Pacific/Gambier Pacific/Guadalcanal Pacific/Guam Pacific/Honolulu Pacific/Johnston
Pacific/Kiritimati Pacific/Kosrae Pacific/Kwajalein Pacific/Majuro Pacific/Marquesas
Pacific/Midway Pacific/Nauru Pacific/Niue Pacific/Norfolk Pacific/Noumea
Pacific/Pago_Pago Pacific/Palau Pacific/Pitcairn Pacific/Ponape Pacific/Port_Moresby
Pacific/Rarotonga Pacific/Saipan Pacific/Samoa Pacific/Tahiti Pacific/Tarawa
Pacific/Tongatapu Pacific/Truk Pacific/Wake Pacific/Wallis Pacific/Yap


Others

Others
Brazil/Acre Brazil/DeNoronha Brazil/East Brazil/West Canada/Atlantic
Canada/Central Canada/East-Saskatchewan Canada/Eastern Canada/Mountain Canada/Newfoundland
Canada/Pacific Canada/Saskatchewan Canada/Yukon CET Chile/Continental
Chile/EasterIsland CST6CDT Cuba EET Egypt
Eire EST EST5EDT Etc/GMT Etc/GMT+0
Etc/GMT+1 Etc/GMT+10 Etc/GMT+11 Etc/GMT+12 Etc/GMT+2
Etc/GMT+3 Etc/GMT+4 Etc/GMT+5 Etc/GMT+6 Etc/GMT+7
Etc/GMT+8 Etc/GMT+9 Etc/GMT-0 Etc/GMT-1 Etc/GMT-10
Etc/GMT-11 Etc/GMT-12 Etc/GMT-13 Etc/GMT-14 Etc/GMT-2
Etc/GMT-3 Etc/GMT-4 Etc/GMT-5 Etc/GMT-6 Etc/GMT-7
Etc/GMT-8 Etc/GMT-9 Etc/GMT0 Etc/Greenwich Etc/UCT
Etc/Universal Etc/UTC Etc/Zulu Factory GB
GB-Eire GMT GMT+0 GMT-0 GMT0
Greenwich Hongkong HST Iceland Iran
Israel Jamaica Japan Kwajalein Libya
MET Mexico/BajaNorte Mexico/BajaSur Mexico/General MST
MST7MDT Navajo NZ NZ-CHAT Poland
Portugal PRC PST8PDT ROC ROK
Singapore Turkey UCT Universal US/Alaska
US/Aleutian US/Arizona US/Central US/East-Indiana US/Eastern
US/Hawaii US/Indiana-Starke US/Michigan US/Mountain US/Pacific
US/Pacific-New US/Samoa UTC W-SU WET
Zulu        
Ostrzeżenie

Proszę nie używać żadnej ze stref czasowych podanych tutaj (za wyjątkiem UTC), istnieją one wyłącznie z powodu wstecznej kompatybilności.




The DateTime class

Wstęp

Representation of date and time.

Krótki opis klasy

DateTime
DateTime {
/* Constants */
const string DateTime::ATOM = Y-m-d\TH:i:sP ;
const string DateTime::COOKIE = l, d-M-y H:i:s T ;
const string DateTime::ISO8601 = Y-m-d\TH:i:sO ;
const string DateTime::RFC822 = D, d M y H:i:s O ;
const string DateTime::RFC850 = l, d-M-y H:i:s T ;
const string DateTime::RFC1036 = D, d M y H:i:s O ;
const string DateTime::RFC1123 = D, d M Y H:i:s O ;
const string DateTime::RFC2822 = D, d M Y H:i:s O ;
const string DateTime::RFC3339 = Y-m-d\TH:i:sP ;
const string DateTime::RSS = D, d M Y H:i:s O ;
const string DateTime::W3C = Y-m-d\TH:i:sP ;
/* Methods */
public DateTime add ( DateInterval $interval )
__construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
public static DateTime createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )
public DateInterval diff ( DateTime $datetime [, bool $absolute ] )
public string format ( string $format )
public static array getLastErrors ( void )
public int getOffset ( void )
public int getTimestamp ( void )
public DateTimeZone getTimezone ( void )
public DateTime modify ( string $modify )
public static DateTime __set_state ( array $array )
public DateTime setDate ( int $year , int $month , int $day )
public DateTime setISODate ( int $year , int $week [, int $day ] )
public DateTime setTime ( int $hour , int $minute [, int $second ] )
public DateTime setTimestamp ( int $unixtimestamp )
public DateTime setTimezone ( DateTimeZone $timezone )
public DateTime sub ( DateInterval $interval )
public DateTime __wakeup ( void )
}

Stałe predefiniowane

DateTime Node Types

DateTime::ATOM
DATE_ATOM
Atom (example: 2005-08-15T15:52:01+00:00)
DateTime::COOKIE
DATE_COOKIE
HTTP Cookies (example: Monday, 15-Aug-05 15:52:01 UTC)
DateTime::ISO8601
DATE_ISO8601
ISO-8601 (example: 2005-08-15T15:52:01+0000)
DateTime::RFC822
DATE_RFC822
RFC 822 (example: Mon, 15 Aug 05 15:52:01 +0000)
DateTime::RFC850
DATE_RFC850
RFC 850 (example: Monday, 15-Aug-05 15:52:01 UTC)
DateTime::RFC1036
DATE_RFC1036
RFC 1036 (example: Mon, 15 Aug 05 15:52:01 +0000)
DateTime::RFC1123
DATE_RFC1123
RFC 1123 (example: Mon, 15 Aug 2005 15:52:01 +0000)
DateTime::RFC2822
DATE_RFC2822
RFC 2822 (Mon, 15 Aug 2005 15:52:01 +0000)
DateTime::RFC3339
DATE_RFC3339
Same as DATE_ATOM (since PHP 5.1.3)
DateTime::RSS
DATE_RSS
RSS (Mon, 15 Aug 2005 15:52:01 +0000)
DateTime::W3C
DATE_W3C
World Wide Web Consortium (example: 2005-08-15T15:52:01+00:00)

DateTime::add

(PHP 5 >= 5.3.0)

DateTime::add Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object

Opis

public DateTime DateTime::add ( DateInterval $interval )
DateTime date_add ( DateTime $object , DateInterval $interval )

Adds the specified DateInterval object to the specified DateTime object.

Parametry

object

Tylko styl proceduralny: Obiekt DateTime zwracany przez date_create()

interval

A DateInterval object

Zwracane wartości

Returns the modified DateTime.

Przykłady

Przykład #1 date_add() example

<?php

$date 
= new DateTime("18-July-2008 16:30:30");
echo 
$date->format("d-m-Y H:i:s").'<br />';

date_add($date, new DateInterval("P5D"));
echo 
'<br />'.$date->format("d-m-Y").' : 5 Days';

date_add($date, new DateInterval("P5M"));
echo 
'<br />'.$date->format("d-m-Y").' : 5 Months';

date_add($date, new DateInterval("P5Y"));
echo 
'<br />'.$date->format("d-m-Y").' : 5 Years';

date_add($date, new DateInterval("P5Y5M5D"));
echo 
'<br />'.$date->format("d-m-Y").' : 5 Days, 5 Months, 5 Years';

date_add($date, new DateInterval("P5YT5H"));
echo 
'<br />'.$date->format("d-m-Y H:i:s").' : 5 Years, 5 Hours';

?>

Zobacz też:

  • DateTime::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
  • DateTime::diff() - Returns the difference between two DateTime objects



DateTime::__construct

(PHP 5 >= 5.2.0)

DateTime::__constructReturns new DateTime object

Opis

DateTime::__construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

Returns new DateTime object.

Parametry

time

String in a format accepted by strtotime(), defaults to "now".

timezone

Time zone of the time.

Błędy/Wyjątki

Emits Exception in case of an error.

Przykłady

Przykład #1 DateTime::__construct() example

<?php
date_default_timezone_set
('Europe/London');

$datetime = new DateTime('2008-08-03 14:52:10');
echo 
$datetime->format(DATE_ATOM);
?>



DateTime::createFromFormat

(PHP 5 >= 5.3.0)

DateTime::createFromFormatReturns new DateTime object formatted according to the specified format

Opis

public static DateTime DateTime::createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )

Returns new DateTime object formatted according to the specified format.

Parametry

format

Format accepted by date().

If format does not contain the character ! then portions of the date/time value specified in format but not specified in time will be set to the current system time.

If format contains the character !, then portions of the generated time specified to the left-hand side of the ! in format will be set to corresponding values from the Unix epoch.

If the first character of format is !, then all portions of the date/time value generated which are not specified in time will be initialized to corresponding values from the Unix epoch.

The Unix epoch is 1970-01-01 00:00:00 UTC.

time

String representing the time.

timezone

Time zone.

Zwracane wartości

Returns new DateTime instance.

Przykłady

Przykład #1 Using ! to reset default date/time values

<?php
echo "Current system date and time: " date('Y-m-d H:i:s') . "\n";

$format 'Y-m-d';
$dt DateTime::createFromFormat($format'2009-02-03');
echo 
"Format: $format; " $dt->date "\n";

$format 'Y-m-d H:i:s';
$dt DateTime::createFromFormat($format'2009-02-03 15:16:17');
echo 
"Format: $format; " $dt->date "\n";

$format 'Y-m-!d H:i:s';
$dt DateTime::createFromFormat($format'2009-02-03 15:16:17');
echo 
"Format: $format; " $dt->date "\n";

$format '!Y-m-d';
$dt DateTime::createFromFormat($format'2009-02-03');
echo 
"Format: $format; " $dt->date "\n";
?>

The above example will output something like the following (taking into account the current system time):

Current system date and time: 2009-09-13 01:04:03
Format: Y-m-d; 2009-02-03 01:04:03
Format: Y-m-d H:i:s; 2009-02-03 15:16:17
Format: Y-m-!d H:i:s; 1970-01-03 15:16:17
Format: !Y-m-d; 2009-02-03 00:00:00



DateTime::diff

(PHP 5 >= 5.3.0)

DateTime::diffReturns the difference between two DateTime objects

Opis

public DateInterval DateTime::diff ( DateTime $datetime [, bool $absolute ] )

Returns the difference between two DateTime objects.

Parametry

datetime

The date to compare to.

absolute

Whether to return absolute difference. Defaults to FALSE.

Zwracane wartości

The difference between two dates.



DateTime::format

(PHP 5 >= 5.2.0)

DateTime::formatReturns date formatted according to given format

Opis

public string DateTime::format ( string $format )
string date_format ( DateTime $object , string $format )

Parametry

object

Tylko styl proceduralny: Obiekt DateTime zwracany przez date_create()

format

Format accepted by date().

Zwracane wartości

Returns formatted date on success or FALSE on failure.

Przykłady

Przykład #1 Displaying the date and time using the procedural form

<?php
date_default_timezone_set
('Europe/London');

$datetime date_create('2008-08-03 14:52:10');
echo 
date_format($datetime'jS, F Y') . "\n";
echo 
date_format($datetimeDATE_ATOM);
?>

Przykład #2 Displaying the date and time using the object oriented form

<?php
date_default_timezone_set
('Europe/London');

$datetime = new DateTime('2008-08-03 14:52:10');
echo 
$datetime->format('jS, F Y') . "\n";
echo 
$datetime->format(DATE_ATOM);
?>
?>

Powyższy przykład wyświetli:

3rd, August 2008
2008-08-03T14:52:10+01:00

Zobacz też:

  • date() - Formatuje lokalny czas/datę



DateTime::getLastErrors

(PHP 5 >= 5.3.0)

DateTime::getLastErrorsReturns the warnings and errors

Opis

public static array DateTime::getLastErrors ( void )

Returns the warnings and errors found while parsing a date/time string.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns array containing info about warnings and errors.

Przykłady

Przykład #1 DateTime::getLastErrors() example

<?php
$date 
date_create('asdfasdf');
print_r(DateTime::getLastErrors());
?>

Powyższy przykład wyświetli:

Array
(
    [warning_count] => 1
    [warnings] => Array
        (
            [6] => Double timezone specification
        )

    [error_count] => 1
    [errors] => Array
        (
            [0] => The timezone could not be found in the database
        )

)



DateTime::getOffset

(PHP 5 >= 5.2.0)

DateTime::getOffsetReturns the timezone offset

Opis

public int DateTime::getOffset ( void )
int date_offset_get ( DateTime $object )

Parametry

object

Tylko styl proceduralny: Obiekt DateTime zwracany przez date_create()

Zwracane wartości

Returns offset in seconds with respect to daylight saving time on success or FALSE on failure.

Przykłady

Przykład #1 Comparing offsets between Summer and Winter

<?php
date_default_timezone_set
('Europe/London');

$winter = new DateTime('2008-12-25 14:25:41');
$summer = new DateTime('2008-07-14 14:25:41');

echo 
$winter->getOffset(); // Winter offset: 0
echo $summer->getOffset(); // Summer offset: 3600 = 1 hour
?>



DateTime::getTimestamp

(PHP 5 >= 5.3.0)

DateTime::getTimestampGets the Unix timestamp

Opis

public int DateTime::getTimestamp ( void )

Gets the Unix timestamp.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns Unix timestamp representing the date.

Zobacz też:



DateTime::getTimezone

(PHP 5 >= 5.2.0)

DateTime::getTimezoneReturn time zone relative to given DateTime

Opis

public DateTimeZone DateTime::getTimezone ( void )

Parametry

object

Tylko styl proceduralny: Obiekt DateTime zwracany przez date_create()

Zwracane wartości

Returns DateTimeZone object on success or FALSE on failure.

Przykłady

Przykład #1 Setting and getting DateTimeZone objects

<?php
date_default_timezone_set
('Europe/London');

$datetime = new DateTime('2008-08-03 12:35:23');
echo 
$datetime->getTimezone()->getName() . "\n";

$datetime = new DateTime('2008-08-03 12:35:23');
$la_time = new DateTimeZone('America/Los_Angeles');
$datetime->setTimezone($la_time);
echo 
$datetime->getTimezone()->getName();
?>

Powyższy przykład wyświetli:

Europe/London
America/Los_Angeles

Zobacz też:



DateTime::modify

(PHP 5 >= 5.2.0)

DateTime::modifyAlters the timestamp

Opis

public DateTime DateTime::modify ( string $modify )
DateTime date_modify ( DateTime $object , string $modify )

Alter the timestamp of a DateTime object by incrementing or decrementing in a format accepted by strtotime().

Parametry

object

Tylko styl proceduralny: Obiekt DateTime zwracany przez date_create()

modify

String in a relative format accepted by strtotime().

Zwracane wartości

Returns the modified DateTime.

Rejestr zmian

Wersja Opis
5.3.0Zmieniono zwracaną wartość z NULL na DateTime.

Przykłady

Przykład #1 A date_modify() example

<?php
$date 
= new DateTime("2006-12-12");
$date->modify("+1 day");
echo 
$date->format("Y-m-d");
?>

Powyższy przykład wyświetli:

2006-12-13

Zobacz też:

  • strtotime() - Parsuje większość angielskich tekstowych opisów daty i czasu do uniksowego znacznika czasu



DateTime::__set_state

(PHP 5 >= 5.2.0)

DateTime::__set_stateThe __set_state handler

Opis

public static DateTime DateTime::__set_state ( array $array )

The __set_state handler.

Parametry

array

Initialization array.

Zwracane wartości

Returns a new instance of a DateTime object.



DateTime::setDate

(PHP 5 >= 5.2.0)

DateTime::setDateSets the date

Opis

public DateTime DateTime::setDate ( int $year , int $month , int $day )
DateTime date_date_set ( DateTime $object , int $year , int $month , int $day )

Resets the current date of the DateTime object to a different date.

Parametry

object

Tylko styl proceduralny: Obiekt DateTime zwracany przez date_create()

year

Year of the date.

month

Month of the date.

day

Day of the date.

Zwracane wartości

Returns the modified DateTime.

Rejestr zmian

Wersja Opis
5.3.0Zmieniono zwracaną wartość z NULL na DateTime.

Przykłady

Przykład #1 Object oriented example usage

<?php
date_default_timezone_set
('Europe/London');

$datetime = new DateTime('2008-08-03 14:52:10');
$datetime->setDate(20081012);

echo 
$datetime->format(DATE_RFC2822);
?>

Przykład #2 Procedural example usage

<?php
date_default_timezone_set
('Europe/London');

$datetime date_create('2008-08-03 14:52:10');
date_date_set($datetime20081012);

echo 
date_format($datetimeDATE_RFC2822);
?>

Powyższy przykład wyświetli:

Sun, 12 Oct 2008 14:52:10 +0100

Zobacz też:



DateTime::setISODate

(PHP 5 >= 5.2.0)

DateTime::setISODateSets the ISO date

Opis

public DateTime DateTime::setISODate ( int $year , int $week [, int $day ] )
DateTime date_isodate_set ( DateTime $object , int $year , int $week [, int $day ] )

Set a date according to the ISO 8601 standard - using weeks and day offsets rather than specific dates.

Parametry

object

Tylko styl proceduralny: Obiekt DateTime zwracany przez date_create()

year

Year of the date.

week

Week of the date.

day

Offset from the first day of the week.

Zwracane wartości

Returns the modified DateTime.

Rejestr zmian

Wersja Opis
5.3.0Zmieniono zwracaną wartość z NULL na DateTime.

Przykłady

Przykład #1 Finding the date from a week number and day offset

<?php
date_default_timezone_set
('Europe/London');

$datetime = new DateTime();

// Offset from start of week 2 (7) = 5
$datetime->setISODate(200825); // Day 5 of week 2 of 2008 is the 11th of January. 

// Offset from start of week 2 (7) = 10
$datetime->setISODate(2008210); // Day 10 of week 2 of 2008 is the 16th of January.
?>

Przykład #2 Finding the month a week is in

<?php
date_default_timezone_set
('Europe/London');

$datetime date_create();
date_isodate_set($datetime20086); // Week 6 of 2008 is in February.
?>

Zobacz też:



DateTime::setTime

(PHP 5 >= 5.2.0)

DateTime::setTimeSets the time

Opis

public DateTime DateTime::setTime ( int $hour , int $minute [, int $second ] )
DateTime date_time_set ( DateTime $object , int $hour , int $minute [, int $second ] )

Resets the current time of the DateTime object to a different time.

Parametry

object

Tylko styl proceduralny: Obiekt DateTime zwracany przez date_create()

hour

Hour of the time.

minute

Minute of the time.

second

Second of the time.

Zwracane wartości

Returns the modified DateTime.

Rejestr zmian

Wersja Opis
5.3.0Zmieniono zwracaną wartość z NULL na DateTime.

Przykłady

Przykład #1 Changing the time of a DateTime object

<?php
date_default_timezone_set
('Europe/London');

$datetime = new DateTime('2008-08-03 12:35:23');
echo 
$datetime->format('Y-m-d H:i:s') . "\n";

$datetime->setTime(145524);
echo 
$datetime->format('Y-m-d H:i:s') . "\n";

// Warning: Does not increment the hour!
// This is because the hour has been set (14) - see date_modify()
$datetime->setTime($datetime->format('H'), $datetime->format('n') + 6);
echo 
$datetime->format('Y-m-d H:i:s') . "\n";

// *Does* increment the day, because the day has not been set
$datetime->setTime($datetime->format('H') + 12$datetime->format('n'));
echo 
$datetime->format('Y-m-d H:i:s') . "\n";
?>

Powyższy przykład wyświetli:

2008-08-03 12:35:23
2008-08-03 14:55:24
2008-08-03 14:14:00
2008-08-04 02:08:00

Zobacz też:



DateTime::setTimestamp

(PHP 5 >= 5.3.0)

DateTime::setTimestampSets the date and time based on an Unix timestamp

Opis

public DateTime DateTime::setTimestamp ( int $unixtimestamp )

Sets the date and time based on an Unix timestamp.

Parametry

unixtimestamp

Unix timestamp representing the date.

Zwracane wartości

Returns the modified DateTime.

Zobacz też:



DateTime::setTimezone

(PHP 5 >= 5.2.0)

DateTime::setTimezoneSets the time zone for the DateTime object

Opis

public DateTime DateTime::setTimezone ( DateTimeZone $timezone )

Parametry

object

Tylko styl proceduralny: Obiekt DateTime zwracany przez date_create()

timezone

Desired time zone.

Zwracane wartości

Returns the modified DateTime.

Rejestr zmian

Wersja Opis
5.3.0 Changed the return value from NULL to DateTime.

Przykłady

Przykład #1 Setting and getting DateTimeZone objects

<?php
date_default_timezone_set
('Europe/London');

$datetime = new DateTime('2008-08-03 12:35:23');
echo 
$datetime->getTimezone()->getName() . "\n";

$datetime = new DateTime('2008-08-03 12:35:23');
$la_time = new DateTimeZone('America/Los_Angeles');
$datetime->setTimezone($la_time);
echo 
$datetime->getTimezone()->getName();
?>

Powyższy przykład wyświetli:

Europe/London
America/Los_Angeles

Zobacz też:



DateTime::sub

(PHP 5 >= 5.3.0)

DateTime::sub Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

Opis

public DateTime DateTime::sub ( DateInterval $interval )
DateTime date_sub ( DateTime $object , DateInterval $interval )

Subtracts the specified DateInterval object from the specified DateTime object.

Parametry

object

Tylko styl proceduralny: Obiekt DateTime zwracany przez date_create()

interval

A DateInterval object

Zwracane wartości

Returns the modified DateTime.

Przykłady

Przykład #1 date_sub() example

<?php

$date 
= new DateTime("18-July-2008 16:30:30");
echo 
$date->format("d-m-Y H:i:s").'<br />';

date_sub($date, new DateInterval("P5D"));
echo 
'<br />'.$date->format("d-m-Y").' : 5 Days';

date_sub($date, new DateInterval("P5M"));
echo 
'<br />'.$date->format("d-m-Y").' : 5 Months';

date_sub($date, new DateInterval("P5Y"));
echo 
'<br />'.$date->format("d-m-Y").' : 5 Years';

date_sub($date, new DateInterval("P5Y5M5D"));
echo 
'<br />'.$date->format("d-m-Y").' : 5 Days, 5 Months, 5 Years';

date_sub($date, new DateInterval("P5YT5H"));
echo 
'<br />'.$date->format("d-m-Y H:i:s").' : 5 Years, 5 Hours';

?>

Zobacz też:

  • DateTime::add() - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
  • DateTime::diff() - Returns the difference between two DateTime objects



DateTime::__wakeup

(PHP 5 >= 5.2.0)

DateTime::__wakeupThe __wakeup handler

Opis

public DateTime DateTime::__wakeup ( void )

The __wakeup handler.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Initializes a DateTime object.


Spis treści



The DateTimeZone class

Wstęp

Representation of time zone.

Krótki opis klasy

DateTimeZone
DateTimeZone {
/* Constants */
const integer DateTimeZone::AFRICA = 1 ;
const integer DateTimeZone::AMERICA = 2 ;
const integer DateTimeZone::ANTARCTICA = 4 ;
const integer DateTimeZone::ARCTIC = 8 ;
const integer DateTimeZone::ASIA = 16 ;
const integer DateTimeZone::ATLANTIC = 32 ;
const integer DateTimeZone::AUSTRALIA = 64 ;
const integer DateTimeZone::EUROPE = 128 ;
const integer DateTimeZone::INDIAN = 256 ;
const integer DateTimeZone::PACIFIC = 512 ;
const integer DateTimeZone::UTC = 1024 ;
const integer DateTimeZone::ALL = 2047 ;
const integer DateTimeZone::ALL_WITH_BC = 4095 ;
const integer DateTimeZone::PER_COUNTRY = 4096 ;
/* Methods */
__construct ( string $timezone )
public array getLocation ( void )
public string getName ( void )
int getOffset ( DateTime $datetime )
array getTransitions ([ int $timestamp_begin [, int $timestamp_end ]] )
staticarray listAbbreviations ( void )
staticarray listIdentifiers ([ int $what = DateTime::ALL [, string $country = NULL ]] )
}

Stałe predefiniowane

DateTimeZone Node Types

DateTimeZone::AFRICA

Africa time zones.

DateTimeZone::AMERICA

America time zones.

DateTimeZone::ANTARCTICA

Antarctica time zones.

DateTimeZone::ARCTIC

Artic time zones.

DateTimeZone::ASIA

Asia time zones.

DateTimeZone::ATLANTIC

Atlantic time zones.

DateTimeZone::AUSTRALIA

Australia time zones.

DateTimeZone::EUROPE

Europe time zones.

DateTimeZone::INDIAN

Indian time zones.

DateTimeZone::PACIFIC

Pacific time zones.

DateTimeZone::UTC

UTC time zones.

DateTimeZone::ALL

All time zones.

DateTimeZone::ALL_WITH_BC

All time zones including backwards compatible.

DateTimeZone::PER_COUNTRY

Time zones per country.


DateTimeZone::__construct

(PHP 5 >= 5.2.0)

DateTimeZone::__constructCreates new DateTimeZone object

Opis

DateTimeZone::__construct ( string $timezone )

Creates new DateTimeZone object.

Parametry

timezone

One of timezones.

Zwracane wartości

Returns DateTimeZone on success.

Błędy/Wyjątki

This method throws Exception if the timezone supplied is not recognised as a valid timezone.

Przykłady

Przykład #1 Catching errors when instantiating DateTimeZone

<?php
// Error handling by catching exceptions
$timezones = array('Europe/London''Mars/Phobos''Jupiter/Europa');

foreach (
$timezones as $tz) {
    try {
        
$mars = new DateTimeZone($tz);
    } catch(
Exception $e) {
        echo 
$e->getMessage() . '<br />';
    }
}
?>

Powyższy przykład wyświetli:

DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Mars/Phobos)
DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Jupiter/Europa)



DateTimeZone::getLocation

(PHP 5 >= 5.3.0)

DateTimeZone::getLocationReturns location information for a timezone

Opis

public array DateTimeZone::getLocation ( void )

Returns location information for a timezone, including country code, latitude/longitude and comments.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Array containing location information about timezone.

Przykłady

Przykład #1 DateTimeZone::getLocation() example

<?php
$tz 
= new DateTimeZone("Europe/Prague");
print_r($tz->getLocation());
?>

Powyższy przykład wyświetli:

Array
(
    [country_code] => CZ
    [latitude] => 50.08333
    [longitude] => 14.43333
    [comments] => 
)



DateTimeZone::getName

(PHP 5 >= 5.2.0)

DateTimeZone::getNameReturns the name of the timezone

Opis

public string DateTimeZone::getName ( void )

Returns the name of the timezone.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

One of timezones.



DateTimeZone::getOffset

(PHP 5 >= 5.2.0)

DateTimeZone::getOffsetReturns the timezone offset from GMT

Opis

int DateTimeZone::getOffset ( DateTime $datetime )
int timezone_offset_get ( DateTimeZone $object , DateTime $datetime )

This function returns the offset to GMT for the date/time specified in the datetime parameter. The GMT offset is calculated with the timezone information contained in the DateTimeZone object being used.

Parametry

object

Tylko styl proceduralny: Obiekt DateTimeZone zwracany przez timezone_open()

datetime

DateTime that contains the date/time to compute the offset from.

Zwracane wartości

Returns time zone offset in seconds on success or FALSE on failure.

Przykłady

Przykład #1 DateTimeZone::getOffset() examples

<?php
// Create two timezone objects, one for Taipei (Taiwan) and one for
// Tokyo (Japan)
$dateTimeZoneTaipei = new DateTimeZone("Asia/Taipei");
$dateTimeZoneJapan = new DateTimeZone("Asia/Tokyo");

// Create two DateTime objects that will contain the same Unix timestamp, but
// have different timezones attached to them.
$dateTimeTaipei = new DateTime("now"$dateTimeZoneTaipei);
$dateTimeJapan = new DateTime("now"$dateTimeZoneJapan);

// Calculate the GMT offset for the date/time contained in the $dateTimeTaipei
// object, but using the timezone rules as defined for Tokyo
// ($dateTimeZoneJapan).
$timeOffset $dateTimeZoneJapan->getOffset($dateTimeTaipei);

// Should show int(32400) (for dates after Sat Sep 8 01:00:00 1951 JST).
var_dump($timeOffset);
?>



DateTimeZone::getTransitions

(PHP 5 >= 5.2.0)

DateTimeZone::getTransitionsReturns all transitions for the timezone

Opis

array DateTimeZone::getTransitions ([ int $timestamp_begin [, int $timestamp_end ]] )
array timezone_transitions_get ( DateTimeZone $object [, int $timestamp_begin [, int $timestamp_end ]] )

Parametry

object

Tylko styl proceduralny: Obiekt DateTimeZone zwracany przez timezone_open()

timestamp_begin

Begin timestamp.

timestamp_end

End timestamp.

Zwracane wartości

Returns numerically indexed array containing associative array with all transitions on success or FALSE on failure.

Rejestr zmian

Wersja Opis
5.3.0 The optional timestamp_begin and timestamp_end were added.

Przykłady

Przykład #1 A timezone_transitions_get() example

<?php
$timezone 
= new DateTimeZone("CET");
print_r(reset($timezone->getTransitions()));
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [ts] => -1693706400
    [time] => 1916-04-30T22:00:00+0000
    [offset] => 7200
    [isdst] => 1
    [abbr] => CEST
)



DateTimeZone::listAbbreviations

(PHP 5 >= 5.2.0)

DateTimeZone::listAbbreviationsReturns associative array containing dst, offset and the timezone name

Opis

staticarray DateTimeZone::listAbbreviations ( void )

Zwracane wartości

Returns array on success or FALSE on failure.

Przykłady

Przykład #1 A timezone_abbreviations_list() example

<?php
$timezone_abbreviations 
DateTimeZone::listAbbreviations();
print_r($timezone_abbreviations["acst"]);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [0] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => America/Porto_Acre
        )

    [1] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => America/Eirunepe
        )

    [2] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => America/Rio_Branco
        )

    [3] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => Brazil/Acre
        )

)

Zobacz też:



DateTimeZone::listIdentifiers

(PHP 5 >= 5.2.0)

DateTimeZone::listIdentifiersReturns numerically index array with all timezone identifiers

Opis

staticarray DateTimeZone::listIdentifiers ([ int $what = DateTime::ALL [, string $country = NULL ]] )
array timezone_identifiers_list ([ int $what = DateTime::ALL [, string $country = NULL ]] )

Parametry

what

One of DateTimeZone class constants, defaults to DateTimeZone::ALL.

country

A two-letter ISO 3166-1 compatible country code.

Informacja: This option is only used when what is set to DateTimeZone::PER_COUNTRY.

Zwracane wartości

Returns array on success or FALSE on failure.

Rejestr zmian

Wersja Opis
5.3.0 Added the optional what and country parameters.

Przykłady

Przykład #1 A timezone_identifiers_list() example

<?php
$timezone_identifiers 
DateTimeZone::listIdentifiers();
for (
$i=0$i 5$i++) {
    echo 
"$timezone_identifiers[$i]\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmera

Zobacz też:


Spis treści



The DateInterval class

Wstęp

Representation of date interval.

Krótki opis klasy

DateInterval
DateInterval {
/* Methods */
__construct ( string $interval_spec )
public static DateInterval createFromDateString ( string $time )
public string format ( string $format )
}

DateInterval::__construct

(PHP 5 >= 5.3.0)

DateInterval::__constructCreates new DateInterval object

Opis

DateInterval::__construct ( string $interval_spec )

Creates new DateInterval object.

Parametry

interval_spec

Interval specification.

The format starts with the letter P, for "period." Each duration period is represented by an integer value followed by a period designator. If the duration contains time elements, that portion of the specification is preceded by the letter T.

interval_spec Period Designators
Period Designator Description
Y years
M months
D days
W weeks. These get converted into days, so can not be combined with D.
H hours
M minutes
S seconds

Here are some simple examples. Two days is P2D. Two seconds is PT2S. Six years and five minutes is P6YT5M.

Informacja: The unit types must be entered from the largest scale unit on the left to the smallest scale unit on the right. So years before months, months before days, days before minutes, etc. Thus one year and four days must be represented as P1Y4D, not P4D1Y.

The specification can also be represented as a date time. A sample of one year and four days would be P0001-00-04T00:00:00. But the values in this format can not exceed a given period's roll-over-point (e.g. 25 hours is invalid).

These formats are based on the » ISO 8601 duration specification.

Przykłady

Przykład #1 DateInterval example

<?php

$interval 
= new DateInterval('P2Y4DT6H8M');
print_r($interval);

?>

Powyższy przykład wyświetli:

DateInterval Object
(
    [y] => 2
    [m] => 0
    [d] => 4
    [h] => 6
    [i] => 8
    [s] => 0
    [invert] => 0
    [days] => 0
)

Zobacz też:



DateInterval::createFromDateString

(PHP 5 >= 5.3.0)

DateInterval::createFromDateStringSets up a DateInterval from the relative parts of the string

Opis

public static DateInterval DateInterval::createFromDateString ( string $time )

Uses the normal date parsers and sets up a DateInterval from the relative parts of the parsed string.

Parametry

time

Date with relative parts.

Zwracane wartości

Returns new DateInterval instance if success.



DateInterval::format

(PHP 5 >= 5.3.0)

DateInterval::formatFormats the interval

Opis

public string DateInterval::format ( string $format )

Formats the interval.

Parametry

format

The following characters are recognized in the format parameter string.
format character Description Example values
Y Years, numeric, at least 2 digits with leading 0 01, 03
y Years, numeric 1, 3
M Months, numeric, at least 2 digits with leading 0 01, 03, 12
m Months, numeric 01, 03, 12
D Days, numeric, at least 2 digits with leading 0 01, 03, 31
d Days, numeric 1, 3, 31
a Total amount of days 4, 18, 8123
H Hours, numeric, at least 2 digits with leading 0 01, 03, 23
h Hours, numeric 1, 3, 23
I Minutes, numeric, at least 2 digits with leading 0 01, 03, 59
i Minutes, numeric 1, 3, 59
S Seconds, numeric, at least 2 digits with leading 0 01, 03, 57
s Seconds, numeric 1, 3, 57
R Sign "-" when negative, "+" when positive -, +
r Sign "-" when negative, empty when positive -,
% Literal % %

Informacja: The prefix % is required in order for the format specifiers to work correctly.

Zwracane wartości

Returns the formatted interval.


Spis treści



The DatePeriod class

Wstęp

Representation of date period.

Krótki opis klasy

DatePeriod
DatePeriod implements Traversable {
/* Constants */
const integer DatePeriod::EXCLUDE_START_DATE = 1 ;
/* Methods */
__construct ( DateTime $start , DateInterval $interval , int $recurrences [, int $options ] )
}

Stałe predefiniowane

DatePeriod Node Types

DatePeriod::EXCLUDE_START_DATE

Exclude start date, used in DatePeriod::__construct().


DatePeriod::__construct

(PHP 5 >= 5.3.0)

DatePeriod::__constructCreates new DatePeriod object

Opis

DatePeriod::__construct ( DateTime $start , DateInterval $interval , int $recurrences [, int $options ] )
DatePeriod::__construct ( DateTime $start , DateInterval $interval , DateTime $end [, int $options ] )
DatePeriod::__construct ( string $isostr [, int $options ] )

Creates new DatePeriod object.

Parametry

start

Start date.

interval

Interval.

recurrences

Number of recurrences.

end

End date.

isostr

String containing the ISO interval.

options

Can be set to DatePeriod::EXCLUDE_START_DATE.


Spis treści



Funkcje daty i czasu


checkdate

(PHP 4, PHP 5)

checkdateWaliduje datę gregoriańską

Opis

bool checkdate ( int $miesiąc , int $dzień , int $rok )

Sprawdza prawdziwość daty podanej jako argument. Data jest uznana za prawidłową, jeśli wszystkie dane parametry są prawidłowe.

Parametry

miesiąc

Miesiąc zawiera się w przedziale od 1 do 12 włącznie.

dzień

Dzień wewnątrz przedziału dozwolonych numerów dni dla danego parametru miesiąc . Każdy rok przestępny jest brany pod uwagę.

rok

Rok zawiera się w przedziale pomiędzy 1 i 32767 włącznie.

Zwracane wartości

Zwraca TRUE jeśli dana data jest poprawna; w przeciwnym razie zwraca FALSE.

Przykłady

Przykład #1 checkdate() - przykład

<?php
var_dump
(checkdate(12312000));
var_dump(checkdate(2292001));
?>

Powyższy przykład wyświetli:

bool(true)
bool(false)

Zobacz też:

  • mktime() - Oblicza uniksowy znacznik czasu dla podanej daty
  • strtotime() - Parsuje większość angielskich tekstowych opisów daty i czasu do uniksowego znacznika czasu



date_add

(PHP 5 >= 5.3.0)

date_addAlias dla DateTime::add

Opis

Ta funkcja jest aliasem dla: DateTime::add



date_create_from_format

(PHP 5 >= 5.3.0)

date_create_from_formatAlias dla DateTime::createFromFormat

Opis

Ta funkcja jest aliasem dla: DateTime::createFromFormat



date_create

(PHP 5 >= 5.2.0)

date_createReturns new DateTime object

Opis

DateTime date_create ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

Parametry

time

String in a format accepted by strtotime(), defaults to "now".

timezone

Time zone of the time.

Zwracane wartości

Returns DateTime object on success or FALSE on failure.

Przykłady

Przykład #1 date_create() example

<?php
date_default_timezone_set
('Europe/London');

$datetime date_create('2008-08-03 14:52:10');
echo 
date_format($datetimeDATE_ATOM);
?>

Powyższy przykład wyświetli:

2008-08-03T14:52:10+01:00



date_date_set

(PHP 5 >= 5.2.0)

date_date_setAlias dla DateTime::setDate

Opis

Ta funkcja jest aliasem dla: DateTime::setDate



date_default_timezone_get

(PHP 5 >= 5.1.0)

date_default_timezone_get Gets the default timezone used by all date/time functions in a script

Opis

string date_default_timezone_get ( void )

In order of preference, this function returns the default timezone by:

  • Reading the timezone set using the date_default_timezone_set() function (if any)

  • Reading the TZ environment variable (if non empty)

  • Reading the value of the date.timezone ini option (if set)

  • Querying the host operating system (if supported and allowed by the OS)

If none of the above succeed, date_default_timezone_get will return a default timezone of UTC.

Zwracane wartości

Returns a string.

Przykłady

Przykład #1 Getting the default timezone

<?php
date_default_timezone_set
('Europe/London');

if (
date_default_timezone_get()) {
    echo 
'date_default_timezone_set: ' date_default_timezone_get() . '<br />';
}

if (
ini_get('date.timezone')) {
    echo 
'date.timezone: ' ini_get('date.timezone');
}

?>

Powyższy przykład wyświetli coś podobnego do:

date_default_timezone_set: Europe/London
date.timezone: Europe/London

Przykład #2 Getting the abbreviation of a timezone

<?php
date_default_timezone_set
('America/Los_Angeles');
echo 
date_default_timezone_get() . ' => ' date('e') . ' => ' date('T');
?>

Powyższy przykład wyświetli:

America/Los_Angeles => America/Los_Angeles => PST

Zobacz też:



date_default_timezone_set

(PHP 5 >= 5.1.0)

date_default_timezone_set Sets the default timezone used by all date/time functions in a script

Opis

bool date_default_timezone_set ( string $timezone_identifier )

date_default_timezone_set() sets the default timezone used by all date/time functions.

Informacja: Since PHP 5.1.0 (when the date/time functions were rewritten), every call to a date/time function will generate a E_NOTICE if the timezone isn't valid, and/or a E_WARNING message if using the system settings or the TZ environment variable.

Instead of using this function to set the default timezone in your script, you can also use the INI setting date.timezone to set the default timezone.

Parametry

timezone_identifier

The timezone identifier, like UTC or Europe/Lisbon. The list of valid identifiers is available in the Lista obsługiwanych stref czasowych.

Zwracane wartości

This function returns FALSE if the timezone_identifier isn't valid, or TRUE otherwise.

Przykłady

Przykład #1 Getting the default timezone

<?php
date_default_timezone_set
('America/Los_Angeles');

$script_tz date_default_timezone_get();

if (
strcmp($script_tzini_get('date.timezone'))){
    echo 
'Script timezone differs from ini-set timezone.';
} else {
    echo 
'Script timezone and ini-set timezone match.';
}
?>

Rejestr zmian

Wersja Opis
5.3.0 Now throws E_WARNING rather then E_STRICT.
5.1.2 The function started to validate the timezone_identifier parameter.

Zobacz też:



date_diff

(PHP 5 >= 5.3.0)

date_diffAlias dla DateTime::diff

Opis

Ta funkcja jest aliasem dla: DateTime::diff



date_format

(PHP 5 >= 5.2.0)

date_formatAlias dla DateTime::format

Opis

Ta funkcja jest aliasem dla: DateTime::format



date_get_last_errors

(PHP 5 >= 5.3.0)

date_get_last_errorsAlias dla DateTime::getLastErrors

Opis

Ta funkcja jest aliasem dla: DateTime::getLastErrors



date_interval_create_from_date_string

(PHP 5 >= 5.3.0)

date_interval_create_from_date_stringAlias dla DateInterval::createFromDateString

Opis

Ta funkcja jest aliasem dla: DateInterval::createFromDateString



date_interval_format

(PHP 5 >= 5.3.0)

date_interval_formatAlias dla DateInterval::format

Opis

Ta funkcja jest aliasem dla: DateInterval::format



date_isodate_set

(PHP 5 >= 5.2.0)

date_isodate_setAlias dla DateTime::setISODate

Opis

Ta funkcja jest aliasem dla: DateTime::setISODate



date_modify

(PHP 5 >= 5.2.0)

date_modifyAlias dla DateTime::modify

Opis

Ta funkcja jest aliasem dla: DateTime::modify



date_offset_get

(PHP 5 >= 5.2.0)

date_offset_getAlias dla DateTime::getOffset

Opis

Ta funkcja jest aliasem dla: DateTime::getOffset



date_parse_from_format

(PHP 5 >= 5.3.0)

date_parse_from_formatGet info about given date

Opis

array date_parse_from_format ( string $format , string $date )

Returns associative array with detailed info about given date.

Parametry

format

Format accepted by date() with some extras.

date

String representing the date.

Zwracane wartości

Returns associative array with detailed info about given date.

Przykłady

Przykład #1 date_parse_from_format() example

<?php
$date 
"6.1.2009 13:00+01:00";
print_r(date_parse_from_format("j.n.Y H:iP"$date));
?>

Powyższy przykład wyświetli:

Array
(
    [year] => 2009
    [month] => 1
    [day] => 6
    [hour] => 13
    [minute] => 0
    [second] => 0
    [fraction] => 
    [warning_count] => 0
    [warnings] => Array
        (
        )

    [error_count] => 0
    [errors] => Array
        (
        )

    [is_localtime] => 1
    [zone_type] => 1
    [zone] => -60
    [is_dst] => 
)



date_parse

(PHP 5 >= 5.2.0)

date_parseReturns associative array with detailed info about given date

Opis

array date_parse ( string $date )

Parametry

date

Date in format accepted by strtotime().

Zwracane wartości

Returns array with information about the parsed date on success or FALSE on failure.

Błędy/Wyjątki

In case the date format has an error, the element 'errors' will contains the error messages.

Przykłady

Przykład #1 A date_parse() example

<?php
print_r
(date_parse("2006-12-12 10:00:00.5"));
?>

Powyższy przykład wyświetli:

Array
(
    [year] => 2006
    [month] => 12
    [day] => 12
    [hour] => 10
    [minute] => 0
    [second] => 0
    [fraction] => 0.5
    [warning_count] => 0
    [warnings] => Array()
    [error_count] => 0
    [errors] => Array()
    [is_localtime] => 
)

Zobacz też:

  • getdate() - Pobiera informację o dacie/czasie



date_sub

(PHP 5 >= 5.3.0)

date_subAlias dla DateTime::sub

Opis

Ta funkcja jest aliasem dla: DateTime::sub



date_sun_info

(PHP 5 >= 5.1.2)

date_sun_infoReturns an array with information about sunset/sunrise and twilight begin/end

Opis

array date_sun_info ( int $time , float $latitude , float $longitude )

Parametry

time

Timestamp.

latitude

Latitude in degrees.

longitude

Longitude in degrees.

Zwracane wartości

Returns array on success or FALSE on failure.

Przykłady

Przykład #1 A date_sun_info() example

<?php
$sun_info 
date_sun_info(strtotime("2006-12-12"), 31.766735.2333);
foreach (
$sun_info as $key => $val) {
    echo 
"$key: " date("H:i:s"$val) . "\n";
}
?>

Powyższy przykład wyświetli:

sunrise: 05:52:11
sunset: 15:41:21
transit: 10:46:46
civil_twilight_begin: 05:24:08
civil_twilight_end: 16:09:24
nautical_twilight_begin: 04:52:25
nautical_twilight_end: 16:41:06
astronomical_twilight_begin: 04:21:32
astronomical_twilight_end: 17:12:00

Zobacz też:

  • date_sunrise() - Returns time of sunrise for a given day and location
  • date_sunset() - Returns time of sunset for a given day and location



date_sunrise

(PHP 5)

date_sunriseReturns time of sunrise for a given day and location

Opis

mixed date_sunrise ( int $timestamp [, int $format = SUNFUNCS_RET_STRING [, float $latitude = ini_get("date.default_latitude") [, float $longitude = ini_get("date.default_longitude") [, float $zenith = ini_get("date.sunrise_zenith") [, float $gmt_offset = 0 ]]]]] )

date_sunrise() returns the sunrise time for a given day (specified as a timestamp ) and location.

Parametry

timestamp

The timestamp of the day from which the sunrise time is taken.

format

format constants
constant description example
SUNFUNCS_RET_STRING returns the result as string 16:46
SUNFUNCS_RET_DOUBLE returns the result as float 16.78243132
SUNFUNCS_RET_TIMESTAMP returns the result as integer (timestamp) 1095034606

latitude

Defaults to North, pass in a negative value for South. See also: date.default_latitude

longitude

Defaults to East, pass in a negative value for West. See also: date.default_longitude

zenith

Default: date.sunrise_zenith

gmtoffset

Specified in hours.

Zwracane wartości

Returns the sunrise time in a specified format on success or FALSE on failure.

Błędy/Wyjątki

Każde wywołanie do funkcji date/time spowoduje wygenerowanie E_NOTICE jeśli strefa czasowa jest nieprawidłowa, lub/i wiadomość E_STRICT jeśli użyto ustawień systemu lub zmiennej środowiskowej TZ. Patrz także date_default_timezone_set()

Rejestr zmian

Wersja Opis
5.1.0

Teraz generuje błędy strefy czasowej o poziomie E_STRICT i E_NOTICE.

Przykłady

Przykład #1 date_sunrise() example

<?php

/* calculate the sunrise time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/

echo date("D M d Y"). ', sunrise time : ' .date_sunrise(time(), SUNFUNCS_RET_STRING38.4, -9901);

?>

Powyższy przykład wyświetli coś podobnego do:

Mon Dec 20 2004, sunrise time : 08:54

Zobacz też:

  • date_sunset() - Returns time of sunset for a given day and location



date_sunset

(PHP 5)

date_sunset Returns time of sunset for a given day and location

Opis

mixed date_sunset ( int $timestamp [, int $format = SUNFUNCS_RET_STRING [, float $latitude = ini_get("date.default_latitude") [, float $longitude = ini_get("date.default_longitude") [, float $zenith = ini_get("date.sunset_zenith") [, float $gmt_offset = 0 ]]]]] )

date_sunset() returns the sunset time for a given day (specified as a timestamp ) and location.

Parametry

timestamp

The timestamp of the day from which the sunset time is taken.

format

format constants
constant description example
SUNFUNCS_RET_STRING returns the result as string 16:46
SUNFUNCS_RET_DOUBLE returns the result as float 16.78243132
SUNFUNCS_RET_TIMESTAMP returns the result as integer (timestamp) 1095034606

latitude

Defaults to North, pass in a negative value for South. See also: date.default_latitude

longitude

Defaults to East, pass in a negative value for West. See also: date.default_longitude

zenith

Default: date.sunset_zenith

gmtoffset

Specified in hours.

Błędy/Wyjątki

Każde wywołanie do funkcji date/time spowoduje wygenerowanie E_NOTICE jeśli strefa czasowa jest nieprawidłowa, lub/i wiadomość E_STRICT jeśli użyto ustawień systemu lub zmiennej środowiskowej TZ. Patrz także date_default_timezone_set()

Rejestr zmian

Wersja Opis
5.1.0

Teraz generuje błędy strefy czasowej o poziomie E_STRICT i E_NOTICE.

Zwracane wartości

Returns the sunset time in a specified format on success or FALSE on failure.

Przykłady

Przykład #1 date_sunset() example

<?php

/* calculate the sunset time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/

echo date("D M d Y"). ', sunset time : ' .date_sunset(time(), SUNFUNCS_RET_STRING38.4, -9901);

?>

Powyższy przykład wyświetli coś podobnego do:

Mon Dec 20 2004, sunset time : 18:13

Zobacz też:

  • date_sunrise() - Returns time of sunrise for a given day and location



date_time_set

(PHP 5 >= 5.2.0)

date_time_setAlias dla DateTime::setTime

Opis

Ta funkcja jest aliasem dla: DateTime::setTime



date_timestamp_get

(PHP 5 >= 5.3.0)

date_timestamp_getAlias dla DateTime::getTimestamp

Opis

Ta funkcja jest aliasem dla: DateTime::getTimestamp



date_timestamp_set

(PHP 5 >= 5.3.0)

date_timestamp_setAlias dla DateTime::setTimestamp

Opis

Ta funkcja jest aliasem dla: DateTime::setTimestamp



date_timezone_get

(PHP 5 >= 5.2.0)

date_timezone_getAlias dla DateTime::getTimezone

Opis

Ta funkcja jest aliasem dla: DateTime::getTimezone



date_timezone_set

(PHP 5 >= 5.2.0)

date_timezone_setAlias dla DateTime::setTimezone

Opis

Ta funkcja jest aliasem dla: DateTime::setTimezone



date

(PHP 4, PHP 5)

dateFormatuje lokalny czas/datę

Opis

string date ( string $format [, int $znacznik_czasu ] )

Zwraca datę sformatowaną zgodnie z szablonem podanym w argumencie jako znacznik_czasu , lub aktualnego czasu w przypadku wywołania jej bez tego argumentu. Innymi słowy, znacznik_czasu jest parametrem opcjonalnym, domyślnie pobierającym wartość funkcji time().

Parametry

format

Format zwracanej daty string. Zobacz możliwe ustawienia formatowania poniżej.

Poniższych znaków używa się jako tekstu w parametrze format
Zawartość parametruformat Opis Przykład zwróconej wartości
Dzień --- ---
d Dzień miesiąca, 2 cyfry z wiodącymi zerami 01 do 31
D Tekstowy opis angielskiej nazwy dnia, trzy litery Mon kończąc na Sun
j Dzień miesiąca bez zer wiodących 1 do 31
l (mała litera 'L') Pełen angielski opis dnia tygodnia Sunday aż do Saturday
N Liczbowa forma dnia tygodnia, zgodna z normą ISO-8601 (dodana w PHP 5.1.0) 1 (dla Poniedziałku) aż do 7 (dla Niedzieli)
S Angielski przyrostek porządkowy dla dnia miesiąca, 2 litery st, nd, rd lub th. Dobrze wygląda w połączeniu z j
w Liczbowa forma dnia tygodnia 0 (dla Niedzieli) aż do 6 (dla Soboty)
z Dzień roku (Zaczynając od 0) 0 aż do 365
Week --- ---
W Numer tygodnia w roku, zgodny z normą ISO-8601, Tygodnie rozpoczynają Poniedziałki (dostępne od PHP 4.1.0) Przykład: 42 (42. tydzień roku)
Month --- ---
F Pełen angielski opis, dnia miesiąca, taki jak January czy March January aż do December
m Liczbowa forma miesiąca, z zerami wiodącymi 01 aż do 12
M Krótki, angielski opis miesiąca, trzy litery Jan a do Dec
n Liczbowa forma miesiąca, bez zer wiodących 1 aż do 12
t Ilość dni w danym miesiącu 28 do 31
Rok --- ---
L Informacja o tym, czy rok jest przestępnym 1 jeśli rok jest przestępny, 0 w przeciwnym wypadku.
o Numer roku, zgodny z normą ISO-8601. Zwraca to taką samą wartość jak Y, z takim wyjątkiem, że numer tygodnia ISO (W) należy do poprzedniego lub następnego roku, niż rok użyty w tym miejscu. (dodane w PHP 5.1.0) Przykłady: 1999 lub 2003
Y Pełna liczbowa forma roku, 4 cyfry Przykłady: 1999 lub 2003
y Dwie cyfry reprezentujące rok Przykłady: 99 or 03
Czas --- ---
a Pora dnia - dwie małe litery (przed/po południu) (ang. Ante/Post meridiem) am lub pm
A Pora dnia - dwie duże litery (przed/po południu) (ang. Ante/Post meridiem) AM lub PM
B Swatch Internet Time 000 aż do 999
g Godzina, w formacie 12-godzinnym, bez zer wiodących 1 aż do 12
G Godzina, w formacie 24-godzinnym, bez zer wiodących 0 aż do 23
h Godzina, w formacie 12-godzinnym, z zerami wiodącymi 01 aż do 12
H Godzina, w formacie 24-godzinnym, z zerami wiodącymi 00 through 23
i Minuty z zerami wiodącymi 00 do 59
s Sekundy, z zerami wiodącymi 00 aż do 59
u Mikrosekundy (dodano w PHP 5.2.2) Przykład: 54321
Strefa czasowa --- ---
e Identyfikator strefy czasowej (dodano w PHP 5.1.0) Przykłady: UTC, GMT, Europe/Zagreb
I (duże i) Informacja o tym, czy czas jest letni 1 jeśli czas jest letni, 0 w przeciwnym razie.
O Różnica z czasem Greenwich (GMT) w godzinach Przykład: +0200
P Różnica z czasem Greenwich (GMT) z dwukropkiem pomiędzy godzinami i minutami (dodano w PHP 5.1.3) Przykład: +02:00
T Skrót dla strefy czasowej Przykłady: EST, MDT ...
Z Różnica dla strefy czasowej w sekundach. Wyrównanie to jest zawsze ujemne dla stref położonych na zachód od południka 0, oraz dodatnie dla tych leżących na wschódod niego. -43200 aż do 50400
Pełna Data/Czas --- ---
c Data w standardzie ISO 8601 (dodana w PHP 5) 2004-02-12T15:19:21+00:00
r Data sformatowana zgodnie z » RFC 2822 Przykład: Thu, 21 Dec 2000 16:01:07 +0200
U Sekundy liczone od ery UNIX-a (1 stycznia 1970 00:00:00 czasu Greenwich - GMT) Zobacz także time()

Inne znaki umieszczone w łańcuchu formatującym zostaną przez parser przepisane. Z zwróci zawsze 0 podczas używania gmdate().

Informacja: Odkąd ta funkcja przyjmuje jako znacznik czasu jedynie typ integer znak formatujący u przydaje się jedynie, gdy używamy funkcji date_format() z samodzielnie zdefiniowanymi znacznikami czasu stworzonymi za pomocą funkcji date_create().

timestamp

Opcjonalny parametr uniksowy znacznik czasu timestamp jest typu integer i domyślnie jest ustawiony na bieżący czas lokalny jeśli timestamp nie został podany. Innymi słowy, domyślnie to wartość funkcji time().

Zwracane wartości

Zwraca sformatowaną datę jako łańcuch. Jeśli użyto wartości parametru znacznik_czasu innej niż liczbowa, cała funkcja zwróci FALSE oraz pojawi się ostrzeżenie klasy E_WARNING.

Błędy/Wyjątki

Każde wywołanie do funkcji date/time spowoduje wygenerowanie E_NOTICE jeśli strefa czasowa jest nieprawidłowa, lub/i wiadomość E_STRICT jeśli użyto ustawień systemu lub zmiennej środowiskowej TZ. Patrz także date_default_timezone_set()

Rejestr zmian

Wersja Opis
5.1.0 Poprawny zakres znacznika czasu to zwykle od piątku, 13 grudnia 1901 20:45:54 GMT (czasu Greenwich) do wtorku, 19 stycznia 2038 03:14:07 GMT. (Wartości te odpowiadają minimalnej i maksymalnej wartości 32-bitowej liczbie całkowitej ze znakiem). Jednakże przed PHP 5.1.0, w niektórych systemach (np. Windows) ten przedział był bardziej ograniczony i zawiera się w przedziale 01-01-1970 do 19-01-2038.
5.1.0

Teraz generuje błędy strefy czasowej o poziomie E_STRICT i E_NOTICE.

5.1.1 Istnieją użyteczne stałe standaryzujące formaty daty/czasu mogące być użyte w celu określenia parametru format .

Przykłady

Przykład #1 Przykłady użycia funkcji date()

<?php
// ustawia domyślnie używaną strefę czasową. Dostępne od PHP 5.1
date_default_timezone_set('UTC');


// wypisuje np.: Monday
echo date("l");

// wypisuje coś jak: Monday 8th August 2005 03:12:46 PM
echo date('l jS F Y h:i:s A');

// wypisuje: 1 lipca, 2000 wypada w Saturday
echo "1 lipca, 2000 wypada w " date("l"mktime(000712000));

/* użycie stałych jako parametru format */
// wypisuje coś jak: Mon, 15 Aug 2005 15:12:46 UTC
echo date(DATE_RFC822);

// wypisuje coś jak: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOMmktime(000712000));
?>

Możesz ochronić rozpoznawalne znaki w łańcuchu formatującym przed zinterpretowaniem przez poprzedzenie ich znakiem ucieczki - backslashem. Jeśli znak razem z backslashem jest specjalną sekwencją, możliwe, iż będzie trzeba poprzedzić kolejnym znakiem ucieczki całą sekwencję.

Przykład #2 Znaki ucieczki w funkcji date()

<?php
// wypisuje coś jak: jest Wednesday, 15th
echo date("\j\e\s\\t l, jS");
?>

Możliwe jest użycie funkcji date() razem z funkcją mktime() w celu znalezienia dat z przeszłości lub przyszłości.

Przykład #3 Przykład użycia date() i mktime()

<?php
$jutro 
mktime(000date("m")  , date("d")+1date("Y"));
$ostatni_miesiac mktime(000date("m")-1date("d"),   date("Y"));
$nastepny_rok  mktime(000date("m"),   date("d"),   date("Y")+1);
?>

Informacja: Rozwiązanie to jest rozsądniejsze, od prostego dodawania lub odejmowania określonej liczby sekund w dniu lub miesiącu, chociażby z powodu zmian czasu.

Poniżej znajduje się kilka przykładów zastosowania date(). Proszę zwrócić uwagę, że powinno się cytować wszystkie znaki aby uniknąć nieoczekiwanych rezultatów, a poza tym, nawet te znaki, które obecnie nie mają specjalnych znaczeń, mogą mieć przypisane jakieś znaczenie w przyszłych wersjach PHP. O ile to możliwe, należy używać cudzysłowów pojedynczych, żeby uniknąć np. zamiany \n na znak nowej linii.

Przykład #4 zastosowania date()

<?php
// Przypuśćmy, że dziś jest 10 marca, 2001, 5:16:18 pm, oraz, że jesteśmy w
// strefie czasowej MST (Mountain Standard Time)

$dzisiaj date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$dzisiaj date("m.d.y");                         // 03.10.01
$dzisiaj date("j, n, Y");                       // 10, 3, 2001
$dzisiaj date("Ymd");                           // 20010310
$dzisiaj date('h-i-s, j-m-y, it is w Day z ');  // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$dzisiaj date('\t\o jS \d\z\i\e\ń');         // to 10. dzień
$dzisiaj date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
$dzisiaj date('H:m:s \m \t\o\ \m\i\e\s\i\ą\c'); // 17:03:18 m is month
$dzisiaj date("H:i:s");                         // 17:16:18
?>

Aby sformatować datę w innych językach, należy użyć funkcji setlocale() i strftime() zamiast date().

Notatki

Informacja: Aby stworzyć znacznik czasu z tekstowego opisu daty, możesz użyć strtotime(). Dodatkowo, niektóre bazy danych mają funkcje konwertujące ich format daty na znacznik czasu (tak jak funkcja » UNIX_TIMESTAMP w MySQL).

Wskazówka

Znacznik czasu z chwili wysłania zapytania jest dostępny w $_SERVER['REQUEST_TIME'] od PHP 5.1.

Zobacz też:

  • getlastmod() - Gets time of last page modification
  • gmdate() - Formatuje datę/czas dla strefy GMT/UTC
  • mktime() - Oblicza uniksowy znacznik czasu dla podanej daty
  • strftime() - Formatuje lokalną datę/czas zgodnie z lokalizacją
  • time() - Zwraca aktualny uniksowy znacznik czasu



getdate

(PHP 4, PHP 5)

getdatePobiera informację o dacie/czasie

Opis

array getdate ([ int $znacznik_czasu = time() ] )

Funkcja zwraca tablicę (array) asocjacyjną zawierającą informacje o dacie podanej jako znacznik_czasu , lub o aktualnej dacie, jeśli nie podano parametru znacznik_czasu .

Parametry

timestamp

Opcjonalny parametr uniksowy znacznik czasu timestamp jest typu integer i domyślnie jest ustawiony na bieżący czas lokalny jeśli timestamp nie został podany. Innymi słowy, domyślnie to wartość funkcji time().

Zwracane wartości

Zwraca asocjacyjną tablicę (array) z informacjami zależnymi od podanego parametru znacznik_czasu . Zwrócona tablica zawiera następujące elementy:

Klucze zwróconej tablicy asocjacyjnej
Klucz Opis Przykłady zwracanych wartości
"seconds" Ilość sekund 0 do 59
"minutes" Liczba minut 0 do 59
"hours" Ilość godzin 0 do 23
"mday" Liczba będąca dniem miesiąca 1 do 31
"wday" Dzień tygodnia w postacy cyfry 0 (dla Niedzieli) aż do 6 (dla Soboty)
"mon" Miesiąc w postaci liczby 1 aż do 12
"year" Pełen rok w postaci liczby, 4 cyfry Przykłady: 1999 lub 2003
"yday" Dzień danego roku, w postaci liczby 0 aż do 365
"weekday" Pełna nazwa dnia tygodnia, w języku angielskim Sunday aż do Saturday
"month" Pełna nazwa miesiąca, w języku angielskim, jak np. January lub March January aż do December
0 Sekundy, które upłynęły od Ery Uniksa, podobnie jak wartość zwracana przez time() i użyta przez funkcję date(). Zależnie od systemu, zazwyczaj -2147483648 aż do 2147483647.

Przykłady

Przykład #1 getdate() - przykład

<?php
$dzisiaj 
getdate();
print_r($dzisiaj);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [seconds] => 40
    [minutes] => 58
    [hours]   => 21
    [mday]    => 17
    [wday]    => 2
    [mon]     => 6
    [year]    => 2003
    [yday]    => 167
    [weekday] => Tuesday
    [month]   => June
    [0]       => 1055901520
)

Zobacz też:

  • date() - Formatuje lokalny czas/datę
  • time() - Zwraca aktualny uniksowy znacznik czasu
  • setlocale() - Set locale information



gettimeofday

(PHP 4, PHP 5)

gettimeofdayPobiera aktualny czas

Opis

array gettimeofday ( void )

Jest to interfejs do gettimeofday(2). Funkcja zwraca tablicę asocjacyjną zawierającą dane odebrane z wywołania systemowego.

  • "sec" - sekundy
  • "usec" - mikrosekundy
  • "minuteswest" - minuty na zachód od Greenwich
  • "dsttime" - rodzaj czasu: letni/zimowy



gmdate

(PHP 4, PHP 5)

gmdateFormatuje datę/czas dla strefy GMT/UTC

Opis

string gmdate ( string $format [, int $znacznik_czasu ] )

Identyczna do funkcji date(), z wyjątkiem tego, że zawsze podaje czas Greenwich (Greenwich Mean Time - GMT). Na przykład w Polsce (GMT +0100 dla czasu zimowego) pierwsza linia zwraca "Jan 01 1998 00:00:00", podczas gdy druga "Dec 31 1997 23:00:00".

Przykład #1 przykład gmdate()

<?php
echo date ("M d Y H:i:s"mktime (0,0,0,1,1,1998));
echo 
gmdate ("M d Y H:i:s"mktime (0,0,0,1,1,1998));
?>

Informacja: Przed PHP 5.1.0, ujemne znaczniki czasu (daty z przed 1970) nie działały na niektórych systemach (np. Windows).

Patrz także date(), mktime(), gmmktime() i strftime().



gmmktime

(PHP 4, PHP 5)

gmmktimeUstala uniksowy znacznik czasu dla daty ze strefy GMT

Opis

int gmmktime ( int $godzina , int $minuta , int $sekunda , int $miesiąc , int $dzień , int $rok [, int $letni/zimowy ] )

Identyczna do mktime() z jednym wyjątkiem, że przekazywane argumenty reprezentują datę w strefie GMT.



gmstrftime

(PHP 4, PHP 5)

gmstrftimeFormatuje czas/datę ze strefy GMT/UTC zgodnie z lokalizacją

Opis

string gmstrftime ( string $format [, int $znacznik_czasu ] )

Zachowuje się identycznie jak strftime() z tym wyjątkiem, że zwracany jest czas strefy Greenwich (Greenwich Mean Time - GMT). Na przykład, uruchomiona we Wschodnim Czasie Standardowym (GMT -0500) pierwsza linia poniżej wyświetla "Dec 31 1998 20:00:00", podczas gdy druga "Jan 01 1999 01:00:00".

Przykłady

Przykład #1 przykład gmstrftime()

<?php
setlocale
(LC_TIME'en_US');
echo 
strftime("%b %d %Y %H:%M:%S"mktime(2000123198)) . "\n";
echo 
gmstrftime("%b %d %Y %H:%M:%S"mktime(2000123198)) . "\n";
?>

Zobacz też:

  • strftime() - Formatuje lokalną datę/czas zgodnie z lokalizacją



idate

(PHP 5)

idateFormat a local time/date as integer

Opis

int idate ( string $format [, int $timestamp = time() ] )

Returns a number formatted according to the given format string using the given integer timestamp or the current local time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().

Unlike the function date(), idate() accepts just one char in the format parameter.

Parametry

format

The following characters are recognized in the format parameter string
format character Description
B Swatch Beat/Internet Time
d Day of the month
h Hour (12 hour format)
H Hour (24 hour format)
i Minutes
I (uppercase i) returns 1 if DST is activated, 0 otherwise
L (uppercase l) returns 1 for leap year, 0 otherwise
m Month number
s Seconds
t Days in current month
U Seconds since the Unix Epoch - January 1 1970 00:00:00 UTC - this is the same as time()
w Day of the week (0 on Sunday)
W ISO-8601 week number of year, weeks starting on Monday
y Year (1 or 2 digits - check note below)
Y Year (4 digits)
z Day of the year
Z Timezone offset in seconds

timestamp

Opcjonalny parametr uniksowy znacznik czasu timestamp jest typu integer i domyślnie jest ustawiony na bieżący czas lokalny jeśli timestamp nie został podany. Innymi słowy, domyślnie to wartość funkcji time().

Zwracane wartości

Returns an integer.

As idate() always returns an integer and as they can't start with a "0", idate() may return fewer digits than you would expect. See the example below.

Błędy/Wyjątki

Każde wywołanie do funkcji date/time spowoduje wygenerowanie E_NOTICE jeśli strefa czasowa jest nieprawidłowa, lub/i wiadomość E_STRICT jeśli użyto ustawień systemu lub zmiennej środowiskowej TZ. Patrz także date_default_timezone_set()

Rejestr zmian

Wersja Opis
5.1.0

Teraz generuje błędy strefy czasowej o poziomie E_STRICT i E_NOTICE.

Przykłady

Przykład #1 idate() example

<?php
$timestamp 
strtotime('1st January 2004'); //1072915200

// this prints the year in a two digit format
// however, as this would start with a "0", it
// only prints "4"
echo idate('y'$timestamp);
?>

Zobacz też:

  • date() - Formatuje lokalny czas/datę
  • time() - Zwraca aktualny uniksowy znacznik czasu



localtime

(PHP 4, PHP 5)

localtimePobiera czas lokalny

Opis

array localtime ([ int $znacznik_czasu [, bool $asocjacyjna ]] )

Funkcja localtime() zwraca tablicę identyczną do tej ze struktury zwracanej przez wywołanie identycznej funkcji w C. Pierwszym argumentem funkcji jest znacznik czasu. Jeśli żaden znacznik czasu nie zostanie podany, funkcja wykorzystuje aktualny czas, taki jak zwrócony przez time(). Drugi argument, asocjacyjna , jeśli jest ustawiony na FALSE, lub nie jest podany, powoduje zwrócenie zwykłej, indeksowanej liczbowo tablicy. Jeśli zaś jest ustawiony na TRUE, to funkcja zwróci tablicę asocjacyjną zawierającą wszystkie rozmaite elementy struktury zwracanej przez wywołanie funkcji w C. Nazwy kluczy tablicy są następujące:

  • "tm_sec" - sekundy
  • "tm_min" - minuty
  • "tm_hour" - godziny
  • "tm_mday" - dzień miesiąca
  • "tm_mon" - miesiąc roku, 0 to styczeń
  • "tm_year" - ilość lat od 1900
  • "tm_wday" - dzień tygodnia
  • "tm_yday" - dzień roku
  • "tm_isdst" - czy aktualnie jest czas zimowy

Informacja: Miesiące rozpoczynają się od 0 (Sty) do 11 (Gru) i dni tygodnia rozpoczynają się od 0 (Nie) do 6 (Sob).

Przykład #1 time() przykład

<?php
$localtime 
localtime();
$localtime_assoc localtime(time(), true);
print_r($localtime);
print_r($localtime_assoc);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [0] => 24
    [1] => 3
    [2] => 19
    [3] => 3
    [4] => 3
    [5] => 105
    [6] => 0
    [7] => 92
    [8] => 1
)

Array
(
    [tm_sec] => 24
    [tm_min] => 3
    [tm_hour] => 19
    [tm_mday] => 3
    [tm_mon] => 3
    [tm_year] => 105
    [tm_wday] => 0
    [tm_yday] => 92
    [tm_isdst] => 1
)



microtime

(PHP 4, PHP 5)

microtime Zwraca aktualny uniksowy znacznik czasu z mikrosekundami

Opis

string microtime ( void )

Zwraca łańcuch znaków "msec sec", gdzie sec jest aktualnym czasem, mierzonym jako liczba sekund od uniksowej Epoki (1 stycznia 1970, 0:00:00 GMT), natomiast msec jest aktualną liczbą mikrosekund. Funkcja ta dostępna jest wyłącznie na systemach operacyjnych, które obsługują wywołanie systemowe gettimeofday().

Obydwie części łańcucha znaków są podawane w sekundach.

Przykład #1 przykład microtime()

<?php
function getmicrotime(){ 
    list(
$usec$sec) = explode(" ",microtime()); 
    return ((float)
$usec + (float)$sec); 
    } 

$time_start getmicrotime();
    
for (
$i=0$i 1000$i++){
    
//nie rób nic przez 1000 iteracji
    
}

$time_end getmicrotime();
$time $time_end $time_start;

echo 
"Nie robił nic przez $time sekund";
?>

Patrz także time().



mktime

(PHP 4, PHP 5)

mktimeOblicza uniksowy znacznik czasu dla podanej daty

Opis

int mktime ( int $godzina , int $minuta , int $sekunda , int $miesiąc , int $dzień , int $rok [, int $letni/zimowy ] )

Uwaga: Proszę zwrócić uwagę na dziwną kolejność argumentów, zupełnie odmienną od spotykanej w standardowym wywołaniu uniksowym mktime(); która w dodatku nie jest praktyczna przy opuszczaniu argumentów od prawej do lewej (patrz niżej). Częstym błędem w skryptach są pomyłki w kolejności tych argumentów.

Funkcja zwraca uniksowy znacznik czasu odpowiadający podanym argumentom. Znacznik czasu jest liczbą całkowitą długą (long integer) zawierającą liczbę sekund dzielącą uniksową Epokę (1 stycznia 1970) od podanego w argumentach czasu.

Argumenty mogą być opuszczane w kolejności od prawej do lewej. Za każdy pominięty argument będzie wówczas wstawiona aktualna wartość, zgodnie z lokalnym czasem/datą.

Argument letni/zimowy może być ustawiony na 1, jeśli to czas zimowy, lub 0 jeśli letni, lub -1 (domyślnie) jeśli niewiadomo, czy letni czy zimowy. Jeśli niewiadomo, PHP spróbuje ustalić to samodzielnie. Może to powodować nieoczekiwane (ale na pewno poprawne) wyniki.

Informacja: Argument letni/zimowy dodano w PHP 3.0.10.

Funkcja mktime() przydaje się przy wykonywaniu arytmetyki dat i walidacji, gdyż automatycznie policzy właściwą wartość dla danych spoza przedziałów. Na przykład, każda poniższa linia wyświetli "Jan-01-1998".

Przykład #1 przykład mktime()

<?php
echo date ("M-d-Y"mktime (0,0,0,12,32,1997));
echo 
date ("M-d-Y"mktime (0,0,0,13,1,1997));
echo 
date ("M-d-Y"mktime (0,0,0,1,1,1998));
echo 
date ("M-d-Y"mktime (0,0,0,1,1,98));
?>

rok może być liczbą dwu lub czterocyfrową, przy czym wartości dwucyfrowe z przedziału 0-69 będą mapowane do 2000-2069, a z przedziału 70-99 do 1970-1999 (w systemach, w których time_t jest 32-bitową liczbą całkowitą ze znakiem, co jest obecnie najpopularniejszym rozwiązaniem, poprawny zakres argumentu rok zawiera się pomiędzy 1902 a 2037).

Informacja: Windows
Żadna znana wersja systemu Windows nie obsługuje ujemnych znaczników czasu. Z tego powodu zakres poprawnych dat zawiera się pomiędzy rokiem 1970 a 2038.

Ostatni dzień dowolnego miesiąca może być wyrażony jako zerowy dzień następnego miesiąca, ale nie jako -1 dzień. Obydwa poniższe przykłady wyświetlą "Ostatni dzień lutego 2000 to: 29".

Przykład #2 Ostatni dzień miesiąca

<?php
$ostatni 
mktime (0,0,0,3,0,2000);
echo 
strftime ("Ostatni dzień lutego 2000 to: %d"$ostatni);
     
$ostatni mktime (0,0,0,4,-31,2000);
echo 
strftime ("Ostatni dzień lutego 2000 to: %d"$ostatni);
?>

Data z rokiem, miesiącem i dniem równym zero jest niepoprawna (w przeciwnym razie oznaczałoby to 30.11.1999, co mogłoby powodować dziwne rezultaty).

Patrz także date() i time().



strftime

(PHP 4, PHP 5)

strftime Formatuje lokalną datę/czas zgodnie z lokalizacją

Opis

string strftime ( string $format [, int $znacznik_czasu ] )

Zwraca łańcuch znaków sformatowany zgodnie z podanym szablonem formatującym, przy użyciu podanego znacznika czasu lub aktualnego czasu, jeśli znacznik nie jest podany. Nazwy miesięcy, dni tygodnia, itp. respektują ustawienia lokalizacji przy użyciu funkcji setlocale().

Poniższe symbole są rozpoznawane w szablonie formatującym:

  • %a - skrótowa nazwa dnia tygodnia zgodnie z lokalizacją
  • %A - pełna nazwa dnia tygodnia zgodnie z lokalizacją
  • %b - skrótowa nazwa miesiąca zgodnie z lokalizacją
  • %B - pełna nazwa miesiąca zgodnie z lokalizacją
  • %c - preferowana reprezentacja daty i czasu zgodnie z lokalizacją
  • %C - numer wieku (rok podzielony przez 100 i skrócony do liczby całkowitej, przedział od 00 do 99)
  • %d - dzień miesiąca jako liczba dziesiętna (przedział od 01 do 31)
  • %D - to samo co %m/%d/%y
  • %e - dzień miesiąca jako liczba dziesiętna, przy czym pojedyncza cyfra poprzedzona jest spacją (przedział od " 1" do "31")
  • %g - tak jak %G, ale bez uwzględnienia wieku
  • %G - rok w zapisie czterocyfrowym, powiązany z numerem tygodnia wg ISO. Symbol ten ma ten sam format i wartość jak %Y, z tym wyjątkiem, że jeśli numer tygodnia wg ISO należy do poprzedniego lub następnego roku, to poprzedni lub następny rok jest zwracany przez ten symbol.
  • %h - tak jak %b
  • %H - godzina jako liczba dziesiętna w systemie 24-godzinnym (przedział od 00 do 23)
  • %I - godzina jako liczba dziesiętna w systemie 12-godzinnym (przedział od 01 do 12)
  • %j - dzień roku jako liczba dziesiętna (przedział od 001 do 366)
  • %m - miesiąc jako liczba dziesiętna (przedział od 01 do 12)
  • %M - minuty jako liczba dziesiętna
  • %n - znak nowej linii
  • %p - albo "am" lub "pm" zgodnie z podanym czasem, albo łańcuchy znaków odpowiadające lokalizacji
  • %r - czas w notacji a.m. lub p.m.
  • %R - czas w notacji 24-godzinnej
  • %S - sekundy jako liczba dziesiętna
  • %t - znak tabulacji
  • %T - aktualny czas, odpowiednik %H:%M:%S
  • %u - numer dnia tygodnia jako liczba dziesiętna [1,7], gdzie 1 oznacza poniedziałek
    Ostrzeżenie

    Sun Solaris podaje niedzielę jako 1, pomimo że ISO 9889:1999 (aktualny standard języka C) jasno określa, że powinien to być poniedziałek.

  • %U - numer tygodnia aktualnego roku jako liczba dziesiętna, począwszy od pierwszej niedzieli jako pierwszego dnia pierwszego tygodnia
  • %V - numer tygodnia aktualnego roku wg ISO 8601:1988 jako liczba dziesiętna, przedział od 01 do 53, gdzie tydzień 1 jest pierwszym tygodniem, którym ma co najmniej 4 dni w aktualnym roku, przy czym pierwszym dniem tygodnia jest poniedziałek. (Przy użyciu %G lub %g otrzymuje się rok, który odpowiada numerowi tygodnia dla podanego znacznika czasu).
  • %W - numer tygodnia aktualnego roku jako liczba dziesiętna, począwszy od pierwszego poniedziałku, jako pierwszego dnia pierwszego tygodnia
  • %w - dzień tygodnia jako liczba dziesiętna, począwszy od niedzieli - numer 0
  • %x - preferowana reprezentacja daty, zgodnie z lokalizacją, bez czasu
  • %X - preferowana reprezentacja czasu, zgodnie z lokalizacją, bez daty
  • %y - rok jako liczba dziesiętna, bez uwzględnienia wieku (przedział od 00 do 99)
  • %Y - rok jako liczba dziesiętna, z wiekiem włącznie
  • %Z - strefa czasowa, nazwa lub skrót
  • %% - znak "%"

Informacja: Nie wszystkie symbole konwersji mogą być obsługiwane przez twoją bibliotekę C, co oznacza, że nie będą obsługiwane przez PHP-owską funkcję strftime(). Oznacza to, że np. %e, %T i %D (oraz być może inne) nie będą funkcjonować w Windows.

Przykład #1 przykład strftime()

setlocale (LC_TIME, "C");
print (strftime ("%A, to w fińskim "));
setlocale (LC_TIME, "fi_FI");
print (strftime ("%A, we francuskim "));
setlocale (LC_TIME, "fr_FR");
print (strftime ("%A, a w niemieckim "));
setlocale (LC_TIME, "de_DE");
print (strftime ("%A.\n"));

Powyższy przykład działa, jeśli masz zainstalowane w swoim systemie odpowiednie lokale.

Patrz także setlocale() i mktime() oraz » Otwarta Specyfikacja Grupowa strftime().



strptime

(PHP 5 >= 5.1.0)

strptime Parse a time/date generated with strftime()

Opis

array strptime ( string $date , string $format )

strptime() returns an array with the date parsed, or FALSE on error.

Month and weekday names and other language dependent strings respect the current locale set with setlocale() (LC_TIME).

Parametry

date (string)

The string to parse (e.g. returned from strftime())

format (string)

The format used in date (e.g. the same as used in strftime()).

For more information about the format options, read the strftime() page.

Zwracane wartości

Returns an array or FALSE on failure.

The following parameters are returned in the array
parameters Description
"tm_sec" Seconds after the minute (0-61)
"tm_min" Minutes after the hour (0-59)
"tm_hour" Hour since midnight (0-23)
"tm_mday" Day of the month (1-31)
"tm_mon" Months since January (0-11)
"tm_year" Years since 1900
"tm_wday" Days since Sunday (0-6)
"tm_yday" Days since January 1 (0-365)
"unparsed" the date part which was not recognized using the specified format

Przykłady

Przykład #1 strptime() example

<?php
$format 
'%d/%m/%Y %H:%M:%S';
$strf strftime($format);

echo 
"$strf\n";

print_r(strptime($strf$format));
?>

Powyższy przykład wyświetli coś podobnego do:

03/10/2004 15:54:19

Array
(
    [tm_sec] => 19
    [tm_min] => 54
    [tm_hour] => 15
    [tm_mday] => 3
    [tm_mon] => 9
    [tm_year] => 104
    [tm_wday] => 0
    [tm_yday] => 276
    [unparsed] =>
)

Notatki

Informacja: Ta funkcja nie jest dostępna na platformie Windows.

Informacja: "tm_sec" includes any leap seconds (currently upto 2 a year). For more information on leap seconds, see the » Wikipedia article on leap seconds.

Zobacz też:

  • strftime() - Formatuje lokalną datę/czas zgodnie z lokalizacją



strtotime

(PHP 4, PHP 5)

strtotime Parsuje większość angielskich tekstowych opisów daty i czasu do uniksowego znacznika czasu

Opis

int strtotime ( string $czas [, int $teraz ] )

Funkcja przyjmuje tekst zawierający datę w formacie angielskim i stara się przeliczyć ją na uniksowy znacznik czasu, relatywnie do znacznika czasu podanego w teraz , lub aktualnego czasu, jeśli znacznik nie zostanie podany. W przypadku fiaska, zwracane jest -1.

Ponieważ strtotime() zachowuje się zgodnie ze składnią daty wg GNU, warto zajrzeć do rozdziału podręcznika GNU zatytułowanego » Formaty Wprowadzania Daty - Date Input Formats. Opisana tam jest poprawna składnia argumentu czas .

Przykład #1 przykłady strtotime()

<?php
echo strtotime ("now"), "\n";
echo 
strtotime ("10 September 2000"), "\n";
echo 
strtotime ("+1 day"), "\n";
echo 
strtotime ("+1 week"), "\n";
echo 
strtotime ("+1 week 2 days 4 hours 2 seconds"), "\n";
echo 
strtotime ("next Thursday"), "\n";
echo 
strtotime ("last Monday"), "\n";
?>

Przykład #2 Checking for failure

<?php
$str 
'Not Good';
if ((
$timestamp strtotime($str)) === -1) {
    echo 
"Tekst daty ($str) jest niepoprawny";
} else {
    echo 
"$str == "date('l dS of F Y h:i:s A',$timestamp);
}
?>

Informacja: Poprawny zakres znacznika czasu to zwykle od piątku, 13 grudnia 1901 20:45:54 GMT (czasu Greenwich) do wtorku, 19 stycznia 2038 03:14:07 GMT. (Wartości te odpowiadają minimalnej i maksymalnej wartości 32-bitowej liczbie całkowitej ze znakiem).



time

(PHP 4, PHP 5)

timeZwraca aktualny uniksowy znacznik czasu

Opis

int time ( void )

Zwraca aktualny czas, podawany jako liczba sekund, które upłynęły od uniksowej Epoki (1 stycznia 1970 00:00:00 GMT).

Przykłady

Przykład #1 time() przykład

<?php
$nextWeek 
time() + (24 60 60);
                   
// 7 dni; 24 godziny; 60 minut; 60 sekund
echo 'Teraz:       'date('Y-m-d') ."\n";
echo 
'Za tydzień: 'date('Y-m-d'$nextWeek) ."\n";
// lub używając strtotime():
echo 'Za tydzień: 'date('Y-m-d'strtotime('+1 week')) ."\n";
?>

Powyższy przykład wyświetli coś podobnego do:

Teraz:      2005-03-30
Za tydzień: 2005-04-06
Za tydzień: 2005-04-06

Notatki

Wskazówka

Znacznik czasu od rozpoczęcia żądania jest dostępny w $_SERVER['REQUEST_TIME'] od PHP 5.1.

Zobacz też:

  • date() - Formatuje lokalny czas/datę
  • microtime() - Zwraca aktualny uniksowy znacznik czasu z mikrosekundami



timezone_abbreviations_list

(PHP 5 >= 5.1.0)

timezone_abbreviations_listAlias dla DateTimeZone::listAbbreviations

Opis

Ta funkcja jest aliasem dla: DateTimeZone::listAbbreviations



timezone_identifiers_list

(PHP 5 >= 5.1.0)

timezone_identifiers_listAlias dla DateTimeZone::listIdentifiers

Opis

Ta funkcja jest aliasem dla: DateTimeZone::listIdentifiers



timezone_location_get

(PHP 5 >= 5.3.0)

timezone_location_getAlias dla DateTimeZone::getLocation

Opis

Ta funkcja jest aliasem dla: DateTimeZone::getLocation



timezone_name_from_abbr

(PHP 5 >= 5.1.3)

timezone_name_from_abbrReturns the timezone name from abbreviation

Opis

string timezone_name_from_abbr ( string $abbr [, int $gmtOffset = -1 [, int $isdst = -1 ]] )

Parametry

abbr

Time zone abbreviation.

gmtOffset

Offset from GMT in seconds. Defaults to -1 which means that first found time zone corresponding to abbr is returned. Otherwise exact offset is searched and only if not found then the first time zone with any offset is returned.

isdst

Daylight saving time indicator. If abbr doesn't exist then the time zone is searched solely by offset and isdst .

Zwracane wartości

Returns time zone name on success or FALSE on failure.

Przykłady

Przykład #1 A timezone_name_from_abbr() example

<?php
echo timezone_name_from_abbr("CET") . "\n";
echo 
timezone_name_from_abbr(""36000) . "\n";
?>

Powyższy przykład wyświetli coś podobnego do:

Europe/Berlin
Europe/Paris

Zobacz też:



timezone_name_get

(PHP 5 >= 5.1.0)

timezone_name_getAlias dla DateTimeZone::getName

Opis

Ta funkcja jest aliasem dla: DateTimeZone::getName



timezone_offset_get

(PHP 5 >= 5.1.0)

timezone_offset_getAlias dla DateTimeZone::getOffset

Opis

Ta funkcja jest aliasem dla: DateTimeZone::getOffset



timezone_open

(PHP 5 >= 5.1.0)

timezone_openReturns new DateTimeZone object

Opis

DateTimeZone timezone_open ( string $timezone )

Parametry

timezone

Time zone identifier as full name (e.g. Europe/Prague) or abbreviation (e.g. CET).

Zwracane wartości

Returns DateTimeZone object on success or FALSE on failure.



timezone_transitions_get

(PHP 5 >= 5.2.0)

timezone_transitions_getAlias dla DateTimeZone::getTransitions

Opis

Ta funkcja jest aliasem dla: DateTimeZone::getTransitions



timezone_version_get

(PHP 5 >= 5.3.0)

timezone_version_get Gets the version of the timezonedb

Opis

string timezone_version_get ( void )

Returns the current version of the timezonedb.

Zwracane wartości

Returns a string.

Przykłady

Przykład #1 Getting the timezonedb version

<?php
echo timezone_version_get();
?>

Powyższy przykład wyświetli coś podobnego do:

2009.7


Spis treści





Rozszerzenia wiersza poleceń


Newt


Wstęp

This is a PHP language extension for RedHat Newt library, a terminal-based window and widget library for writing applications with user friendly interface. Once this extension is enabled in PHP it will provide the use of Newt widgets, such as windows, buttons, checkboxes, radiobuttons, labels, editboxes, scrolls, textareas, scales, etc. Use of this extension if very similar to the original Newt API of C programming language.



Instalacja/Konfiguracja

Spis treści


Wymagania

This module uses the functions of the RedHat Newt library. You need libnewt version >= 0.51.0.



Instalacja

To rozszerzenie » PECL nie jest dołączane do PHP. Informacje na temat instalacji tego rozszerzenia PECL można znaleźć w podręczniku w rozdziale zatytułowanym Instalacja rozszerzeń PECL. Dodatkowe informacje, takie jak nowe wersje, pliki do pobrania, pliki źródłowe, informacje o opiekunach czy rejestr zmian, można znaleźć tutaj: » http://pecl.php.net/package/newt.

W PHP 4 to rozszerzenie PECL można znaleźć w podkatalogu ext/ źródeł PHP lub pod znajdującym się wyżej odnośnikiem PECL. In order to use these functions you must compile CGI or CLI PHP with newt support by using the --with-newt[=DIR] configure option.

Informacja: This extension is not available for Windows platform.
You may need also curses and slang libraries, in order to compile this extension. To specify locations of these libraries, use the following configuration options: --with-curses-dir=/path/to/libcurses --with-slang-dir=/path/to/libslang



Konfiguracja wykonawcza

To rozszerzenie nie definiuje posiada żadnych dyrektyw konfiguracyjnych w pliku php.ini.



Typy zasobów

This extension uses two resource types: "newt component" and "newt grid".

Resource type "newt component" is returned by functions, which create common newt widgets (for example: newt_button())

Resource type "newt grid" is a special link identifier for components, returned by newt grid factory functions (for example: newt_create_grid())




Stałe predefiniowane

Spis treści

Poniższe stałe są zdefiniowane w tym rozszerzeniu i stają się dostępne, gdy rozszerzenie jest dokompilowane z PHP, lub załadowane dynamicznie przy starcie.


Newt form exit reasons

Newt form exit reasons
constant meaning
NEWT_EXIT_HOTKEY hotkey defined by newt_form_add_hot_key() was pressed
NEWT_EXIT_COMPONENT some component has caused form to exit
NEWT_EXIT_FDREADY file descriptor specified in newt_form_watch_fd() is ready to be read or written to
NEWT_EXIT_TIMER time specified in newt_form_set_timer() has elapsed


Newt colorsets

Newt colorsets
constant meaning
NEWT_COLORSET_ROOT  
NEWT_COLORSET_BORDER  
NEWT_COLORSET_WINDOW  
NEWT_COLORSET_SHADOW  
NEWT_COLORSET_TITLE  
NEWT_COLORSET_BUTTON  
NEWT_COLORSET_ACTBUTTON  
NEWT_COLORSET_CHECKBOX  
NEWT_COLORSET_ACTCHECKBOX  
NEWT_COLORSET_ENTRY  
NEWT_COLORSET_LABEL  
NEWT_COLORSET_LISTBOX  
NEWT_COLORSET_ACTLISTBOX  
NEWT_COLORSET_TEXTBOX  
NEWT_COLORSET_ACTTEXTBOX  
NEWT_COLORSET_HELPLINE  
NEWT_COLORSET_ROOTTEXT  
NEWT_COLORSET_ROOTTEXT  
NEWT_COLORSET_EMPTYSCALE  
NEWT_COLORSET_FULLSCALE  
NEWT_COLORSET_DISENTRY  
NEWT_COLORSET_COMPACTBUTTON  
NEWT_COLORSET_ACTSELLISTBOX  
NEWT_COLORSET_SELLISTBOX  


Newt argument flags

Newt argument flags
constant meaning
NEWT_ARG_LAST  
NEWT_ARG_APPEND  


Newt Flags Sense

Newt Flags Sense
constant meaning
NEWT_FLAGS_SET  
NEWT_FLAGS_RESET  
NEWT_FLAGS_TOGGLE  


Newt Components Flags

Newt Components Flags
constant meaning
NEWT_FLAG_RETURNEXIT Exit form, when component is activated
NEWT_FLAG_HIDDEN Component is hidden
NEWT_FLAG_SCROLL Component is scrollable
NEWT_FLAG_DISABLED Component is disabled
NEWT_FLAG_BORDER  
NEWT_FLAG_WRAP Wrap text
NEWT_FLAG_NOF12 Don't exit form on pressing F12
NEWT_FLAG_MULTIPLE  
NEWT_FLAG_SELECTED Component is selected
NEWT_FLAG_CHECKBOX Component is checkbox
NEWT_FLAG_PASSWORD Entry component is password entry
NEWT_FLAG_SHOWCURSOR Show cursor


File Descriptor Flags

File Descriptor Flags
constant meaning
NEWT_FD_READ  
NEWT_FD_WRITE  
NEWT_FD_EXCEPT  


Checkbox Tree Flags

Checkbox Tree Flags
constant meaning
NEWT_CHECKBOXTREE_UNSELECTABLE  
NEWT_CHECKBOXTREE_HIDE_BOX  
NEWT_CHECKBOXTREE_COLLAPSED  
NEWT_CHECKBOXTREE_EXPANDED  
NEWT_CHECKBOXTREE_UNSELECTED  
NEWT_CHECKBOXTREE_SELECTED  


Entry Flags

Entry Flags
constant meaning
NEWT_ENTRY_SCROLL  
NEWT_ENTRY_HIDDEN  
NEWT_ENTRY_RETURNEXIT  
NEWT_ENTRY_DISABLED  


Listbox Flags

Listbox Flags
constant meaning
NEWT_LISTBOX_RETURNEXIT  


Textbox Flags

Textbox Flags
constant meaning
NEWT_TEXTBOX_WRAP Wrap text in the textbox
NEWT_TEXTBOX_SCROLL Scroll text in the textbox


Form Flags

Form Flags
constant meaning
NEWT_FORM_NOF12 Don't exit form on F12 press


Newt Keys

Newt Keys
constant meaning
NEWT_KEY_TAB  
NEWT_KEY_ENTER  
NEWT_KEY_SUSPEND  
NEWT_KEY_ESCAPE  
NEWT_KEY_RETURN  
NEWT_KEY_EXTRA_BASE  
NEWT_KEY_UP  
NEWT_KEY_DOWN  
NEWT_KEY_LEFT  
NEWT_KEY_RIGHT  
NEWT_KEY_BKSPC  
NEWT_KEY_DELETE  
NEWT_KEY_HOME  
NEWT_KEY_END  
NEWT_KEY_UNTAB  
NEWT_KEY_PGUP  
NEWT_KEY_PGDN  
NEWT_KEY_INSERT  
NEWT_KEY_F1  
NEWT_KEY_F2  
NEWT_KEY_F3  
NEWT_KEY_F4  
NEWT_KEY_F5  
NEWT_KEY_F6  
NEWT_KEY_F7  
NEWT_KEY_F8  
NEWT_KEY_F9  
NEWT_KEY_F10  
NEWT_KEY_F11  
NEWT_KEY_F12  
NEWT_KEY_RESIZE  


Newt Anchors

Newt Anchors
constant meaning
NEWT_ANCHOR_LEFT  
NEWT_ANCHOR_RIGHT  
NEWT_ANCHOR_TOP  
NEWT_ANCHOR_BOTTOM  


Grid Flags

Grid Flags
constant meaning
NEWT_GRID_FLAG_GROWX  
NEWT_GRID_FLAG_GROWY  
NEWT_GRID_EMPTY  
NEWT_GRID_COMPONENT  
NEWT_GRID_SUBGRID  



Przykłady

Spis treści


Basic usage

This example is a PHP port of RedHat 'setup' utility dialog, executed in text mode.

Przykład #1 Newt Usage Example

<?php
newt_init 
();
newt_cls ();

newt_draw_root_text (00"Test Mode Setup Utility 1.12");
newt_push_help_line (null);
newt_draw_root_text (-300"(c) 1999-2002 RedHat, Inc");

newt_get_screen_size ($rows$cols);

newt_open_window ($rows/2-17$cols/2-103417"Choose a Tool");

$form newt_form ();

$list newt_listbox (3210);

foreach (array (
    
"Authentication configuration",
    
"Firewall configuration",
    
"Mouse configuration",
    
"Network configuration",
    
"Printer configuration",
    
"System services") as $l_item)
{
    
newt_listbox_add_entry ($list$l_item$l_item);
}

$b1 newt_button (512"Run Tool");
$b2 newt_button (2112"Quit");

newt_form_add_component ($form$list);
newt_form_add_components ($form, array($b1$b2));

newt_refresh ();
newt_run_form ($form);

newt_pop_window ();
newt_pop_help_line ();
newt_finished ();
newt_form_destroy ($form);
?>



Newt Funkcje


newt_bell

(PECL newt >= 0.1)

newt_bellSend a beep to the terminal

Opis

void newt_bell ( void )

This function sends a beep to the terminal.

Informacja: Depending on the terminal's settings, this beep may or may not be audible.

Zwracane wartości

nie jest zwracana żadna wartość.



newt_button_bar

(PECL newt >= 0.1)

newt_button_barThis function returns a grid containing the buttons created.

Opis

resource newt_button_bar ( array &$buttons )

This function returns a grid containing the buttons created.

Parametry

buttons

Zwracane wartości

Returns grid containing the buttons created.



newt_button

(PECL newt >= 0.1)

newt_buttonCreate a new button

Opis

resource newt_button ( int $left , int $top , string $text )

Creates a new button.

Parametry

left

X-coordinate of the button.

top

Y-coordinate of the button.

text

The text which should be displayed in the button.

Zwracane wartości

Returns a resource link to the created button component, or FALSE on error.

Przykłady

Przykład #1 A newt_button() example

<?php

$form 
newt_form();

$ok_button newt_button(512"Run Tool");
    
newt_form_add_component($form$ok_button);

?>

Zobacz też:



newt_centered_window

(PECL newt >= 0.1)

newt_centered_windowOpen a centered window of the specified size

Opis

int newt_centered_window ( int $width , int $height [, string $title ] )

Open a centered window of the specified size.

Parametry

width

Window width

height

Window height

title

Window title

Zwracane wartości

Undefined value.

Zobacz też:



newt_checkbox_get_value

(PECL newt >= 0.1)

newt_checkbox_get_valueRetreives value of checkox resource

Opis

string newt_checkbox_get_value ( resource $checkbox )

This function returns the character in the sequence which indicates the current value of the checkbox.

Parametry

checkbox

Zwracane wartości

Returns character indicating the value of the checkbox.



newt_checkbox_set_flags

(PECL newt >= 0.1)

newt_checkbox_set_flagsConfigures checkbox resource

Opis

void newt_checkbox_set_flags ( resource $checkbox , int $flags , int $sense )

This function allows to set various flags on checkbox resource.

Parametry

checkbox

flags

sense

Zwracane wartości

nie jest zwracana żadna wartość.



newt_checkbox_set_value

(PECL newt >= 0.1)

newt_checkbox_set_valueSets the value of the checkbox

Opis

void newt_checkbox_set_value ( resource $checkbox , string $value )

This function allows to set the current value of the checkbox resource.

Parametry

checkbox

value

Zwracane wartości

nie jest zwracana żadna wartość.



newt_checkbox_tree_add_item

(PECL newt >= 0.1)

newt_checkbox_tree_add_itemAdds new item to the checkbox tree

Opis

void newt_checkbox_tree_add_item ( resource $checkboxtree , string $text , mixed $data , int $flags , int $index [, int $... ] )

This function allows to add new item to the checkbox tree.

Parametry

checkboxtree

text

data

flags

index

Zwracane wartości

nie jest zwracana żadna wartość.



newt_checkbox_tree_find_item

(PECL newt >= 0.1)

newt_checkbox_tree_find_itemFinds an item in the checkbox tree

Opis

array newt_checkbox_tree_find_item ( resource $checkboxtree , mixed $data )

Finds an item in the checkbox tree by item's data.

Parametry

checkboxtree

data

Zwracane wartości

Returns checkbox tree item resource, or NULL if it wasn't found.



newt_checkbox_tree_get_current

(PECL newt >= 0.1)

newt_checkbox_tree_get_currentReturns checkbox tree selected item

Opis

mixed newt_checkbox_tree_get_current ( resource $checkboxtree )

This method returns checkbox tree selected tem.

Parametry

checkboxtree

Zwracane wartości

Returns current (selected) checkbox tree item.



newt_checkbox_tree_get_entry_value

(PECL newt >= 0.1)

newt_checkbox_tree_get_entry_value

Opis

string newt_checkbox_tree_get_entry_value ( resource $checkboxtree , mixed $data )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

checkboxtree

data

Zwracane wartości



newt_checkbox_tree_get_multi_selection

(PECL newt >= 0.1)

newt_checkbox_tree_get_multi_selection

Opis

array newt_checkbox_tree_get_multi_selection ( resource $checkboxtree , string $seqnum )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

checkboxtree

seqnum

Zwracane wartości



newt_checkbox_tree_get_selection

(PECL newt >= 0.1)

newt_checkbox_tree_get_selection

Opis

array newt_checkbox_tree_get_selection ( resource $checkboxtree )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

checkboxtree

Zwracane wartości



newt_checkbox_tree_multi

(PECL newt >= 0.1)

newt_checkbox_tree_multi

Opis

resource newt_checkbox_tree_multi ( int $left , int $top , int $height , string $seq [, int $flags ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

left

top

height

seq

flags

Zwracane wartości



newt_checkbox_tree_set_current

(PECL newt >= 0.1)

newt_checkbox_tree_set_current

Opis

void newt_checkbox_tree_set_current ( resource $checkboxtree , mixed $data )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

checkboxtree

data

Zwracane wartości

nie jest zwracana żadna wartość.



newt_checkbox_tree_set_entry_value

(PECL newt >= 0.1)

newt_checkbox_tree_set_entry_value

Opis

void newt_checkbox_tree_set_entry_value ( resource $checkboxtree , mixed $data , string $value )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

checkboxtree

data

value

Zwracane wartości

nie jest zwracana żadna wartość.



newt_checkbox_tree_set_entry

(PECL newt >= 0.1)

newt_checkbox_tree_set_entry

Opis

void newt_checkbox_tree_set_entry ( resource $checkboxtree , mixed $data , string $text )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

checkboxtree

data

text

Zwracane wartości

nie jest zwracana żadna wartość.



newt_checkbox_tree_set_width

(PECL newt >= 0.1)

newt_checkbox_tree_set_width

Opis

void newt_checkbox_tree_set_width ( resource $checkbox_tree , int $width )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

checkbox_tree

width

Zwracane wartości

nie jest zwracana żadna wartość.



newt_checkbox_tree

(PECL newt >= 0.1)

newt_checkbox_tree

Opis

resource newt_checkbox_tree ( int $left , int $top , int $height [, int $flags ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

left

top

height

flags

Zwracane wartości



newt_checkbox

(PECL newt >= 0.1)

newt_checkbox

Opis

resource newt_checkbox ( int $left , int $top , string $text , string $def_value [, string $seq ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

left

top

text

def_value

seq

Zwracane wartości



newt_clear_key_buffer

(PECL newt >= 0.1)

newt_clear_key_bufferDiscards the contents of the terminal's input buffer without waiting for additional input

Opis

void newt_clear_key_buffer ( void )

Discards the contents of the terminal's input buffer without waiting for additional input.

Zwracane wartości

nie jest zwracana żadna wartość.

Zobacz też:



newt_cls

(PECL newt >= 0.1)

newt_cls

Opis

void newt_cls ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

Zwracane wartości

nie jest zwracana żadna wartość.



newt_compact_button

(PECL newt >= 0.1)

newt_compact_button

Opis

resource newt_compact_button ( int $left , int $top , string $text )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

left

top

text

Zwracane wartości



newt_component_add_callback

(PECL newt >= 0.1)

newt_component_add_callback

Opis

void newt_component_add_callback ( resource $component , mixed $func_name , mixed $data )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

component

func_name

data

Zwracane wartości

nie jest zwracana żadna wartość.



newt_component_takes_focus

(PECL newt >= 0.1)

newt_component_takes_focus

Opis

void newt_component_takes_focus ( resource $component , bool $takes_focus )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

component

takes_focus

Zwracane wartości

nie jest zwracana żadna wartość.



newt_create_grid

(PECL newt >= 0.1)

newt_create_grid

Opis

resource newt_create_grid ( int $cols , int $rows )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

cols

rows

Zwracane wartości



newt_cursor_off

(PECL newt >= 0.1)

newt_cursor_off

Opis

void newt_cursor_off ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

Zwracane wartości

nie jest zwracana żadna wartość.



newt_cursor_on

(PECL newt >= 0.1)

newt_cursor_on

Opis

void newt_cursor_on ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

nie jest zwracana żadna wartość.



newt_delay

(PECL newt >= 0.1)

newt_delay

Opis

void newt_delay ( int $microseconds )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

microseconds

Zwracane wartości

nie jest zwracana żadna wartość.



newt_draw_form

(PECL newt >= 0.1)

newt_draw_form

Opis

void newt_draw_form ( resource $form )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

form

Zwracane wartości

nie jest zwracana żadna wartość.



newt_draw_root_text

(PECL newt >= 0.1)

newt_draw_root_textDisplays the string text at the position indicated

Opis

void newt_draw_root_text ( int $left , int $top , string $text )

Displays the string text at the position indicated.

Parametry

left

Column number

Informacja: If left is negative, the position is measured from the opposite side of the screen.

top

Line number

Informacja: If top is negative, the position is measured from the opposite side of the screen.

text

Text to display.

Zwracane wartości

nie jest zwracana żadna wartość.

Przykłady

Przykład #1 A newt_draw_root_text() example

This code demonstrates drawing of titles in the both corners of the screen.

<?php
 newt_init
();
 
newt_cls();

 
newt_draw_root_text (20"Some root text");
 
newt_refresh();
 
sleep(1);

 
newt_draw_root_text (-300"Root text in the other corner");
 
newt_refresh();
 
sleep(1);

 
newt_finished();
?>

Zobacz też:



newt_entry_get_value

(PECL newt >= 0.1)

newt_entry_get_value

Opis

string newt_entry_get_value ( resource $entry )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

entry

Zwracane wartości



newt_entry_set_filter

(PECL newt >= 0.1)

newt_entry_set_filter

Opis

void newt_entry_set_filter ( resource $entry , callback $filter , mixed $data )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

entry

filter

data

Zwracane wartości

nie jest zwracana żadna wartość.



newt_entry_set_flags

(PECL newt >= 0.1)

newt_entry_set_flags

Opis

void newt_entry_set_flags ( resource $entry , int $flags , int $sense )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

entry

flags

sense

Zwracane wartości

nie jest zwracana żadna wartość.



newt_entry_set

(PECL newt >= 0.1)

newt_entry_set

Opis

void newt_entry_set ( resource $entry , string $value [, bool $cursor_at_end ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

entry

value

cursor_at_end

Zwracane wartości

nie jest zwracana żadna wartość.



newt_entry

(PECL newt >= 0.1)

newt_entry

Opis

resource newt_entry ( int $left , int $top , int $width [, string $init_value [, int $flags ]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

left

top

width

init_value

flags

Zwracane wartości



newt_finished

(PECL newt >= 0.1)

newt_finishedUninitializes newt interface

Opis

int newt_finished ( void )

Uninitializes newt interface. This function be called, when program is ready to exit.

Zwracane wartości

Returns 1 on success, 0 on failure.

Zobacz też:



newt_form_add_component

(PECL newt >= 0.1)

newt_form_add_componentAdds a single component to the form

Opis

void newt_form_add_component ( resource $form , resource $component )

Adds a single component to the form .

Parametry

form

Form to which component will be added

component

Component to add to the form

Zwracane wartości

nie jest zwracana żadna wartość.

Przykłady

Przykład #1 A newt_form_add_component() example

<?php
$form 
newt_form();

$options = array("Authentication configuration""Firewall configuration",
"Mouse configuration""Network configuration""Printer configuration",
"System services");

$list newt_listbox(3210);

foreach (
$options as $l_item) {
    
newt_listbox_add_entry($list$l_item$l_item);
}

newt_form_add_component($form$list);
?>

Zobacz też:



newt_form_add_components

(PECL newt >= 0.1)

newt_form_add_componentsAdd several components to the form

Opis

void newt_form_add_components ( resource $form , array $components )

Adds several components to the form .

Parametry

form

Form to which components will be added

components

Array of components to add to the form

Zwracane wartości

nie jest zwracana żadna wartość.

Przykłady

Przykład #1 A newt_form_add_components() example

<?php
$form 
newt_form();

$b1 newt_button(512"Run Tool");
$b2 newt_button(2112"Quit");

newt_form_add_components($form, array($b1$b2));
?>

Zobacz też:



newt_form_add_hot_key

(PECL newt >= 0.1)

newt_form_add_hot_key

Opis

void newt_form_add_hot_key ( resource $form , int $key )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

form

key

Zwracane wartości

nie jest zwracana żadna wartość.



newt_form_destroy

(PECL newt >= 0.1)

newt_form_destroyDestroys a form

Opis

void newt_form_destroy ( resource $form )

This function frees the memory resources used by the form and all of the components which have been added to the form (including those components which are on subforms). Once a form has been destroyed, none of the form's components can be used.

Parametry

form

Form component, which is going to be destroyed

Zwracane wartości

nie jest zwracana żadna wartość.

Zobacz też:



newt_form_get_current

(PECL newt >= 0.1)

newt_form_get_current

Opis

resource newt_form_get_current ( resource $form )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

form

Zwracane wartości



newt_form_run

(PECL newt >= 0.1)

newt_form_runRuns a form

Opis

void newt_form_run ( resource $form , array &$exit_struct )

This function runs the form passed to it.

Parametry

form

Form component

exit_struct

Array, used for returning information after running the form component. Keys and values are described in the following table:

Form Exit Structure
Index Key Value Type Description
reason integer The reason, why the form has been exited. Possible values are defined here.
watch resource Resource link, specified in newt_form_watch_fd()
key integer Hotkey
component resource Component, which caused the form to exit

Zwracane wartości

nie jest zwracana żadna wartość.

Zobacz też:



newt_form_set_background

(PECL newt >= 0.1)

newt_form_set_background

Opis

void newt_form_set_background ( resource $from , int $background )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

from

background

Zwracane wartości

nie jest zwracana żadna wartość.



newt_form_set_height

(PECL newt >= 0.1)

newt_form_set_height

Opis

void newt_form_set_height ( resource $form , int $height )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

form

height

Zwracane wartości

nie jest zwracana żadna wartość.



newt_form_set_size

(PECL newt >= 0.1)

newt_form_set_size

Opis

void newt_form_set_size ( resource $form )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

form

Zwracane wartości

nie jest zwracana żadna wartość.



newt_form_set_timer

(PECL newt >= 0.1)

newt_form_set_timer

Opis

void newt_form_set_timer ( resource $form , int $milliseconds )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

form

milliseconds

Zwracane wartości

nie jest zwracana żadna wartość.



newt_form_set_width

(PECL newt >= 0.1)

newt_form_set_width

Opis

void newt_form_set_width ( resource $form , int $width )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

form

width

Zwracane wartości

nie jest zwracana żadna wartość.



newt_form_watch_fd

(PECL newt >= 0.1)

newt_form_watch_fd

Opis

void newt_form_watch_fd ( resource $form , resource $stream [, int $flags ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

form

stream

flags

Zwracane wartości

nie jest zwracana żadna wartość.



newt_form

(PECL newt >= 0.1)

newt_formCreate a form

Opis

resource newt_form ([ resource $vert_bar [, string $help [, int $flags ]]] )

Create a new form.

Parametry

vert_bar

Vertical scrollbar which should be associated with the form

help

Help text string

flags

Various flags

Zwracane wartości

Returns a resource link to the created form component, or FALSE on error.

Przykłady

Przykład #1 A newt_form() example

Displays a single button "Quit", which closes the application once it's pressed.

<?php
newt_init
();
newt_cls();

$myform newt_form();
$button newt_button (512"Quit");

newt_form_add_component ($myform$button);
newt_refresh ();
newt_run_form ($myform);

newt_finished ();
newt_form_destroy ($myform);
?>

Zobacz też:



newt_get_screen_size

(PECL newt >= 0.1)

newt_get_screen_sizeFills in the passed references with the current size of the terminal

Opis

void newt_get_screen_size ( int &$cols , int &$rows )

Fills in the passed references with the current size of the terminal.

Parametry

cols

Number of columns in the terminal

rows

Number of rows in the terminal

Zwracane wartości

nie jest zwracana żadna wartość.

Przykłady

Przykład #1 A newt_get_screen_size() example

This code prints out the screen size of your terminal.

<?php
 newt_init
();
 
newt_get_screen_size (&$cols, &$rows);
 
newt_finished();

 print 
"Your terminal size is: {$cols}x{$rows}\n";
?>

Powyższy przykład wyświetli:

Your terminal size is: 138x47



newt_grid_add_components_to_form

(PECL newt >= 0.1)

newt_grid_add_components_to_form

Opis

void newt_grid_add_components_to_form ( resource $grid , resource $form , bool $recurse )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

grid

form

recurse

Zwracane wartości

nie jest zwracana żadna wartość.



newt_grid_basic_window

(PECL newt >= 0.1)

newt_grid_basic_window

Opis

resource newt_grid_basic_window ( resource $text , resource $middle , resource $buttons )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

text

middle

buttons

Zwracane wartości



newt_grid_free

(PECL newt >= 0.1)

newt_grid_free

Opis

void newt_grid_free ( resource $grid , bool $recurse )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

grid

recurse

Zwracane wartości

nie jest zwracana żadna wartość.



newt_grid_get_size

(PECL newt >= 0.1)

newt_grid_get_size

Opis

void newt_grid_get_size ( resouce $grid , int &$width , int &$height )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

grid

width

height

Zwracane wartości

nie jest zwracana żadna wartość.



newt_grid_h_close_stacked

(PECL newt >= 0.1)

newt_grid_h_close_stacked

Opis

resource newt_grid_h_close_stacked ( int $element1_type , resource $element1 [, int $... [, resource $... ]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

element1_type

element1

Zwracane wartości



newt_grid_h_stacked

(PECL newt >= 0.1)

newt_grid_h_stacked

Opis

resource newt_grid_h_stacked ( int $element1_type , resource $element1 [, int $... [, resource $... ]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

element1_type

element1

Zwracane wartości



newt_grid_place

(PECL newt >= 0.1)

newt_grid_place

Opis

void newt_grid_place ( resource $grid , int $left , int $top )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

grid

left

top

Zwracane wartości

nie jest zwracana żadna wartość.



newt_grid_set_field

(PECL newt >= 0.1)

newt_grid_set_field

Opis

void newt_grid_set_field ( resource $grid , int $col , int $row , int $type , resource $val , int $pad_left , int $pad_top , int $pad_right , int $pad_bottom , int $anchor [, int $flags ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

grid

col

row

type

val

pad_left

pad_top

pad_right

pad_bottom

anchor

flags

Zwracane wartości

nie jest zwracana żadna wartość.



newt_grid_simple_window

(PECL newt >= 0.1)

newt_grid_simple_window

Opis

resource newt_grid_simple_window ( resource $text , resource $middle , resource $buttons )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

text

middle

buttons

Zwracane wartości



newt_grid_v_close_stacked

(PECL newt >= 0.1)

newt_grid_v_close_stacked

Opis

resource newt_grid_v_close_stacked ( int $element1_type , resource $element1 [, int $... [, resource $... ]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

element1_type

element1

Zwracane wartości



newt_grid_v_stacked

(PECL newt >= 0.1)

newt_grid_v_stacked

Opis

resource newt_grid_v_stacked ( int $element1_type , resource $element1 [, int $... [, resource $... ]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

element1_type

element1

Zwracane wartości



newt_grid_wrapped_window_at

(PECL newt >= 0.1)

newt_grid_wrapped_window_at

Opis

void newt_grid_wrapped_window_at ( resource $grid , string $title , int $left , int $top )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

grid

title

left

top

Zwracane wartości

nie jest zwracana żadna wartość.



newt_grid_wrapped_window

(PECL newt >= 0.1)

newt_grid_wrapped_window

Opis

void newt_grid_wrapped_window ( resource $grid , string $title )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

grid

title

Zwracane wartości

nie jest zwracana żadna wartość.



newt_init

(PECL newt >= 0.1)

newt_initInitialize newt

Opis

int newt_init ( void )

Initializes the newt interface. This function must be called before any other newt function.

Zwracane wartości

Returns 1 on success, 0 on failure.

Zobacz też:



newt_label_set_text

(PECL newt >= 0.1)

newt_label_set_text

Opis

void newt_label_set_text ( resource $label , string $text )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

label

text

Zwracane wartości

nie jest zwracana żadna wartość.



newt_label

(PECL newt >= 0.1)

newt_label

Opis

resource newt_label ( int $left , int $top , string $text )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

left

top

text

Zwracane wartości



newt_listbox_append_entry

(PECL newt >= 0.1)

newt_listbox_append_entry

Opis

void newt_listbox_append_entry ( resource $listbox , string $text , mixed $data )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

listbox

text

data

Zwracane wartości

nie jest zwracana żadna wartość.



newt_listbox_clear_selection

(PECL newt >= 0.1)

newt_listbox_clear_selection

Opis

void newt_listbox_clear_selection ( resource $listbox )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

listbox

Zwracane wartości

nie jest zwracana żadna wartość.



newt_listbox_clear

(PECL newt >= 0.1)

newt_listbox_clear

Opis

void newt_listbox_clear ( resource $listobx )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

listobx

Zwracane wartości

nie jest zwracana żadna wartość.



newt_listbox_delete_entry

(PECL newt >= 0.1)

newt_listbox_delete_entry

Opis

void newt_listbox_delete_entry ( resource $listbox , mixed $key )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

listbox

key

Zwracane wartości

nie jest zwracana żadna wartość.



newt_listbox_get_current

(PECL newt >= 0.1)

newt_listbox_get_current

Opis

string newt_listbox_get_current ( resource $listbox )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

listbox

Zwracane wartości



newt_listbox_get_selection

(PECL newt >= 0.1)

newt_listbox_get_selection

Opis

array newt_listbox_get_selection ( resource $listbox )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

listbox

Zwracane wartości



newt_listbox_insert_entry

(PECL newt >= 0.1)

newt_listbox_insert_entry

Opis

void newt_listbox_insert_entry ( resource $listbox , string $text , mixed $data , mixed $key )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

listbox

text

data

key

Zwracane wartości

nie jest zwracana żadna wartość.



newt_listbox_item_count

(PECL newt >= 0.1)

newt_listbox_item_count

Opis

int newt_listbox_item_count ( resource $listbox )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

listbox

Zwracane wartości



newt_listbox_select_item

(PECL newt >= 0.1)

newt_listbox_select_item

Opis

void newt_listbox_select_item ( resource $listbox , mixed $key , int $sense )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

listbox

key

sense

Zwracane wartości

nie jest zwracana żadna wartość.



newt_listbox_set_current_by_key

(PECL newt >= 0.1)

newt_listbox_set_current_by_key

Opis

void newt_listbox_set_current_by_key ( resource $listbox , mixed $key )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

listbox

key

Zwracane wartości

nie jest zwracana żadna wartość.



newt_listbox_set_current

(PECL newt >= 0.1)

newt_listbox_set_current

Opis

void newt_listbox_set_current ( resource $listbox , int $num )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

listbox

num

Zwracane wartości

nie jest zwracana żadna wartość.



newt_listbox_set_data

(PECL newt >= 0.1)

newt_listbox_set_data

Opis

void newt_listbox_set_data ( resource $listbox , int $num , mixed $data )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

listbox

num

data

Zwracane wartości

nie jest zwracana żadna wartość.



newt_listbox_set_entry

(PECL newt >= 0.1)

newt_listbox_set_entry

Opis

void newt_listbox_set_entry ( resource $listbox , int $num , string $text )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

listbox

num

text

Zwracane wartości

nie jest zwracana żadna wartość.



newt_listbox_set_width

(PECL newt >= 0.1)

newt_listbox_set_width

Opis

void newt_listbox_set_width ( resource $listbox , int $width )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

listbox

width

Zwracane wartości

nie jest zwracana żadna wartość.



newt_listbox

(PECL newt >= 0.1)

newt_listbox

Opis

resource newt_listbox ( int $left , int $top , int $height [, int $flags ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

left

top

height

flags

Zwracane wartości



newt_listitem_get_data

(PECL newt >= 0.1)

newt_listitem_get_data

Opis

mixed newt_listitem_get_data ( resource $item )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

item

Zwracane wartości



newt_listitem_set

(PECL newt >= 0.1)

newt_listitem_set

Opis

void newt_listitem_set ( resource $item , string $text )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

item

text

Zwracane wartości

nie jest zwracana żadna wartość.



newt_listitem

(PECL newt >= 0.1)

newt_listitem

Opis

resource newt_listitem ( int $left , int $top , string $text , bool $is_default , resouce $prev_item , mixed $data [, int $flags ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

left

top

text

is_default

prev_item

data

flags

Zwracane wartości



newt_open_window

(PECL newt >= 0.1)

newt_open_windowOpen a window of the specified size and position

Opis

int newt_open_window ( int $left , int $top , int $width , int $height [, string $title ] )

Open a window of the specified size and position.

Parametry

left

Location of the upper left-hand corner of the window (column number)

top

Location of the upper left-hand corner of the window (row number)

width

Window width

height

Window height

title

Window title

Zwracane wartości

Returns 1 on success, 0 on failure.

Zobacz też:



newt_pop_help_line

(PECL newt >= 0.1)

newt_pop_help_lineReplaces the current help line with the one from the stack

Opis

void newt_pop_help_line ( void )

Replaces the current help line with the one from the stack.

Informacja: It's important not to call to newt_pop_help_line() more than newt_push_help_line().

Zwracane wartości

nie jest zwracana żadna wartość.

Zobacz też:



newt_pop_window

(PECL newt >= 0.1)

newt_pop_windowRemoves the top window from the display

Opis

void newt_pop_window ( void )

Removes the top window from the display, and redraws the display areas which the window overwrote.

Zwracane wartości

nie jest zwracana żadna wartość.

Zobacz też:



newt_push_help_line

(PECL newt >= 0.1)

newt_push_help_lineSaves the current help line on a stack, and displays the new line

Opis

void newt_push_help_line ([ string $text ] )

Saves the current help line on a stack, and displays the new line.

Parametry

text

New help text message

Informacja: If not specified, the help line is cleared.

Zwracane wartości

nie jest zwracana żadna wartość.

Zobacz też:



newt_radio_get_current

(PECL newt >= 0.1)

newt_radio_get_current

Opis

resource newt_radio_get_current ( resource $set_member )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

set_member

Zwracane wartości



newt_radiobutton

(PECL newt >= 0.1)

newt_radiobutton

Opis

resource newt_radiobutton ( int $left , int $top , string $text , bool $is_default [, resource $prev_button ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

left

top

text

is_default

prev_button

Zwracane wartości



newt_redraw_help_line

(PECL newt >= 0.1)

newt_redraw_help_line

Opis

void newt_redraw_help_line ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

Zwracane wartości

nie jest zwracana żadna wartość.



newt_reflow_text

(PECL newt >= 0.1)

newt_reflow_text

Opis

string newt_reflow_text ( string $text , int $width , int $flex_down , int $flex_up , int &$actual_width , int &$actual_height )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

text

width

flex_down

flex_up

actual_width

actual_height

Zwracane wartości



newt_refresh

(PECL newt >= 0.1)

newt_refreshUpdates modified portions of the screen

Opis

void newt_refresh ( void )

To increase performance, newt only updates the display when it needs to, not when the program tells it to write to the terminal. Applications can force newt to immediately update modified portions of the screen by calling this function.

Zwracane wartości

nie jest zwracana żadna wartość.



newt_resize_screen

(PECL newt >= 0.1)

newt_resize_screen

Opis

void newt_resize_screen ([ bool $redraw ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

redraw

Zwracane wartości

nie jest zwracana żadna wartość.



newt_resume

(PECL newt >= 0.1)

newt_resumeResume using the newt interface after calling newt_suspend()

Opis

void newt_resume ( void )

Resume using the newt interface after calling newt_suspend().

Zwracane wartości

nie jest zwracana żadna wartość.

Zobacz też:

  • newt_suspend() - Tells newt to return the terminal to its initial state



newt_run_form

(PECL newt >= 0.1)

newt_run_formRuns a form

Opis

resource newt_run_form ( resource $form )

This function runs the form passed to it.

Parametry

form

Form component

Zwracane wartości

The component which caused the form to stop running.

Informacja: Notice that this function doesn't fit in with newt's normal naming convention. It is an older interface which will not work for all forms. It was left in newt only for legacy applications. It is a simpler interface than the new newt_form_run() though, and is still used quite often as a result. When an application is done with a form, it destroys the form and all of the components the form contains.

Zobacz też:



newt_scale_set

(PECL newt >= 0.1)

newt_scale_set

Opis

void newt_scale_set ( resource $scale , int $amount )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

scale

amount

Zwracane wartości

nie jest zwracana żadna wartość.



newt_scale

(PECL newt >= 0.1)

newt_scale

Opis

resource newt_scale ( int $left , int $top , int $width , int $full_value )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

left

top

width

full_value

Zwracane wartości



newt_scrollbar_set

(PECL newt >= 0.1)

newt_scrollbar_set

Opis

void newt_scrollbar_set ( resource $scrollbar , int $where , int $total )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

scrollbar

where

total

Zwracane wartości

nie jest zwracana żadna wartość.



newt_set_help_callback

(PECL newt >= 0.1)

newt_set_help_callback

Opis

void newt_set_help_callback ( mixed $function )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

function

Zwracane wartości

nie jest zwracana żadna wartość.



newt_set_suspend_callback

(PECL newt >= 0.1)

newt_set_suspend_callbackSet a callback function which gets invoked when user presses the suspend key

Opis

void newt_set_suspend_callback ( callback $function , mixed $data )

Set a callback function which gets invoked when user presses the suspend key (normally ^Z). If no suspend callback is registered, the suspend keystroke is ignored.

Parametry

function

A callback function, which accepts one argument: data

data

This data is been passed to the callback function

Zwracane wartości

nie jest zwracana żadna wartość.

Zobacz też:

  • newt_suspend() - Tells newt to return the terminal to its initial state
  • newt_resume() - Resume using the newt interface after calling newt_suspend



newt_suspend

(PECL newt >= 0.1)

newt_suspendTells newt to return the terminal to its initial state

Opis

void newt_suspend ( void )

Tells newt to return the terminal to its initial state. Once this is done, the application can suspend itself (by sending itself a SIGTSTP, fork a child program, or do whatever else it likes).

Zwracane wartości

nie jest zwracana żadna wartość.

Zobacz też:

  • newt_resume() - Resume using the newt interface after calling newt_suspend



newt_textbox_get_num_lines

(PECL newt >= 0.1)

newt_textbox_get_num_lines

Opis

int newt_textbox_get_num_lines ( resource $textbox )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

textbox

Zwracane wartości



newt_textbox_reflowed

(PECL newt >= 0.1)

newt_textbox_reflowed

Opis

resource newt_textbox_reflowed ( int $left , int $top , char $*text , int $width , int $flex_down , int $flex_up [, int $flags ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

left

top

*text

width

flex_down

flex_up

flags

Zwracane wartości



newt_textbox_set_height

(PECL newt >= 0.1)

newt_textbox_set_height

Opis

void newt_textbox_set_height ( resource $textbox , int $height )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

textbox

height

Zwracane wartości

nie jest zwracana żadna wartość.



newt_textbox_set_text

(PECL newt >= 0.1)

newt_textbox_set_text

Opis

void newt_textbox_set_text ( resource $textbox , string $text )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

textbox

text

Zwracane wartości

nie jest zwracana żadna wartość.



newt_textbox

(PECL newt >= 0.1)

newt_textbox

Opis

resource newt_textbox ( int $left , int $top , int $width , int $height [, int $flags ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

left

top

width

height

flags

Zwracane wartości



newt_vertical_scrollbar

(PECL newt >= 0.1)

newt_vertical_scrollbar

Opis

resource newt_vertical_scrollbar ( int $left , int $top , int $height [, int $normal_colorset [, int $thumb_colorset ]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

left

top

height

normal_colorset

thumb_colorset

Zwracane wartości



newt_wait_for_key

(PECL newt >= 0.1)

newt_wait_for_keyDoesn't return until a key has been pressed

Opis

void newt_wait_for_key ( void )

This function doesn't return until a key has been pressed. The keystroke is then ignored. If a key is already in the terminal's buffer, this function discards a keystroke and returns immediately.

Zwracane wartości

nie jest zwracana żadna wartość.

Zobacz też:

  • newt_clear_key_buffer() - Discards the contents of the terminal's input buffer without waiting for additional input



newt_win_choice

(PECL newt >= 0.1)

newt_win_choice

Opis

int newt_win_choice ( string $title , string $button1_text , string $button2_text , string $format [, mixed $args [, mixed $... ]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

title

button1_text

button2_text

format

args

Zwracane wartości



newt_win_entries

(PECL newt >= 0.1)

newt_win_entries

Opis

int newt_win_entries ( string $title , string $text , int $suggested_width , int $flex_down , int $flex_up , int $data_width , array &$items , string $button1 [, string $... ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

title

text

suggested_width

flex_down

flex_up

data_width

items

button1

button2

Zwracane wartości

Przykłady

Przykład #1 A newt_win_entries() example

<?php

newt_init
();
newt_cls();

$entries[] = array('text' => 'First name:''value' => &$f_name);
$entries[] = array('text' => 'Last name:',  'value' => &$l_name);

$rc newt_win_entries("User information""Please enter your credentials:"507730$entries"Ok""Back");
newt_finished ();

if (
$rc != 2) {
    echo 
"Your name is: $f_name $l_name\n";
}
?>



newt_win_menu

(PECL newt >= 0.1)

newt_win_menu

Opis

int newt_win_menu ( string $title , string $text , int $suggestedWidth , int $flexDown , int $flexUp , int $maxListHeight , array $items , int &$listItem [, string $button1 [, string $... ]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

title

text

suggestedWidth

flexDown

flexUp

maxListHeight

items

listItem

button1

Zwracane wartości

nie jest zwracana żadna wartość.



newt_win_message

(PECL newt >= 0.1)

newt_win_message

Opis

void newt_win_message ( string $title , string $button_text , string $format [, mixed $args [, mixed $... ]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

title

button_text

format

args

Zwracane wartości

nie jest zwracana żadna wartość.



newt_win_messagev

(PECL newt >= 0.1)

newt_win_messagev

Opis

void newt_win_messagev ( string $title , string $button_text , string $format , array $args )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

title

button_text

format

args

Zwracane wartości

nie jest zwracana żadna wartość.



newt_win_ternary

(PECL newt >= 0.1)

newt_win_ternary

Opis

int newt_win_ternary ( string $title , string $button1_text , string $button2_text , string $button3_text , string $format [, mixed $args [, mixed $... ]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

title

Its description

button1_text

Its description

button2_text

Its description

button3_text

Its description

format

Its description

args

Its description

Zwracane wartości

What the function returns, first on success, then on failure. See also the &return.success; entity


Spis treści




Ncurses Terminal Screen Control


Wstęp

ncurses (new curses) is a free software emulation of curses in System V Rel 4.0 (and above). It uses terminfo format, supports pads, colors, multiple highlights, form characters and function key mapping. Because of the interactive nature of this library, it will be of little use for writing Web applications, but may be useful when writing scripts meant using PHP from the command line.

The features available, such as colors, depend on the terminal that you are using. Use functions such as ncurses_has_colors(), ncurses_can_change_color(), and ncurses_has_ic() to check for individual capabilities.

Informacja: To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.3.0.

ncurses is available for the following platforms:

  • AIX
  • BeOS
  • BSD variants (FreeBSD, NetBSD, OpenBSD)
  • Cygwin
  • Digital Unix (aka OSF1)
  • GNU/Linux
  • HPUX
  • IRIX64
  • Mac OS X
  • OS/2
  • QNX
  • SCO OpenServer
  • Solaris
  • Tru64



Instalacja/Konfiguracja

Spis treści


Wymagania

You need the ncurses libraries and headerfiles. Download the latest version from the » ftp://ftp.gnu.org/pub/gnu/ncurses/ or from an other GNU-Mirror.



Instalacja

To get these functions to work, you have to compile the CGI or CLI version of PHP with --with-ncurses[=DIR].



Konfiguracja wykonawcza

To rozszerzenie nie definiuje posiada żadnych dyrektyw konfiguracyjnych w pliku php.ini.



Typy zasobów

This extension defines window, panel and pad resources.




Stałe predefiniowane

Spis treści

Poniższe stałe są zdefiniowane w tym rozszerzeniu i stają się dostępne, gdy rozszerzenie jest dokompilowane z PHP, lub załadowane dynamicznie przy starcie.


Error codes

On error ncurses functions return -1. Some functions return 0 on success. See the relevant pages in the documentation for actual return values.



Colors

ncurses color constants
constant meaning
NCURSES_COLOR_BLACK no color (black)
NCURSES_COLOR_WHITE white
NCURSES_COLOR_RED red - supported when terminal is in color mode
NCURSES_COLOR_GREEN green - supported when terminal is in color mode
NCURSES_COLOR_YELLOW yellow - supported when terminal is in color mode
NCURSES_COLOR_BLUE blue - supported when terminal is in color mode
NCURSES_COLOR_CYAN cyan - supported when terminal is in color mode
NCURSES_COLOR_MAGENTA magenta - supported when terminal is in color mode


Keys

ncurses key constants
constant meaning
NCURSES_KEY_F0 - NCURSES_KEY_F64 function keys F1 - F64
NCURSES_KEY_DOWN down arrow
NCURSES_KEY_UP up arrow
NCURSES_KEY_LEFT left arrow
NCURSES_KEY_RIGHT right arrow
NCURSES_KEY_HOME home key (upward+left arrow)
NCURSES_KEY_BACKSPACE backspace
NCURSES_KEY_DL delete line
NCURSES_KEY_IL insert line
NCURSES_KEY_DC delete character
NCURSES_KEY_IC insert char or enter insert mode
NCURSES_KEY_EIC exit insert char mode
NCURSES_KEY_CLEAR clear screen
NCURSES_KEY_EOS clear to end of screen
NCURSES_KEY_EOL clear to end of line
NCURSES_KEY_SF scroll one line forward
NCURSES_KEY_SR scroll one line backward
NCURSES_KEY_NPAGE next page
NCURSES_KEY_PPAGE previous page
NCURSES_KEY_STAB set tab
NCURSES_KEY_CTAB clear tab
NCURSES_KEY_CATAB clear all tabs
NCURSES_KEY_SRESET soft (partial) reset
NCURSES_KEY_RESET reset or hard reset
NCURSES_KEY_PRINT print
NCURSES_KEY_LL lower left
NCURSES_KEY_A1 upper left of keypad
NCURSES_KEY_A3 upper right of keypad
NCURSES_KEY_B2 center of keypad
NCURSES_KEY_C1 lower left of keypad
NCURSES_KEY_C3 lower right of keypad
NCURSES_KEY_BTAB back tab
NCURSES_KEY_BEG beginning
NCURSES_KEY_CANCEL cancel
NCURSES_KEY_CLOSE close
NCURSES_KEY_COMMAND cmd (command)
NCURSES_KEY_COPY copy
NCURSES_KEY_CREATE create
NCURSES_KEY_END end
NCURSES_KEY_EXIT exit
NCURSES_KEY_FIND find
NCURSES_KEY_HELP help
NCURSES_KEY_MARK mark
NCURSES_KEY_MESSAGE message
NCURSES_KEY_MOVE move
NCURSES_KEY_NEXT next
NCURSES_KEY_OPEN open
NCURSES_KEY_OPTIONS options
NCURSES_KEY_PREVIOUS previous
NCURSES_KEY_REDO redo
NCURSES_KEY_REFERENCE ref (reference)
NCURSES_KEY_REFRESH refresh
NCURSES_KEY_REPLACE replace
NCURSES_KEY_RESTART restart
NCURSES_KEY_RESUME resume
NCURSES_KEY_SAVE save
NCURSES_KEY_SBEG shiftet beg (beginning)
NCURSES_KEY_SCANCEL shifted cancel
NCURSES_KEY_SCOMMAND shifted command
NCURSES_KEY_SCOPY shifted copy
NCURSES_KEY_SCREATE shifted create
NCURSES_KEY_SDC shifted delete char
NCURSES_KEY_SDL shifted delete line
NCURSES_KEY_SELECT select
NCURSES_KEY_SEND shifted end
NCURSES_KEY_SEOL shifted end of line
NCURSES_KEY_SEXIT shifted exit
NCURSES_KEY_SFIND shifted find
NCURSES_KEY_SHELP shifted help
NCURSES_KEY_SHOME shifted home
NCURSES_KEY_SIC shifted input
NCURSES_KEY_SLEFT shifted left arrow
NCURSES_KEY_SMESSAGE shifted message
NCURSES_KEY_SMOVE shifted move
NCURSES_KEY_SNEXT shifted next
NCURSES_KEY_SOPTIONS shifted options
NCURSES_KEY_SPREVIOUS shifted previous
NCURSES_KEY_SPRINT shifted print
NCURSES_KEY_SREDO shifted redo
NCURSES_KEY_SREPLACE shifted replace
NCURSES_KEY_SRIGHT shifted right arrow
NCURSES_KEY_SRSUME shifted resume
NCURSES_KEY_SSAVE shifted save
NCURSES_KEY_SSUSPEND shifted suspend
NCURSES_KEY_UNDO undo
NCURSES_KEY_MOUSE mouse event has occurred
NCURSES_KEY_MAX maximum key value


Mouse

mouse constants
Constant meaning
NCURSES_BUTTON1_RELEASED - NCURSES_BUTTON4_RELEASED button (1-4) released
NCURSES_BUTTON1_PRESSED - NCURSES_BUTTON4_PRESSED button (1-4) pressed
NCURSES_BUTTON1_CLICKED - NCURSES_BUTTON4_CLICKED button (1-4) clicked
NCURSES_BUTTON1_DOUBLE_CLICKED - NCURSES_BUTTON4_DOUBLE_CLICKED button (1-4) double clicked
NCURSES_BUTTON1_TRIPLE_CLICKED - NCURSES_BUTTON4_TRIPLE_CLICKED button (1-4) triple clicked
NCURSES_BUTTON_CTRL ctrl pressed during click
NCURSES_BUTTON_SHIFT shift pressed during click
NCURSES_BUTTON_ALT alt pressed during click
NCURSES_ALL_MOUSE_EVENTS report all mouse events
NCURSES_REPORT_MOUSE_POSITION report mouse position



Ncurses Funkcje


ncurses_addch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addchAdd character at current position and advance cursor

Opis

int ncurses_addch ( int $ch )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

ch



ncurses_addchnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addchnstrAdd attributed string with specified length at current position

Opis

int ncurses_addchnstr ( string $s , int $n )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

s

n



ncurses_addchstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addchstrAdd attributed string at current position

Opis

int ncurses_addchstr ( string $s )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

s



ncurses_addnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addnstrAdd string with specified length at current position

Opis

int ncurses_addnstr ( string $s , int $n )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

s

n



ncurses_addstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addstrOutput text at current position

Opis

int ncurses_addstr ( string $text )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

text



ncurses_assume_default_colors

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_assume_default_colorsDefine default colors for color 0

Opis

int ncurses_assume_default_colors ( int $fg , int $bg )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

fg

bg



ncurses_attroff

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_attroffTurn off the given attributes

Opis

int ncurses_attroff ( int $attributes )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

attributes



ncurses_attron

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_attronTurn on the given attributes

Opis

int ncurses_attron ( int $attributes )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

attributes



ncurses_attrset

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_attrsetSet given attributes

Opis

int ncurses_attrset ( int $attributes )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

attributes



ncurses_baudrate

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_baudrateReturns baudrate of terminal

Opis

int ncurses_baudrate ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.



ncurses_beep

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_beepLet the terminal beep

Opis

int ncurses_beep ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

ncurses_beep() sends an audible alert (bell) and if its not possible flashes the screen.

Zobacz też:



ncurses_bkgd

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_bkgdSet background property for terminal screen

Opis

int ncurses_bkgd ( int $attrchar )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

attrchar



ncurses_bkgdset

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_bkgdsetControl screen background

Opis

void ncurses_bkgdset ( int $attrchar )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

attrchar



ncurses_border

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_borderDraw a border around the screen using attributed characters

Opis

int ncurses_border ( int $left , int $right , int $top , int $bottom , int $tl_corner , int $tr_corner , int $bl_corner , int $br_corner )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Draws the specified lines and corners around the main window.

Use ncurses_wborder() for borders around subwindows!

Parametry

Every parameter expects 0 to draw a line or 1 to skip it.

left

right

top

bottom

tl_corner

Top left corner

tr_corner

Top right corner

bl_corner

Bottom left corner

br_corner

Bottom right corner

Zobacz też:



ncurses_bottom_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_bottom_panelMoves a visible panel to the bottom of the stack

Opis

int ncurses_bottom_panel ( resource $panel )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

panel



ncurses_can_change_color

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_can_change_colorChecks if terminal color definitions can be changed

Opis

bool ncurses_can_change_color ( void )

Checks whether the terminal has color capabilities and whether the programmer can change color definitions using ncurses_init_color(). ncurses must be initialized using ncurses_init() before calling this function.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Return TRUE if the programmer can change color definitions, FALSE otherwise.

Zobacz też:



ncurses_cbreak

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_cbreakSwitch of input buffering

Opis

bool ncurses_cbreak ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Disables line buffering and character processing (interrupt and flow control characters are unaffected), making characters typed by the user immediately available to the program.

Zwracane wartości

Returns TRUE or NCURSES_ERR if any error occurred.

Zobacz też:



ncurses_clear

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_clearClear screen

Opis

bool ncurses_clear ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Clears the screen completely without setting blanks.

Note: ncurses_clear() clears the screen without setting blanks, which have the current background rendition. To clear screen with blanks, use ncurses_erase().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



ncurses_clrtobot

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_clrtobotClear screen from current position to bottom

Opis

bool ncurses_clrtobot ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Erases all lines from cursor to end of screen and creates blanks. Blanks created by ncurses_clrtobot() have the current background rendition.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



ncurses_clrtoeol

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_clrtoeolClear screen from current position to end of line

Opis

bool ncurses_clrtoeol ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Erases the current line from cursor position to the end. Blanks created by ncurses_clrtoeol() have the current background rendition.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



ncurses_color_content

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_color_contentRetrieves RGB components of a color

Opis

int ncurses_color_content ( int $color , int &$r , int &$g , int &$b )

Retrieves the red, green, and blue components for the given color definition. Terminal color capabilities must be initialized with ncurses_start_color() prior to calling this function.

Parametry

color

The number of the color to retrieve information for. May be one of the pre-defined color constants.

r

A reference to which to return the red component of the color. The value returned to the reference will be between 0 and 1000.

g

A reference to which to return the green component of the color. The value returned to the reference will be between 0 and 1000.

b

A reference to which to return the blue component of the color. The value returned to the reference will be between 0 and 1000.

Zwracane wartości

Returns -1 if the function was successful, and 0 if ncurses or terminal color capabilities have not been initialized.

Zobacz też:



ncurses_color_set

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_color_setSet active foreground and background colors

Opis

int ncurses_color_set ( int $pair )

Sets the active foreground and background colors. Any characters written after this function is invoked will have these colors. This function requires terminal colors to be supported and initialized using ncurses_start_color() beforehand.

ncurses uses color pairs to specify both foreground and background colors. Use ncurses_init_pair() to define a color pair.

Parametry

pair

The color pair from which to get the foreground and background colors to set as the active colors.

Zwracane wartości

Returns -1 on success, and 0 on failure.

Przykłady

Przykład #1 Writing a string with a specified color to the screen

<?php
ncurses_init
();

// If the terminal supports colors, initialize and set active color
if (ncurses_has_colors()) {
    
ncurses_start_color();
    
ncurses_init_pair(1NCURSES_COLOR_YELLOWNCURSES_COLOR_BLUE);
    
ncurses_color_set(1);
}

// Write a string at specified location
ncurses_mvaddstr(1010"Hello world! Yellow on blue text!");

// Flush output to screen
ncurses_refresh();

ncurses_end();
?>

Zobacz też:



ncurses_curs_set

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_curs_setSet cursor state

Opis

int ncurses_curs_set ( int $visibility )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

visibility



ncurses_def_prog_mode

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_def_prog_modeSaves terminals (program) mode

Opis

bool ncurses_def_prog_mode ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Saves the current terminal modes for program (in curses) for use by ncurses_reset_prog_mode().

Zwracane wartości

Returns FALSE on success, otherwise TRUE.

Zobacz też:



ncurses_def_shell_mode

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_def_shell_modeSaves terminals (shell) mode

Opis

bool ncurses_def_shell_mode ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Saves the current terminal modes for shell (not in curses) for use by ncurses_reset_shell_mode().

Zwracane wartości

Returns FALSE on success, TRUE otherwise.

Zobacz też:



ncurses_define_key

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_define_keyDefine a keycode

Opis

int ncurses_define_key ( string $definition , int $keycode )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

definition

keycode



ncurses_del_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_del_panelRemove panel from the stack and delete it (but not the associated window)

Opis

bool ncurses_del_panel ( resource $panel )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

panel



ncurses_delay_output

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_delay_outputDelay output on terminal using padding characters

Opis

int ncurses_delay_output ( int $milliseconds )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

milliseconds



ncurses_delch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_delchDelete character at current position, move rest of line left

Opis

bool ncurses_delch ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Deletes the character under the cursor. All characters to the right of the cursor on the same line are moved to the left one position and the last character on the line is filled with a blank. The cursor position does not change.

Zwracane wartości

Returns FALSE on success, TRUE otherwise.

Zobacz też:



ncurses_deleteln

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_deletelnDelete line at current position, move rest of screen up

Opis

bool ncurses_deleteln ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Deletes the current line under cursorposition. All lines below the current line are moved up one line. The bottom line of window is cleared. Cursor position does not change.

Zwracane wartości

Returns FALSE on success, otherwise TRUE.

Zobacz też:

  • ncurses_delch() - Delete character at current position, move rest of line left



ncurses_delwin

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_delwinDelete a ncurses window

Opis

bool ncurses_delwin ( resource $window )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

window



ncurses_doupdate

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_doupdateWrite all prepared refreshes to terminal

Opis

bool ncurses_doupdate ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Compares the virtual screen to the physical screen and updates the physical screen. This way is more effective than using multiple refresh calls.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.



ncurses_echo

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_echoActivate keyboard input echo

Opis

bool ncurses_echo ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Enables echo mode. All characters typed by user are echoed by ncurses_getch().

Zwracane wartości

Returns FALSE on success, TRUE if any error occurred.

Zobacz też:



ncurses_echochar

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_echocharSingle character output including refresh

Opis

int ncurses_echochar ( int $character )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

character



ncurses_end

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_endStop using ncurses, clean up the screen

Opis

int ncurses_end ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.



ncurses_erase

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_eraseErase terminal screen

Opis

bool ncurses_erase ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Fills the terminal screen with blanks.

Created blanks have the current background rendition, set by ncurses_bkgd().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



ncurses_erasechar

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_erasecharReturns current erase character

Opis

string ncurses_erasechar ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Returns the current erase character.

Zwracane wartości

The current erase char, as a string.

Zobacz też:



ncurses_filter

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_filterSet LINES for iniscr() and newterm() to 1

Opis

void ncurses_filter ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.



ncurses_flash

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_flashFlash terminal screen (visual bell)

Opis

bool ncurses_flash ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Flashes the screen, and if its not possible, sends an audible alert (bell).

Zwracane wartości

Returns FALSE on success, otherwise TRUE.

Zobacz też:



ncurses_flushinp

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_flushinpFlush keyboard input buffer

Opis

bool ncurses_flushinp ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Throws away any typeahead that has been typed and has not yet been read by your program.

Zwracane wartości

Returns FALSE on success, otherwise TRUE.



ncurses_getch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getchRead a character from keyboard

Opis

int ncurses_getch ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.



ncurses_getmaxyx

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getmaxyxReturns the size of a window

Opis

void ncurses_getmaxyx ( resource $window , int &$y , int &$x )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Gets the horizontal and vertical size of the given window into the given variables.

Variables must be passed as reference, so they are updated when the user changes the terminal size.

Parametry

window

The measured window

x

This will be set to the window width

y

This will be set to the window height

Zwracane wartości

nie jest zwracana żadna wartość.



ncurses_getmouse

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getmouseReads mouse event

Opis

bool ncurses_getmouse ( array &$mevent )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

ncurses_getmouse() reads mouse event out of queue.

Parametry

mevent

Event options will be delivered in this parameter which has to be an array, passed by reference (see example below).

On success an associative array with following keys will be delivered:

  • "id" : Id to distinguish multiple devices

  • "x" : screen relative x-position in character cells

  • "y" : screen relative y-position in character cells

  • "z" : currently not supported

  • "mmask" : Mouse action

Zwracane wartości

Returns FALSE if a mouse event is actually visible in the given window, otherwise returns TRUE.

Przykłady

Przykład #1 ncurses_getmouse() example

<?php
switch (ncurses_getch()){
  case 
NCURSES_KEY_MOUSE:
    if (!
ncurses_getmouse($mevent)){
      if (
$mevent["mmask"] & NCURSES_MOUSE_BUTTON1_PRESSED){
        
$mouse_x $mevent["x"]; // Save mouse position
        
$mouse_y $mevent["y"];
      }
    }
  break;

  default:
    
/* .... */
}
?>

Zobacz też:



ncurses_getyx

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getyxReturns the current cursor position for a window

Opis

void ncurses_getyx ( resource $window , int &$y , int &$x )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

window

y

x



ncurses_halfdelay

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_halfdelayPut terminal into halfdelay mode

Opis

int ncurses_halfdelay ( int $tenth )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

tenth



ncurses_has_colors

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_has_colorsChecks if terminal has color capabilities

Opis

bool ncurses_has_colors ( void )

Checks whether the terminal has color capabilities. This function can be used to write terminal-independent programs. ncurses must be initialized using ncurses_init() before calling this function.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Return TRUE if the terminal has color capabilities, FALSE otherwise.

Przykłady

Przykład #1 Writing a string with a specified color to the screen

<?php
ncurses_init
();

// If the terminal supports colors, initialize and set active color
if (ncurses_has_colors()) {
    
ncurses_start_color();
    
ncurses_init_pair(1NCURSES_COLOR_YELLOWNCURSES_COLOR_BLUE);
    
ncurses_color_set(1);
}

// Write a string at specified location
ncurses_mvaddstr(1010"Hello world! Yellow on blue text!");

// Flush output to screen
ncurses_refresh();

ncurses_end();
?>

Zobacz też:



ncurses_has_ic

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_has_icCheck for insert- and delete-capabilities

Opis

bool ncurses_has_ic ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Checks whether the terminal has insert and delete capabilities.

Zwracane wartości

Returns TRUE if the terminal has insert/delete-capabilities, FALSE otherwise.

Zobacz też:



ncurses_has_il

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_has_ilCheck for line insert- and delete-capabilities

Opis

bool ncurses_has_il ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Checks whether the terminal has insert- and delete-line-capabilities.

Zwracane wartości

Returns TRUE if the terminal has insert/delete-line capabilities, FALSE otherwise.

Zobacz też:



ncurses_has_key

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_has_keyCheck for presence of a function key on terminal keyboard

Opis

int ncurses_has_key ( int $keycode )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

keycode



ncurses_hide_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_hide_panelRemove panel from the stack, making it invisible

Opis

int ncurses_hide_panel ( resource $panel )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

panel



ncurses_hline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_hlineDraw a horizontal line at current position using an attributed character and max. n characters long

Opis

int ncurses_hline ( int $charattr , int $n )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

charattr

n



ncurses_inch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_inchGet character and attribute at current position

Opis

string ncurses_inch ( void )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Returns the character from the current position.

Zwracane wartości

Returns the character, as a string.



ncurses_init_color

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_init_colorDefine a terminal color

Opis

int ncurses_init_color ( int $color , int $r , int $g , int $b )

Defines or redefines the given color. When this function is called, all occurrences of the given color on the screen, if any, immediately change to the new definition.

Color capabilities must be supported by the terminal and initialized using ncurses_start_color() prior to calling this function. In addition, the terminal must have color changing capabilities; use ncurses_can_change_color() to check for this.

Parametry

color

The identification number of the color to redefine. It may be one of the default color constants.

r

A color value, between 0 and 1000, for the red component.

g

A color value, between 0 and 1000, for the green component.

b

A color value, between 0 and 1000, for the blue component.

Zwracane wartości

Returns -1 if the function was successful, and 0 if ncurses or terminal color capabilities have not been initialized or the terminal does not have color changing capabilities.

Zobacz też:



ncurses_init_pair

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_init_pairDefine a color pair

Opis

int ncurses_init_pair ( int $pair , int $fg , int $bg )

Defines or redefines the given color pair to have the given foreground and background colors. If the color pair was previously initialized, the screen is refreshed and all occurrences of it are changed to reflect the new definition.

Color capabilities must be initialized using ncurses_start_color() before calling this function. The first color pair (color pair 0) is assumed to be white on black by default, but can be changed using ncurses_assume_default_colors().

Parametry

pair

The number of the color pair to define.

fg

The foreground color for the color pair. May be one of the p